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.openecomp.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.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
44 import org.json.JSONObject;
45 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
46 import org.openecomp.policy.common.logging.flexlogger.Logger;
47 import org.openecomp.policy.model.PDPGroupContainer;
48 import org.openecomp.policy.model.PDPPolicyContainer;
49 import org.openecomp.policy.model.Roles;
50 import org.openecomp.policy.rest.adapter.AutoPushTabAdapter;
51 import org.openecomp.policy.rest.dao.CommonClassDao;
52 import org.openecomp.policy.rest.jpa.PolicyEntity;
53 import org.openecomp.policy.rest.jpa.PolicyVersion;
54 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
55 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
56 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
57 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.JsonMessage;
60 import org.openecomp.portalsdk.core.web.support.UserUtils;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.http.MediaType;
63 import org.springframework.stereotype.Controller;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.servlet.ModelAndView;
67 import com.att.research.xacml.api.pap.PAPException;
68 import com.att.research.xacml.api.pap.PDPPolicy;
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
75 @RequestMapping({"/"})
76 public class AutoPushController extends RestrictedBaseController{
78 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
81 CommonClassDao commonClassDao;
83 private PDPGroupContainer container;
84 protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
86 private static PDPPolicyContainer policyContainer;
87 Set<PDPPolicy> selectedPolicies;
89 private List<Object> data;
91 public synchronized void refreshGroups() {
92 synchronized(this.groups) {
95 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
96 } catch (PAPException e) {
97 String message = "Unable to retrieve Groups from server: " + e;
98 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
104 @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
105 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
107 Set<String> scopes = null;
108 List<String> roles = null;
110 String userId = UserUtils.getUserSession(request).getOrgUserId();
111 Map<String, Object> model = new HashMap<String, Object>();
112 ObjectMapper mapper = new ObjectMapper();
113 List<Object> userRoles = PolicyController.getRoles(userId);
114 roles = new ArrayList<String>();
115 scopes = new HashSet<String>();
116 for(Object role: userRoles){
117 Roles userRole = (Roles) role;
118 roles.add(userRole.getRole());
119 if(userRole.getScope() != null){
120 if(userRole.getScope().contains(",")){
121 String[] multipleScopes = userRole.getScope().split(",");
122 for(int i =0; i < multipleScopes.length; i++){
123 scopes.add(multipleScopes[i]);
126 scopes.add(userRole.getScope());
130 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) {
131 data = commonClassDao.getData(PolicyVersion.class);
133 List<Object> filterdatas = commonClassDao.getData(PolicyVersion.class);
134 for(Object filter : filterdatas){
135 PolicyVersion filterdata = (PolicyVersion) filter;
136 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
137 if(scopes.contains(scopeName)){
138 data.add(filterdata);
142 model.put("policydatas", mapper.writeValueAsString(data));
143 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
144 JSONObject j = new JSONObject(msg);
145 response.getWriter().write(j.toString());
152 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
153 public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
155 ArrayList<Object> selectedPDPS = new ArrayList<Object>();
156 ArrayList<String> selectedPoliciesInUI = new ArrayList<String>();
157 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
158 ObjectMapper mapper = new ObjectMapper();
159 this.container = new PDPGroupContainer(PolicyController.getPapEngine());
160 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
161 JsonNode root = mapper.readTree(request.getReader());
162 AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
163 for (Object pdpGroupId : adapter.getPdpDatas()) {
164 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
165 for(EcompPDPGroup pdpGroup : this.groups){
166 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
167 selectedPDPS.add(pdpGroup);
172 for (Object policyId : adapter.getPolicyDatas()) {
173 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
174 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
175 selectedPoliciesInUI.add(policyName);
178 for (Object pdpDestinationGroupId : selectedPDPS) {
179 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
180 Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
181 for (String policyId : selectedPoliciesInUI) {
182 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
185 // Get the current selection
186 String selectedItem = policyId;
188 assert (selectedItem != null);
189 // create the id of the target file
190 // Our standard for file naming is:
191 // <domain>.<filename>.<version>.xml
192 // since the file name usually has a ".xml", we need to strip
194 // before adding the other parts
195 String name = selectedItem.replace(File.separator, ".");
197 if (id.endsWith(".xml")) {
198 id = id.replace(".xml", "");
199 id = id.substring(0, id.lastIndexOf("."));
202 // Default policy to be Root policy; user can change to deferred
205 StdPDPPolicy selectedPolicy = null;
206 String dbCheckName = name;
207 if(dbCheckName.contains("Config_")){
208 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
209 }else if(dbCheckName.contains("Action_")){
210 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
211 }else if(dbCheckName.contains("Decision_")){
212 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
214 PolicyController controller = new PolicyController();
215 String[] split = dbCheckName.split(":");
216 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
217 System.out.println(query);
218 List<Object> queryData = controller.getDataByQuery(query);
219 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
220 File temp = new File(name);
221 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
222 bw.write(policyEntity.getPolicyData());
224 URI selectedURI = temp.toURI();
228 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
229 } catch (IOException e) {
230 logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
231 //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
233 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
234 if (selectedPolicy != null) {
235 // Add Current policies from container
236 for (EcompPDPGroup group : container.getGroups()) {
237 if (group.getId().equals(selectedGroup.getId())) {
238 currentPoliciesInGroup.addAll(group.getPolicies());
241 // copy policy to PAP
243 PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
244 } catch (PAPException e) {
248 selectedPolicies.add(selectedPolicy);
252 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
253 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
254 updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
255 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
256 updatedGroupObject.setStatus(pdpGroup.getStatus());
258 // replace the original set of Policies with the set from the
259 // container (possibly modified by the user)
260 // do not allow multiple copies of same policy
261 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
262 logger.debug("policyIterator....." + selectedPolicies);
263 while (policyIterator.hasNext()) {
264 PDPPolicy existingPolicy = policyIterator.next();
265 for (PDPPolicy selPolicy : selectedPolicies) {
266 if (selPolicy.getName().equals(existingPolicy.getName())) {
267 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
268 if (selPolicy.getId().equals(existingPolicy.getId())) {
269 policyIterator.remove();
270 logger.debug("Removing policy: " + selPolicy);
274 policyIterator.remove();
275 logger.debug("Removing Old Policy version: "+ selPolicy);
282 currentPoliciesInGroup.addAll(selectedPolicies);
283 updatedGroupObject.setPolicies(currentPoliciesInGroup);
284 this.container.updateGroup(updatedGroupObject);
286 response.setCharacterEncoding("UTF-8");
287 response.setContentType("application / json");
288 request.setCharacterEncoding("UTF-8");
290 PrintWriter out = response.getWriter();
292 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
293 JSONObject j = new JSONObject(msg);
294 out.write(j.toString());
299 response.setCharacterEncoding("UTF-8");
300 request.setCharacterEncoding("UTF-8");
301 PrintWriter out = response.getWriter();
302 out.write(e.getMessage());
307 @SuppressWarnings("unchecked")
308 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
309 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
311 this.container = new PDPGroupContainer(PolicyController.getPapEngine());
312 ObjectMapper mapper = new ObjectMapper();
313 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
314 JsonNode root = mapper.readTree(request.getReader());
315 StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
316 JsonNode removePolicyData = root.get("data");
317 policyContainer = new PDPPolicyContainer(group);
318 if(removePolicyData.size() > 0){
319 for(int i = 0 ; i < removePolicyData.size(); i++){
320 String data = removePolicyData.get(i).toString();
321 AutoPushController.policyContainer.removeItem(data);
323 Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
324 changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
325 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
326 updatedGroupObject.setPolicies(changedPolicies);
327 updatedGroupObject.setEcompPdps(group.getEcompPdps());
328 updatedGroupObject.setPipConfigs(group.getPipConfigs());
329 updatedGroupObject.setStatus(group.getStatus());
330 this.container.updateGroup(updatedGroupObject);
333 response.setCharacterEncoding("UTF-8");
334 response.setContentType("application / json");
335 request.setCharacterEncoding("UTF-8");
337 PrintWriter out = response.getWriter();
339 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
340 JSONObject j = new JSONObject(msg);
342 out.write(j.toString());
347 response.setCharacterEncoding("UTF-8");
348 request.setCharacterEncoding("UTF-8");
349 PrintWriter out = response.getWriter();
350 out.write(e.getMessage());