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 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.policy.admin;
23 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.PrintWriter;
29 import java.net.HttpURLConnection;
31 import java.nio.charset.StandardCharsets;
32 import java.util.ArrayList;
33 import java.util.Base64;
34 import java.util.List;
36 import javax.mail.MessagingException;
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 importDictionary = "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";
101 private static CommonClassDao commonClassDao;
103 public PolicyRestController(){
104 //default constructor
108 private PolicyRestController(CommonClassDao commonClassDao){
109 PolicyRestController.commonClassDao = commonClassDao;
112 public static CommonClassDao getCommonClassDao() {
113 return commonClassDao;
116 public static void setCommonClassDao(CommonClassDao commonClassDao) {
117 PolicyRestController.commonClassDao = commonClassDao;
122 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
123 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
124 String userId = UserUtils.getUserSession(request).getOrgUserId();
125 ObjectMapper mapper = new ObjectMapper();
126 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
128 updateAndSendToPAP(request, response, userId, mapper);
130 policyLogger.error("Exception Occured while saving policy" , e);
134 private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException, MessagingException {
135 JsonNode root = mapper.readTree(request.getReader());
137 policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
138 policyLogger.info("UserId: " + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
139 policyLogger.info("***********************************************************************************************************************************");
141 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
143 modifyPolicyData(root, policyData);
145 if(policyData.getConfigPolicyType() != null){
146 if(CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())){
147 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
148 }else if(FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())){
149 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
150 }else if(MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())){
151 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
152 }else if(OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())){
153 policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
157 policyData.setUserId(userId);
160 String body = PolicyUtils.objectToJsonString(policyData);
161 String uri = request.getRequestURI();
162 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
163 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
164 result = "PolicyExists";
165 }else if(responseEntity != null){
166 result = responseEntity.getBody().toString();
167 String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
168 if(policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)){
169 PolicyNotificationMail email = new PolicyNotificationMail();
170 String mode = "EditPolicy";
171 String watchPolicyName = policyName.replace(XML, "");
172 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
173 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
174 String policyVersionName = watchPolicyName.replace(".", File.separator);
175 watchPolicyName = watchPolicyName + "." + version + XML;
176 PolicyVersion entityItem = new PolicyVersion();
177 entityItem.setPolicyName(policyVersionName);
178 entityItem.setActiveVersion(Integer.parseInt(version));
179 entityItem.setModifiedBy(userId);
180 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
183 result = "Response is null from PAP";
186 response.setCharacterEncoding(PolicyController.getCharacterencoding());
187 response.setContentType(PolicyController.getContenttype());
188 request.setCharacterEncoding(PolicyController.getCharacterencoding());
190 PrintWriter out = response.getWriter();
191 String responseString = mapper.writeValueAsString(result);
192 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
193 out.write(j.toString());
196 private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
197 if(FILE.equals(root.get(PolicyController.getPolicydata()).get(model).get(TYPE).toString().replace("\"", ""))){
198 policyData.setEditPolicy(true);
200 if(root.get(PolicyController.getPolicydata()).get(model).get(PATH).size() != 0){
202 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(model).get(PATH).size(); i++){
203 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(model).get(PATH).get(i).toString().replace("\"", "") + File.separator;
205 if(policyData.isEditPolicy()){
206 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
208 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(model).get(NAME).toString().replace("\"", ""));
211 String domain = root.get(PolicyController.getPolicydata()).get(model).get(NAME).toString();
212 if(domain.contains("/")){
213 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
215 domain = domain.replace("\"", "");
216 policyData.setDomainDir(domain);
221 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
222 String papUrl = PolicyController.getPapUrl();
223 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
224 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
226 Base64.Encoder encoder = Base64.getEncoder();
227 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
228 HttpHeaders headers = new HttpHeaders();
229 headers.set("Authorization", "Basic " + encoding);
230 headers.set("Content-Type", PolicyController.getContenttype());
232 RestTemplate restTemplate = new RestTemplate();
233 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
234 ResponseEntity<?> result = null;
235 HttpClientErrorException exception = null;
236 String uri = requestURI;
237 if(uri.startsWith("/")){
238 uri = uri.substring(uri.indexOf('/')+1);
240 uri = "onap" + uri.substring(uri.indexOf('/'));
242 result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
244 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
245 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
246 if("409 Conflict".equals(e.getMessage())){
247 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
250 if(exception != null && exception.getStatusCode()!=null){
251 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
252 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
253 policyLogger.error(message);
255 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
256 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
257 policyLogger.error(message);
259 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
260 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
261 policyLogger.error(message);
263 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
264 policyLogger.error(message);
269 private String callPAP(HttpServletRequest request , String method, String uriValue){
270 String uri = uriValue;
271 String boundary = null;
272 String papUrl = PolicyController.getPapUrl();
273 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
274 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
276 Base64.Encoder encoder = Base64.getEncoder();
277 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
278 HttpHeaders headers = new HttpHeaders();
279 headers.set("Authorization", "Basic " + encoding);
280 headers.set("Content-Type", PolicyController.getContenttype());
283 HttpURLConnection connection = null;
284 List<FileItem> items;
285 FileItem item = null;
287 if(uri.contains(importDictionary)){
289 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
291 file = new File(item.getName());
292 String newFile = file.toString();
293 uri = uri +"&dictionaryName="+newFile;
294 } catch (Exception e2) {
295 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
300 URL url = new URL(papUrl + uri);
301 connection = (HttpURLConnection)url.openConnection();
302 connection.setRequestMethod(method);
303 connection.setUseCaches(false);
304 connection.setInstanceFollowRedirects(false);
305 connection.setRequestProperty("Authorization", "Basic " + encoding);
306 connection.setDoOutput(true);
307 connection.setDoInput(true);
309 if(uri.contains("searchPolicy?action=delete&")){
311 return doConnect(connection);
314 checkURI(request, uri, connection, item);
316 return doConnect(connection);
317 } catch (Exception e) {
318 policyLogger.error("Exception Occured"+e);
320 if(file != null && file.exists() && file.delete()){
321 policyLogger.info("File Deleted Successfully");
323 if (connection != null) {
325 // For some reason trying to get the inputStream from the connection
326 // throws an exception rather than returning null when the InputStream does not exist.
327 InputStream is = connection.getInputStream();
331 } catch (IOException ex) {
332 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
334 connection.disconnect();
340 private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException {
342 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
343 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
344 ObjectMapper mapper = new ObjectMapper();
345 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
346 JsonNode root = getJsonNode(request, mapper);
348 ObjectMapper mapper1 = new ObjectMapper();
349 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
351 Object obj = mapper1.treeToValue(root, Object.class);
352 String json = mapper1.writeValueAsString(obj);
354 // send current configuration
355 try(InputStream content = new ByteArrayInputStream(json.getBytes());
356 OutputStream os = connection.getOutputStream()) {
357 int count = IOUtils.copy(content, os);
358 if (policyLogger.isDebugEnabled()) {
359 policyLogger.debug("copied to output, bytes=" + count);
363 if(uri.endsWith("set_BRMSParamData")){
364 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
365 try (OutputStream os = connection.getOutputStream()) {
366 IOUtils.copy((InputStream) request.getInputStream(), os);
369 boundary = "===" + System.currentTimeMillis() + "===";
370 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
371 try (OutputStream os = connection.getOutputStream()) {
373 IOUtils.copy((InputStream) item.getInputStream(), os);
380 private JsonNode getJsonNode(HttpServletRequest request, ObjectMapper mapper) {
381 JsonNode root = null;
383 root = mapper.readTree(request.getReader());
384 }catch (Exception e1) {
385 policyLogger.error("Exception Occured while calling PAP"+e1);
390 private String doConnect(final HttpURLConnection connection) throws IOException{
391 connection.connect();
392 int responseCode = connection.getResponseCode();
393 if(responseCode == 200){
394 // get the response content into a String
395 String responseJson = null;
396 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
397 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
398 scanner.useDelimiter("\\A");
399 responseJson = scanner.hasNext() ? scanner.next() : "";
400 } catch (Exception e){
401 //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
402 //then the exception handling is done by the outer block without returning the response immediately
403 //Also finally block is existing only in outer block and not here so all exception handling is
404 //done in only one place
405 policyLogger.error("Exception Occured"+e);
409 policyLogger.info("JSON response from PAP: " + responseJson);
415 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
416 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
417 String uri = request.getRequestURI().replace("/getDictionary", "");
419 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
420 if(responseEntity != null){
421 body = responseEntity.getBody().toString();
426 response.getWriter().write(body);
427 } catch (IOException e) {
428 policyLogger.error("Exception occured while getting Dictionary entries", e);
432 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
433 public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
435 String uri = request.getRequestURI().replace("/saveDictionary", "");
436 if(uri.startsWith("/")){
437 uri = uri.substring(uri.indexOf('/')+1);
439 uri = "/onap" + uri.substring(uri.indexOf('/'));
440 if(uri.contains(importDictionary)){
441 userId = UserUtils.getUserSession(request).getOrgUserId();
442 uri = uri+ "?userId=" +userId;
445 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
446 policyLogger.info("UserId: " + userId);
447 policyLogger.info("***********************************************************************************************************************************");
449 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
450 if(body != null && !body.isEmpty()){
451 response.getWriter().write(body);
453 response.getWriter().write("Failed");
457 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
458 public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
459 String uri = request.getRequestURI().replace("/deleteDictionary", "");
460 if(uri.startsWith("/")){
461 uri = uri.substring(uri.indexOf('/')+1);
463 uri = "/onap" + uri.substring(uri.indexOf('/'));
465 String userId = UserUtils.getUserSession(request).getOrgUserId();
466 policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
467 policyLogger.info("UserId: " + userId);
468 policyLogger.info("*************************************************************************************************************************************");
470 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
471 if(body != null && !body.isEmpty()){
472 response.getWriter().write(body);
474 response.getWriter().write("Failed");
478 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
479 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
481 String uri = request.getRequestURI();
482 if(uri.startsWith("/")){
483 uri = uri.substring(uri.indexOf('/')+1);
485 uri = "/onap" + uri.substring(uri.indexOf('/'));
487 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
488 if(body.contains("CouldNotConnectException")){
489 List<String> data = new ArrayList<>();
490 data.add("Elastic Search Server is down");
493 JSONObject json = new JSONObject(body);
494 resultList = json.get("policyresult");
497 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
498 List<String> data = new ArrayList<>();
499 data.add("Elastic Search Server is down");
503 response.setCharacterEncoding(PolicyController.getCharacterencoding());
504 response.setContentType(PolicyController.getContenttype());
505 PrintWriter out = response.getWriter();
506 JSONObject j = new JSONObject("{result: " + resultList + "}");
507 out.write(j.toString());
511 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
512 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
514 String uri = request.getRequestURI()+"?action=search";
515 if(uri.startsWith("/")){
516 uri = uri.substring(uri.indexOf('/')+1);
518 uri = "/onap" + uri.substring(uri.indexOf('/'));
519 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
521 JSONObject json = new JSONObject(body);
523 resultList = json.get("policyresult");
525 List<String> data = new ArrayList<>();
526 resultList = json.get(DATA);
527 data.add("Exception");
528 data.add(resultList.toString());
530 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
533 response.setCharacterEncoding(UTF_8);
534 response.setContentType("application / json");
535 request.setCharacterEncoding(UTF_8);
537 PrintWriter out = response.getWriter();
538 JSONObject j = new JSONObject("{result: " + resultList + "}");
539 out.write(j.toString());
543 public void deleteElasticData(String fileName){
544 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
545 callPAP(null, "POST", uri.trim());
548 public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
549 String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
550 return callPAP(null, "POST", uri.trim());