Refactor to provide Common Policy Validation 75/25175/4
authorMichael Mokry <mm117s@att.com>
Tue, 14 Nov 2017 21:01:13 +0000 (15:01 -0600)
committerMichael Mokry <mm117s@att.com>
Mon, 4 Dec 2017 15:19:21 +0000 (15:19 +0000)
Provides a common class to perform policy validation during
create/udpate of policies by the GUI and API for consistency.

Change-Id: Ied459e73d48517bb50064cd10d6a1c871b8311e5
Issue-ID: POLICY-449
Signed-off-by: Michael Mokry <mm117s@att.com>
17 files changed:
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java
ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java
ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java
ONAP-REST/pom.xml
ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java
ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPMBody.java
ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java
ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java [new file with mode: 0644]
ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java [new file with mode: 0644]
ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java [new file with mode: 0644]
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSRawPolicyTemplate.html

index 1766cb3..c714821 100644 (file)
@@ -44,9 +44,12 @@ import org.onap.policy.rest.jpa.GroupPolicyScopeList;
 import org.onap.policy.rest.jpa.PolicyRoles;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Primary;
+import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Service;
 
 @Service("CommonClassDao")
+@Primary
 public class CommonClassDaoImpl implements CommonClassDao{
 
        private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class);
@@ -54,6 +57,7 @@ public class CommonClassDaoImpl implements CommonClassDao{
        
        private static SessionFactory sessionFactory;
        
+       
        @Autowired
        private CommonClassDaoImpl(SessionFactory sessionFactory){
                CommonClassDaoImpl.sessionFactory = sessionFactory;
index 528e5cd..483e13c 100644 (file)
@@ -23,14 +23,20 @@ import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.UUID;
 
+import org.glassfish.jersey.spi.Contract;
 import org.onap.policy.api.PolicyException;
 import org.onap.policy.api.PolicyParameters;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
 import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils;
-import org.onap.policy.utils.PolicyUtils;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.util.PolicyValidation;
+import org.onap.policy.rest.util.PolicyValidationRequestWrapper;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Controller;
+
+import com.google.common.base.Strings;
 
 public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService {
        private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.class.getName());
@@ -213,54 +219,83 @@ public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService
     }
 
     protected boolean getValidation() {
-        if(policyParameters == null){
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. ";
-            return false;
-        }
-        if(policyParameters.getPolicyName() == null){
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
-            return false;
-        }
-        if (policyParameters.getPolicyName().contains(".")) {
-            policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1,
-                    policyParameters.getPolicyName().length());
-            policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.'));
-            LOGGER.info("Name is " + policyName + "   scope is " + policyScope);
-        } else {
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
-            return false;
-        }
-        if (policyName==null||policyName.trim().isEmpty()){
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
-            return false;
-        }
-        message = PolicyUtils.policySpecialCharValidator(policyScope);
-        if(!message.contains("success")){
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
-            return false;
-        }
-        message = PolicyUtils.policySpecialCharValidator(policyName);
-        if(!message.contains("success")){
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
-            return false;
-        }
-        if(policyParameters.getPolicyDescription()!=null){
-            message = PolicyUtils.descriptionValidator(policyParameters.getPolicyDescription());
-            if(!message.contains("success")){
-                message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message;
-                return false;
-            }
-        }
-        if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.toString())){
-            message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "This requests contains Non ASCII Characters. Please review your input parameter"
-                    + " values and correct the illegal characters.";
-            return false;
-        }
+       
+       PolicyValidation validation = new PolicyValidation();
+       
+               StringBuilder responseString;
+               
+       if (policyParameters != null) {
+               
+               if (!Strings.isNullOrEmpty(policyParameters.getPolicyName())){
+                if (policyParameters.getPolicyName().contains(".")) {
+                    policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1,
+                            policyParameters.getPolicyName().length());
+                    policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.'));
+                    policyParameters.setPolicyName(policyName);
+                    LOGGER.info("Name is " + policyName + "   scope is " + policyScope);
+                } else {
+                    message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Scope: No Policy Scope given";
+                       LOGGER.error("Common validation did not return success:  " + message);
+                    return false;
+                }
+               } else {
+                       message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PolicyName: PolicyName Should not be empty";
+                       LOGGER.error("Common validation did not return success:  " + message);
+                       return false;
+               }
+               
+               if(policyParameters.getPolicyClass() != null){
+                       if ("Config".equals(policyParameters.getPolicyClass().toString())){
+                               String policyConfigType = policyParameters.getPolicyConfigType().toString();
+                               if(!"BRMS_Param".equalsIgnoreCase(policyConfigType)){
+                               if(Strings.isNullOrEmpty(policyParameters.getConfigBody())){
+                                       message = XACMLErrorConstants.ERROR_DATA_ISSUE + "ConfigBody: No Config Body given";
+                               LOGGER.error("Common validation did not return success:  " + message);
+                            return false;
+                               }
+                               }
+                       }
+               }
+
+               try {
+                       PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();                          
+                       PolicyRestAdapter policyData = wrapper.populateRequestParameters(policyParameters);
+                               responseString = validation.validatePolicy(policyData);
+                       } catch (Exception e) {
+                               LOGGER.error("Exception Occured during Policy Validation" +e);
+                               if(e.getMessage()!=null){
+                                       if("Action".equals(policyParameters.getPolicyClass().toString()) && e.getMessage().contains("Index:")){
+                                               message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Rule Algorithms: One or more Fields in Rule Algorithms is Empty.";
+                                       } else {
+                                               message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured During Policy Validation: " + e;
+                                       }
+                               }
+                               return false;
+                       }
+       } else {
+               message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. ";
+               return false;
+       }
+
         // Set some default Values. 
         if (policyParameters.getTtlDate()!=null){
             date = convertDate(policyParameters.getTtlDate());
         }
-        return true;
+        
+        if (responseString!=null){
+               if("success".equals(responseString.toString())||"success@#".equals(responseString.toString())){
+                       return true;
+               } else {
+                       message = XACMLErrorConstants.ERROR_DATA_ISSUE + PolicyApiUtils.formatResponse(responseString);
+                       LOGGER.error("Common validation did not return success:  " + message);
+                       return false;
+               }
+        } else {
+                       message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unknown Error Occured During Policy Validation";
+                       LOGGER.error(message);
+                       return false;
+        }
+
     }
     
     protected String convertDate(Date date) {
index 22d8873..4474039 100644 (file)
@@ -101,6 +101,7 @@ public class MicroServicesPolicyService{
         String policyDescription=null;
         String priority=null;
         String version=null;
+        
         if (microServiceAttributes.get("service")!=null){
                microService = microServiceAttributes.get("service").toString().replace("\"", "");
         }
index cd107d0..5477a8b 100644 (file)
@@ -53,7 +53,17 @@ public class PolicyApiUtils {
         }
         return isValidForm;
     }
-
+    
+    public static String formatResponse(StringBuilder responseString){
+       
+       LOGGER.info("Formatting response message from Policy Validator");
+               String response = null;
+       response = responseString.toString().replace("<br>", " | ");            
+               response = response.replaceAll("(<b>|<\\/b>|<br>|<i>|<\\/i>|@#)", "");
+                               
+       return response;
+    }
+    
     public static boolean isNumeric(String str) {
         for (char c : str.toCharArray()) {
             if (!Character.isDigit(c))
index 078cab2..b563c6c 100644 (file)
  */
 package org.onap.policy.pdp.rest.config;
 
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import javax.annotation.PostConstruct;
 import javax.servlet.MultipartConfigElement;
+import javax.sql.DataSource;
 
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.hibernate.SessionFactory;
 import org.onap.policy.common.logging.eelf.PolicyLogger;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
 import org.onap.policy.pdp.rest.api.controller.PolicyEngineServices;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.orm.hibernate4.HibernateTransactionManager;
+import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@@ -41,8 +55,31 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
 @Configuration
 @EnableWebMvc
 @EnableSwagger2
-@ComponentScan(basePackageClasses = PolicyEngineServices.class)
+@ComponentScan(basePackages = { "org.onap.*", "com.*" })
 public class PDPRestConfig extends WebMvcConfigurerAdapter{
+       
+       private static final Logger LOGGER      = FlexLogger.getLogger(PDPRestConfig.class);
+
+       private static String dbDriver = null;
+       private static String dbUrl = null;
+       private static String dbUserName = null;
+       private static String dbPassword = null;
+       
+       @PostConstruct
+       public void init(){
+               Properties prop = new Properties();
+               try (InputStream input = new FileInputStream("xacml.pdp.properties")){
+                       // load a properties file
+                       prop.load(input);
+                       setDbDriver(prop.getProperty("javax.persistence.jdbc.driver"));
+                       setDbUrl(prop.getProperty("javax.persistence.jdbc.url"));
+                       setDbUserName(prop.getProperty("javax.persistence.jdbc.user"));
+                       setDbPassword(prop.getProperty("javax.persistence.jdbc.password"));
+               }catch(Exception e){
+                       LOGGER.error("Exception Occured while loading properties file"+e);
+               }
+       }
+       
        @Override 
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
@@ -68,10 +105,74 @@ public class PDPRestConfig extends WebMvcConfigurerAdapter{
                 .apiInfo(apiInfo());
     }
     
+       @Bean(name = "dataSource")
+       public DataSource getDataSource() {
+           BasicDataSource dataSource = new BasicDataSource();
+           dataSource.setDriverClassName(PDPRestConfig.getDbDriver());
+           dataSource.setUrl(PDPRestConfig.getDbUrl());
+           dataSource.setUsername(PDPRestConfig.getDbUserName());
+           dataSource.setPassword(PDPRestConfig.getDbPassword());
+           return dataSource;
+       }
+       
+       @Autowired
+       @Bean(name = "sessionFactory")
+       public SessionFactory getSessionFactory(DataSource dataSource) {
+           LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
+           sessionBuilder.scanPackages("org.onap.*", "com.*");
+           sessionBuilder.addProperties(getHibernateProperties());
+           return sessionBuilder.buildSessionFactory();
+       }
+       
+       private Properties getHibernateProperties() {
+               Properties properties = new Properties();
+               properties.put("hibernate.show_sql", "true");
+               properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
+               return properties;
+       }
+       
+       @Autowired
+       @Bean(name = "transactionManager")
+       public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
+               return new HibernateTransactionManager(sessionFactory);
+       }
+    
     @Bean
     public MultipartConfigElement multipartConfigElement(){
         String location = System.getProperty("java.io.tmpdir");
         MultipartConfigElement mp = new MultipartConfigElement(location);
         return mp;
     }
+
+       public static String getDbDriver() {
+               return dbDriver;
+       }
+
+       public static void setDbDriver(String dbDriver) {
+               PDPRestConfig.dbDriver = dbDriver;
+       }
+
+       public static String getDbUrl() {
+               return dbUrl;
+       }
+
+       public static void setDbUrl(String dbUrl) {
+               PDPRestConfig.dbUrl = dbUrl;
+       }
+
+       public static String getDbUserName() {
+               return dbUserName;
+       }
+
+       public static void setDbUserName(String dbUserName) {
+               PDPRestConfig.dbUserName = dbUserName;
+       }
+
+       public static String getDbPassword() {
+               return dbPassword;
+       }
+
+       public static void setDbPassword(String dbPassword) {
+               PDPRestConfig.dbPassword = dbPassword;
+       }
 }
index ac8b269..8fea627 100644 (file)
@@ -453,9 +453,9 @@ public class PolicyEngineServicesTest {
                pep.setAttributes(attributes);
                pep.setRiskLevel("5");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                // Checks for BRMS Raw Policy
                pep.setPolicyConfigType(PolicyConfigType.BRMS_RAW);
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
@@ -469,9 +469,9 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setRiskLevel("5");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
@@ -505,11 +505,11 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setConfigName("configName");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                pep.setConfigBody("{'test':'test}");
                pep.setConfigBodyType(PolicyType.JSON);
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                Map<AttributeType, Map<String,String>> attributes = new HashMap<>();
                Map<String,String> matching = new HashMap<>();
                matching.put("key", "value");
@@ -517,7 +517,7 @@ public class PolicyEngineServicesTest {
                pep.setAttributes(attributes);
                pep.setConfigBody("testBody");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
@@ -546,15 +546,15 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setConfigBody("{\"onapname\":\"test\"}");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                pep.setRiskLevel("test");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setRiskLevel("4");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
@@ -588,15 +588,15 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setConfigBody("{\"onapname\":\"test\", \"serviceTypePolicyName\":\"value\"}");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                pep.setRiskLevel("test");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setRiskLevel("4");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
@@ -626,9 +626,9 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setConfigBody("{\"configName\":\"test\"}");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
@@ -659,10 +659,10 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setRiskLevel("4");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                pep.setConfigBody("{\"service\":\"test\",\"uuid\":\"test\",\"location\":\"test\",\"configName\":\"test\",\"description\":\"test\",\"priority\":\"test\",\"version\":\"test\"}");
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
@@ -708,18 +708,18 @@ public class PolicyEngineServicesTest {
                                .headers(headers)).andExpect(status().isBadRequest());
                pep.setOnapName("xyz");
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                attributes.remove(AttributeType.MATCHING);
                attributes.put(AttributeType.SETTINGS, matching);
                pep.setAttributes(attributes);
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                attributes.put(AttributeType.MATCHING, matching);
                pep.setAttributes(attributes);
                mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
                mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)
-                               .headers(headers)).andExpect(status().isInternalServerError());
+                               .headers(headers)).andExpect(status().isBadRequest());
        }
        
        @Test
index 8879cc6..3253081 100644 (file)
                        <version>${project.version}</version>
                        <artifactId>ONAP-XACML</artifactId>
                </dependency>
+               <dependency>
+                       <groupId>org.onap.policy.engine</groupId>
+                       <artifactId>PolicyEngineAPI</artifactId>
+                       <version>${project.version}</version>
+                       <exclusions>
+                               <exclusion>
+                                       <groupId>org.glassfish.tyrus</groupId>
+                                       <artifactId>tyrus-client</artifactId>
+                               </exclusion>
+                               <exclusion>
+                                       <groupId>org.glassfish.tyrus</groupId>
+                                       <artifactId>tyrus-container-grizzly-client</artifactId>
+                               </exclusion>
+                               <exclusion>
+                                       <groupId>javax.persistence</groupId>
+                                       <artifactId>persistence-api</artifactId>
+                               </exclusion>
+                               <exclusion>
+                                       <groupId>com.att.aft</groupId>
+                                       <artifactId>dme2</artifactId>
+                               </exclusion>
+                       </exclusions>
+               </dependency>
                <dependency>
                        <groupId>javax.servlet</groupId>
                        <artifactId>javax.servlet-api</artifactId>
                        <artifactId>json</artifactId>
                        <version>[20090211,)</version>
                </dependency>
+               <!-- Spring -->
+               <dependency>
+                       <groupId>org.springframework</groupId>
+                       <artifactId>spring-core</artifactId>
+                       <version>${springframework.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework</groupId>
+                       <artifactId>spring-web</artifactId>
+                       <version>${springframework.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework</groupId>
+                       <artifactId>spring-webmvc</artifactId>
+                       <version>${springframework.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework</groupId>
+                       <artifactId>spring-tx</artifactId>
+                       <version>${springframework.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework</groupId>
+                       <artifactId>spring-context-support</artifactId>
+                       <version>${springframework.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.springframework</groupId>
+                       <artifactId>spring-orm</artifactId>
+                       <version>${springframework.version}</version>
+               </dependency>
+               <!-- Hibernate -->
+               <dependency>
+                       <groupId>org.hibernate</groupId>
+                       <artifactId>hibernate-core</artifactId>
+                       <version>${hibernate.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.hibernate</groupId>
+                       <artifactId>hibernate-validator</artifactId>
+                       <version>5.1.3.Final</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.apache.tomcat</groupId>
+                       <artifactId>tomcat-dbcp</artifactId>
+                       <version>8.5.9</version>
+               </dependency>
        </dependencies>
+
+       <properties>
+               <springframework.version>4.2.0.RELEASE</springframework.version>
+               <hibernate.version>4.3.10.Final</hibernate.version>
+       </properties>
 </project>
index 80853af..3d85f9f 100644 (file)
@@ -27,7 +27,7 @@ public class ClosedLoopFaultBody {
        private boolean trinity;
        private boolean vUSP;
        private boolean mcr;
-       private boolean gama;
+       private boolean gamma;
        private boolean vDNS;
        
        private String vnfType;
@@ -49,19 +49,19 @@ public class ClosedLoopFaultBody {
        private ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI;
        private ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI;
        private int triggerTimeWindowUsedForUI;
-       private int verfificationTimeWindowUsedForUI;
+       private int verificationTimeWindowUsedForUI;
        private String pepName;
        private String pepAction;
        private String templateVersion;
-       private int trapMaxAgeUsedForUI;
+       private int trapMaxAge;
        
        
-       public Integer getTrapMaxAgeUsedForUI() {
-               return trapMaxAgeUsedForUI;
+       public Integer getTrapMaxAge() {
+               return trapMaxAge;
        }
 
-       public void setTrapMaxAgeUsedForUI(int trapMaxAgeUsedForUI) {
-               this.trapMaxAgeUsedForUI = trapMaxAgeUsedForUI;
+       public void setTrapMaxAge(int trapMaxAge) {
+               this.trapMaxAge = trapMaxAge;
        }
 
        public String getTemplateVersion() {
@@ -105,13 +105,13 @@ public class ClosedLoopFaultBody {
                this.triggerTimeWindowUsedForUI = triggerTimeWindowUsedForUI;
        }
 
-       public Integer getVerfificationTimeWindowUsedForUI() {
-               return verfificationTimeWindowUsedForUI;
+       public Integer getVerificationTimeWindowUsedForUI() {
+               return verificationTimeWindowUsedForUI;
        }
 
-       public void setVerfificationTimeWindowUsedForUI(
-                       int verfificationTimeWindowUsedForUI) {
-               this.verfificationTimeWindowUsedForUI = verfificationTimeWindowUsedForUI;
+       public void setVerificationTimeWindowUsedForUI(
+                       int verificationTimeWindowUsedForUI) {
+               this.verificationTimeWindowUsedForUI = verificationTimeWindowUsedForUI;
        }
 
        public String getONAPname(){
@@ -269,12 +269,12 @@ public class ClosedLoopFaultBody {
                this.mcr = mcr;
        }
 
-       public boolean isGama() {
-               return gama;
+       public boolean isGamma() {
+               return gamma;
        }
 
-       public void setGama(boolean gama) {
-               this.gama = gama;
+       public void setGamma(boolean gamma) {
+               this.gamma = gamma;
        }
 }
 
index 1898bc4..53a9b12 100644 (file)
@@ -28,7 +28,7 @@ public class ClosedLoopPMBody {
        private boolean trinity;
        private boolean vUSP;
        private boolean mcr;
-       private boolean gama;
+       private boolean gamma;
        private boolean vDNS;
        private String geoLink;
        private String vServices;
@@ -97,11 +97,11 @@ public class ClosedLoopPMBody {
                this.serviceTypePolicyName = serviceTypePolicyName;
        }
        
-       public boolean isGama() {
-               return gama;
+       public boolean isGamma() {
+               return gamma;
        }
-       public void setGama(boolean gama) {
-               this.gama = gama;
+       public void setGamma(boolean gamma) {
+               this.gamma = gamma;
        }
        public boolean isvDNS() {
                return vDNS;
index 9d05e39..6de0c9b 100644 (file)
@@ -139,6 +139,7 @@ public class PolicyRestAdapter {
        private String location = null;
     private String priority = null;
     private String msLocation = null;
+    private Object policyJSON = null;
     
     //BRMS Policies
     private String ruleName;
@@ -893,4 +894,16 @@ public class PolicyRestAdapter {
                public void setRainydayMap(Map<String,String> rainydayMap) {
                        this.rainydayMap = rainydayMap;
                }
+               /**
+                * @return the policyJSON
+                */
+               public Object getPolicyJSON() {
+                       return policyJSON;
+               }
+               /**
+                * @param policyJSON the policyJSON to set
+                */
+               public void setPolicyJSON(Object policyJSON) {
+                       this.policyJSON = policyJSON;
+               }
 }
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java b/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java
new file mode 100644 (file)
index 0000000..f6682eb
--- /dev/null
@@ -0,0 +1,410 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.rest.daoimpl;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.script.SimpleBindings;
+
+import org.hibernate.Criteria;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Conjunction;
+import org.hibernate.criterion.Disjunction;
+import org.hibernate.criterion.Projections;
+import org.hibernate.criterion.Restrictions;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.PolicyRoles;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.stereotype.Service;
+
+@Component
+public class PolicyValidationDaoImpl implements CommonClassDao{
+
+       private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationDaoImpl.class);
+       private static SessionFactory sessionfactory;
+    
+    public static SessionFactory getSessionfactory() {
+          return sessionfactory;
+    }
+
+    public static void setSessionfactory(SessionFactory sessionfactory) {
+          PolicyValidationDaoImpl.sessionfactory = sessionfactory;
+    }
+
+    @Autowired
+    private PolicyValidationDaoImpl(SessionFactory sessionfactory){
+          PolicyValidationDaoImpl.sessionfactory = sessionfactory;
+    }
+    
+    public PolicyValidationDaoImpl(){
+          //Default Constructor
+    }
+
+       @SuppressWarnings({ "unchecked", "rawtypes" })
+       @Override
+       public List<Object> getData(Class className) {
+               Session session = sessionfactory.openSession();
+               List<Object> data = null;
+               try{
+                       Criteria cr = session.createCriteria(className);
+                       data = cr.list();
+               }catch(Exception e){
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);  
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
+                       }
+               }
+               return data;
+       }
+
+
+       @SuppressWarnings({ "rawtypes", "unchecked" })
+       @Override
+       public List<Object> getDataById(Class className, String columnName, String key) {
+               Session session = sessionfactory.openSession();
+               List<Object> data = null;
+               try {
+                       Criteria cr = session.createCriteria(className);
+                       if(columnName.contains(":") && key.contains(":")){
+                               String[] columns = columnName.split(":");
+                               String[] keys = key.split(":");
+                               for(int i=0; i < columns.length; i++){
+                                       cr.add(Restrictions.eq(columns[i], keys[i]));
+                               }
+                       }else{
+                               cr.add(Restrictions.eq(columnName, key));       
+                       }
+                       data = cr.list();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);          
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               return data;
+       }
+       
+       @Override
+       public void save(Object entity) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               try {
+                       session.persist(entity);
+                       tx.commit();    
+               }catch(Exception e){
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving  data to Table"+e);   
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               
+       }
+
+       @Override
+       public void delete(Object entity) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               try {
+                       session.delete(entity);
+                       tx.commit();    
+               }catch(Exception e){
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e);        
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               
+       }
+
+
+       @Override
+       public void update(Object entity) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               try {
+                       session.update(entity);
+                       tx.commit();    
+               }catch(Exception e){
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e);  
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               
+       }
+
+
+       @SuppressWarnings({ "unchecked", "rawtypes" })
+       @Override
+       public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               List<Object> data = null;
+               String[] columnNames = null;
+               if(columnName != null && columnName.contains(":")){
+                       columnNames = columnName.split(":");
+               }
+               String[] values = null;
+               if(value != null && value.contains(":")){
+                       values = value.split(":");
+               }               
+               try {
+                       Criteria cr = session.createCriteria(className);
+                       if(columnNames != null && values != null && columnNames.length == values.length){
+                               for (int i = 0; i < columnNames.length; i++){
+                                       cr.add(Restrictions.eq(columnNames[i],values[i]));
+                               }
+                       }else{
+                               cr.add(Restrictions.eq(columnName,value));
+                       }
+                       data = cr.list();
+                       tx.commit();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className);    
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               return data;
+       }
+
+
+       @SuppressWarnings("unchecked")
+       @Override
+       public List<PolicyRoles> getUserRoles() {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               List<PolicyRoles> rolesData = null;
+               try {
+                       Criteria cr = session.createCriteria(PolicyRoles.class);                
+                       Disjunction disjunction = Restrictions.disjunction(); 
+                       Conjunction conjunction1  = Restrictions.conjunction();
+                       conjunction1.add(Restrictions.eq("role", "admin"));
+                       Conjunction conjunction2  = Restrictions.conjunction();
+                       conjunction2.add(Restrictions.eq("role", "editor"));    
+                       Conjunction conjunction3  = Restrictions.conjunction();
+                       conjunction3.add(Restrictions.eq("role", "guest"));     
+                       disjunction.add(conjunction1);
+                       disjunction.add(conjunction2);
+                       disjunction.add(conjunction3);
+                       rolesData = cr.add(disjunction).list();
+                       tx.commit();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e);      
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               return rolesData;
+       }
+
+
+       @Override
+       public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
+               return null;
+       }
+
+
+       @Override
+       public void deleteAll() {}
+
+       
+       @SuppressWarnings("unchecked")
+       @Override
+       public List<Object> getDataByQuery(String query, SimpleBindings params) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               List<Object> data = null;
+               try {
+                       Query hbquery = session.createQuery(query);
+                       for (Map.Entry<String, Object> paramPair : params.entrySet()) {
+                               if(paramPair.getValue() instanceof java.lang.Long){
+                                       hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
+                               }
+                               else{
+                                       hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
+                               }
+                       }
+                       data = hbquery.list();
+                       tx.commit();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e);
+                       throw e;
+               }finally{
+                       try{
+                               session.close();
+                       }catch(HibernateException e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               return data;
+       }
+
+
+       @SuppressWarnings("rawtypes")
+       @Override
+       public Object getEntityItem(Class className, String columnName, String key) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               Object data = null;
+               try {
+                       Criteria cr = session.createCriteria(className);
+                       if(columnName.contains(":") && key.contains(":")){
+                               String[] columns = columnName.split(":");
+                               String[] keys = key.split(":");
+                               for(int i=0; i < columns.length; i++){
+                                       cr.add(Restrictions.eq(columns[i], keys[i]));
+                               }
+                       }else{
+                               cr.add(Restrictions.eq(columnName, key));       
+                       }
+                       data = cr.list().get(0);
+                       tx.commit();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); 
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               return data;
+       }
+
+
+       @Override
+       public void updateClAlarms(String arg0, String arg1) {}
+
+
+       @Override
+       public void updateClYaml(String arg0, String arg1) {}
+
+
+       @Override
+       public void updateQuery(String query) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();    
+               try {
+                       Query hbquery = session.createQuery(query);
+                       hbquery.executeUpdate();
+                       tx.commit();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); 
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               
+       }
+
+
+       @SuppressWarnings({ "rawtypes", "unchecked" })
+       @Override
+       public List<String> getDataByColumn(Class className, String columnName) {
+               Session session = sessionfactory.openSession();
+               List<String> data = null;
+               try{
+                       Criteria cr = session.createCriteria(className);
+                       cr.setProjection(Projections.property(columnName));
+                       data = cr.list();
+               }catch(Exception e){
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e);  
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
+                       }
+               }
+               return data;
+       }
+
+
+       @SuppressWarnings({ "rawtypes", "unchecked" })
+       @Override
+       public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) {
+               Session session = sessionfactory.openSession();
+               Transaction tx = session.beginTransaction();
+               List<Object> entityData = null;
+               try {
+                       Criteria cr = session.createCriteria(className);                
+                       Disjunction disjunction = Restrictions.disjunction(); 
+                       List<Conjunction> conjunctionList = new ArrayList<>();
+                       String[] columNames = columnName.split(":");
+                       for(int i =0; i < data.size(); i++){
+                               String[] entiySplit = data.get(i).split(":");
+                               Conjunction conjunction = Restrictions.conjunction();
+                               conjunction.add(Restrictions.eq(columNames[0], entiySplit[0]));
+                               conjunction.add(Restrictions.eq(columNames[1], entiySplit[1]));
+                               conjunctionList.add(conjunction);
+                       }
+                       for(int j =0 ; j < conjunctionList.size(); j++){
+                               disjunction.add(conjunctionList.get(j));
+                       }
+                       entityData = cr.add(disjunction).list();
+                       tx.commit();
+               } catch (Exception e) {
+                       LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e);      
+               }finally{
+                       try{
+                               session.close();
+                       }catch(Exception e1){
+                               LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
+                       }
+               }
+               return entityData;
+       }
+
+}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java
new file mode 100644 (file)
index 0000000..223381a
--- /dev/null
@@ -0,0 +1,730 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.rest.util;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang.StringUtils;
+import org.json.JSONObject;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
+import org.onap.policy.rest.adapter.ClosedLoopPMBody;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.MicroServiceModels;
+import org.onap.policy.rest.jpa.SafePolicyWarning;
+import org.onap.policy.utils.PolicyUtils;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+
+@Service
+public class PolicyValidation {
+       
+       private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidation.class);
+       
+       public static final String CONFIG_POLICY = "Config";
+       public static final String ACTION_POLICY = "Action";
+       public static final String DECISION_POLICY = "Decision";
+       public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
+       public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
+       public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
+       public static final String MICROSERVICES="Micro Service";
+       public static final String FIREWALL="Firewall Config";
+       
+       private static Map<String, String> mapAttribute = new HashMap<>();
+       
+       private static CommonClassDao commonClassDao;
+       
+       @Autowired
+       public PolicyValidation(CommonClassDao commonClassDao){
+               PolicyValidation.commonClassDao = commonClassDao;
+       }
+       
+       /*
+        * This is an empty constructor
+        */
+       public PolicyValidation(){}     
+       
+       
+       public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{
+               try{
+                       boolean valid = true;
+                       StringBuilder responseString = new StringBuilder();
+                       ObjectMapper mapper = new ObjectMapper();
+                       
+                       if(policyData.getPolicyName() != null){
+                               String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
+                               if(!policyNameValidate.contains("success")){
+                                       responseString.append("PolicyName:" +  policyNameValidate + "<br>");
+                                       valid = false;
+                               };
+                       }else{
+                               responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
+                               valid = false;
+                       }
+                       if(policyData.getPolicyDescription() != null){
+                               String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
+                               if(!descriptionValidate.contains("success")){
+                                       responseString.append("Description:" +  descriptionValidate + "<br>");
+                                       valid = false;
+                               }       
+                       }
+
+                       if(CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
+                               if ("Base".equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
+                                               ||  CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType()) 
+                                               || MICROSERVICES.equals(policyData.getConfigPolicyType())) {
+                                       
+                                       if(!Strings.isNullOrEmpty(policyData.getOnapName())) {
+                                               String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
+                                               if(!onapNameValidate.contains("success")){
+                                                       responseString.append("OnapName:" +  onapNameValidate + "<br>");
+                                                       valid = false;
+                                               }
+                                       }else{
+                                               responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
+                                               valid = false;
+                                       }
+                               }
+
+                               if(!Strings.isNullOrEmpty(policyData.getRiskType())) {
+                                       String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
+                                       if(!riskTypeValidate.contains("success")){
+                                               responseString.append("RiskType:" +  riskTypeValidate + "<br>");
+                                               valid = false;
+                                       }
+                               }else {
+                                       responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
+                                       valid = false;
+                               }
+
+                               if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
+                                       String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
+                                       if(!validateRiskLevel.contains("success")){
+                                               responseString.append("RiskLevel:" +  validateRiskLevel + "<br>");
+                                               valid = false;
+                                       }
+                               }else {
+                                       responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
+                                       valid = false;
+                               }
+
+                               if(!Strings.isNullOrEmpty(policyData.getGuard())) {
+                                       String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
+                                       if(!validateGuard.contains("success")){
+                                               responseString.append("Guard:" +  validateGuard + "<br>");
+                                               valid = false;
+                                       }
+                               }else {
+                                       responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
+                                       valid = false;
+                               }
+
+                               if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       if(!Strings.isNullOrEmpty(policyData.getConfigName())) {
+                                               String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
+                                               if(!configNameValidate.contains("success")){
+                                                       responseString.append("ConfigName:" +  configNameValidate + "<br>");
+                                                       valid = false;
+                                               }
+                                       }else{
+                                               responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
+                                               valid = false;
+                                       }
+                                       if(!Strings.isNullOrEmpty(policyData.getConfigType())) {
+                                               String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
+                                               if(!configTypeValidate.contains("success")){
+                                                       responseString.append("ConfigType:" +  configTypeValidate + "<br>");
+                                                       valid = false;
+                                               }
+                                       }else{
+                                               responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
+                                               valid = false;
+                                       }
+                                       if(!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
+                                               String configBodyData = policyData.getConfigBodyData();
+                                               String configType = policyData.getConfigType();
+                                               if (configType != null) {
+                                                       if (configType.equals("JSON")) {
+                                                               if (!PolicyUtils.isJSONValid(configBodyData)) {
+                                                                       responseString.append("Config Body: JSON Content is not valid" + "<br>");
+                                                                       valid = false;
+                                                               }
+                                                       } else if (configType.equals("XML")) {
+                                                               if (!PolicyUtils.isXMLValid(configBodyData)) {
+                                                                       responseString.append("Config Body: XML Content data is not valid" + "<br>");
+                                                                       valid = false;
+                                                               }
+                                                       } else if (configType.equals("PROPERTIES")) {
+                                                               if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
+                                                                       responseString.append("Config Body: Property data is not valid" + "<br>");
+                                                                       valid = false;
+                                                               } 
+                                                       } else if (configType.equals("OTHER")) {
+                                                               if (configBodyData.equals("")) {
+                                                                       responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
+                                                                       valid = false;
+                                                               }
+                                                       }
+                                               }
+                                       }else{
+                                               responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
+                                               valid = false;
+                                       }
+                               }
+
+                               if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){
+                                               String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
+                                               if(!configNameValidate.contains("success")){
+                                                       responseString.append("<b>ConfigName</b>:<i>" +  configNameValidate + "</i><br>");
+                                                       valid = false;
+                                               }
+                                       }else{
+                                               responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
+                                               valid = false;
+                                       }
+                                       if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){
+                                               responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
+                                               valid = false;
+                                       }
+                               }
+                               if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       if(policyData.getRuleName() == null || policyData.getRuleName().isEmpty()){
+                                               responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
+                                               valid = false;
+                                       }
+                               }
+                               if("BRMS_Raw".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){
+                                               String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
+                                               
+                                               // If there are any error other than Annotations then this is not Valid
+                                               if(message.contains("[ERR")){
+                                                       responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
+                                                       valid = false;
+                                               }
+                                       }else{
+                                               responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
+                                               valid = false;
+                                       }
+                               }
+                               if("ClosedLoop_PM".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       try{
+                                               if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){
+                                                       responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
+                                                       valid = false; 
+                                               }
+                                               
+                                       }catch(Exception e){
+                                           LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
+                                               responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
+                                               valid = false;
+                                       }
+
+                                       if(policyData.getJsonBody() != null){
+                                               ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
+                                               if(pmBody.getEmailAddress() != null){
+                                                       String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
+                                                       if(result != "success"){
+                                                               responseString.append(result + "<br>");
+                                                               valid = false;
+                                                       }
+                                               }
+                                               if((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() || pmBody.isvUSP()) != true){
+                                                       responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services</i><br>");
+                                                       valid = false; 
+                                               }
+                                               if(pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()){
+                                                       String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
+                                                       if(!result.contains("success")){
+                                                               responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
+                                                               valid = false;
+                                                       };
+                                               }
+                                               if(pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()){
+                                                       for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
+                                                               String key = entry.getKey();
+                                                               String value = entry.getValue();
+                                                               if(!key.contains("Message")){
+                                                                       String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
+                                                                       if(!attributeValidate.contains("success")){
+                                                                               responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces or invalid characters</i><br>");
+                                                                               valid = false;
+                                                                       };
+                                                               }
+                                                       }       
+                                               }
+                                       }else{
+                                               responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
+                                               valid = false;
+                                       }
+                               }
+                               if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
+                                       if(policyData.getJsonBody() != null){
+
+                                               // For API we need to get the conditions key from the Json request and check it before deserializing to POJO due to the enum
+                                               if("API".equals(policyData.getApiflag())){
+                                                       JSONObject json = new JSONObject(policyData.getJsonBody());
+                                                       if(!json.isNull("conditions")){
+                                                               String apiCondition = (String) json.get("conditions");
+                                                               if(Strings.isNullOrEmpty(apiCondition)){
+                                                                       responseString.append("<b>Conditions</b>: <i>Select At least one Condition</i><br>");
+                                                                       return responseString;
+                                                               }
+                                                       } else {
+                                                               responseString.append("<b>Conditions</b>: <i>There were no conditions provided in configBody json</i><br>");
+                                                               return responseString;
+                                                       }
+                                               }
+
+                                               ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
+                                               if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){
+                                                       String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
+                                                       if(result != "success"){
+                                                               responseString.append(result+ "<br>");
+                                                               valid = false;
+                                                       }
+                                               }
+                                               if((faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
+                                                       responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services</i><br>");
+                                                       valid = false; 
+                                               }
+                                               if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){
+                                                       responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){
+                                                       responseString.append("<b>Policy Status</b>: <i>Policy Status is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getConditions() == null){
+                                                       responseString.append("<b>Conditions</b>: <i>Select At least one Condition</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()){
+                                                       String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
+                                                       if(!result.contains("success")){
+                                                               responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
+                                                               valid = false;
+                                                       }
+                                               }
+                                               if(faultBody.getAgingWindow() == 0){
+                                                       responseString.append("<b>Aging Window</b>: <i>Aging Window is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getTimeInterval() == 0){
+                                                       responseString.append("<b>Time Interval</b>: <i>Time Interval is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getRetrys() == 0){
+                                                       responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getTimeOutvPRO() == 0){
+                                                       responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getTimeOutRuby() == 0){
+                                                       responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required</i><br>");
+                                                       valid = false;
+                                               }
+                                               if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){
+                                                       responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required</i><br>");
+                                                       valid = false;
+                                               }
+                                       }else{
+                                               responseString.append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services</i><br>");
+                                               responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required</i><br>");
+                                               responseString.append("<b>Aging Window</b>: <i>Aging Window is required</i><br>");
+                                               responseString.append("<b>Policy Status</b>: <i>Policy Status is required</i><br>");
+                                               responseString.append("<b>Conditions</b>: <i>Select Atleast one Condition</i><br>");
+                                               responseString.append("<b>PEP Name</b>: <i>PEP Name is required</i><br>");
+                                               responseString.append("<b>PEP Action</b>: <i>PEP Action is required</i><br>");
+                                               responseString.append("<b>Time Interval</b>: <i>Time Interval is required</i><br>");
+                                               responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required</i><br>");
+                                               responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required</i><br>");
+                                               responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required</i><br>");
+                                               responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required</i><br>");
+                                               valid = false; 
+                                       }
+                               }
+
+                               if ("Micro Service".equals(policyData.getConfigPolicyType())){
+                                       if(!Strings.isNullOrEmpty(policyData.getServiceType())){
+                                               pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
+                                               MicroServiceModels returnModel = new MicroServiceModels();
+                                               String service = null;
+                                               String version = null;
+                                               if (policyData.getServiceType().contains("-v")){
+                                                       service = policyData.getServiceType().split("-v")[0];
+                                                       version = policyData.getServiceType().split("-v")[1];
+                                               }else {
+                                                       service = policyData.getServiceType();
+                                                       version = policyData.getVersion();
+                                               }
+                                               
+                                               if(!Strings.isNullOrEmpty(version)) {
+                                                       returnModel = getAttributeObject(service, version);
+                                                       
+                                                       if(returnModel != null) {
+                                                               String annotation = returnModel.getAnnotation();
+                                                               if (!Strings.isNullOrEmpty(annotation)){ 
+                                                                       Map<String, String> rangeMap = new HashMap<>();
+                                                                       rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
+                                                                       for (Entry<String, String> rMap : rangeMap.entrySet()){
+                                                                               if (rMap.getValue().contains("range::")){
+                                                                                       String value = mapAttribute.get(rMap.getKey().trim());
+                                                                                       String[] tempString = rMap.getValue().split("::")[1].split("-");
+                                                                                       int startNum = Integer.parseInt(tempString[0]);
+                                                                                       int endNum = Integer.parseInt(tempString[1]);
+                                                                                       String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between " 
+                                                                                                       + startNum + " - "  + endNum + ",";
+                                                                                       
+                                                                                       if(value != null) {
+                                                                                               if (PolicyUtils.isInteger(value.replace("\"", ""))){
+                                                                                                       int result = Integer.parseInt(value.replace("\"", ""));
+                                                                                                       if (result < startNum || result > endNum){
+                                                                                                               responseString.append(returnString);                                                                    
+                                                                                                               valid = false;
+                                                                                                       }
+                                                                                               }else {
+                                                                                                       responseString.append(returnString);
+                                                                                                       valid = false;
+                                                                                               }
+                                                                                       } else {
+                                                                                               responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey() 
+                                                                                               + " is required for the MicroService model " + service + "</i><br>");
+                                                                                               valid = false;
+                                                                                       }
+
+                                                                               }
+                                                                       }
+                                                               }
+                                                       } else {
+                                                               responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service + 
+                                                                               " of version, " + version + " was not found in the dictionary</i><br>");
+                                                               valid = false;
+                                                       }
+                                               } else {
+                                                       responseString.append("<b>Micro Version</b>:<i> Micro Service Version is required" + "</i><br>");
+                                                       valid = false;
+                                               }
+                                       } else {
+                                               responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
+                                               valid = false;
+                                       }
+
+                                       if(Strings.isNullOrEmpty(policyData.getPriority())){
+                                               responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
+                                               valid = false;
+                                       }
+                               }       
+                       }
+                       if (DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
+                               if(!Strings.isNullOrEmpty(policyData.getOnapName())){
+                                       String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
+                                       if(!onapNameValidate.contains("success")){
+                                               responseString.append("OnapName:" +  onapNameValidate + "<br>");
+                                               valid = false;
+                                       }
+                               }else{
+                                       responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
+                                       valid = false;
+                               }
+
+                               if("Rainy_Day".equals(policyData.getRuleProvider())){
+                                       if(policyData.getRainyday()==null){
+                                               responseString.append("<b> Rainy Day Parameters are Required </b><br>");
+                                               valid = false;
+                                       }else{
+                                               if(Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())){
+                                                       responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
+                                                       valid = false;
+                                               }
+                                               if(Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())){
+                                                       responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
+                                                       valid = false;
+                                               }                                               
+                                               if(Strings.isNullOrEmpty(policyData.getRainyday().getBbid())){
+                                                       responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
+                                                       valid = false;
+                                               }
+                                               if(Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())){
+                                                       responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
+                                                       valid = false;
+                                               }
+                                               if(!policyData.getRainyday().getTreatmentTableChoices().isEmpty() &&
+                                                               policyData.getRainyday().getTreatmentTableChoices() != null){
+                                                       
+                                                       for(Object treatmentMap: policyData.getRainyday().getTreatmentTableChoices()){
+                                                               String errorCode = null;
+                                                               String treatment = null;
+                                                               if(treatmentMap instanceof LinkedHashMap<?, ?>){
+                                                                       
+                                                                       if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")){
+                                                                               errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
+                                                                       }
+                                                                       if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")){
+                                                                               treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
+                                                                       }
+                                                                       
+                                                               }
+                                                               if(Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)){
+                                                                       responseString.append("Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
+                                                                       valid = false;
+                                                                       break;
+                                                               }
+                                                               if(Strings.isNullOrEmpty(errorCode)){
+                                                                       responseString.append("Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
+                                                                       valid = false;
+                                                                       break;
+                                                               }
+                                                               if(Strings.isNullOrEmpty(treatment)){
+                                                                       responseString.append("Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
+                                                                       valid = false;
+                                                                       break;
+                                                               }
+                                                       }
+                                                       
+                                               } else {
+                                                       responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
+                                                       valid = false;
+                                               }
+                                       }
+                               }
+                               
+                               if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
+                                       if(policyData.getYamlparams()==null){
+                                               responseString.append("<b> Guard Params are Required </b>" + "<br>");
+                                               valid = false;
+                                       }else{
+                                               if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){
+                                                       responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
+                                                       valid = false;
+                                               }
+                                               if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){
+                                                       responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
+                                                       valid = false;
+                                               }
+                                               if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){
+                                                       responseString.append("Guard Params <b>Guard Active Start</b> is Required " + "<br>");
+                                                       valid = false;
+                                               }
+                                               if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){
+                                                       responseString.append("Guard Params <b>Guard Active End</b> is Required " + "<br>");
+                                                       valid = false;
+                                               }
+                                               if("GUARD_YAML".equals(policyData.getRuleProvider())){
+                                                       if(Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())){
+                                                               responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
+                                                               valid = false;
+                                                       }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
+                                                               responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
+                                                               valid = false;
+                                                       }
+                                                       if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){
+                                                               responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
+                                                               valid = false;
+                                                       }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
+                                                               responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
+                                                               valid = false;
+                                                       }
+                                                       if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){
+                                                               responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
+                                                               valid = false;
+                                                       }
+                                               }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
+                                                       if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
+                                                               responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
+                                                               valid = false;
+                                                       }else{
+                                                               for(String blackList: policyData.getYamlparams().getBlackList()){
+                                                                       if(blackList==null || !("success".equals(PolicyUtils.policySpecialCharValidator(blackList)))){
+                                                                               responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
+                                                                               valid = false;
+                                                                               break;
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+
+                       if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
+                               if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){
+                                       String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
+                                       if(!actionPerformer.contains("success")){
+                                               responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
+                                               valid = false;
+                                       }
+                               }else{
+                                       responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
+                                       valid = false;
+                               }
+                               if(policyData.getAttributes() != null){
+                                       for(Object attribute : policyData.getAttributes()){
+                                               if(attribute instanceof LinkedHashMap<?, ?>){
+                                                       try{
+                                                               //This is for validation check if the value exists or not
+                                                               String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+                                                               String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+                                                               if("".equals(key) || "".equals(value)){
+                                                                       responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+                                                                       valid = false;
+                                                                       break;  
+                                                               }
+                                                       }catch(Exception e){
+                                                               LOGGER.error("This is a Policy Validation check" +e);
+                                                               responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+                                                               valid = false;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+                               }else{
+                                       responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+                                       valid = false;
+                               }
+                               if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){
+                                       String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
+                                       if(!actionAttribute.contains("success")){
+                                               responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
+                                               valid = false;
+                                       };
+                               }else{
+                                       responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
+                                       valid = false;
+                               }
+                               
+                               if(!policyData.getRuleAlgorithmschoices().isEmpty()){
+                                       for(Object attribute : policyData.getRuleAlgorithmschoices()){
+                                               if(attribute instanceof LinkedHashMap<?, ?>){
+                                                       try{
+                                                               String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
+                                                               String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
+                                                               String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
+                                                               String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
+
+                                                               if(Strings.isNullOrEmpty(label) || Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(rule) || Strings.isNullOrEmpty(value)){
+                                                                       responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
+                                                                       valid = false;
+                                                               }
+                                                       }catch(Exception e){
+                                                               LOGGER.error("This is a Policy Validation check" +e);
+                                                               responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
+                                                               valid = false;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+
+                       if(CONFIG_POLICY.equals(policyData.getPolicyType())){
+                               String value = "";
+                               if(valid){
+                                       if(commonClassDao!=null){
+                                               List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
+                                               if (!spData.isEmpty()){
+                                                       SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
+                                                       value = "Message:" +  safePolicyWarningData.getMessage();
+                                               }
+                                       }
+                                       responseString.append("success" + "@#"+ value);
+                               }
+                       }else{
+                               if(valid){
+                                       responseString.append("success");
+                               }
+                       }
+
+                       return responseString;
+               }
+               catch (Exception e){
+                       LOGGER.error("Exception Occured during Policy Validation" +e);
+                       return null;
+               }
+       }
+
+       protected String emailValidation(String email, String response){
+               if(email != null){
+                       String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
+                       if(!validateEmail.contains("success")){
+                               response += "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
+                       }else{
+                               return "success";
+                       }
+               }
+               return response;
+       }
+
+       private MicroServiceModels getAttributeObject(String name, String version) {    
+               MicroServiceModels workingModel = null;
+               try{
+                       List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
+                       if(microServiceModelsData != null){
+                               workingModel = (MicroServiceModels) microServiceModelsData.get(0);
+                       }
+               }catch(Exception e){
+                       String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
+                    + name + " was not found in the dictionary: ";
+                       LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
+                       return null;
+               }
+
+               return workingModel;
+       }
+
+       private void pullJsonKeyPairs(JsonNode rootNode) {
+               Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
+
+               while (fieldsIterator.hasNext()) {
+                       Map.Entry<String, JsonNode> field = fieldsIterator.next();
+                       final String key = field.getKey();
+                       final JsonNode value = field.getValue();
+                       if (value.isContainerNode() && !value.isArray()) {
+                               pullJsonKeyPairs(value); // RECURSIVE CALL
+                       } else {
+                               if (value.isArray()){
+                                       String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
+                                       mapAttribute.put(key, newValue);
+                               }else {
+                                       mapAttribute.put(key, value.toString().trim());
+                               }
+                       }
+               }
+       }
+
+}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java
new file mode 100644 (file)
index 0000000..0724622
--- /dev/null
@@ -0,0 +1,376 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */package org.onap.policy.rest.util;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.json.Json;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.policy.api.AttributeType;
+import org.onap.policy.api.PolicyParameters;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.adapter.RainyDayParams;
+import org.onap.policy.rest.adapter.YAMLParams;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+
+public class PolicyValidationRequestWrapper {
+       
+       private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidationRequestWrapper.class);
+       public static final String CONFIG_NAME="configName";
+
+       public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
+               
+               PolicyRestAdapter policyData = null;
+               
+               try {
+                       ObjectMapper mapper = new ObjectMapper();
+                       mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+                       JsonNode root = mapper.readTree(request.getReader());
+                       policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
+                       
+                       JsonObject json = null;
+                       if(root != null){
+                               json = stringToJsonObject(root.toString());
+                               
+                               if(json != null){
+                                       if(json.containsKey("policyJSON")){
+                                               policyData.setPolicyJSON(root.get("policyJSON"));
+                                       }else{
+                                               String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
+                                               policyData.setJsonBody(jsonBodyData);
+                                       }
+                               }
+                       }                       
+                                               
+               } catch (Exception e) {
+                       LOGGER.error("Exception Occured while populating request parameters: " +e);
+               }
+               
+               return policyData;
+       }
+       
+       public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
+               
+               PolicyRestAdapter policyData = new PolicyRestAdapter();
+        
+               /*
+                * set policy adapter values for Building JSON object containing policy data
+                */
+               //Common among policy types
+               policyData.setPolicyName(parameters.getPolicyName());
+               policyData.setOnapName(parameters.getOnapName()); 
+               
+               //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
+               JsonObject json = null;
+        try{
+               if(parameters.getConfigBody()!= null){
+                       json = stringToJsonObject(parameters.getConfigBody());
+               }
+        } catch(JsonException| IllegalStateException e){
+            String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
+            LOGGER.error(message, e);
+            return null;
+        }
+        
+               if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
+                       
+                       policyData.setPolicyType(parameters.getPolicyClass().toString());
+                       
+                       //Get Matching attribute values
+                       Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
+                       Map<String, String> matching = null;
+                       if(attributes != null){
+                               matching = attributes.get(AttributeType.MATCHING);
+                       }
+                       
+                       if("Decision".equals(parameters.getPolicyClass().toString())){
+                               
+                               String ruleProvider = parameters.getRuleProvider().toString();
+                               policyData.setRuleProvider(ruleProvider);
+                               
+                               if("Rainy_Day".equals(ruleProvider)){
+                                       
+                                       // Set Matching attributes in RainyDayParams in adapter
+                                       RainyDayParams rainyday = new RainyDayParams();
+                                       
+                                       rainyday.setServiceType(matching.get("ServiceType"));
+                                       rainyday.setVnfType(matching.get("VNFType"));
+                                       rainyday.setBbid(matching.get("BB_ID"));
+                                       rainyday.setWorkstep(matching.get("WorkStep"));
+                                       
+                                       
+                                       
+                                       Map<String, String> treatments = parameters.getTreatments();
+                                       ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
+                                       
+                                       for (String keyField : treatments.keySet()) {
+                                               LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
+                                               String errorcode = keyField;
+                                               String treatment = treatments.get(errorcode);
+                                               treatmentMap.put("errorcode", errorcode);
+                                               treatmentMap.put("treatment", treatment);
+                                               treatmentsTableChoices.add(treatmentMap);
+                                       }
+                                       rainyday.setTreatmentTableChoices(treatmentsTableChoices);
+                                       policyData.setRainyday(rainyday);
+                                       
+                               }else if("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)) {
+                                       
+                                       // Set Matching attributes in YAMLParams in adapter
+                                       YAMLParams yamlparams = new YAMLParams();
+                                       
+                                       yamlparams.setActor(matching.get("actor"));
+                                       yamlparams.setRecipe(matching.get("recipe"));
+                                       yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
+                                       yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
+                                       
+                                       if("GUARD_YAML".equals(ruleProvider)){
+                                               yamlparams.setLimit(matching.get("limit"));
+                                               yamlparams.setTimeWindow(matching.get("timeWindow"));
+                                               yamlparams.setTimeUnits(matching.get("timeUnits"));     
+                                       }else{
+                                               
+                                               List<String> blackList = new ArrayList<>();
+
+                                               if(!Strings.isNullOrEmpty(matching.get("blackList"))){
+                                                       String[] blackListArray = matching.get("blackList").split(",");
+                                                       for(String element : blackListArray){
+                                                               blackList.add(element);
+                                                       }                                       
+                                               }       
+                                               
+                                               yamlparams.setBlackList(blackList);
+
+                                       }                                       
+                                       
+                                       policyData.setYamlparams(yamlparams);
+;                                      
+                               }
+                               
+                       } else if("Action".equals(parameters.getPolicyClass().toString())){
+                               
+                               ArrayList<Object> ruleAlgorithmChoices = new ArrayList<Object>();
+                                                               
+                               List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
+                               List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
+                               List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
+                               List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
+                   
+                               if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
+                       int i = dynamicLabelRuleAlgorithms.size() - 1;
+
+                       for (String labelAttr : dynamicLabelRuleAlgorithms) {
+                                       LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
+
+                               String id = dynamicLabelRuleAlgorithms.get(i);
+                               String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
+                               String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
+                               String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
+                               
+                               ruleAlgorithm.put("id", id);
+                               ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
+                               ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
+                               ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
+                               
+                               ruleAlgorithmChoices.add(ruleAlgorithm);
+                               
+                               i--;
+                               
+                       }
+                   }
+                   
+                   policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
+                   
+                   ArrayList<Object> attributeList = new ArrayList<>();
+                   
+                   for (String keyField : matching.keySet()) {
+                                       LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
+                                       String key = keyField;
+                                       String value = matching.get(keyField);
+                                       attributeMap.put("key", key);
+                                       attributeMap.put("value", value);
+                                       attributeList.add(attributeMap);
+                               }                   
+                   
+                   policyData.setAttributes(attributeList);        
+                   policyData.setActionAttributeValue(parameters.getActionAttribute());
+                   policyData.setActionPerformer(parameters.getActionPerformer());
+                               
+                       }
+               }else {
+                       
+                       policyData.setPolicyType("Config");
+                       policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
+                       
+                       //Config Specific
+                       policyData.setConfigBodyData(parameters.getConfigBody()); //Base
+                       policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null);  //Base
+                       
+                       if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
+                               
+                               policyData.setConfigPolicyType("Firewall Config"); 
+
+                       // get values and attributes from the JsonObject
+                               if(json != null){
+                               if (json.get("securityZoneId")!=null){
+                                       String securityZone = json.get("securityZoneId").toString().replace("\"", "");
+                                       policyData.setSecurityZone(securityZone);
+                               }
+                               if (json.get(CONFIG_NAME)!=null){
+                                   String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
+                                   policyData.setConfigName(configName);
+                               }
+                               }
+                                                               
+                       }else if("MS".equals(parameters.getPolicyConfigType().toString())){
+                               
+                               policyData.setConfigPolicyType("Micro Service");
+                               
+                       // get values and attributes from the JsonObject
+                               if(json != null){
+                                       if (json.containsKey("content")){
+                                               String content = json.get("content").toString();
+                                               ObjectMapper mapper = new ObjectMapper();
+                                               JsonNode policyJSON = null;
+                                               try {
+                                                       policyJSON = mapper.readTree(content);
+                                               } catch (IOException e) {
+                                           String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
+                                           LOGGER.error(message, e);
+                                           return null;                                        
+                                       }
+                                               policyData.setPolicyJSON(policyJSON);
+                                       }
+                               if (json.containsKey("service")){
+                                       String serviceType = json.get("service").toString().replace("\"", "");
+                                       policyData.setServiceType(serviceType);
+                               }
+                               if (json.containsKey("uuid")){
+                                   String uuid = json.get("uuid").toString().replace("\"", "");
+                                   policyData.setUuid(uuid);
+                               }
+                               if (json.containsKey("location")){
+                                   String msLocation = json.get("location").toString().replace("\"", "");
+                                   policyData.setMsLocation(msLocation);
+                               }
+                               if (json.containsKey(CONFIG_NAME)){
+                                   String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
+                                   policyData.setConfigName(configName);
+                               }
+                               if(json.containsKey("priority")){
+                                       String priority = json.get("priority").toString().replace("\"", "");
+                                       policyData.setPriority(priority);
+                               }
+                               if(json.containsKey("version")){
+                                       String version = json.get("version").toString().replace("\"", "");
+                                       policyData.setVersion(version);
+                               }
+                               }
+                               
+                       } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
+                               
+                               policyData.setConfigPolicyType("ClosedLoop_Fault");
+                               policyData.setApiflag("API");
+                               
+                               if(json != null){
+                                       policyData.setJsonBody(json.toString());
+                               if (json.get("onapname")!=null){
+                                       String onapName = json.get("onapname").toString().replace("\"", "");
+                                       policyData.setOnapName(onapName);
+                               }
+                               }
+                               
+                       } else if("PM".equals(parameters.getPolicyConfigType().toString())){
+                               
+                               policyData.setConfigPolicyType("ClosedLoop_PM");
+                               
+                               if(json != null){
+                                       policyData.setJsonBody(json.toString());
+                               if (json.get("onapname")!=null){
+                                       String onapName = json.get("onapname").toString().replace("\"", "");
+                                       policyData.setOnapName(onapName);
+                               }
+                               if (json.get("serviceTypePolicyName")!=null){
+                                       String serviceType = json.get("serviceTypePolicyName").toString().replace("\"", "");
+                                               LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
+                                               serviceTypePolicyName.put("serviceTypePolicyName", serviceType);
+                                       policyData.setServiceTypePolicyName(serviceTypePolicyName);
+                               }
+                               }
+                       } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
+                               Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
+                               Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
+                               policyData.setRuleName(rule.get("templateName"));
+                               
+                       }
+               }
+               
+               policyData.setPriority(parameters.getPriority()); //Micro Service
+               policyData.setConfigName(parameters.getConfigName());  //Base and Firewall
+               policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes
+               policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes
+               policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes
+               policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes
+
+               return policyData;
+                               
+       }
+       
+    private JsonObject stringToJsonObject(String value)
+            throws JsonException, IllegalStateException {
+       
+       try{
+            JsonReader jsonReader = Json.createReader(new StringReader(value));
+            JsonObject object = jsonReader.readObject();
+            jsonReader.close();
+            return object;
+        } catch(JsonException| IllegalStateException e){
+            LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
+            return null;
+        }
+    }
+    
+    private String convertDate(Date date) {
+        String strDate = null;
+        if (date!=null) {
+            SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
+            strDate = dateformatJava.format(date);
+        }
+        return (strDate==null) ? "NA": strDate;
+    }
+
+}
index 20a671b..7a8212c 100644 (file)
@@ -120,7 +120,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
                                }                       
                                jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
                                jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut()));
-                               jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge()));
+                               jsonBody.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
                        }
 
                        jsonBody.setTriggerSignatures(triggerSignatures);
@@ -150,7 +150,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
                                }
 
                                jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
-                               jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
+                               jsonBody.setVerificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
                        }               
                        jsonBody.setVerificationSignatures(faultSignatures);
                        ObjectWriter om = new ObjectMapper().writer();
@@ -590,14 +590,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{
                                closedLoopBody.setClosedLoopPolicyStatus("InActive");
                        }
                        policyAdapter.setJsonBodyData(closedLoopBody);
-                       if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){
-                               policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString());
+                       if(closedLoopBody.getTrapMaxAge() != null){
+                               policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAge().toString());
                        }
                        if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){
                                policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString());
                        }
-                       if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){
-                               policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString());
+                       if(closedLoopBody.getVerificationTimeWindowUsedForUI() != null){
+                               policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString());
                        }
 
                } catch (Exception e) {
index 050455a..a82fac2 100644 (file)
@@ -23,39 +23,23 @@ package org.onap.policy.controller;
 
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.apache.commons.lang.StringUtils;
 import org.json.JSONObject;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
-import org.onap.policy.rest.adapter.ClosedLoopPMBody;
 import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.dao.CommonClassDao;
-import org.onap.policy.rest.jpa.MicroServiceModels;
-import org.onap.policy.rest.jpa.SafePolicyWarning;
-import org.onap.policy.utils.PolicyUtils;
+import org.onap.policy.rest.util.PolicyValidation;
+import org.onap.policy.rest.util.PolicyValidationRequestWrapper;
 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
 import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.servlet.ModelAndView;
 
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Splitter;
-import com.google.common.base.Strings;
 
 @Controller
 @RequestMapping("/")
@@ -70,527 +54,19 @@ public class PolicyValidationController extends RestrictedBaseController {
        public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
        public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
        public static final String MICROSERVICES="Micro Service";
-       private static Map<String, String> mapAttribute = new HashMap<>();
-
-       @Autowired
-       CommonClassDao commonClassDao;
 
        @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
        public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
                try{
-                       boolean valid = true;
-                       StringBuilder responseString = new StringBuilder();
+                       
+                       PolicyValidation validation = new PolicyValidation();
+                       PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+                       StringBuilder responseString;
                        ObjectMapper mapper = new ObjectMapper();
-                       mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-                       JsonNode root = mapper.readTree(request.getReader());
-                       PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
-                       if(policyData.getPolicyName() != null){
-                               String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
-                               if(!policyNameValidate.contains("success")){
-                                       responseString.append("PolicyName:" +  policyNameValidate + "<br>");
-                                       valid = false;
-                               };
-                       }else{
-                               responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
-                               valid = false;
-                       }
-                       if(policyData.getPolicyDescription() != null){
-                               String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
-                               if(!descriptionValidate.contains("success")){
-                                       responseString.append("Description:" +  descriptionValidate + "<br>");
-                                       valid = false;
-                               }       
-                       }
-
-                       if(policyData.getPolicyType().equals(CONFIG_POLICY)){
-                               if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) 
-                                               ||  policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
-                                       if(policyData.getOnapName() != null){
-                                               String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
-                                               if(!onapNameValidate.contains("success")){
-                                                       responseString.append("OnapName:" +  onapNameValidate + "<br>");
-                                                       valid = false;
-                                               }
-                                       }else{
-                                               responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
-                                               valid = false;
-                                       }
-                               }
-
-                               if(policyData.getRiskType() != null){
-                                       String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
-                                       if(!riskTypeValidate.contains("success")){
-                                               responseString.append("RiskType:" +  riskTypeValidate + "<br>");
-                                               valid = false;
-                                       }
-                               }else {
-                                       responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
-                                       valid = false;
-                               }
-
-                               if(policyData.getRiskLevel() != null){
-                                       String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
-                                       if(!validateRiskLevel.contains("success")){
-                                               responseString.append("RiskLevel:" +  validateRiskLevel + "<br>");
-                                               valid = false;
-                                       }
-                               }else {
-                                       responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
-                                       valid = false;
-                               }
-
-                               if(policyData.getGuard() != null){
-                                       String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
-                                       if(!validateGuard.contains("success")){
-                                               responseString.append("Guard:" +  validateGuard + "<br>");
-                                               valid = false;
-                                       }
-                               }else {
-                                       responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
-                                       valid = false;
-                               }
-
-                               if(policyData.getConfigPolicyType().equals("Base")){
-                                       if(policyData.getConfigName() != null){
-                                               String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
-                                               if(!configNameValidate.contains("success")){
-                                                       responseString.append("ConfigName:" +  configNameValidate + "<br>");
-                                                       valid = false;
-                                               }
-                                       }else{
-                                               responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
-                                               valid = false;
-                                       }
-                                       if(policyData.getConfigType() != null){
-                                               String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
-                                               if(!configTypeValidate.contains("success")){
-                                                       responseString.append("ConfigType:" +  configTypeValidate + "<br>");
-                                                       valid = false;
-                                               }
-                                       }else{
-                                               responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
-                                               valid = false;
-                                       }
-                                       if(policyData.getConfigBodyData() != null){
-                                               String configBodyData = policyData.getConfigBodyData();
-                                               String policyType = policyData.getConfigType();
-                                               if (policyType != null) {
-                                                       if (policyType.equals("JSON")) {
-                                                               if (!PolicyUtils.isJSONValid(configBodyData)) {
-                                                                       responseString.append("Config Body: JSON Content is not valid" + "<br>");
-                                                                       valid = false;
-                                                               }
-                                                       } else if (policyType.equals("XML")) {
-                                                               if (!PolicyUtils.isXMLValid(configBodyData)) {
-                                                                       responseString.append("Config Body: XML Content data is not valid" + "<br>");
-                                                                       valid = false;
-                                                               }
-                                                       } else if (policyType.equals("PROPERTIES")) {
-                                                               if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
-                                                                       responseString.append("Config Body: Property data is not valid" + "<br>");
-                                                                       valid = false;
-                                                               } 
-                                                       } else if (policyType.equals("OTHER")) {
-                                                               if (configBodyData.equals("")) {
-                                                                       responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
-                                                                       valid = false;
-                                                               }
-                                                       }
-                                               }
-                                       }else{
-                                               responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
-                                               valid = false;
-                                       }
-                               }
-
-                               if(policyData.getConfigPolicyType().equals("Firewall Config")){
-                                       if(policyData.getConfigName() != null){
-                                               String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
-                                               if(!configNameValidate.contains("success")){
-                                                       responseString.append("<b>ConfigName</b>:<i>" +  configNameValidate + "</i><br>");
-                                                       valid = false;
-                                               }
-                                       }else{
-                                               responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
-                                               valid = false;
-                                       }
-                                       if(policyData.getSecurityZone() == null){
-                                               responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
-                                               valid = false;
-                                       }
-                               }
-                               if(policyData.getConfigPolicyType().equals("BRMS_Param")){
-                                       if(policyData.getRuleName() == null){
-                                               responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
-                                               valid = false;
-                                       }
-                               }
-                               if(policyData.getConfigPolicyType().equals("BRMS_Raw")){
-                                       if(policyData.getConfigBodyData() != null){
-                                               String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
-                                               // If there are any error other than Annotations then this is not Valid
-                                               if(message.contains("[ERR")){
-                                                       responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
-                                                       valid = false;
-                                               }
-                                       }else{
-                                               responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
-                                               valid = false;
-                                       }
-                               }
-                               if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
-                                       try{
-                                               if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){
-                                                       responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
-                                                       valid = false; 
-                                               }
-                                       }catch(Exception e){
-                                           LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
-                                               responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
-                                               valid = false;
-                                       }
-
-                                       if(root.get("policyData").get("jsonBodyData") != null){
-                                               ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
-                                               if(pmBody.getEmailAddress() != null){
-                                                       String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
-                                                       if(result != "success"){
-                                                               responseString.append(result + "<br>");
-                                                               valid = false;
-                                                       }
-                                               }
-                                               if(pmBody.getGeoLink() != null){
-                                                       String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
-                                                       if(!result.contains("success")){
-                                                               responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
-                                                               valid = false;
-                                                       };
-                                               }
-                                               if(pmBody.getAttributes() != null){
-                                                       for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
-                                                               String key = entry.getKey();
-                                                               String value = entry.getValue();
-                                                               if(!key.contains("Message")){
-                                                                       String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
-                                                                       if(!attributeValidate.contains("success")){
-                                                                               responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces</i><br>");
-                                                                               valid = false;
-                                                                       };
-                                                               }
-                                                       }       
-                                               }
-                                       }else{
-                                               responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
-                                               valid = false;
-                                       }
-                               }
-                               if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
-                                       if(root.get("policyData").get("jsonBodyData") != null){
-                                               ClosedLoopFaultBody faultBody = mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
-                                               if(faultBody.getEmailAddress() != null){
-                                                       String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
-                                                       if(result != "success"){
-                                                               responseString.append(result+ "<br>");
-                                                               valid = false;
-                                                       }
-                                               }
-                                               if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
-                                                       responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
-                                                       valid = false; 
-                                               }
-                                               if(faultBody.getActions() == null){
-                                                       responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getClosedLoopPolicyStatus() == null){
-                                                       responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getConditions() == null){
-                                                       responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getGeoLink() != null){
-                                                       String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
-                                                       if(!result.contains("success")){
-                                                               responseString.append("<b>GeoLink</b>:<i>" +  result + "</i><br>");
-                                                               valid = false;
-                                                       }
-                                               }
-
-                                               if(faultBody.getTimeInterval() == 0){
-                                                       responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getRetrys() == 0){
-                                                       responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getTimeOutvPRO() == 0){
-                                                       responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getTimeOutRuby() == 0){
-                                                       responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
-                                                       valid = false;
-                                               }
-                                               if(faultBody.getVnfType() == null){
-                                                       responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
-                                                       valid = false;
-                                               }
-                                       }else{
-                                               responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
-                                               responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
-                                               responseString.append("<b>Aging Window</b>:<i>Aging Window is required</i><br>");
-                                               responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
-                                               responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
-                                               responseString.append("<b>PEP Name</b>:<i>PEP Name is required</i><br>");
-                                               responseString.append("<b>PEP Action</b>:<i>PEP Action is required</i><br>");
-                                               responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
-                                               responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
-                                               responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
-                                               responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
-                                               responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
-                                               valid = false; 
-                                       }
-                               }
-
-                               if (policyData.getConfigPolicyType().contains("Micro Service")){
-                                       if(policyData.getServiceType() != null){
-                                               pullJsonKeyPairs(root.get("policyJSON"));
-                                               MicroServiceModels returnModel = new MicroServiceModels();
-                                               String service = null;
-                                               String version = null;
-                                               if (policyData.getServiceType().contains("-v")){
-                                                       service = policyData.getServiceType().split("-v")[0];
-                                                       version = policyData.getServiceType().split("-v")[1];
-                                               }else {
-                                                       service = policyData.getServiceType();
-                                                       version = policyData.getVersion();
-                                               }
-                                               returnModel = getAttributeObject(service, version);
-                                               String annoation = returnModel.getAnnotation();
-                                               if (!Strings.isNullOrEmpty(annoation)){
-                                                        Map<String, String> rangeMap = new HashMap<>();
-                                                       rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
-                                                       for (Entry<String, String> rMap : rangeMap.entrySet()){
-                                                               if (rMap.getValue().contains("range::")){
-                                                                       String value = mapAttribute.get(rMap.getKey().trim());
-                                                                       String[] tempString = rMap.getValue().split("::")[1].split("-");
-                                                                       int startNum = Integer.parseInt(tempString[0]);
-                                                                       int endNum = Integer.parseInt(tempString[1]);
-                                                                       String returnString = "Invalid Range:" + rMap.getKey() + " must be between " 
-                                                                                       + startNum + " - "  + endNum + ",";
-                                                                       if (PolicyUtils.isInteger(value.replace("\"", ""))){
-                                                                               int result = Integer.parseInt(value.replace("\"", ""));
-                                                                               if (result < startNum || result > endNum){
-                                                                                       responseString.append(returnString);                                                                    
-                                                                                       valid = false;
-                                                                               }
-                                                                       }else {
-                                                                               responseString.append(returnString);
-                                                                               valid = false;
-                                                                       }
-                                                               }
-                                                       }
-                                               }
-                                       }else{
-                                               responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
-                                               valid = false;
-                                       }
-
-                                       if(policyData.getPriority() == null){
-                                               responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
-                                               valid = false;
-                                       }
-                               }       
-                       }
-                       if (policyData.getPolicyType().equals(DECISION_POLICY)){
-                               if(policyData.getOnapName() != null){
-                                       String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
-                                       if(!onapNameValidate.contains("success")){
-                                               responseString.append("OnapName:" +  onapNameValidate + "<br>");
-                                               valid = false;
-                                       }
-                               }else{
-                                       responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
-                                       valid = false;
-                               }
-                               
-                               if("Rainy_Day".equals(policyData.getRuleProvider())){
-                                       if(policyData.getRainyday()==null){
-                                               responseString.append("<b> Rainy Day Parameters are Required </b><br>");
-                                               valid = false;
-                                       }else{
-                                               if(policyData.getRainyday().getServiceType()==null){
-                                                       responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
-                                                       valid = false;
-                                               }
-                                               if(policyData.getRainyday().getVnfType()==null){
-                                                       responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
-                                                       valid = false;
-                                               }                                               
-                                               if(policyData.getRainyday().getBbid()==null){
-                                                       responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
-                                                       valid = false;
-                                               }
-                                               if(policyData.getRainyday().getWorkstep()==null){
-                                                       responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
-                                                       valid = false;
-                                               }
-                                               if(policyData.getRainyday().getServiceType()==null){
-                                                       responseString.append("Rainy Day <b>Error Code</b> is Required<br>");
-                                                       valid = false;
-                                               }
-                                       }
-                               }
-                               
-                               if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
-                                       if(policyData.getYamlparams()==null){
-                                               responseString.append("<b> Guard Params are Required </b>" + "<br>");
-                                               valid = false;
-                                       }else{
-                                               if(policyData.getYamlparams().getActor()==null){
-                                                       responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
-                                                       valid = false;
-                                               }
-                                               if(policyData.getYamlparams().getRecipe()==null){
-                                                       responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
-                                                       valid = false;
-                                               }
-                                               if(policyData.getYamlparams().getGuardActiveStart()==null){
-                                                       responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
-                                                       valid = false;
-                                               }
-                                               if(policyData.getYamlparams().getGuardActiveEnd()==null){
-                                                       responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
-                                                       valid = false;
-                                               }
-                                               if("GUARD_YAML".equals(policyData.getRuleProvider())){
-                                                       if(policyData.getYamlparams().getLimit()==null){
-                                                               responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
-                                                               valid = false;
-                                                       }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
-                                                               responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
-                                                               valid = false;
-                                                       }
-                                                       if(policyData.getYamlparams().getTimeWindow()==null){
-                                                               responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
-                                                               valid = false;
-                                                       }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
-                                                               responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
-                                                               valid = false;
-                                                       }
-                                                       if(policyData.getYamlparams().getTimeUnits()==null){
-                                                               responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
-                                                               valid = false;
-                                                       }
-                                               }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
-                                                       if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
-                                                               responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
-                                                               valid = false;
-                                                       }else{
-                                                               for(String blackList: policyData.getYamlparams().getBlackList()){
-                                                                       if(blackList==null || !("success".equals(PolicyUtils.policySpecialCharValidator(blackList)))){
-                                                                               responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
-                                                                               valid = false;
-                                                                               break;
-                                                                       }
-                                                               }
-                                                       }
-                                               }
-                                       }
-                               }
-                       }
-
-                       if(policyData.getPolicyType().equals(ACTION_POLICY)){
-                               if(policyData.getActionPerformer() != null){
-                                       String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
-                                       if(!actionPerformer.contains("success")){
-                                               responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
-                                               valid = false;
-                                       }
-                               }else{
-                                       responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
-                                       valid = false;
-                               }
-                               if(policyData.getAttributes() != null){
-                                       for(Object attribute : policyData.getAttributes()){
-                                               if(attribute instanceof LinkedHashMap<?, ?>){
-                                                       try{
-                                                               //This is for validation check if the value exists or not
-                                                               String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
-                                                               String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
-                                                               if("".equals(key) || "".equals(value)){
-                                                                       responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
-                                                                       valid = false;
-                                                                       break;  
-                                                               }
-                                                       }catch(Exception e){
-                                                               LOGGER.error("This is a Policy Validation check" +e);
-                                                               responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
-                                                               valid = false;
-                                                               break;
-                                                       }
-                                               }
-                                       }
-                               }else{
-                                       responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
-                                       valid = false;
-                               }
-                               if(policyData.getActionAttributeValue() != null){
-                                       String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
-                                       if(!actionAttribute.contains("success")){
-                                               responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
-                                               valid = false;
-                                       };
-                               }else{
-                                       responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
-                                       valid = false;
-                               }                       
-                       }
                        
-                       if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
-                               if(!policyData.getRuleAlgorithmschoices().isEmpty()){
-                                       for(Object attribute : policyData.getRuleAlgorithmschoices()){
-                                               if(attribute instanceof LinkedHashMap<?, ?>){
-                                                       try{
-                                                               String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
-                                                               String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
-                                                               String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
-                                                               String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
-                                                               if("".equals(label) || "".equals(key) || "".equals(rule)  || "".equals(value)){
-                                                                       responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
-                                                                       valid = false;
-                                                               }
-                                                       }catch(Exception e){
-                                                               LOGGER.error("This is a Policy Validation check" +e);
-                                                               responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
-                                                               valid = false;
-                                                               break;
-                                                       }
-                                               }
-                                       }
-                               }
-                       }
-
-                       if(policyData.getPolicyType().equals(CONFIG_POLICY)){
-                               String value = "";
-                               if(valid){
-                                       List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
-                                       if (!spData.isEmpty()){
-                                               SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
-                                               safePolicyWarningData.getMessage();
-                                               value = "Message:" +  safePolicyWarningData.getMessage();
-                                       }
-                                       responseString.append("success" + "@#"+ value);
-                               }
-                       }else{
-                               if(valid){
-                                       responseString.append("success");
-                               }
-                       }
-
+                       PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
+                       responseString = validation.validatePolicy(policyData);
+                       
                        PrintWriter out = response.getWriter();
                        JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
                        JSONObject j = new JSONObject(msg);
@@ -599,7 +75,7 @@ public class PolicyValidationController extends RestrictedBaseController {
                        return null;
                }
                catch (Exception e){
-                       LOGGER.error("Exception Occured while Policy Validation" +e);
+                       LOGGER.error("Exception Occured During Policy Validation" +e);
                        response.setCharacterEncoding("UTF-8");
                        request.setCharacterEncoding("UTF-8");
                        PrintWriter out = response.getWriter();
@@ -607,45 +83,4 @@ public class PolicyValidationController extends RestrictedBaseController {
                }
                return null;
        }
-
-       protected String emailValidation(String email, String response){
-               if(email != null){
-                       String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
-                       if(!validateEmail.contains("success")){
-                               response += "<b>Email</b>:<i>" +  validateEmail+ "</i><br>";
-                       }else{
-                               return "success";
-                       }
-               }
-               return response;
-       }
-
-       private MicroServiceModels getAttributeObject(String name, String version) {    
-               MicroServiceModels workingModel = new MicroServiceModels();
-               List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
-               if(microServiceModelsData != null){
-                       workingModel = (MicroServiceModels) microServiceModelsData.get(0);
-               }
-               return workingModel;
-       }
-
-       private void pullJsonKeyPairs(JsonNode rootNode) {
-               Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
-
-               while (fieldsIterator.hasNext()) {
-                       Map.Entry<String, JsonNode> field = fieldsIterator.next();
-                       final String key = field.getKey();
-                       final JsonNode value = field.getValue();
-                       if (value.isContainerNode() && !value.isArray()) {
-                               pullJsonKeyPairs(value); // RECURSIVE CALL
-                       } else {
-                               if (value.isArray()){
-                                       String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
-                                       mapAttribute.put(key, newValue);
-                               }else {
-                                       mapAttribute.put(key, value.toString().trim());
-                               }
-                       }
-               }
-       }
 }
\ No newline at end of file
index c8ed3a0..81db14c 100644 (file)
@@ -42,9 +42,12 @@ import org.onap.policy.rest.dao.CommonClassDao;
 import org.onap.policy.rest.jpa.PolicyRoles;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Primary;
+import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Service;
 
 @Service("CommonClassDao")
+@Primary
 public class CommonClassDaoImpl implements CommonClassDao{
 
        private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class);
index 1557f97..8751768 100644 (file)
@@ -66,7 +66,7 @@
                <div class="well">
                        <div class="form-group row">
                                <div class="form-group col-sm-2">
-                                       <label>Rule Attributes:<sup><b>*</b></sup></label>
+                                       <label>Rule Attributes:<sup></sup></label>
                                        <button type="button" class="btn btn-default"
                                                ng-disabled="temp.policy.readOnly" ng-click="addNewChoice()">
                                                <i class="fa fa-plus"></i>