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;
25 import java.io.IOException;
26 import java.io.PrintWriter;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Date;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
43 import org.apache.commons.io.FilenameUtils;
44 import org.json.JSONArray;
45 import org.json.JSONObject;
46 import org.openecomp.policy.adapter.AutoPushTabAdapter;
47 import org.openecomp.policy.dao.PolicyVersionDao;
48 import org.openecomp.policy.model.PDPGroupContainer;
49 import org.openecomp.policy.model.PDPPolicyContainer;
50 import org.openecomp.policy.model.Roles;
51 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
52 import org.openecomp.portalsdk.core.web.support.JsonMessage;
53 import org.openecomp.portalsdk.core.web.support.UserUtils;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.http.MediaType;
56 import org.springframework.stereotype.Controller;
57 import org.springframework.web.bind.annotation.RequestMapping;
58 import org.springframework.web.servlet.ModelAndView;
60 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
61 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
63 import com.att.research.xacml.api.pap.PAPException;
64 //import com.att.research.xacml.api.pap.PDPGroup;
65 import com.att.research.xacml.api.pap.PDPPolicy;
66 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
67 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
68 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
74 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
75 import org.openecomp.policy.common.logging.flexlogger.Logger;
79 @RequestMapping({"/"})
80 public class AutoPushController extends RestrictedBaseController{
82 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
84 private PDPGroupContainer container;
85 protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
87 private static PDPPolicyContainer policyContainer;
88 Set<PDPPolicy> selectedPolicies;
91 PolicyVersionDao policyVersionDao;
93 public synchronized void refreshGroups() {
94 synchronized(this.groups) {
97 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
98 } catch (PAPException e) {
99 String message = "Unable to retrieve Groups from server: " + e;
100 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
106 @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
107 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
109 Path gitPath = PolicyController.getGitPath().toAbsolutePath();
110 PrintWriter out = response.getWriter();
111 JSONObject j = new JSONObject("{data: " + readFileRepository(gitPath,0,0,request).toString() + "}");
112 out.write(j.toString());
119 @SuppressWarnings("rawtypes")
120 public JSONArray readFileRepository(Path path, int id, int parentid, HttpServletRequest request){
121 Set<String> scopes = null;
122 List<String> roles = null;
123 String userId = null;
125 userId = UserUtils.getUserIdFromCookie(request);
126 } catch (Exception e) {
127 logger.error("Exception Occured while reading userid from cookie" +e);
129 JSONArray fileJSONArray = new JSONArray();
130 File root = new File(path.toString());
134 List<Roles> userRoles = PolicyController.getRoles(userId);
135 roles = new ArrayList<String>();
136 scopes = new HashSet<String>();
137 for(Roles userRole: userRoles){
138 roles.add(userRole.getRole());
139 scopes.add(userRole.getScope());
142 for ( File file : root.listFiles()){
143 if (!(file.toString().contains(".git") || file.equals(".DS_Store"))) {
144 if(file.isDirectory()){
145 JSONObject el = new JSONObject();
146 String fileName = file.getName().toString();
147 el.put("categoryId", id+1);
148 el.put("name", fileName);
149 el.put("dateModified", lastModified(file));
150 el.put("filePath", file.getPath());
151 el.put("parentCategoryId", parentid);
152 el.put("files",readFileRepository(file.toPath(),id+1, id+1, request));
153 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) {
154 fileJSONArray.put(el);
156 String filePath = file.getPath().toString();
157 int startIndex = filePath.indexOf("repository") + 11;
158 filePath = filePath.substring(startIndex, filePath.length());
159 if (scopes.contains(filePath)) {
160 fileJSONArray.put(el);
164 JSONObject el = new JSONObject();
165 String policyName = "";
167 String fileName = file.getName().toString();
168 if(fileName.endsWith(".xml")){
169 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
170 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
172 String parent = file.toString().substring(file.toString().indexOf("repository")+ 11);
173 parent = FilenameUtils.removeExtension(parent);
174 version = parent.substring(parent.indexOf(".")+1);
175 policyName = parent.substring(0, parent.lastIndexOf("."));
176 if(policyName.contains("\\")){
177 String scope = policyName.substring(0, policyName.lastIndexOf("\\"));
178 policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\"));
181 el.put("categoryId", id+1);
182 el.put("name", fileName);
183 el.put("parentCategoryId", parentid);
184 el.put("dateModified", lastModified(file));
185 el.put("version", version);
186 el.put("filePath", file.getPath());
187 el.put("files",new ArrayList());
188 String query = "from PolicyVersion where POLICY_NAME ='" +policyName+"' and ACTIVE_VERSION ='"+version+"'";
189 Boolean active = PolicyController.getActivePolicy(query);
191 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) {
192 fileJSONArray.put(el);
194 String filePath = file.getPath().toString();
195 int startIndex = filePath.indexOf("repository") + 11;
196 filePath = filePath.substring(startIndex, filePath.length());
197 filePath = filePath.substring(0, filePath.lastIndexOf(File.separator));
198 if (scopes.contains(filePath)) {
199 fileJSONArray.put(el);
206 return fileJSONArray;
209 public Date lastModified(File file) {
210 return new Date(file.lastModified());
213 public String getVersion(File file) {
215 return XACMLPolicyScanner.getVersion(Paths.get(file.getAbsolutePath()));
216 } catch (IOException e) {
221 public String getDomain(File file) {
222 String filePath = file.getAbsolutePath();
223 int startIndex = filePath.indexOf("repository") + 11;
224 return filePath.substring(startIndex, filePath.length());
228 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
229 public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
231 ArrayList<Object> selectedPDPS = new ArrayList<Object>();
232 ArrayList<File> selectedPoliciesInUI = new ArrayList<File>();
233 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
234 ObjectMapper mapper = new ObjectMapper();
235 this.container = new PDPGroupContainer(PolicyController.getPapEngine());
236 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
237 JsonNode root = mapper.readTree(request.getReader());
238 AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
239 for (Object pdpGroupId : adapter.getPdpDatas()) {
240 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
241 for(EcompPDPGroup pdpGroup : this.groups){
242 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
243 selectedPDPS.add(pdpGroup);
248 for (Object policyId : adapter.getPolicyDatas()) {
249 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
250 Path file = Paths.get(selected.get("filePath").toString());
251 selectedPoliciesInUI.add(file.toFile());
254 for (Object pdpDestinationGroupId : selectedPDPS) {
255 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
256 Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
257 for (File policyId : selectedPoliciesInUI) {
258 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
260 // Get the current selection
261 File selectedItem = policyId;
263 assert (selectedItem != null);
264 if (selectedItem.isDirectory()) {
265 //AdminNotification.warn("Select only the Policy");
268 // create the id of the target file
269 // Our standard for file naming is:
270 // <domain>.<filename>.<version>.xml
271 // since the file name usually has a ".xml", we need to strip
273 // before adding the other parts
274 String name = selectedItem.getName();
275 if(name.endsWith(".xml")){
276 name = name.substring(0, name.length() - 4);
277 name = name.substring(0, name.lastIndexOf("."));
280 if (id.endsWith(".xml")) {
281 id = id.substring(0, id.length() - 4);
282 id = id.substring(0, id.lastIndexOf("."));
284 // add on the version string
285 String version = getVersion(selectedItem);
287 // put the .xml on the end
289 // track on the domain in front. Do this one level at a time
291 // reach one of the roots
292 String domain = getDomain(selectedItem);
293 String mainDomain = domain.substring(0, domain.lastIndexOf(File.separator) );
294 logger.info("print the main domain value"+mainDomain);
295 String path = mainDomain.replace('\\', '.');
296 if(path.contains("/")){
297 path = mainDomain.replace('/', '.');
298 logger.info("print the path:" +path);
300 id = path + "." + id;
301 // Default policy to be Root policy; user can change to deferred
303 URI selectedURI = selectedItem.toURI();
304 StdPDPPolicy selectedPolicy = null;
308 selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI);
309 } catch (IOException e) {
310 logger.error("Unable to create policy '" + id + "': "+ e.getMessage());
311 //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
313 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
314 if (selectedPolicy != null) {
315 // Add Current policies from container
316 for (EcompPDPGroup group : container.getGroups()) {
317 if (group.getId().equals(selectedGroup.getId())) {
318 currentPoliciesInGroup.addAll(group.getPolicies());
321 // copy policy to PAP
323 PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
324 } catch (PAPException e) {
328 selectedPolicies.add(selectedPolicy);
331 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
332 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
333 updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
334 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
335 updatedGroupObject.setStatus(pdpGroup.getStatus());
337 // replace the original set of Policies with the set from the
338 // container (possibly modified by the user)
339 // do not allow multiple copies of same policy
340 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
341 logger.debug("policyIterator....." + selectedPolicies);
342 while (policyIterator.hasNext()) {
343 PDPPolicy existingPolicy = policyIterator.next();
344 for (PDPPolicy selPolicy : selectedPolicies) {
345 if (selPolicy.getName().equals(existingPolicy.getName())) {
346 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
347 if (selPolicy.getId().equals(existingPolicy.getId())) {
348 policyIterator.remove();
349 logger.debug("Removing policy: " + selPolicy);
353 policyIterator.remove();
354 logger.debug("Removing Old Policy version: "+ selPolicy);
361 currentPoliciesInGroup.addAll(selectedPolicies);
362 updatedGroupObject.setPolicies(currentPoliciesInGroup);
363 this.container.updateGroup(updatedGroupObject);
365 response.setCharacterEncoding("UTF-8");
366 response.setContentType("application / json");
367 request.setCharacterEncoding("UTF-8");
369 PrintWriter out = response.getWriter();
371 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
372 JSONObject j = new JSONObject(msg);
373 out.write(j.toString());
378 response.setCharacterEncoding("UTF-8");
379 request.setCharacterEncoding("UTF-8");
380 PrintWriter out = response.getWriter();
381 out.write(e.getMessage());
386 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
387 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
389 this.container = new PDPGroupContainer(PolicyController.getPapEngine());
390 ObjectMapper mapper = new ObjectMapper();
391 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
392 JsonNode root = mapper.readTree(request.getReader());
393 StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
394 JsonNode removePolicyData = root.get("data");
395 policyContainer = new PDPPolicyContainer(group);
396 if(removePolicyData.size() > 0){
397 for(int i = 0 ; i < removePolicyData.size(); i++){
398 String data = removePolicyData.get(i).toString();
399 AutoPushController.policyContainer.removeItem(data);
401 Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
402 changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
403 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
404 updatedGroupObject.setPolicies(changedPolicies);
405 updatedGroupObject.setEcompPdps(group.getEcompPdps());
406 updatedGroupObject.setPipConfigs(group.getPipConfigs());
407 updatedGroupObject.setStatus(group.getStatus());
408 this.container.updateGroup(updatedGroupObject);
411 response.setCharacterEncoding("UTF-8");
412 response.setContentType("application / json");
413 request.setCharacterEncoding("UTF-8");
415 PrintWriter out = response.getWriter();
417 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
418 JSONObject j = new JSONObject(msg);
420 out.write(j.toString());
425 response.setCharacterEncoding("UTF-8");
426 request.setCharacterEncoding("UTF-8");
427 PrintWriter out = response.getWriter();
428 out.write(e.getMessage());