Policy TestSuite Enabled
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / controller / PushPolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20 package org.openecomp.policy.pap.xacml.rest.controller;
21
22 import java.io.BufferedWriter;
23 import java.io.File;
24 import java.io.FileWriter;
25 import java.io.IOException;
26 import java.io.ObjectOutputStream;
27 import java.net.URI;
28 import java.util.List;
29 import java.util.UUID;
30
31 import javax.persistence.EntityManager;
32 import javax.persistence.Query;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.openecomp.policy.common.logging.eelf.MessageCodes;
37 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
38 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
39 import org.openecomp.policy.common.logging.flexlogger.Logger;
40 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
41 import org.openecomp.policy.rest.dao.CommonClassDao;
42 import org.openecomp.policy.rest.jpa.PolicyEntity;
43 import org.openecomp.policy.rest.jpa.PolicyVersion;
44 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
45 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.stereotype.Controller;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.bind.annotation.RequestMethod;
50
51 import com.att.research.xacml.api.pap.PAPException;
52 import com.fasterxml.jackson.databind.DeserializationFeature;
53 import com.fasterxml.jackson.databind.JsonNode;
54 import com.fasterxml.jackson.databind.ObjectMapper;
55
56 @Controller
57 public class PushPolicyController {
58         private static final Logger LOGGER  = FlexLogger.getLogger(PushPolicyController.class);
59         
60         private static CommonClassDao commonClassDao;
61         
62         @Autowired
63         public PushPolicyController(CommonClassDao commonClassDao){
64                 PushPolicyController.commonClassDao = commonClassDao;
65         }
66         
67         public PushPolicyController(){}
68         
69         @RequestMapping(value="/pushPolicy", method=RequestMethod.POST)
70         public void pushPolicy(HttpServletRequest request, HttpServletResponse response){
71                 ObjectMapper mapper = new ObjectMapper();
72                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
73                 try {
74                         JsonNode root = mapper.readTree(request.getInputStream());
75                         String policyScope = root.get("policyScope").asText();
76                         String filePrefix = root.get("filePrefix").asText();
77                         String policyName = root.get("policyName").asText();
78                         String pdpGroup = root.get("pdpGroup").asText();
79                         String requestID = request.getHeader("X-ECOMP-RequestID");
80                         if(requestID==null){
81                                 requestID = UUID.randomUUID().toString();
82                 LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString());
83                         }
84                         LOGGER.info("Push policy Request : " + root.asText());
85                         String policyVersionName = policyScope.replace(".", File.separator) + File.separator
86                                         + filePrefix + policyName;
87                         List<?> policyVersionObject = commonClassDao.getDataById(PolicyVersion.class, "policyName", policyVersionName);
88                         if(policyVersionObject!=null){
89                                 PolicyVersion policyVersion = (PolicyVersion) policyVersionObject.get(0);
90                                 String policyID = policyVersionName.replace(File.separator, "."); // This is before adding version.
91                                 policyVersionName += "." + policyVersion.getActiveVersion() + ".xml";
92                                 addPolicyToGroup(policyScope, policyID, policyVersionName.replace(File.separator, "."), pdpGroup, response);
93                         }else{
94                                 String message = "Unknown Policy '" + policyName + "'";
95                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
96                                 response.addHeader("error", "unknownPolicy");
97                                 response.addHeader("operation", "push");
98                                 response.addHeader("message", message);
99                                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
100                                 return;
101                         }
102                         //safetyChecker(policyName);
103                 } catch (NullPointerException | IOException e) {
104                         LOGGER.error(e);
105                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
106                         response.addHeader("error", "unknown");
107                         response.addHeader("operation", "push");
108                         return;
109                 }
110         }
111
112         /*private void safetyChecker(String policyName) {
113                 if (XACMLProperties.getProperty("xacml.rest.pap.safetychecker").equals("on")) {
114                         if (policyName.contains("Config_MS_") || policyName.contains("BRMS_Param")) {
115                                 SafetyCheckerService service = new SafetyCheckerService();
116                                 PolicySafetyChecker safetyChecker = new PolicySafetyChecker();
117                                 boolean isEntered = false;
118                                 try {
119                                         JSONObject policyDataObj = service.getConfigByPolicyName(policyName, XACMLPapServlet.getConfigHome());
120                                         isEntered = safetyChecker.addItem(policyDataObj);
121                                 } catch (Exception e) {
122                                         PolicyLogger.warn(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", e, "Error while adding ClosedLoop in the database: "
123                                                         + "This is a PolicySafetyChecker warning, the push execution may proceed normally.");
124                                 }
125                                 if (isEntered) {
126                                         LOGGER.info("SafetyChecker successfully added the closedLoop to the DB table.");
127                                 } else {
128                                         LOGGER.info("SafetyChecker failed to add the closedLoop to the DB table.");
129                                 }
130                         }
131                 } else {
132                         LOGGER.info("PolicySafetyChecker is turned off.");
133                 }
134         }*/
135
136         private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) {
137                 StdPDPGroup selectedPDPGroup = null;
138                 StdPDPPolicy selectedPolicy = null;
139                 //Get the current policies from the Group and Add the new one
140                 //Set<PDPPolicy> currentPoliciesInGroup = null;
141                 try {
142                         selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup);
143                 } catch (PAPException e1) {
144                         PolicyLogger.error(e1);
145                 }
146                 if(selectedPDPGroup==null){
147                         String message = "Unknown groupId '" + selectedPDPGroup + "'";
148                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
149                         response.addHeader("error", "unknownGroupId");
150                         response.addHeader("operation", "push");
151                         response.addHeader("message", message);
152                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
153                         return;
154                 }
155                 //Get PolicyEntity from DB;
156                 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
157                 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");                     
158                 createPolicyQuery.setParameter("scope", policyScope);
159                 createPolicyQuery.setParameter("policyName", policyName.substring(policyScope.length()+1));
160                 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
161                 PolicyEntity policyEntity = null;
162                 if(createPolicyQueryList.size()>0){
163                         policyEntity = (PolicyEntity)createPolicyQueryList.get(0);
164                 }else{
165                         PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
166                         String message = "Unknown Policy '" + policyName + "'";
167                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
168                         response.addHeader("error", "unknownPolicy");
169                         response.addHeader("operation", "push");
170                         response.addHeader("message", message);
171                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
172                         return;
173                 }
174                 File temp = new File(policyName);
175                 try {
176                         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
177                         bw.write(policyEntity.getPolicyData());
178                         bw.close();
179                         URI selectedURI = temp.toURI();
180                         // Create the policy Object
181                         selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI);
182                 } catch (IOException e) {
183                         LOGGER.error("Unable to create policy '" + policyName + "': "+ e.getMessage());
184                 } 
185                 try {
186                         new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy);
187                 } catch (IOException e) {
188                         LOGGER.error(e);
189                         response.addHeader("error", "policyCopyError");
190                         response.addHeader("message", e.getMessage());
191                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
192                         return;
193                 }
194                 response.addHeader("Content-Type","application/json");
195                 response.setStatus(HttpServletResponse.SC_ACCEPTED);
196                 response.addHeader("operation", "push");
197                 response.addHeader("policyId", policyName);
198                 return;
199                 // TODO : Check point to push policies within PAP. 
200                 /*PolicyDBDaoTransaction addPolicyToGroupTransaction = XACMLPapServlet.getDbDaoTransaction();
201                 try{
202                         if (selectedPolicy != null) {
203                                 // Add Current policies from container
204                                 currentPoliciesInGroup = selectedPDPGroup.getPolicies();
205                                 // copy policy to PAP
206                                 addPolicyToGroupTransaction.addPolicyToGroup(selectedPDPGroup.getId(), policyName,"XACMLPapServlet.pushPolicyController");
207                                 ((StdPDPGroup) selectedPDPGroup).copyPolicyToFile(policyName, policyID, new FileInputStream(temp));
208                                 addPolicyToGroupTransaction.commitTransaction();
209                         }
210                 }catch (Exception e) {
211                         addPolicyToGroupTransaction.rollbackTransaction();
212                         String message = "Policy '" + policyName + "' not copied to group '" + pdpGroup +"': " + e;
213                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
214                         PolicyLogger.audit("Transaction Failed - See Error.log");
215                         response.addHeader("error", "policyCopyError");
216                         response.addHeader("message", message);
217                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
218                         return;
219                 }
220                 //If the selected policy is in the group we must remove it because the name is default
221                 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
222                         if (existingPolicy.getId().equals(selectedPolicy.getId())) {
223                                 selectedPDPGroup.removePolicyFromGroup(existingPolicy);
224                                 LOGGER.debug("Removing existing policy: " + existingPolicy);
225                                 break;
226                         }
227                 }
228                 //Update the PDP Group after removing old version of policy
229                 //Set<PDPPolicy> updatedPoliciesInGroup = selectedPDPGroup.getPolicies();
230                 //need to remove the policy with default name from group
231                 for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
232                         if (updatedPolicy.getName().equalsIgnoreCase("default")) {
233                                 selectedPDPGroup.removePolicyFromGroup(updatedPolicy);
234                         }
235                 }
236                 Set<PDPPolicy> policies = selectedPDPGroup.getPolicies();
237                 policies.add(selectedPolicy);
238                 selectedPDPGroup.setPolicies(policies);
239                 // Update now. 
240                 try {
241                         XACMLPapServlet.getPAPEngine().updateGroup(selectedPDPGroup);
242                 } catch (PAPException e) {
243                         // TODO Auto-generated catch block
244                         logger.error("Exception Occured"+e);
245                 }
246                 // policy file copied ok and the Group was updated on the PDP
247                 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
248                 response.addHeader("operation", "push");
249                 response.addHeader("policyId", policyName);
250                 response.addHeader("groupId", pdpGroup);
251                 return;*/
252         }
253 }