17fce7142bab6ceea0647babcc21d12761e7e7b1
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / PushPolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 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
21 package org.onap.policy.pap.xacml.rest.controller;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.fasterxml.jackson.databind.DeserializationFeature;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import java.io.BufferedWriter;
28 import java.io.File;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.io.ObjectOutputStream;
32 import java.net.URI;
33 import java.util.List;
34 import java.util.UUID;
35 import javax.script.SimpleBindings;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38 import org.onap.policy.common.logging.eelf.MessageCodes;
39 import org.onap.policy.common.logging.eelf.PolicyLogger;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
43 import org.onap.policy.rest.dao.CommonClassDao;
44 import org.onap.policy.rest.jpa.PolicyEntity;
45 import org.onap.policy.rest.jpa.PolicyVersion;
46 import org.onap.policy.xacml.std.pap.StdPDPGroup;
47 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.stereotype.Controller;
50 import org.springframework.web.bind.annotation.RequestMapping;
51 import org.springframework.web.bind.annotation.RequestMethod;
52
53 @Controller
54 public class PushPolicyController {
55     private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyController.class);
56
57     private static CommonClassDao commonClassDao;
58     private static String policyNames = "policyName";
59     private static String errorMsg = "error";
60     private static String operation = "operation";
61     private static String messageContent = "message";
62
63     private static final String REGEX = "[0-9a-zA-Z._ ]*";
64
65     @Autowired
66     public PushPolicyController(CommonClassDao commonClassDao) {
67         PushPolicyController.commonClassDao = commonClassDao;
68     }
69
70     public void setCommonClassDao(CommonClassDao commonClassDao) {
71         PushPolicyController.commonClassDao = commonClassDao;
72     }
73
74     /*
75      * This is an empty constructor
76      */
77     public PushPolicyController() {
78     }
79
80     @RequestMapping(value = "/pushPolicy", method = RequestMethod.POST)
81     public void pushPolicy(HttpServletRequest request, HttpServletResponse response) {
82         ObjectMapper mapper = new ObjectMapper();
83         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
84         try {
85             JsonNode root = mapper.readTree(request.getInputStream());
86             String policyScope = root.get("policyScope").asText();
87             String filePrefix = root.get("filePrefix").asText();
88             String policyName = root.get(policyNames).asText();
89             String pdpGroup = root.get("pdpGroup").asText();
90             String requestID = request.getHeader("X-ECOMP-RequestID");
91             if (requestID == null) {
92                 requestID = UUID.randomUUID().toString();
93                 LOGGER.info("No request ID provided, sending generated ID: " + requestID);
94             }
95             LOGGER.info("Push policy Request to get the selectedPolicy : " + root.asText());
96             String policyVersionName = policyScope.replace(".", File.separator) + File.separator
97                     + filePrefix + policyName;
98             List<?> policyVersionObject =
99                     commonClassDao.getDataById(PolicyVersion.class, policyNames, policyVersionName);
100             if (policyVersionObject != null) {
101                 PolicyVersion policyVersion = (PolicyVersion) policyVersionObject.get(0);
102                 String policyID = policyVersionName.replace(File.separator, "."); // This is before adding version.
103                 policyVersionName += "." + policyVersion.getActiveVersion() + ".xml";
104                 addPolicyToGroup(policyScope, policyID, policyVersionName.replace(File.separator, "."), pdpGroup,
105                         response);
106             } else {
107                 String message = "Unknown Policy '" + policyName + "'";
108                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
109                 response.addHeader(errorMsg, "unknownPolicy");
110                 response.addHeader(operation, "push");
111                 response.addHeader(messageContent, message);
112                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
113             }
114         } catch (NullPointerException | IOException e) {
115             LOGGER.error(e);
116             response.setStatus(HttpServletResponse.SC_NOT_FOUND);
117             response.addHeader(errorMsg, "unknown");
118             response.addHeader(operation, "push");
119         }
120     }
121
122     private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup,
123                                   HttpServletResponse response) {
124         StdPDPGroup selectedPDPGroup = null;
125         StdPDPPolicy selectedPolicy = null;
126         //Get the selected PDP Group to push the policy
127         try {
128             selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup);
129         } catch (PAPException e1) {
130             PolicyLogger.error(e1);
131         }
132         if (selectedPDPGroup == null) {
133             String message = "Unknown groupId '" + selectedPDPGroup + "'";
134             if (!message.matches(REGEX)) {
135                 message = "Unknown groupId";
136             }
137             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
138             response.addHeader(errorMsg, "unknownGroupId");
139             response.addHeader(operation, "push");
140             response.addHeader(messageContent, message);
141             response.setStatus(HttpServletResponse.SC_NOT_FOUND);
142             return;
143         }
144         // Get PolicyEntity from DB;
145         String createPolicyQuery = "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName";
146         SimpleBindings params = new SimpleBindings();
147         params.put("scope", policyScope);
148         params.put(policyNames, policyName.substring(policyScope.length() + 1));
149         List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params);
150         LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames
151                 + " from PolicyEntity");
152
153         PolicyEntity policyEntity = null;
154         if (!createPolicyQueryList.isEmpty()) {
155             policyEntity = (PolicyEntity) createPolicyQueryList.get(0);
156         } else {
157             PolicyLogger
158                     .error("Somehow, more than one policy with the same scope, name, and deleted status were found in" +
159                             " the database");
160             String message = "Unknown Policy '" + policyName + "'";
161             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
162             response.addHeader(errorMsg, "unknownPolicy");
163             response.addHeader(operation, "push");
164             response.addHeader(messageContent, message);
165             response.setStatus(HttpServletResponse.SC_NOT_FOUND);
166             return;
167         }
168         File temp = new File(policyName);
169         try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
170             bw.write(policyEntity.getPolicyData());
171             URI selectedURI = temp.toURI();
172             // Create the policy Object
173             selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI);
174         } catch (IOException e) {
175             LOGGER.error("Unable to get policy '" + policyName + "': " + e.getMessage(), e);
176         }
177         try {
178             new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy);
179         } catch (IOException e) {
180             LOGGER.error(e);
181             response.addHeader(errorMsg, "policyCopyError");
182             response.addHeader(messageContent, e.getMessage());
183             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
184             return;
185         }
186         response.addHeader("Content-Type", "application/json");
187         response.setStatus(HttpServletResponse.SC_ACCEPTED);
188         response.addHeader(operation, "push");
189         response.addHeader("policyId", policyName);
190         // TODO : Check point to push policies within PAP.
191     }
192 }