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