2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.CreateOptimizationController;
49 import org.onap.policy.controller.PolicyController;
50 import org.onap.policy.rest.XACMLRestProperties;
51 import org.onap.policy.rest.adapter.PolicyRestAdapter;
52 import org.onap.policy.rest.dao.CommonClassDao;
53 import org.onap.policy.rest.jpa.PolicyVersion;
54 import org.onap.policy.utils.PolicyUtils;
55 import org.onap.policy.xacml.api.XACMLErrorConstants;
56 import org.onap.portalsdk.core.controller.RestrictedBaseController;
57 import org.onap.portalsdk.core.web.support.UserUtils;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.HttpEntity;
60 import org.springframework.http.HttpHeaders;
61 import org.springframework.http.HttpMethod;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.http.ResponseEntity;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RequestMethod;
66 import org.springframework.web.bind.annotation.RestController;
67 import org.springframework.web.client.HttpClientErrorException;
68 import org.springframework.web.client.RestTemplate;
69 import org.springframework.web.servlet.ModelAndView;
70 import org.onap.policy.utils.CryptoUtils;
71 import com.att.research.xacml.util.XACMLProperties;
72 import com.fasterxml.jackson.databind.DeserializationFeature;
73 import com.fasterxml.jackson.databind.JsonNode;
74 import com.fasterxml.jackson.databind.ObjectMapper;
75 import com.fasterxml.jackson.databind.SerializationFeature;
79 public class PolicyRestController extends RestrictedBaseController{
81 private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
83 private static final String model = "model";
84 private static final String importDictionary = "import_dictionary";
86 private static CommonClassDao commonClassDao;
88 public PolicyRestController(){
93 private PolicyRestController(CommonClassDao commonClassDao){
94 PolicyRestController.commonClassDao = commonClassDao;
97 public static CommonClassDao getCommonClassDao() {
98 return commonClassDao;
101 public static void setCommonClassDao(CommonClassDao commonClassDao) {
102 PolicyRestController.commonClassDao = commonClassDao;
107 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
108 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
109 String userId = UserUtils.getUserSession(request).getOrgUserId();
110 ObjectMapper mapper = new ObjectMapper();
111 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
113 JsonNode root = mapper.readTree(request.getReader());
115 policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
116 policyLogger.info("UserId: " + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
117 policyLogger.info("***********************************************************************************************************************************");
119 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
121 if("file".equals(root.get(PolicyController.getPolicydata()).get(model).get("type").toString().replace("\"", ""))){
122 policyData.setEditPolicy(true);
124 if(root.get(PolicyController.getPolicydata()).get(model).get("path").size() != 0){
126 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(model).get("path").size(); i++){
127 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(model).get("path").get(i).toString().replace("\"", "") + File.separator;
129 if(policyData.isEditPolicy()){
130 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
132 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(model).get("name").toString().replace("\"", ""));
135 String domain = root.get(PolicyController.getPolicydata()).get(model).get("name").toString();
136 if(domain.contains("/")){
137 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
139 domain = domain.replace("\"", "");
140 policyData.setDomainDir(domain);
143 if(policyData.getConfigPolicyType() != null){
144 if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
145 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
146 }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
147 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
148 }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
149 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
150 }else if("Optimization".equalsIgnoreCase(policyData.getConfigPolicyType())){
151 policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
155 policyData.setUserId(userId);
158 String body = PolicyUtils.objectToJsonString(policyData);
159 String uri = request.getRequestURI();
160 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
161 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
162 result = "PolicyExists";
163 }else if(responseEntity != null){
164 result = responseEntity.getBody().toString();
165 String policyName = responseEntity.getHeaders().get("policyName").get(0);
166 if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){
167 PolicyNotificationMail email = new PolicyNotificationMail();
168 String mode = "EditPolicy";
169 String watchPolicyName = policyName.replace(".xml", "");
170 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
171 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
172 String policyVersionName = watchPolicyName.replace(".", File.separator);
173 watchPolicyName = watchPolicyName + "." + version + ".xml";
174 PolicyVersion entityItem = new PolicyVersion();
175 entityItem.setPolicyName(policyVersionName);
176 entityItem.setActiveVersion(Integer.parseInt(version));
177 entityItem.setModifiedBy(userId);
178 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
181 result = "Response is null from PAP";
184 response.setCharacterEncoding(PolicyController.getCharacterencoding());
185 response.setContentType(PolicyController.getContenttype());
186 request.setCharacterEncoding(PolicyController.getCharacterencoding());
188 PrintWriter out = response.getWriter();
189 String responseString = mapper.writeValueAsString(result);
190 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
191 out.write(j.toString());
193 policyLogger.error("Exception Occured while saving policy" , e);
198 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
199 String papUrl = PolicyController.getPapUrl();
200 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
201 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
203 Base64.Encoder encoder = Base64.getEncoder();
204 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
205 HttpHeaders headers = new HttpHeaders();
206 headers.set("Authorization", "Basic " + encoding);
207 headers.set("Content-Type", PolicyController.getContenttype());
209 RestTemplate restTemplate = new RestTemplate();
210 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
211 ResponseEntity<?> result = null;
212 HttpClientErrorException exception = null;
213 String uri = requestURI;
214 if(uri.startsWith("/")){
215 uri = uri.substring(uri.indexOf('/')+1);
217 uri = "onap" + uri.substring(uri.indexOf('/'));
219 result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
221 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
222 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
223 if("409 Conflict".equals(e.getMessage())){
224 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
227 if(exception != null && exception.getStatusCode()!=null){
228 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
229 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
230 policyLogger.error(message);
232 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
233 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
234 policyLogger.error(message);
236 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
237 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
238 policyLogger.error(message);
240 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
241 policyLogger.error(message);
246 private String callPAP(HttpServletRequest request , String method, String uriValue){
247 String uri = uriValue;
248 String boundary = null;
249 String papUrl = PolicyController.getPapUrl();
250 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
251 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
253 Base64.Encoder encoder = Base64.getEncoder();
254 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
255 HttpHeaders headers = new HttpHeaders();
256 headers.set("Authorization", "Basic " + encoding);
257 headers.set("Content-Type", PolicyController.getContenttype());
260 HttpURLConnection connection = null;
261 List<FileItem> items;
262 FileItem item = null;
264 if(uri.contains(importDictionary)){
266 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
268 file = new File(item.getName());
269 String newFile = file.toString();
270 uri = uri +"&dictionaryName="+newFile;
271 } catch (Exception e2) {
272 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
277 URL url = new URL(papUrl + uri);
278 connection = (HttpURLConnection)url.openConnection();
279 connection.setRequestMethod(method);
280 connection.setUseCaches(false);
281 connection.setInstanceFollowRedirects(false);
282 connection.setRequestProperty("Authorization", "Basic " + encoding);
283 connection.setDoOutput(true);
284 connection.setDoInput(true);
286 if(!uri.contains("searchPolicy?action=delete&")){
288 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
289 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
290 ObjectMapper mapper = new ObjectMapper();
291 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
292 JsonNode root = getJsonNode(request, mapper);
294 ObjectMapper mapper1 = new ObjectMapper();
295 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
297 Object obj = mapper1.treeToValue(root, Object.class);
298 String json = mapper1.writeValueAsString(obj);
300 Object content = new ByteArrayInputStream(json.getBytes());
302 if (content instanceof InputStream) {
303 // send current configuration
304 try (OutputStream os = connection.getOutputStream()) {
305 int count = IOUtils.copy((InputStream) content, os);
306 if (policyLogger.isDebugEnabled()) {
307 policyLogger.debug("copied to output, bytes=" + count);
312 if(uri.endsWith("set_BRMSParamData")){
313 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
314 try (OutputStream os = connection.getOutputStream()) {
315 IOUtils.copy((InputStream) request.getInputStream(), os);
318 boundary = "===" + System.currentTimeMillis() + "===";
319 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
320 try (OutputStream os = connection.getOutputStream()) {
322 IOUtils.copy((InputStream) item.getInputStream(), os);
328 return doConnect(connection);
329 } catch (Exception e) {
330 policyLogger.error("Exception Occured"+e);
332 if(file != null && file.exists() && file.delete()){
333 policyLogger.info("File Deleted Successfully");
335 if (connection != null) {
337 // For some reason trying to get the inputStream from the connection
338 // throws an exception rather than returning null when the InputStream does not exist.
339 InputStream is = connection.getInputStream();
343 } catch (IOException ex) {
344 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
346 connection.disconnect();
352 private JsonNode getJsonNode(HttpServletRequest request, ObjectMapper mapper) {
353 JsonNode root = null;
355 root = mapper.readTree(request.getReader());
356 }catch (Exception e1) {
357 policyLogger.error("Exception Occured while calling PAP"+e1);
362 private String doConnect(final HttpURLConnection connection) throws IOException{
363 connection.connect();
364 int responseCode = connection.getResponseCode();
365 if(responseCode == 200){
366 // get the response content into a String
367 String responseJson = null;
368 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
369 try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
370 scanner.useDelimiter("\\A");
371 responseJson = scanner.hasNext() ? scanner.next() : "";
372 } catch (Exception e){
373 //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
374 //then the exception handling is done by the outer block without returning the response immediately
375 //Also finally block is existing only in outer block and not here so all exception handling is
376 //done in only one place
377 policyLogger.error("Exception Occured"+e);
381 policyLogger.info("JSON response from PAP: " + responseJson);
387 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
388 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
389 String uri = request.getRequestURI().replace("/getDictionary", "");
391 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
392 if(responseEntity != null){
393 body = responseEntity.getBody().toString();
398 response.getWriter().write(body);
399 } catch (IOException e) {
400 policyLogger.error("Exception occured while getting Dictionary entries", e);
404 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
405 public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
407 String uri = request.getRequestURI().replace("/saveDictionary", "");
408 if(uri.startsWith("/")){
409 uri = uri.substring(uri.indexOf('/')+1);
411 uri = "/onap" + uri.substring(uri.indexOf('/'));
412 if(uri.contains(importDictionary)){
413 userId = UserUtils.getUserSession(request).getOrgUserId();
414 uri = uri+ "?userId=" +userId;
417 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
418 policyLogger.info("UserId: " + userId);
419 policyLogger.info("***********************************************************************************************************************************");
421 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
422 if(body != null && !body.isEmpty()){
423 response.getWriter().write(body);
425 response.getWriter().write("Failed");
429 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
430 public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
431 String uri = request.getRequestURI().replace("/deleteDictionary", "");
432 if(uri.startsWith("/")){
433 uri = uri.substring(uri.indexOf('/')+1);
435 uri = "/onap" + uri.substring(uri.indexOf('/'));
437 String userId = UserUtils.getUserSession(request).getOrgUserId();
438 policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
439 policyLogger.info("UserId: " + userId);
440 policyLogger.info("*************************************************************************************************************************************");
442 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
443 if(body != null && !body.isEmpty()){
444 response.getWriter().write(body);
446 response.getWriter().write("Failed");
450 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
451 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
453 String uri = request.getRequestURI();
454 if(uri.startsWith("/")){
455 uri = uri.substring(uri.indexOf('/')+1);
457 uri = "/onap" + uri.substring(uri.indexOf('/'));
459 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
460 if(body.contains("CouldNotConnectException")){
461 List<String> data = new ArrayList<>();
462 data.add("Elastic Search Server is down");
465 JSONObject json = new JSONObject(body);
466 resultList = json.get("policyresult");
469 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
470 List<String> data = new ArrayList<>();
471 data.add("Elastic Search Server is down");
475 response.setCharacterEncoding(PolicyController.getCharacterencoding());
476 response.setContentType(PolicyController.getContenttype());
477 PrintWriter out = response.getWriter();
478 JSONObject j = new JSONObject("{result: " + resultList + "}");
479 out.write(j.toString());
483 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
484 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
486 String uri = request.getRequestURI()+"?action=search";
487 if(uri.startsWith("/")){
488 uri = uri.substring(uri.indexOf('/')+1);
490 uri = "/onap" + uri.substring(uri.indexOf('/'));
491 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
493 JSONObject json = new JSONObject(body);
495 resultList = json.get("policyresult");
497 List<String> data = new ArrayList<>();
498 resultList = json.get("data");
499 data.add("Exception");
500 data.add(resultList.toString());
502 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
505 response.setCharacterEncoding("UTF-8");
506 response.setContentType("application / json");
507 request.setCharacterEncoding("UTF-8");
509 PrintWriter out = response.getWriter();
510 JSONObject j = new JSONObject("{result: " + resultList + "}");
511 out.write(j.toString());
515 public void deleteElasticData(String fileName){
516 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
517 callPAP(null, "POST", uri.trim());
520 public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
521 String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
522 return callPAP(null, "POST", uri.trim());