Sonar fixes for ONAP-PAP-REST
[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 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         @Autowired
66         public PushPolicyController(CommonClassDao commonClassDao){
67                 PushPolicyController.commonClassDao = commonClassDao;
68         }
69         /*
70          * This is an empty constructor
71          */
72         public PushPolicyController(){}
73         
74         @RequestMapping(value="/pushPolicy", method=RequestMethod.POST)
75         public void pushPolicy(HttpServletRequest request, HttpServletResponse response){
76                 ObjectMapper mapper = new ObjectMapper();
77                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
78                 try {
79                         JsonNode root = mapper.readTree(request.getInputStream());
80                         String policyScope = root.get("policyScope").asText();
81                         String filePrefix = root.get("filePrefix").asText();
82                         String policyName = root.get(policyNames).asText();
83                         String pdpGroup = root.get("pdpGroup").asText();
84                         String requestID = request.getHeader("X-ECOMP-RequestID");
85                         if(requestID==null){
86                                 requestID = UUID.randomUUID().toString();
87                 LOGGER.info("No request ID provided, sending generated ID: " + requestID);
88                         }
89                         LOGGER.info("Push policy Request : " + root.asText());
90                         String policyVersionName = policyScope.replace(".", File.separator) + File.separator
91                                         + filePrefix + policyName;
92                         List<?> policyVersionObject = commonClassDao.getDataById(PolicyVersion.class, policyNames, policyVersionName);
93                         if(policyVersionObject!=null){
94                                 PolicyVersion policyVersion = (PolicyVersion) policyVersionObject.get(0);
95                                 String policyID = policyVersionName.replace(File.separator, "."); // This is before adding version.
96                                 policyVersionName += "." + policyVersion.getActiveVersion() + ".xml";
97                                 addPolicyToGroup(policyScope, policyID, policyVersionName.replace(File.separator, "."), pdpGroup, response);
98                         }else{
99                                 String message = "Unknown Policy '" + policyName + "'";
100                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
101                                 response.addHeader(errorMsg, "unknownPolicy");
102                                 response.addHeader(operation, "push");
103                                 response.addHeader(messageContent, message);
104                                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
105                                 return;
106                         }
107                 } catch (NullPointerException | IOException e) {
108                         LOGGER.error(e);
109                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
110                         response.addHeader(errorMsg, "unknown");
111                         response.addHeader(operation, "push");
112                         return;
113                 }
114         }
115
116         private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) {
117                 StdPDPGroup selectedPDPGroup = null;
118                 StdPDPPolicy selectedPolicy = null;
119                 //Get the current policies from the Group and Add the new one
120                 try {
121                         selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup);
122                 } catch (PAPException e1) {
123                         PolicyLogger.error(e1);
124                 }
125                 if(selectedPDPGroup==null){
126                         String message = "Unknown groupId '" + selectedPDPGroup + "'";
127                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
128                         response.addHeader(errorMsg, "unknownGroupId");
129                         response.addHeader(operation, "push");
130                         response.addHeader(messageContent, message);
131                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
132                         return;
133                 }
134                 //Get PolicyEntity from DB;
135                 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
136                 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");                     
137                 createPolicyQuery.setParameter("scope", policyScope);
138                 createPolicyQuery.setParameter(policyNames, policyName.substring(policyScope.length()+1));
139                 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
140                 PolicyEntity policyEntity = null;
141                 if(!createPolicyQueryList.isEmpty()){
142                         policyEntity = (PolicyEntity)createPolicyQueryList.get(0);
143                 }else{
144                         PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
145                         String message = "Unknown Policy '" + policyName + "'";
146                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
147                         response.addHeader(errorMsg, "unknownPolicy");
148                         response.addHeader(operation, "push");
149                         response.addHeader(messageContent, message);
150                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
151                         return;
152                 }
153                 File temp = new File(policyName);
154                 try {
155                         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
156                         bw.write(policyEntity.getPolicyData());
157                         bw.close();
158                         URI selectedURI = temp.toURI();
159                         // Create the policy Object
160                         selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI);
161                 } catch (IOException e) {
162                         LOGGER.error("Unable to create policy '" + policyName + "': "+ e.getMessage(),e);
163                 } 
164                 try {
165                         new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy);
166                 } catch (IOException e) {
167                         LOGGER.error(e);
168                         response.addHeader(errorMsg, "policyCopyError");
169                         response.addHeader(messageContent, e.getMessage());
170                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
171                         return;
172                 }
173                 response.addHeader("Content-Type","application/json");
174                 response.setStatus(HttpServletResponse.SC_ACCEPTED);
175                 response.addHeader(operation, "push");
176                 response.addHeader("policyId", policyName);
177                 return;
178                 // TODO : Check point to push policies within PAP. 
179         }
180 }