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 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, MessagingException {
140 JsonNode root = mapper.readTree(request.getReader());
142 policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
143 policyLogger.info(USER_ID + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
144 policyLogger.info("***********************************************************************************************************************************");
146 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
148 modifyPolicyData(root, policyData);
150 if(policyData.getConfigPolicyType() != null){
151 if(CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())){
152 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
153 }else if(FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())){
154 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
155 }else if(MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())){
156 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
157 }else if(OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())){
158 policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
162 policyData.setUserId(userId);
165 String body = PolicyUtils.objectToJsonString(policyData);
166 String uri = request.getRequestURI();
167 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
168 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
169 result = "PolicyExists";
170 }else if(responseEntity != null){
171 result = responseEntity.getBody().toString();
172 String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
173 if(policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)){
174 PolicyNotificationMail email = new PolicyNotificationMail();
175 String mode = "EditPolicy";
176 String watchPolicyName = policyName.replace(XML, "");
177 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
178 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
179 String policyVersionName = watchPolicyName.replace(".", File.separator);
180 watchPolicyName = watchPolicyName + "." + version + XML;
181 PolicyVersion entityItem = new PolicyVersion();
182 entityItem.setPolicyName(policyVersionName);
183 entityItem.setActiveVersion(Integer.parseInt(version));
184 entityItem.setModifiedBy(userId);
185 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
188 result = "Response is null from PAP";
191 response.setCharacterEncoding(PolicyController.getCharacterencoding());
192 response.setContentType(PolicyController.getContenttype());
193 request.setCharacterEncoding(PolicyController.getCharacterencoding());
195 PrintWriter out = response.getWriter();
196 String responseString = mapper.writeValueAsString(result);
197 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
198 out.write(j.toString());
201 private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
202 if(FILE.equals(root.get(PolicyController.getPolicydata()).get(MODEL).get(TYPE).toString().replace("\"", ""))){
203 policyData.setEditPolicy(true);
205 if(root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size() != 0){
207 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size(); i++){
208 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(
209 MODEL).get(PATH).get(i).toString().replace("\"", "") + File.separator;
211 if(policyData.isEditPolicy()){
212 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
214 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(
215 MODEL).get(NAME).toString().replace("\"", ""));
218 String domain = root.get(PolicyController.getPolicydata()).get(MODEL).get(NAME).toString();
219 if(domain.contains("/")){
220 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
222 domain = domain.replace("\"", "");
223 policyData.setDomainDir(domain);
228 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
229 String papUrl = PolicyController.getPapUrl();
230 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
231 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
233 Base64.Encoder encoder = Base64.getEncoder();
234 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
235 HttpHeaders headers = new HttpHeaders();
236 headers.set(AUTHORIZATION, BASIC + encoding);
237 headers.set(CONTENT_TYPE, PolicyController.getContenttype());
239 RestTemplate restTemplate = new RestTemplate();
240 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
241 ResponseEntity<?> result = null;
242 HttpClientErrorException exception = null;
243 String uri = requestURI;
244 if(uri.startsWith("/")){
245 uri = uri.substring(uri.indexOf('/')+1);
247 uri = "onap" + uri.substring(uri.indexOf('/'));
249 result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
251 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
252 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
253 if("409 Conflict".equals(e.getMessage())){
254 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
257 if(exception != null && exception.getStatusCode()!=null){
258 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
259 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
260 policyLogger.error(message);
262 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
263 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
264 policyLogger.error(message);
266 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
267 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
268 policyLogger.error(message);
270 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
271 policyLogger.error(message);
276 private String callPAP(HttpServletRequest request , String method, String uriValue){
277 String uri = uriValue;
278 String papUrl = PolicyController.getPapUrl();
279 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
280 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
282 Base64.Encoder encoder = Base64.getEncoder();
283 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
284 HttpHeaders headers = new HttpHeaders();
285 headers.set(AUTHORIZATION, BASIC + encoding);
286 headers.set(CONTENT_TYPE, PolicyController.getContenttype());
289 HttpURLConnection connection = null;
290 List<FileItem> items;
291 FileItem item = null;
293 if(uri.contains(IMPORT_DICTIONARY)){
295 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
297 file = new File(item.getName());
298 String newFile = file.toString();
299 uri = uri +"&dictionaryName="+newFile;
300 } catch (Exception e2) {
301 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
306 URL url = new URL(papUrl + uri);
307 connection = (HttpURLConnection)url.openConnection();
308 connection.setRequestMethod(method);
309 connection.setUseCaches(false);
310 connection.setInstanceFollowRedirects(false);
311 connection.setRequestProperty(AUTHORIZATION, BASIC + encoding);
312 connection.setDoOutput(true);
313 connection.setDoInput(true);
315 if(uri.contains("searchPolicy?action=delete&")){
317 return doConnect(connection);
320 checkURI(request, uri, connection, item);
322 return doConnect(connection);
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 private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException {
348 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))){
349 connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype());
350 ObjectMapper mapper = new ObjectMapper();
351 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
352 JsonNode root = getJsonNode(request, mapper);
354 ObjectMapper mapper1 = new ObjectMapper();
355 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
357 Object obj = mapper1.treeToValue(root, Object.class);
358 String json = mapper1.writeValueAsString(obj);
360 // send current configuration
361 try(InputStream content = new ByteArrayInputStream(json.getBytes());
362 OutputStream os = connection.getOutputStream()) {
363 int count = IOUtils.copy(content, os);
364 if (policyLogger.isDebugEnabled()) {
365 policyLogger.debug("copied to output, bytes=" + count);
369 if(uri.endsWith("set_BRMSParamData")){
370 connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype());
371 try (OutputStream os = connection.getOutputStream()) {
372 IOUtils.copy((InputStream) request.getInputStream(), os);
375 boundary = "===" + System.currentTimeMillis() + "===";
376 connection.setRequestProperty(CONTENT_TYPE,"multipart/form-data; boundary=" + boundary);
377 try (OutputStream os = connection.getOutputStream()) {
379 IOUtils.copy((InputStream) item.getInputStream(), os);
386 private JsonNode getJsonNode(HttpServletRequest request, ObjectMapper mapper) {
387 JsonNode root = null;
389 root = mapper.readTree(request.getReader());
390 }catch (Exception e1) {
391 policyLogger.error("Exception Occured while calling PAP"+e1);
396 private String doConnect(final HttpURLConnection connection) throws IOException{
397 connection.connect();
398 int responseCode = connection.getResponseCode();
399 if(responseCode == 200){
400 // get the response content into a String
401 String responseJson = null;
402 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
403 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
404 scanner.useDelimiter("\\A");
405 responseJson = scanner.hasNext() ? scanner.next() : "";
406 } catch (Exception e){
407 //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
408 //then the exception handling is done by the outer block without returning the response immediately
409 //Also finally block is existing only in outer block and not here so all exception handling is
410 //done in only one place
411 policyLogger.error("Exception Occured"+e);
415 policyLogger.info("JSON response from PAP: " + responseJson);
421 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
422 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
423 String uri = request.getRequestURI().replace("/getDictionary", "");
425 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
426 if(responseEntity != null){
427 body = responseEntity.getBody().toString();
432 response.getWriter().write(body);
433 } catch (IOException e) {
434 policyLogger.error("Exception occured while getting Dictionary entries", e);
438 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
439 public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
441 String uri = request.getRequestURI().replace("/saveDictionary", "");
442 if(uri.startsWith("/")){
443 uri = uri.substring(uri.indexOf('/')+1);
445 uri = ONAP + uri.substring(uri.indexOf('/'));
446 if(uri.contains(IMPORT_DICTIONARY)){
447 userId = UserUtils.getUserSession(request).getOrgUserId();
448 uri = uri+ "?userId=" +userId;
451 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
452 policyLogger.info(USER_ID + userId);
453 policyLogger.info("***********************************************************************************************************************************");
455 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
456 if(body != null && !body.isEmpty()){
457 response.getWriter().write(body);
459 response.getWriter().write("Failed");
463 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
464 public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
465 String uri = request.getRequestURI().replace("/deleteDictionary", "");
466 if(uri.startsWith("/")){
467 uri = uri.substring(uri.indexOf('/')+1);
469 uri = ONAP + uri.substring(uri.indexOf('/'));
471 String userId = UserUtils.getUserSession(request).getOrgUserId();
472 policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
473 policyLogger.info(USER_ID + userId);
474 policyLogger.info("*************************************************************************************************************************************");
476 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
477 if(body != null && !body.isEmpty()){
478 response.getWriter().write(body);
480 response.getWriter().write("Failed");
484 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
485 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
487 String uri = request.getRequestURI();
488 if(uri.startsWith("/")){
489 uri = uri.substring(uri.indexOf('/')+1);
491 uri = ONAP + uri.substring(uri.indexOf('/'));
493 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
494 if(body.contains("CouldNotConnectException")){
495 List<String> data = new ArrayList<>();
496 data.add("Elastic Search Server is down");
499 JSONObject json = new JSONObject(body);
500 resultList = json.get("policyresult");
503 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
504 List<String> data = new ArrayList<>();
505 data.add("Elastic Search Server is down");
509 response.setCharacterEncoding(PolicyController.getCharacterencoding());
510 response.setContentType(PolicyController.getContenttype());
511 PrintWriter out = response.getWriter();
512 JSONObject j = new JSONObject("{result: " + resultList + "}");
513 out.write(j.toString());
517 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
518 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
520 String uri = request.getRequestURI()+"?action=search";
521 if(uri.startsWith("/")){
522 uri = uri.substring(uri.indexOf('/')+1);
524 uri = ONAP + uri.substring(uri.indexOf('/'));
525 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
527 JSONObject json = new JSONObject(body);
529 resultList = json.get("policyresult");
531 List<String> data = new ArrayList<>();
532 resultList = json.get(DATA);
533 data.add("Exception");
534 data.add(resultList.toString());
536 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
539 response.setCharacterEncoding(UTF_8);
540 response.setContentType("application / json");
541 request.setCharacterEncoding(UTF_8);
543 PrintWriter out = response.getWriter();
544 JSONObject j = new JSONObject("{result: " + resultList + "}");
545 out.write(j.toString());
549 public void deleteElasticData(String fileName){
550 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
551 callPAP(null, "POST", uri.trim());
554 public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
555 String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
556 return callPAP(null, "POST", uri.trim());