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=========================================================
20 package org.openecomp.policy.pap.xacml.rest.controller;
22 import java.io.BufferedWriter;
24 import java.io.FileWriter;
25 import java.io.IOException;
26 import java.io.ObjectOutputStream;
28 import java.util.List;
29 import java.util.UUID;
31 import javax.persistence.EntityManager;
32 import javax.persistence.Query;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
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;
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;
57 public class PushPolicyController {
58 private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyController.class);
60 private static CommonClassDao commonClassDao;
63 public PushPolicyController(CommonClassDao commonClassDao){
64 PushPolicyController.commonClassDao = commonClassDao;
67 public PushPolicyController(){}
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);
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");
81 requestID = UUID.randomUUID().toString();
82 LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString());
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);
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);
102 //safetyChecker(policyName);
103 } catch (NullPointerException | IOException e) {
105 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
106 response.addHeader("error", "unknown");
107 response.addHeader("operation", "push");
112 private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) {
113 StdPDPGroup selectedPDPGroup = null;
114 StdPDPPolicy selectedPolicy = null;
115 //Get the current policies from the Group and Add the new one
116 //Set<PDPPolicy> currentPoliciesInGroup = null;
118 selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup);
119 } catch (PAPException e1) {
120 PolicyLogger.error(e1);
122 if(selectedPDPGroup==null){
123 String message = "Unknown groupId '" + selectedPDPGroup + "'";
124 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
125 response.addHeader("error", "unknownGroupId");
126 response.addHeader("operation", "push");
127 response.addHeader("message", message);
128 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
131 //Get PolicyEntity from DB;
132 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
133 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
134 createPolicyQuery.setParameter("scope", policyScope);
135 createPolicyQuery.setParameter("policyName", policyName.substring(policyScope.length()+1));
136 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
137 PolicyEntity policyEntity = null;
138 if(createPolicyQueryList.size()>0){
139 policyEntity = (PolicyEntity)createPolicyQueryList.get(0);
141 PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
142 String message = "Unknown Policy '" + policyName + "'";
143 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
144 response.addHeader("error", "unknownPolicy");
145 response.addHeader("operation", "push");
146 response.addHeader("message", message);
147 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
150 File temp = new File(policyName);
152 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
153 bw.write(policyEntity.getPolicyData());
155 URI selectedURI = temp.toURI();
156 // Create the policy Object
157 selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI);
158 } catch (IOException e) {
159 LOGGER.error("Unable to create policy '" + policyName + "': "+ e.getMessage());
162 new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy);
163 } catch (IOException e) {
165 response.addHeader("error", "policyCopyError");
166 response.addHeader("message", e.getMessage());
167 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
170 response.addHeader("Content-Type","application/json");
171 response.setStatus(HttpServletResponse.SC_ACCEPTED);
172 response.addHeader("operation", "push");
173 response.addHeader("policyId", policyName);
175 // TODO : Check point to push policies within PAP.
176 /*PolicyDBDaoTransaction addPolicyToGroupTransaction = XACMLPapServlet.getDbDaoTransaction();
178 if (selectedPolicy != null) {
179 // Add Current policies from container
180 currentPoliciesInGroup = selectedPDPGroup.getPolicies();
181 // copy policy to PAP
182 addPolicyToGroupTransaction.addPolicyToGroup(selectedPDPGroup.getId(), policyName,"XACMLPapServlet.pushPolicyController");
183 ((StdPDPGroup) selectedPDPGroup).copyPolicyToFile(policyName, policyID, new FileInputStream(temp));
184 addPolicyToGroupTransaction.commitTransaction();
186 }catch (Exception e) {
187 addPolicyToGroupTransaction.rollbackTransaction();
188 String message = "Policy '" + policyName + "' not copied to group '" + pdpGroup +"': " + e;
189 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
190 PolicyLogger.audit("Transaction Failed - See Error.log");
191 response.addHeader("error", "policyCopyError");
192 response.addHeader("message", message);
193 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
196 //If the selected policy is in the group we must remove it because the name is default
197 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
198 if (existingPolicy.getId().equals(selectedPolicy.getId())) {
199 selectedPDPGroup.removePolicyFromGroup(existingPolicy);
200 LOGGER.debug("Removing existing policy: " + existingPolicy);
204 //Update the PDP Group after removing old version of policy
205 //Set<PDPPolicy> updatedPoliciesInGroup = selectedPDPGroup.getPolicies();
206 //need to remove the policy with default name from group
207 for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
208 if (updatedPolicy.getName().equalsIgnoreCase("default")) {
209 selectedPDPGroup.removePolicyFromGroup(updatedPolicy);
212 Set<PDPPolicy> policies = selectedPDPGroup.getPolicies();
213 policies.add(selectedPolicy);
214 selectedPDPGroup.setPolicies(policies);
217 XACMLPapServlet.getPAPEngine().updateGroup(selectedPDPGroup);
218 } catch (PAPException e) {
219 // TODO Auto-generated catch block
220 logger.error("Exception Occured"+e);
222 // policy file copied ok and the Group was updated on the PDP
223 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
224 response.addHeader("operation", "push");
225 response.addHeader("policyId", policyName);
226 response.addHeader("groupId", pdpGroup);