Convert tabs to space in ONAP PAP REST1
[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-2018 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.onap.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.onap.policy.common.logging.eelf.MessageCodes;
37 import org.onap.policy.common.logging.eelf.PolicyLogger;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
41 import org.onap.policy.rest.dao.CommonClassDao;
42 import org.onap.policy.rest.jpa.PolicyEntity;
43 import org.onap.policy.rest.jpa.PolicyVersion;
44 import org.onap.policy.xacml.std.pap.StdPDPGroup;
45 import org.onap.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     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      * This is an empty constructor
78      */
79     public PushPolicyController(){}
80
81     @RequestMapping(value="/pushPolicy", method=RequestMethod.POST)
82     public void pushPolicy(HttpServletRequest request, HttpServletResponse response){
83         ObjectMapper mapper = new ObjectMapper();
84         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
85         try {
86             JsonNode root = mapper.readTree(request.getInputStream());
87             String policyScope = root.get("policyScope").asText();
88             String filePrefix = root.get("filePrefix").asText();
89             String policyName = root.get(policyNames).asText();
90             String pdpGroup = root.get("pdpGroup").asText();
91             String requestID = request.getHeader("X-ECOMP-RequestID");
92             if(requestID==null){
93                 requestID = UUID.randomUUID().toString();
94                 LOGGER.info("No request ID provided, sending generated ID: " + requestID);
95             }
96             LOGGER.info("Push policy Request to get the selectedPolicy : " + root.asText());
97             String policyVersionName = policyScope.replace(".", File.separator) + File.separator
98                     + filePrefix + policyName;
99             List<?> policyVersionObject = 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, response);
105             }else{
106                 String message = "Unknown Policy '" + policyName + "'";
107                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
108                 response.addHeader(errorMsg, "unknownPolicy");
109                 response.addHeader(operation, "push");
110                 response.addHeader(messageContent, message);
111                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
112                 return;
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             return;
120         }
121     }
122
123     private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, 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         EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
146         Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
147         createPolicyQuery.setParameter("scope", policyScope);
148         createPolicyQuery.setParameter(policyNames, policyName.substring(policyScope.length()+1));
149         List<?> createPolicyQueryList = createPolicyQuery.getResultList();
150         PolicyEntity policyEntity = null;
151         if(!createPolicyQueryList.isEmpty()){
152             policyEntity = (PolicyEntity)createPolicyQueryList.get(0);
153         }else{
154             PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
155             String message = "Unknown Policy '" + policyName + "'";
156             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
157             response.addHeader(errorMsg, "unknownPolicy");
158             response.addHeader(operation, "push");
159             response.addHeader(messageContent, message);
160             response.setStatus(HttpServletResponse.SC_NOT_FOUND);
161             return;
162         }
163         File temp = new File(policyName);
164         try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))){
165             bw.write(policyEntity.getPolicyData());
166             URI selectedURI = temp.toURI();
167             // Create the policy Object
168             selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI);
169         } catch (IOException e) {
170             LOGGER.error("Unable to get policy '" + policyName + "': "+ e.getMessage(),e);
171         }
172         try {
173             new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy);
174         } catch (IOException e) {
175             LOGGER.error(e);
176             response.addHeader(errorMsg, "policyCopyError");
177             response.addHeader(messageContent, e.getMessage());
178             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
179             return;
180         }
181         response.addHeader("Content-Type","application/json");
182         response.setStatus(HttpServletResponse.SC_ACCEPTED);
183         response.addHeader(operation, "push");
184         response.addHeader("policyId", policyName);
185         return;
186         // TODO : Check point to push policies within PAP.
187     }
188 }