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.onap.policy.admin;
22 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.io.PrintWriter;
28 import java.net.HttpURLConnection;
30 import java.nio.charset.StandardCharsets;
31 import java.util.ArrayList;
32 import java.util.Base64;
33 import java.util.List;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
38 import org.apache.commons.fileupload.FileItem;
39 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
40 import org.apache.commons.fileupload.servlet.ServletFileUpload;
41 import org.apache.commons.io.IOUtils;
42 import org.json.JSONObject;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.controller.CreateClosedLoopFaultController;
46 import org.onap.policy.controller.CreateDcaeMicroServiceController;
47 import org.onap.policy.controller.CreateFirewallController;
48 import org.onap.policy.controller.PolicyController;
49 import org.onap.policy.rest.XACMLRestProperties;
50 import org.onap.policy.rest.adapter.PolicyRestAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.PolicyVersion;
53 import org.onap.policy.utils.PolicyUtils;
54 import org.onap.policy.xacml.api.XACMLErrorConstants;
55 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
56 import org.openecomp.portalsdk.core.web.support.UserUtils;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.http.HttpEntity;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.HttpMethod;
61 import org.springframework.http.HttpStatus;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.web.bind.annotation.RequestMapping;
64 import org.springframework.web.bind.annotation.RequestMethod;
65 import org.springframework.web.bind.annotation.RestController;
66 import org.springframework.web.client.HttpClientErrorException;
67 import org.springframework.web.client.RestTemplate;
68 import org.springframework.web.servlet.ModelAndView;
70 import com.att.research.xacml.util.XACMLProperties;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74 import com.fasterxml.jackson.databind.SerializationFeature;
78 public class PolicyRestController extends RestrictedBaseController{
80 private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
82 private static final String modal = "model";
83 private static final String importDictionary = "import_dictionary";
86 CommonClassDao commonClassDao;
88 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
89 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
90 String userId = UserUtils.getUserSession(request).getOrgUserId();
91 ObjectMapper mapper = new ObjectMapper();
92 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
94 JsonNode root = mapper.readTree(request.getReader());
96 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
98 if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){
99 policyData.setEditPolicy(true);
101 if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){
103 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){
104 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator;
106 if(policyData.isEditPolicy()){
107 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
109 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", ""));
112 String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString();
113 if(domain.contains("/")){
114 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
116 domain = domain.replace("\"", "");
117 policyData.setDomainDir(domain);
120 if(policyData.getConfigPolicyType() != null){
121 if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
122 CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
123 policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
124 }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
125 CreateFirewallController fwController = new CreateFirewallController();
126 policyData = fwController.setDataToPolicyRestAdapter(policyData);
127 }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
128 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
129 policyData = msController.setDataToPolicyRestAdapter(policyData, root);
133 policyData.setUserId(userId);
136 String body = PolicyUtils.objectToJsonString(policyData);
137 String uri = request.getRequestURI();
138 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
139 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
140 result = "PolicyExists";
141 }else if(responseEntity != null){
142 result = responseEntity.getBody().toString();
143 String policyName = responseEntity.getHeaders().get("policyName").get(0);
144 if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){
145 PolicyNotificationMail email = new PolicyNotificationMail();
146 String mode = "EditPolicy";
147 String watchPolicyName = policyName.replace(".xml", "");
148 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
149 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
150 String policyVersionName = watchPolicyName.replace(".", File.separator);
151 watchPolicyName = watchPolicyName + "." + version + ".xml";
152 PolicyVersion entityItem = new PolicyVersion();
153 entityItem.setPolicyName(policyVersionName);
154 entityItem.setActiveVersion(Integer.parseInt(version));
155 entityItem.setModifiedBy(userId);
156 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
159 result = "Response is null from PAP";
162 response.setCharacterEncoding(PolicyController.getCharacterencoding());
163 response.setContentType(PolicyController.getContenttype());
164 request.setCharacterEncoding(PolicyController.getCharacterencoding());
166 PrintWriter out = response.getWriter();
167 String responseString = mapper.writeValueAsString(result);
168 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
169 out.write(j.toString());
171 policyLogger.error("Exception Occured while saving policy" , e);
176 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
177 String papUrl = PolicyController.getPapUrl();
178 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
179 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
181 Base64.Encoder encoder = Base64.getEncoder();
182 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
183 HttpHeaders headers = new HttpHeaders();
184 headers.set("Authorization", "Basic " + encoding);
185 headers.set("Content-Type", PolicyController.getContenttype());
187 RestTemplate restTemplate = new RestTemplate();
188 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
189 ResponseEntity<?> result = null;
190 HttpClientErrorException exception = null;
193 result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class);
195 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
196 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
197 if("409 Conflict".equals(e.getMessage())){
198 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
201 if(exception != null && exception.getStatusCode()!=null){
202 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
203 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
204 policyLogger.error(message);
206 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
207 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
208 policyLogger.error(message);
210 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
211 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
212 policyLogger.error(message);
214 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
215 policyLogger.error(message);
220 private String callPAP(HttpServletRequest request , String method, String uriValue){
221 String uri = uriValue;
222 String boundary = null;
223 String papUrl = PolicyController.getPapUrl();
224 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
225 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
227 Base64.Encoder encoder = Base64.getEncoder();
228 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
229 HttpHeaders headers = new HttpHeaders();
230 headers.set("Authorization", "Basic " + encoding);
231 headers.set("Content-Type", PolicyController.getContenttype());
234 HttpURLConnection connection = null;
235 List<FileItem> items;
236 FileItem item = null;
238 if(uri.contains(importDictionary)){
240 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
242 file = new File(item.getName());
243 String newFile = file.toString();
244 uri = uri +"&dictionaryName="+newFile;
245 } catch (Exception e2) {
246 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
251 URL url = new URL(papUrl + uri);
252 connection = (HttpURLConnection)url.openConnection();
253 connection.setRequestMethod(method);
254 connection.setUseCaches(false);
255 connection.setInstanceFollowRedirects(false);
256 connection.setRequestProperty("Authorization", "Basic " + encoding);
257 connection.setDoOutput(true);
258 connection.setDoInput(true);
260 if(!uri.contains("searchPolicy?action=delete&")){
262 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
263 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
264 ObjectMapper mapper = new ObjectMapper();
265 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
266 JsonNode root = null;
268 root = mapper.readTree(request.getReader());
269 }catch (Exception e1) {
270 policyLogger.error("Exception Occured while calling PAP"+e1);
273 ObjectMapper mapper1 = new ObjectMapper();
274 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
276 Object obj = mapper1.treeToValue(root, Object.class);
277 String json = mapper1.writeValueAsString(obj);
279 Object content = new ByteArrayInputStream(json.getBytes());
281 if (content instanceof InputStream) {
282 // send current configuration
283 try (OutputStream os = connection.getOutputStream()) {
284 int count = IOUtils.copy((InputStream) content, os);
285 if (policyLogger.isDebugEnabled()) {
286 policyLogger.debug("copied to output, bytes=" + count);
291 if(uri.endsWith("set_BRMSParamData")){
292 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
293 try (OutputStream os = connection.getOutputStream()) {
294 IOUtils.copy((InputStream) request.getInputStream(), os);
297 boundary = "===" + System.currentTimeMillis() + "===";
298 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
299 try (OutputStream os = connection.getOutputStream()) {
301 IOUtils.copy((InputStream) item.getInputStream(), os);
308 connection.connect();
310 int responseCode = connection.getResponseCode();
311 if(responseCode == 200){
312 // get the response content into a String
313 String responseJson = null;
314 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
315 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
316 scanner.useDelimiter("\\A");
317 responseJson = scanner.hasNext() ? scanner.next() : "";
319 policyLogger.info("JSON response from PAP: " + responseJson);
323 } catch (Exception e) {
324 policyLogger.error("Exception Occured"+e);
326 if(file != null && file.exists() && file.delete()){
327 policyLogger.info("File Deleted Successfully");
329 if (connection != null) {
331 // For some reason trying to get the inputStream from the connection
332 // throws an exception rather than returning null when the InputStream does not exist.
333 InputStream is = connection.getInputStream();
337 } catch (IOException ex) {
338 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
340 connection.disconnect();
346 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
347 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
348 String uri = request.getRequestURI().replace("/getDictionary", "");
350 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
351 if(responseEntity != null){
352 body = responseEntity.getBody().toString();
357 response.getWriter().write(body);
358 } catch (IOException e) {
359 policyLogger.error("Exception occured while getting Dictionary entries", e);
363 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
364 public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
365 String uri = request.getRequestURI().replace("/saveDictionary", "");
366 if(uri.contains(importDictionary)){
367 String userId = UserUtils.getUserSession(request).getOrgUserId();
368 uri = uri+ "?userId=" +userId;
370 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
371 response.getWriter().write(body);
375 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
376 public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
377 String uri = request.getRequestURI().replace("/deleteDictionary", "");
378 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
379 response.getWriter().write(body);
383 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
384 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
385 Object resultList = null;
386 String uri = request.getRequestURI();
388 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
389 if(body.contains("CouldNotConnectException")){
390 List<String> data = new ArrayList<>();
391 data.add("Elastic Search Server is down");
394 JSONObject json = new JSONObject(body);
395 resultList = json.get("policyresult");
398 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
399 List<String> data = new ArrayList<>();
400 data.add("Elastic Search Server is down");
404 response.setCharacterEncoding(PolicyController.getCharacterencoding());
405 response.setContentType(PolicyController.getContenttype());
406 PrintWriter out = response.getWriter();
407 JSONObject j = new JSONObject("{result: " + resultList + "}");
408 out.write(j.toString());
412 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
413 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
414 Object resultList = null;
415 String uri = request.getRequestURI()+"?action=search";
416 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
418 JSONObject json = new JSONObject(body);
420 resultList = json.get("policyresult");
422 List<String> data = new ArrayList<>();
423 data.add("Elastic Search Server is down");
425 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
428 response.setCharacterEncoding("UTF-8");
429 response.setContentType("application / json");
430 request.setCharacterEncoding("UTF-8");
432 PrintWriter out = response.getWriter();
433 JSONObject j = new JSONObject("{result: " + resultList + "}");
434 out.write(j.toString());
438 public void deleteElasticData(String fileName){
439 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
440 callPAP(null, "POST", uri.trim());