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;
109 data = new ArrayList<Object>();
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 if(!userRole.getScope().equals("")){
127 scopes.add(userRole.getScope());
132 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
133 data = commonClassDao.getData(PolicyVersion.class);
135 if(!scopes.isEmpty()){
136 for(String scope : scopes){
137 String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0";
138 List<Object> filterdatas = commonClassDao.getDataByQuery(query);
139 if(filterdatas != null){
140 for(int i =0; i < filterdatas.size(); i++){
141 data.add(filterdatas.get(i));
146 PolicyVersion emptyPolicyName = new PolicyVersion();
147 emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
148 data.add(emptyPolicyName);
151 model.put("policydatas", mapper.writeValueAsString(data));
152 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
153 JSONObject j = new JSONObject(msg);
154 response.getWriter().write(j.toString());
157 logger.error("Exception Occured"+e);
161 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
162 public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
164 ArrayList<Object> selectedPDPS = new ArrayList<Object>();
165 ArrayList<String> selectedPoliciesInUI = new ArrayList<String>();
166 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
167 ObjectMapper mapper = new ObjectMapper();
168 this.container = new PDPGroupContainer(PolicyController.getPapEngine());
169 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
170 JsonNode root = mapper.readTree(request.getReader());
171 AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
172 for (Object pdpGroupId : adapter.getPdpDatas()) {
173 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
174 for(EcompPDPGroup pdpGroup : this.groups){
175 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
176 selectedPDPS.add(pdpGroup);
181 for (Object policyId : adapter.getPolicyDatas()) {
182 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
183 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
184 selectedPoliciesInUI.add(policyName);
187 for (Object pdpDestinationGroupId : selectedPDPS) {
188 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
189 Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
190 for (String policyId : selectedPoliciesInUI) {
191 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
194 // Get the current selection
195 String selectedItem = policyId;
197 assert (selectedItem != null);
198 // create the id of the target file
199 // Our standard for file naming is:
200 // <domain>.<filename>.<version>.xml
201 // since the file name usually has a ".xml", we need to strip
203 // before adding the other parts
204 String name = selectedItem.replace(File.separator, ".");
206 if (id.endsWith(".xml")) {
207 id = id.replace(".xml", "");
208 id = id.substring(0, id.lastIndexOf("."));
211 // Default policy to be Root policy; user can change to deferred
214 StdPDPPolicy selectedPolicy = null;
215 String dbCheckName = name;
216 if(dbCheckName.contains("Config_")){
217 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
218 }else if(dbCheckName.contains("Action_")){
219 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
220 }else if(dbCheckName.contains("Decision_")){
221 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
223 PolicyController controller = new PolicyController();
224 String[] split = dbCheckName.split(":");
225 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
226 System.out.println(query);
227 List<Object> queryData = controller.getDataByQuery(query);
228 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
229 File temp = new File(name);
230 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
231 bw.write(policyEntity.getPolicyData());
233 URI selectedURI = temp.toURI();
237 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
238 } catch (IOException e) {
239 logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
240 //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
242 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
243 if (selectedPolicy != null) {
244 // Add Current policies from container
245 for (EcompPDPGroup group : container.getGroups()) {
246 if (group.getId().equals(selectedGroup.getId())) {
247 currentPoliciesInGroup.addAll(group.getPolicies());
250 // copy policy to PAP
252 PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
253 } catch (PAPException e) {
254 logger.error("Exception Occured"+e);
257 selectedPolicies.add(selectedPolicy);
261 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
262 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
263 updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
264 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
265 updatedGroupObject.setStatus(pdpGroup.getStatus());
267 // replace the original set of Policies with the set from the
268 // container (possibly modified by the user)
269 // do not allow multiple copies of same policy
270 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
271 logger.debug("policyIterator....." + selectedPolicies);
272 while (policyIterator.hasNext()) {
273 PDPPolicy existingPolicy = policyIterator.next();
274 for (PDPPolicy selPolicy : selectedPolicies) {
275 if (selPolicy.getName().equals(existingPolicy.getName())) {
276 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
277 if (selPolicy.getId().equals(existingPolicy.getId())) {
278 policyIterator.remove();
279 logger.debug("Removing policy: " + selPolicy);
283 policyIterator.remove();
284 logger.debug("Removing Old Policy version: "+ selPolicy);
291 currentPoliciesInGroup.addAll(selectedPolicies);
292 updatedGroupObject.setPolicies(currentPoliciesInGroup);
293 this.container.updateGroup(updatedGroupObject);
295 response.setCharacterEncoding("UTF-8");
296 response.setContentType("application / json");
297 request.setCharacterEncoding("UTF-8");
299 PrintWriter out = response.getWriter();
301 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
302 JSONObject j = new JSONObject(msg);
303 out.write(j.toString());
308 response.setCharacterEncoding("UTF-8");
309 request.setCharacterEncoding("UTF-8");
310 PrintWriter out = response.getWriter();
311 out.write(e.getMessage());
316 @SuppressWarnings("unchecked")
317 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
318 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
320 this.container = new PDPGroupContainer(PolicyController.getPapEngine());
321 ObjectMapper mapper = new ObjectMapper();
322 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
323 JsonNode root = mapper.readTree(request.getReader());
324 StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
325 JsonNode removePolicyData = root.get("data");
326 policyContainer = new PDPPolicyContainer(group);
327 if(removePolicyData.size() > 0){
328 for(int i = 0 ; i < removePolicyData.size(); i++){
329 String data = removePolicyData.get(i).toString();
330 AutoPushController.policyContainer.removeItem(data);
332 Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
333 changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
334 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
335 updatedGroupObject.setPolicies(changedPolicies);
336 updatedGroupObject.setEcompPdps(group.getEcompPdps());
337 updatedGroupObject.setPipConfigs(group.getPipConfigs());
338 updatedGroupObject.setStatus(group.getStatus());
339 this.container.updateGroup(updatedGroupObject);
342 response.setCharacterEncoding("UTF-8");
343 response.setContentType("application / json");
344 request.setCharacterEncoding("UTF-8");
346 PrintWriter out = response.getWriter();
348 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
349 JSONObject j = new JSONObject(msg);
351 out.write(j.toString());
356 response.setCharacterEncoding("UTF-8");
357 request.setCharacterEncoding("UTF-8");
358 PrintWriter out = response.getWriter();
359 out.write(e.getMessage());