New Optimization Policy
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / PolicyRestController.java
index e99f35b..8df9d1b 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -45,6 +45,7 @@ import org.onap.policy.common.logging.flexlogger.Logger;
 import org.onap.policy.controller.CreateClosedLoopFaultController;
 import org.onap.policy.controller.CreateDcaeMicroServiceController;
 import org.onap.policy.controller.CreateFirewallController;
+import org.onap.policy.controller.CreateOptimizationController;
 import org.onap.policy.controller.PolicyController;
 import org.onap.policy.rest.XACMLRestProperties;
 import org.onap.policy.rest.adapter.PolicyRestAdapter;
@@ -52,8 +53,8 @@ import org.onap.policy.rest.dao.CommonClassDao;
 import org.onap.policy.rest.jpa.PolicyVersion;
 import org.onap.policy.utils.PolicyUtils;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.web.support.UserUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
@@ -66,7 +67,7 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.client.HttpClientErrorException;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.servlet.ModelAndView;
-
+import org.onap.policy.utils.CryptoUtils;
 import com.att.research.xacml.util.XACMLProperties;
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
@@ -79,11 +80,29 @@ public class PolicyRestController extends RestrictedBaseController{
 
        private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
        
-       private static final String modal = "model";
+       private static final String model = "model";
        private static final String importDictionary = "import_dictionary";
        
+       private static CommonClassDao commonClassDao;
+       
+       public PolicyRestController(){
+               //default constructor
+       }
+
        @Autowired
-       CommonClassDao commonClassDao;
+       private PolicyRestController(CommonClassDao commonClassDao){
+               PolicyRestController.commonClassDao = commonClassDao;
+       }
+       
+       public static CommonClassDao getCommonClassDao() {
+               return commonClassDao;
+       }
+
+       public static void setCommonClassDao(CommonClassDao commonClassDao) {
+               PolicyRestController.commonClassDao = commonClassDao;
+       }
+       
+
 
        @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
        public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
@@ -92,24 +111,28 @@ public class PolicyRestController extends RestrictedBaseController{
                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                try{
                        JsonNode root = mapper.readTree(request.getReader());
-
+                       
+                       policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
+                       policyLogger.info("UserId:  " + userId + "Policy Data Object:  "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
+                       policyLogger.info("***********************************************************************************************************************************");
+                       
                        PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
 
-                       if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){
+                       if("file".equals(root.get(PolicyController.getPolicydata()).get(model).get("type").toString().replace("\"", ""))){
                                policyData.setEditPolicy(true);
                        }
-                       if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){
+                       if(root.get(PolicyController.getPolicydata()).get(model).get("path").size() != 0){
                                String dirName = "";
-                               for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){
-                                       dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator;
+                               for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(model).get("path").size(); i++){
+                                       dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(model).get("path").get(i).toString().replace("\"", "") + File.separator;
                                }
                                if(policyData.isEditPolicy()){
                                        policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
                                }else{
-                                       policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", ""));
+                                       policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(model).get("name").toString().replace("\"", ""));
                                }
                        }else{
-                               String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString();
+                               String domain = root.get(PolicyController.getPolicydata()).get(model).get("name").toString();
                                if(domain.contains("/")){
                                        domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
                                }
@@ -119,14 +142,13 @@ public class PolicyRestController extends RestrictedBaseController{
 
                        if(policyData.getConfigPolicyType() != null){
                                if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
-                                       CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
-                                       policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
+                                       policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
                                }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
-                                       CreateFirewallController fwController = new CreateFirewallController();
-                                       policyData = fwController.setDataToPolicyRestAdapter(policyData);
+                                       policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
                                }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
-                                       CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
-                                       policyData = msController.setDataToPolicyRestAdapter(policyData, root);
+                                       policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
+                               }else if("Optimization".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
                                }
                        }
 
@@ -176,7 +198,7 @@ public class PolicyRestController extends RestrictedBaseController{
        private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
                String papUrl = PolicyController.getPapUrl();
                String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
-               String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
+               String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
 
                Base64.Encoder encoder = Base64.getEncoder();
                String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
@@ -188,9 +210,13 @@ public class PolicyRestController extends RestrictedBaseController{
                HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
                ResponseEntity<?> result = null;
                HttpClientErrorException exception = null;
-       
+               String uri = requestURI;
+               if(uri.startsWith("/")){
+                       uri = uri.substring(uri.indexOf('/')+1);
+               }
+               uri = "onap" + uri.substring(uri.indexOf('/'));
                try{
-                       result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class);
+                       result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
                }catch(Exception e){
                        policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
                        exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
@@ -222,7 +248,7 @@ public class PolicyRestController extends RestrictedBaseController{
                String boundary = null;
                String papUrl = PolicyController.getPapUrl();
                String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
-               String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
+               String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
        
                Base64.Encoder encoder = Base64.getEncoder();
                String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
@@ -346,7 +372,7 @@ public class PolicyRestController extends RestrictedBaseController{
        @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
        public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
                String uri = request.getRequestURI().replace("/getDictionary", "");
-               String body = null;
+               String body;
                ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
                if(responseEntity != null){
                        body = responseEntity.getBody().toString();
@@ -361,29 +387,59 @@ public class PolicyRestController extends RestrictedBaseController{
        }
        
        @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
-       public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
+       public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
+               String userId = "";
                String uri = request.getRequestURI().replace("/saveDictionary", "");
+               if(uri.startsWith("/")){
+                       uri = uri.substring(uri.indexOf('/')+1);
+               }
+               uri = "/onap" + uri.substring(uri.indexOf('/'));
                if(uri.contains(importDictionary)){
-                       String userId = UserUtils.getUserSession(request).getOrgUserId();
+                       userId = UserUtils.getUserSession(request).getOrgUserId();
                        uri = uri+ "?userId=" +userId;
                }
+               
+               policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
+               policyLogger.info("UserId:  " + userId);
+               policyLogger.info("***********************************************************************************************************************************");
+               
                String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
-               response.getWriter().write(body);
-               return null;
+               if(body != null && !body.isEmpty()){
+                       response.getWriter().write(body);
+               }else{
+                       response.getWriter().write("Failed");
+               }               
        }
        
        @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
-       public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
+       public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
                String uri = request.getRequestURI().replace("/deleteDictionary", "");
+               if(uri.startsWith("/")){
+                       uri = uri.substring(uri.indexOf('/')+1);
+               }
+               uri = "/onap" + uri.substring(uri.indexOf('/'));
+               
+               String userId = UserUtils.getUserSession(request).getOrgUserId();
+               policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
+               policyLogger.info("UserId:  " + userId);
+               policyLogger.info("*************************************************************************************************************************************");
+               
                String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
-               response.getWriter().write(body);
-               return null;
+               if(body != null && !body.isEmpty()){
+                       response.getWriter().write(body);
+               }else{
+                       response.getWriter().write("Failed");
+               }               
        }
        
        @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
-       public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
-               Object resultList = null;
+       public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
+               Object resultList;
                String uri = request.getRequestURI();
+               if(uri.startsWith("/")){
+                       uri = uri.substring(uri.indexOf('/')+1);
+               }
+               uri = "/onap" + uri.substring(uri.indexOf('/'));
                try{
                        String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
                        if(body.contains("CouldNotConnectException")){
@@ -410,9 +466,13 @@ public class PolicyRestController extends RestrictedBaseController{
        }
        
        @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
-       public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
-               Object resultList = null;
+       public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
+               Object resultList;
                String uri = request.getRequestURI()+"?action=search";
+               if(uri.startsWith("/")){
+                       uri = uri.substring(uri.indexOf('/')+1);
+               }
+               uri = "/onap" + uri.substring(uri.indexOf('/'));
                String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
 
                JSONObject json = new JSONObject(body);
@@ -420,7 +480,9 @@ public class PolicyRestController extends RestrictedBaseController{
                        resultList = json.get("policyresult");
                }catch(Exception e){
                        List<String> data = new ArrayList<>();
-                       data.add("Elastic Search Server is down");
+                       resultList = json.get("data");
+                       data.add("Exception");
+                       data.add(resultList.toString());
                        resultList = data;
                        policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
                }
@@ -439,5 +501,10 @@ public class PolicyRestController extends RestrictedBaseController{
                String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
                callPAP(null, "POST", uri.trim());
        }
+       
+       public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
+               String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
+               return callPAP(null, "POST", uri.trim());
+       }
 
-}
\ No newline at end of file
+}