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";
85 private static CommonClassDao commonClassDao;
87 public static CommonClassDao getCommonClassDao() {
88 return commonClassDao;
91 public static void setCommonClassDao(CommonClassDao commonClassDao) {
92 PolicyRestController.commonClassDao = commonClassDao;
96 private PolicyRestController(CommonClassDao commonClassDao){
97 PolicyRestController.commonClassDao = commonClassDao;
100 public PolicyRestController(){
101 //default constructor
104 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
105 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
106 String userId = UserUtils.getUserSession(request).getOrgUserId();
107 ObjectMapper mapper = new ObjectMapper();
108 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
110 JsonNode root = mapper.readTree(request.getReader());
112 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
114 if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){
115 policyData.setEditPolicy(true);
117 if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){
119 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){
120 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator;
122 if(policyData.isEditPolicy()){
123 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
125 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", ""));
128 String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString();
129 if(domain.contains("/")){
130 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
132 domain = domain.replace("\"", "");
133 policyData.setDomainDir(domain);
136 if(policyData.getConfigPolicyType() != null){
137 if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
138 CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
139 policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
140 }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
141 CreateFirewallController fwController = new CreateFirewallController();
142 policyData = fwController.setDataToPolicyRestAdapter(policyData);
143 }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
144 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
145 policyData = msController.setDataToPolicyRestAdapter(policyData, root);
149 policyData.setUserId(userId);
152 String body = PolicyUtils.objectToJsonString(policyData);
153 String uri = request.getRequestURI();
154 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
155 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
156 result = "PolicyExists";
157 }else if(responseEntity != null){
158 result = responseEntity.getBody().toString();
159 String policyName = responseEntity.getHeaders().get("policyName").get(0);
160 if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){
161 PolicyNotificationMail email = new PolicyNotificationMail();
162 String mode = "EditPolicy";
163 String watchPolicyName = policyName.replace(".xml", "");
164 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
165 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
166 String policyVersionName = watchPolicyName.replace(".", File.separator);
167 watchPolicyName = watchPolicyName + "." + version + ".xml";
168 PolicyVersion entityItem = new PolicyVersion();
169 entityItem.setPolicyName(policyVersionName);
170 entityItem.setActiveVersion(Integer.parseInt(version));
171 entityItem.setModifiedBy(userId);
172 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
175 result = "Response is null from PAP";
178 response.setCharacterEncoding(PolicyController.getCharacterencoding());
179 response.setContentType(PolicyController.getContenttype());
180 request.setCharacterEncoding(PolicyController.getCharacterencoding());
182 PrintWriter out = response.getWriter();
183 String responseString = mapper.writeValueAsString(result);
184 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
185 out.write(j.toString());
187 policyLogger.error("Exception Occured while saving policy" , e);
192 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
193 String papUrl = PolicyController.getPapUrl();
194 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
195 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
197 Base64.Encoder encoder = Base64.getEncoder();
198 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
199 HttpHeaders headers = new HttpHeaders();
200 headers.set("Authorization", "Basic " + encoding);
201 headers.set("Content-Type", PolicyController.getContenttype());
203 RestTemplate restTemplate = new RestTemplate();
204 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
205 ResponseEntity<?> result = null;
206 HttpClientErrorException exception = null;
209 result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class);
211 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
212 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
213 if("409 Conflict".equals(e.getMessage())){
214 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
217 if(exception != null && exception.getStatusCode()!=null){
218 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
219 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
220 policyLogger.error(message);
222 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
223 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
224 policyLogger.error(message);
226 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
227 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
228 policyLogger.error(message);
230 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
231 policyLogger.error(message);
236 private String callPAP(HttpServletRequest request , String method, String uriValue){
237 String uri = uriValue;
238 String boundary = null;
239 String papUrl = PolicyController.getPapUrl();
240 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
241 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
243 Base64.Encoder encoder = Base64.getEncoder();
244 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
245 HttpHeaders headers = new HttpHeaders();
246 headers.set("Authorization", "Basic " + encoding);
247 headers.set("Content-Type", PolicyController.getContenttype());
250 HttpURLConnection connection = null;
251 List<FileItem> items;
252 FileItem item = null;
254 if(uri.contains(importDictionary)){
256 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
258 file = new File(item.getName());
259 String newFile = file.toString();
260 uri = uri +"&dictionaryName="+newFile;
261 } catch (Exception e2) {
262 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
267 URL url = new URL(papUrl + uri);
268 connection = (HttpURLConnection)url.openConnection();
269 connection.setRequestMethod(method);
270 connection.setUseCaches(false);
271 connection.setInstanceFollowRedirects(false);
272 connection.setRequestProperty("Authorization", "Basic " + encoding);
273 connection.setDoOutput(true);
274 connection.setDoInput(true);
276 if(!uri.contains("searchPolicy?action=delete&")){
278 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
279 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
280 ObjectMapper mapper = new ObjectMapper();
281 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
282 JsonNode root = null;
284 root = mapper.readTree(request.getReader());
285 }catch (Exception e1) {
286 policyLogger.error("Exception Occured while calling PAP"+e1);
289 ObjectMapper mapper1 = new ObjectMapper();
290 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
292 Object obj = mapper1.treeToValue(root, Object.class);
293 String json = mapper1.writeValueAsString(obj);
295 Object content = new ByteArrayInputStream(json.getBytes());
297 if (content instanceof InputStream) {
298 // send current configuration
299 try (OutputStream os = connection.getOutputStream()) {
300 int count = IOUtils.copy((InputStream) content, os);
301 if (policyLogger.isDebugEnabled()) {
302 policyLogger.debug("copied to output, bytes=" + count);
307 if(uri.endsWith("set_BRMSParamData")){
308 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
309 try (OutputStream os = connection.getOutputStream()) {
310 IOUtils.copy((InputStream) request.getInputStream(), os);
313 boundary = "===" + System.currentTimeMillis() + "===";
314 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
315 try (OutputStream os = connection.getOutputStream()) {
317 IOUtils.copy((InputStream) item.getInputStream(), os);
324 connection.connect();
326 int responseCode = connection.getResponseCode();
327 if(responseCode == 200){
328 // get the response content into a String
329 String responseJson = null;
330 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
331 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
332 scanner.useDelimiter("\\A");
333 responseJson = scanner.hasNext() ? scanner.next() : "";
335 policyLogger.info("JSON response from PAP: " + responseJson);
339 } catch (Exception e) {
340 policyLogger.error("Exception Occured"+e);
342 if(file != null && file.exists() && file.delete()){
343 policyLogger.info("File Deleted Successfully");
345 if (connection != null) {
347 // For some reason trying to get the inputStream from the connection
348 // throws an exception rather than returning null when the InputStream does not exist.
349 InputStream is = connection.getInputStream();
353 } catch (IOException ex) {
354 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
356 connection.disconnect();
362 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
363 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
364 String uri = request.getRequestURI().replace("/getDictionary", "");
366 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
367 if(responseEntity != null){
368 body = responseEntity.getBody().toString();
373 response.getWriter().write(body);
374 } catch (IOException e) {
375 policyLogger.error("Exception occured while getting Dictionary entries", e);
379 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
380 public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
381 String uri = request.getRequestURI().replace("/saveDictionary", "");
382 if(uri.contains(importDictionary)){
383 String userId = UserUtils.getUserSession(request).getOrgUserId();
384 uri = uri+ "?userId=" +userId;
386 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
387 response.getWriter().write(body);
391 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
392 public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
393 String uri = request.getRequestURI().replace("/deleteDictionary", "");
394 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
395 response.getWriter().write(body);
399 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
400 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
401 Object resultList = null;
402 String uri = request.getRequestURI();
404 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
405 if(body.contains("CouldNotConnectException")){
406 List<String> data = new ArrayList<>();
407 data.add("Elastic Search Server is down");
410 JSONObject json = new JSONObject(body);
411 resultList = json.get("policyresult");
414 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
415 List<String> data = new ArrayList<>();
416 data.add("Elastic Search Server is down");
420 response.setCharacterEncoding(PolicyController.getCharacterencoding());
421 response.setContentType(PolicyController.getContenttype());
422 PrintWriter out = response.getWriter();
423 JSONObject j = new JSONObject("{result: " + resultList + "}");
424 out.write(j.toString());
428 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
429 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
430 Object resultList = null;
431 String uri = request.getRequestURI()+"?action=search";
432 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
434 JSONObject json = new JSONObject(body);
436 resultList = json.get("policyresult");
438 List<String> data = new ArrayList<>();
439 data.add("Elastic Search Server is down");
441 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
444 response.setCharacterEncoding("UTF-8");
445 response.setContentType("application / json");
446 request.setCharacterEncoding("UTF-8");
448 PrintWriter out = response.getWriter();
449 JSONObject j = new JSONObject("{result: " + resultList + "}");
450 out.write(j.toString());
454 public void deleteElasticData(String fileName){
455 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
456 callPAP(null, "POST", uri.trim());