2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * Modifications Copyright (C) 2019 Bell Canada
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
22 package org.onap.policy.admin;
24 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.io.PrintWriter;
30 import java.net.HttpURLConnection;
32 import java.nio.charset.StandardCharsets;
33 import java.util.ArrayList;
34 import java.util.Base64;
35 import java.util.List;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
40 import org.apache.commons.fileupload.FileItem;
41 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
42 import org.apache.commons.fileupload.servlet.ServletFileUpload;
43 import org.apache.commons.io.IOUtils;
44 import org.json.JSONObject;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.controller.CreateClosedLoopFaultController;
48 import org.onap.policy.controller.CreateDcaeMicroServiceController;
49 import org.onap.policy.controller.CreateFirewallController;
50 import org.onap.policy.controller.CreateOptimizationController;
51 import org.onap.policy.controller.PolicyController;
52 import org.onap.policy.rest.XACMLRestProperties;
53 import org.onap.policy.rest.adapter.PolicyRestAdapter;
54 import org.onap.policy.rest.dao.CommonClassDao;
55 import org.onap.policy.rest.jpa.PolicyVersion;
56 import org.onap.policy.utils.PolicyUtils;
57 import org.onap.policy.xacml.api.XACMLErrorConstants;
58 import org.onap.portalsdk.core.controller.RestrictedBaseController;
59 import org.onap.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.http.HttpEntity;
62 import org.springframework.http.HttpHeaders;
63 import org.springframework.http.HttpMethod;
64 import org.springframework.http.HttpStatus;
65 import org.springframework.http.ResponseEntity;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.bind.annotation.RequestMethod;
68 import org.springframework.web.bind.annotation.RestController;
69 import org.springframework.web.client.HttpClientErrorException;
70 import org.springframework.web.client.RestTemplate;
71 import org.springframework.web.servlet.ModelAndView;
72 import org.onap.policy.utils.CryptoUtils;
73 import com.att.research.xacml.util.XACMLProperties;
74 import com.fasterxml.jackson.databind.DeserializationFeature;
75 import com.fasterxml.jackson.databind.JsonNode;
76 import com.fasterxml.jackson.databind.ObjectMapper;
77 import com.fasterxml.jackson.databind.SerializationFeature;
81 public class PolicyRestController extends RestrictedBaseController{
83 private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
85 private static final String MODEL = "model";
86 private static final String IMPORT_DICTIONARY = "import_dictionary";
87 private static final String FILE = "file";
88 private static final String TYPE = "type";
89 private static final String PATH = "path";
90 private static final String NAME = "name";
91 private static final String CLOSED_LOOP_FAULT = "ClosedLoop_Fault";
92 private static final String FIREWALL_CONFIG = "Firewall Config";
93 private static final String MICRO_SERVICE = "Micro Service";
94 private static final String OPTIMIZATION = "Optimization";
95 private static final String POLICY_NAME = "policyName";
96 private static final String SUCCESS = "success";
97 private static final String XML = ".xml";
98 private static final String UTF_8 = "UTF-8";
99 private static final String DATA = "data";
100 private static final String USER_ID = "UserId: ";
101 private static final String BASIC = "Basic ";
102 private static final String AUTHORIZATION = "Authorization";
103 private static final String CONTENT_TYPE = "Content-Type";
104 private static final String ONAP = "/onap";
106 private static CommonClassDao commonClassDao;
108 public PolicyRestController(){
109 //default constructor
113 private PolicyRestController(CommonClassDao commonClassDao){
114 PolicyRestController.commonClassDao = commonClassDao;
117 public static CommonClassDao getCommonClassDao() {
118 return commonClassDao;
121 public static void setCommonClassDao(CommonClassDao commonClassDao) {
122 PolicyRestController.commonClassDao = commonClassDao;
127 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
128 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
129 String userId = UserUtils.getUserSession(request).getOrgUserId();
130 ObjectMapper mapper = new ObjectMapper();
131 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
133 updateAndSendToPAP(request, response, userId, mapper);
135 policyLogger.error("Exception Occured while saving policy" , e);
139 private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException {
140 JsonNode root = mapper.readTree(request.getReader());
142 "****************************************Logging UserID while Create/Update Policy**************************************************");
144 USER_ID + userId + "Policy Data Object: " + root.get(PolicyController.getPolicydata()).get("policy")
147 "***********************************************************************************************************************************");
149 PolicyRestAdapter policyData = mapper
150 .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
151 modifyPolicyData(root, policyData);
153 if (policyData.getConfigPolicyType() != null) {
154 if (CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())) {
155 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
156 } else if (FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())) {
157 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
158 } else if (MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())) {
159 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
160 } else if (OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())) {
161 policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
165 policyData.setUserId(userId);
168 String body = PolicyUtils.objectToJsonString(policyData);
169 String uri = request.getRequestURI();
170 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
171 if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) {
172 result = "PolicyExists";
173 } else if (responseEntity != null) {
174 result = responseEntity.getBody().toString();
175 String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
176 if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) {
177 PolicyNotificationMail email = new PolicyNotificationMail();
178 String mode = "EditPolicy";
179 String watchPolicyName = policyName.replace(XML, "");
180 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1);
181 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.'))
182 .replace(".", File.separator);
183 String policyVersionName = watchPolicyName.replace(".", File.separator);
184 watchPolicyName = watchPolicyName + "." + version + XML;
185 PolicyVersion entityItem = new PolicyVersion();
186 entityItem.setPolicyName(policyVersionName);
187 entityItem.setActiveVersion(Integer.parseInt(version));
188 entityItem.setModifiedBy(userId);
189 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
192 result = "Response is null from PAP";
195 response.setCharacterEncoding(PolicyController.getCharacterencoding());
196 response.setContentType(PolicyController.getContenttype());
197 request.setCharacterEncoding(PolicyController.getCharacterencoding());
199 PrintWriter out = response.getWriter();
200 String responseString = mapper.writeValueAsString(result);
201 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
202 out.write(j.toString());
205 private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
206 if(FILE.equals(root.get(PolicyController.getPolicydata()).get(MODEL).get(TYPE).toString().replace("\"", ""))){
207 policyData.setEditPolicy(true);
209 if(root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size() != 0){
211 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size(); i++){
212 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(
213 MODEL).get(PATH).get(i).toString().replace("\"", "") + File.separator;
215 if(policyData.isEditPolicy()){
216 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
218 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(
219 MODEL).get(NAME).toString().replace("\"", ""));
222 String domain = root.get(PolicyController.getPolicydata()).get(MODEL).get(NAME).toString();
223 if(domain.contains("/")){
224 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
226 domain = domain.replace("\"", "");
227 policyData.setDomainDir(domain);
232 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
233 String papUrl = PolicyController.getPapUrl();
234 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
235 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
237 Base64.Encoder encoder = Base64.getEncoder();
238 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
239 HttpHeaders headers = new HttpHeaders();
240 headers.set(AUTHORIZATION, BASIC + encoding);
241 headers.set(CONTENT_TYPE, PolicyController.getContenttype());
243 RestTemplate restTemplate = new RestTemplate();
244 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
245 ResponseEntity<?> result = null;
246 HttpClientErrorException exception = null;
247 String uri = requestURI;
248 if(uri.startsWith("/")){
249 uri = uri.substring(uri.indexOf('/')+1);
251 uri = "onap" + uri.substring(uri.indexOf('/'));
253 result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
255 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
256 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
257 if("409 Conflict".equals(e.getMessage())){
258 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
261 if(exception != null && exception.getStatusCode()!=null){
262 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
263 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
264 policyLogger.error(message);
266 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
267 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
268 policyLogger.error(message);
270 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
271 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
272 policyLogger.error(message);
274 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
275 policyLogger.error(message);
280 private String callPAP(HttpServletRequest request , String method, String uriValue){
281 String uri = uriValue;
282 String papUrl = PolicyController.getPapUrl();
283 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
284 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
286 Base64.Encoder encoder = Base64.getEncoder();
287 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
288 HttpHeaders headers = new HttpHeaders();
289 headers.set(AUTHORIZATION, BASIC + encoding);
290 headers.set(CONTENT_TYPE, PolicyController.getContenttype());
293 HttpURLConnection connection = null;
294 List<FileItem> items;
295 FileItem item = null;
297 if(uri.contains(IMPORT_DICTIONARY)){
299 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
301 file = new File(item.getName());
302 String newFile = file.toString();
303 uri = uri +"&dictionaryName="+newFile;
304 } catch (Exception e2) {
305 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
310 URL url = new URL(papUrl + uri);
311 connection = (HttpURLConnection)url.openConnection();
312 connection.setRequestMethod(method);
313 connection.setUseCaches(false);
314 connection.setInstanceFollowRedirects(false);
315 connection.setRequestProperty(AUTHORIZATION, BASIC + encoding);
316 connection.setDoOutput(true);
317 connection.setDoInput(true);
319 if(uri.contains("searchPolicy?action=delete&")){
321 return doConnect(connection);
324 checkURI(request, uri, connection, item);
326 return doConnect(connection);
327 } catch (Exception e) {
328 policyLogger.error("Exception Occured"+e);
330 if(file != null && file.exists() && file.delete()){
331 policyLogger.info("File Deleted Successfully");
333 if (connection != null) {
335 // For some reason trying to get the inputStream from the connection
336 // throws an exception rather than returning null when the InputStream does not exist.
337 InputStream is = connection.getInputStream();
341 } catch (IOException ex) {
342 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
344 connection.disconnect();
350 private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
353 if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
354 connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
355 ObjectMapper mapper = new ObjectMapper();
356 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
357 JsonNode root = getJsonNode(request, mapper);
359 ObjectMapper mapper1 = new ObjectMapper();
360 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
362 Object obj = mapper1.treeToValue(root, Object.class);
363 String json = mapper1.writeValueAsString(obj);
365 // send current configuration
366 try (InputStream content = new ByteArrayInputStream(json.getBytes());
367 OutputStream os = connection.getOutputStream()) {
368 int count = IOUtils.copy(content, os);
369 if (policyLogger.isDebugEnabled()) {
370 policyLogger.debug("copied to output, bytes=" + count);
373 } else if (uri.endsWith("set_BRMSParamData")) {
374 connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
375 try (OutputStream os = connection.getOutputStream()) {
376 IOUtils.copy(request.getInputStream(), os);
379 boundary = "===" + System.currentTimeMillis() + "===";
380 connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
381 try (OutputStream os = connection.getOutputStream()) {
383 IOUtils.copy(item.getInputStream(), os);
389 private JsonNode getJsonNode(HttpServletRequest request, ObjectMapper mapper) {
390 JsonNode root = null;
392 root = mapper.readTree(request.getReader());
393 }catch (Exception e1) {
394 policyLogger.error("Exception Occured while calling PAP"+e1);
399 private String doConnect(final HttpURLConnection connection) throws IOException{
400 connection.connect();
401 int responseCode = connection.getResponseCode();
402 if(responseCode == 200){
403 // get the response content into a String
404 String responseJson = null;
405 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
406 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
407 scanner.useDelimiter("\\A");
408 responseJson = scanner.hasNext() ? scanner.next() : "";
409 } catch (Exception e){
410 //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
411 //then the exception handling is done by the outer block without returning the response immediately
412 //Also finally block is existing only in outer block and not here so all exception handling is
413 //done in only one place
414 policyLogger.error("Exception Occured"+e);
418 policyLogger.info("JSON response from PAP: " + responseJson);
424 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
425 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
426 String uri = request.getRequestURI().replace("/getDictionary", "");
428 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
429 if(responseEntity != null){
430 body = responseEntity.getBody().toString();
435 response.getWriter().write(body);
436 } catch (IOException e) {
437 policyLogger.error("Exception occured while getting Dictionary entries", e);
441 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
442 public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
444 String uri = request.getRequestURI().replace("/saveDictionary", "");
445 if(uri.startsWith("/")){
446 uri = uri.substring(uri.indexOf('/')+1);
448 uri = ONAP + uri.substring(uri.indexOf('/'));
449 if(uri.contains(IMPORT_DICTIONARY)){
450 userId = UserUtils.getUserSession(request).getOrgUserId();
451 uri = uri+ "?userId=" +userId;
454 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
455 policyLogger.info(USER_ID + userId);
456 policyLogger.info("***********************************************************************************************************************************");
458 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
459 if(body != null && !body.isEmpty()){
460 response.getWriter().write(body);
462 response.getWriter().write("Failed");
466 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
467 public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
468 String uri = request.getRequestURI().replace("/deleteDictionary", "");
469 if(uri.startsWith("/")){
470 uri = uri.substring(uri.indexOf('/')+1);
472 uri = ONAP + uri.substring(uri.indexOf('/'));
474 String userId = UserUtils.getUserSession(request).getOrgUserId();
475 policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
476 policyLogger.info(USER_ID + userId);
477 policyLogger.info("*************************************************************************************************************************************");
479 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
480 if(body != null && !body.isEmpty()){
481 response.getWriter().write(body);
483 response.getWriter().write("Failed");
487 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
488 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
490 String uri = request.getRequestURI();
491 if(uri.startsWith("/")){
492 uri = uri.substring(uri.indexOf('/')+1);
494 uri = ONAP + uri.substring(uri.indexOf('/'));
496 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
497 if(body.contains("CouldNotConnectException")){
498 List<String> data = new ArrayList<>();
499 data.add("Elastic Search Server is down");
502 JSONObject json = new JSONObject(body);
503 resultList = json.get("policyresult");
506 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
507 List<String> data = new ArrayList<>();
508 data.add("Elastic Search Server is down");
512 response.setCharacterEncoding(PolicyController.getCharacterencoding());
513 response.setContentType(PolicyController.getContenttype());
514 PrintWriter out = response.getWriter();
515 JSONObject j = new JSONObject("{result: " + resultList + "}");
516 out.write(j.toString());
520 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
521 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
523 String uri = request.getRequestURI()+"?action=search";
524 if(uri.startsWith("/")){
525 uri = uri.substring(uri.indexOf('/')+1);
527 uri = ONAP + uri.substring(uri.indexOf('/'));
528 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
530 JSONObject json = new JSONObject(body);
532 resultList = json.get("policyresult");
534 List<String> data = new ArrayList<>();
535 resultList = json.get(DATA);
536 data.add("Exception");
537 data.add(resultList.toString());
539 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
542 response.setCharacterEncoding(UTF_8);
543 response.setContentType("application / json");
544 request.setCharacterEncoding(UTF_8);
546 PrintWriter out = response.getWriter();
547 JSONObject j = new JSONObject("{result: " + resultList + "}");
548 out.write(j.toString());
552 public void deleteElasticData(String fileName){
553 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
554 callPAP(null, "POST", uri.trim());
557 public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
558 String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
559 return callPAP(null, "POST", uri.trim());