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.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.onap.portalsdk.core.controller.RestrictedBaseController;
56 import org.onap.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;
69 import org.onap.policy.utils.CryptoUtils;
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 PolicyRestController(){
92 private PolicyRestController(CommonClassDao commonClassDao){
93 PolicyRestController.commonClassDao = commonClassDao;
96 public static CommonClassDao getCommonClassDao() {
97 return commonClassDao;
100 public static void setCommonClassDao(CommonClassDao commonClassDao) {
101 PolicyRestController.commonClassDao = commonClassDao;
106 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
107 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
108 String userId = UserUtils.getUserSession(request).getOrgUserId();
109 ObjectMapper mapper = new ObjectMapper();
110 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
112 JsonNode root = mapper.readTree(request.getReader());
114 policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
115 policyLogger.info("UserId: " + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
116 policyLogger.info("***********************************************************************************************************************************");
118 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
120 if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){
121 policyData.setEditPolicy(true);
123 if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){
125 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){
126 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator;
128 if(policyData.isEditPolicy()){
129 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
131 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", ""));
134 String domain = root.get(PolicyController.getPolicydata()).get(modal).get("name").toString();
135 if(domain.contains("/")){
136 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
138 domain = domain.replace("\"", "");
139 policyData.setDomainDir(domain);
142 if(policyData.getConfigPolicyType() != null){
143 if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
144 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
145 }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
146 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
147 }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
148 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
152 policyData.setUserId(userId);
155 String body = PolicyUtils.objectToJsonString(policyData);
156 String uri = request.getRequestURI();
157 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
158 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
159 result = "PolicyExists";
160 }else if(responseEntity != null){
161 result = responseEntity.getBody().toString();
162 String policyName = responseEntity.getHeaders().get("policyName").get(0);
163 if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){
164 PolicyNotificationMail email = new PolicyNotificationMail();
165 String mode = "EditPolicy";
166 String watchPolicyName = policyName.replace(".xml", "");
167 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
168 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
169 String policyVersionName = watchPolicyName.replace(".", File.separator);
170 watchPolicyName = watchPolicyName + "." + version + ".xml";
171 PolicyVersion entityItem = new PolicyVersion();
172 entityItem.setPolicyName(policyVersionName);
173 entityItem.setActiveVersion(Integer.parseInt(version));
174 entityItem.setModifiedBy(userId);
175 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
178 result = "Response is null from PAP";
181 response.setCharacterEncoding(PolicyController.getCharacterencoding());
182 response.setContentType(PolicyController.getContenttype());
183 request.setCharacterEncoding(PolicyController.getCharacterencoding());
185 PrintWriter out = response.getWriter();
186 String responseString = mapper.writeValueAsString(result);
187 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
188 out.write(j.toString());
190 policyLogger.error("Exception Occured while saving policy" , e);
195 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
196 String papUrl = PolicyController.getPapUrl();
197 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
198 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
200 Base64.Encoder encoder = Base64.getEncoder();
201 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
202 HttpHeaders headers = new HttpHeaders();
203 headers.set("Authorization", "Basic " + encoding);
204 headers.set("Content-Type", PolicyController.getContenttype());
206 RestTemplate restTemplate = new RestTemplate();
207 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
208 ResponseEntity<?> result = null;
209 HttpClientErrorException exception = null;
210 String uri = requestURI;
211 if(uri.startsWith("/")){
212 uri = uri.substring(uri.indexOf('/')+1);
214 uri = "onap" + uri.substring(uri.indexOf('/'));
216 result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
218 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
219 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
220 if("409 Conflict".equals(e.getMessage())){
221 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
224 if(exception != null && exception.getStatusCode()!=null){
225 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
226 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
227 policyLogger.error(message);
229 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
230 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
231 policyLogger.error(message);
233 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
234 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
235 policyLogger.error(message);
237 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
238 policyLogger.error(message);
243 private String callPAP(HttpServletRequest request , String method, String uriValue){
244 String uri = uriValue;
245 String boundary = null;
246 String papUrl = PolicyController.getPapUrl();
247 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
248 String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
250 Base64.Encoder encoder = Base64.getEncoder();
251 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
252 HttpHeaders headers = new HttpHeaders();
253 headers.set("Authorization", "Basic " + encoding);
254 headers.set("Content-Type", PolicyController.getContenttype());
257 HttpURLConnection connection = null;
258 List<FileItem> items;
259 FileItem item = null;
261 if(uri.contains(importDictionary)){
263 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
265 file = new File(item.getName());
266 String newFile = file.toString();
267 uri = uri +"&dictionaryName="+newFile;
268 } catch (Exception e2) {
269 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
274 URL url = new URL(papUrl + uri);
275 connection = (HttpURLConnection)url.openConnection();
276 connection.setRequestMethod(method);
277 connection.setUseCaches(false);
278 connection.setInstanceFollowRedirects(false);
279 connection.setRequestProperty("Authorization", "Basic " + encoding);
280 connection.setDoOutput(true);
281 connection.setDoInput(true);
283 if(!uri.contains("searchPolicy?action=delete&")){
285 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
286 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
287 ObjectMapper mapper = new ObjectMapper();
288 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
289 JsonNode root = null;
291 root = mapper.readTree(request.getReader());
292 }catch (Exception e1) {
293 policyLogger.error("Exception Occured while calling PAP"+e1);
296 ObjectMapper mapper1 = new ObjectMapper();
297 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
299 Object obj = mapper1.treeToValue(root, Object.class);
300 String json = mapper1.writeValueAsString(obj);
302 Object content = new ByteArrayInputStream(json.getBytes());
304 if (content instanceof InputStream) {
305 // send current configuration
306 try (OutputStream os = connection.getOutputStream()) {
307 int count = IOUtils.copy((InputStream) content, os);
308 if (policyLogger.isDebugEnabled()) {
309 policyLogger.debug("copied to output, bytes=" + count);
314 if(uri.endsWith("set_BRMSParamData")){
315 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
316 try (OutputStream os = connection.getOutputStream()) {
317 IOUtils.copy((InputStream) request.getInputStream(), os);
320 boundary = "===" + System.currentTimeMillis() + "===";
321 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
322 try (OutputStream os = connection.getOutputStream()) {
324 IOUtils.copy((InputStream) item.getInputStream(), os);
331 connection.connect();
333 int responseCode = connection.getResponseCode();
334 if(responseCode == 200){
335 // get the response content into a String
336 String responseJson = null;
337 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
338 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
339 scanner.useDelimiter("\\A");
340 responseJson = scanner.hasNext() ? scanner.next() : "";
342 policyLogger.info("JSON response from PAP: " + responseJson);
346 } catch (Exception e) {
347 policyLogger.error("Exception Occured"+e);
349 if(file != null && file.exists() && file.delete()){
350 policyLogger.info("File Deleted Successfully");
352 if (connection != null) {
354 // For some reason trying to get the inputStream from the connection
355 // throws an exception rather than returning null when the InputStream does not exist.
356 InputStream is = connection.getInputStream();
360 } catch (IOException ex) {
361 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
363 connection.disconnect();
369 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
370 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
371 String uri = request.getRequestURI().replace("/getDictionary", "");
373 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
374 if(responseEntity != null){
375 body = responseEntity.getBody().toString();
380 response.getWriter().write(body);
381 } catch (IOException e) {
382 policyLogger.error("Exception occured while getting Dictionary entries", e);
386 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
387 public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
389 String uri = request.getRequestURI().replace("/saveDictionary", "");
390 if(uri.startsWith("/")){
391 uri = uri.substring(uri.indexOf('/')+1);
393 uri = "/onap" + uri.substring(uri.indexOf('/'));
394 if(uri.contains(importDictionary)){
395 userId = UserUtils.getUserSession(request).getOrgUserId();
396 uri = uri+ "?userId=" +userId;
399 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
400 policyLogger.info("UserId: " + userId);
401 policyLogger.info("***********************************************************************************************************************************");
403 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
404 if(body != null && !body.isEmpty()){
405 response.getWriter().write(body);
407 response.getWriter().write("Failed");
411 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
412 public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
413 String uri = request.getRequestURI().replace("/deleteDictionary", "");
414 if(uri.startsWith("/")){
415 uri = uri.substring(uri.indexOf('/')+1);
417 uri = "/onap" + uri.substring(uri.indexOf('/'));
419 String userId = UserUtils.getUserSession(request).getOrgUserId();
420 policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
421 policyLogger.info("UserId: " + userId);
422 policyLogger.info("*************************************************************************************************************************************");
424 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
425 if(body != null && !body.isEmpty()){
426 response.getWriter().write(body);
428 response.getWriter().write("Failed");
432 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
433 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
435 String uri = request.getRequestURI();
436 if(uri.startsWith("/")){
437 uri = uri.substring(uri.indexOf('/')+1);
439 uri = "/onap" + uri.substring(uri.indexOf('/'));
441 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
442 if(body.contains("CouldNotConnectException")){
443 List<String> data = new ArrayList<>();
444 data.add("Elastic Search Server is down");
447 JSONObject json = new JSONObject(body);
448 resultList = json.get("policyresult");
451 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
452 List<String> data = new ArrayList<>();
453 data.add("Elastic Search Server is down");
457 response.setCharacterEncoding(PolicyController.getCharacterencoding());
458 response.setContentType(PolicyController.getContenttype());
459 PrintWriter out = response.getWriter();
460 JSONObject j = new JSONObject("{result: " + resultList + "}");
461 out.write(j.toString());
465 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
466 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
468 String uri = request.getRequestURI()+"?action=search";
469 if(uri.startsWith("/")){
470 uri = uri.substring(uri.indexOf('/')+1);
472 uri = "/onap" + uri.substring(uri.indexOf('/'));
473 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
475 JSONObject json = new JSONObject(body);
477 resultList = json.get("policyresult");
479 List<String> data = new ArrayList<>();
480 resultList = json.get("data");
481 data.add("Exception");
482 data.add(resultList.toString());
484 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
487 response.setCharacterEncoding("UTF-8");
488 response.setContentType("application / json");
489 request.setCharacterEncoding("UTF-8");
491 PrintWriter out = response.getWriter();
492 JSONObject j = new JSONObject("{result: " + resultList + "}");
493 out.write(j.toString());
497 public void deleteElasticData(String fileName){
498 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
499 callPAP(null, "POST", uri.trim());
502 public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
503 String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
504 return callPAP(null, "POST", uri.trim());