diff options
124 files changed, 5855 insertions, 2046 deletions
diff --git a/BRMSGateway/pom.xml b/BRMSGateway/pom.xml index bee9747f8..5512f7ae3 100644 --- a/BRMSGateway/pom.xml +++ b/BRMSGateway/pom.xml @@ -61,6 +61,11 @@ <version>2.3.1</version> </dependency> <dependency> + <groupId>com.thoughtworks.xstream</groupId> + <artifactId>xstream</artifactId> + <version>1.3.1</version> + </dependency> + <dependency> <groupId>com.att.nsa</groupId> <artifactId>cambriaClient</artifactId> <version>0.0.1</version> diff --git a/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSHandler.java b/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSHandler.java index 67713420e..b28624e61 100644 --- a/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSHandler.java +++ b/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSHandler.java @@ -20,6 +20,7 @@ package org.openecomp.policy.brmsInterface; +import java.util.ArrayList; import java.util.Collection; import org.openecomp.policy.api.ConfigRequestParameters; @@ -31,11 +32,10 @@ import org.openecomp.policy.api.PolicyConfigStatus; import org.openecomp.policy.api.PolicyEngine; import org.openecomp.policy.api.PolicyException; import org.openecomp.policy.api.RemovedPolicy; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.utils.BackUpHandler; import org.openecomp.policy.xacml.api.XACMLErrorConstants; -//import org.apache.log4j.Logger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; /** * BRMSHandler: Notification Handler which listens for PDP Notifications. @@ -56,7 +56,12 @@ public class BRMSHandler implements BackUpHandler{ public void setBRMSPush(BRMSPush brmsPush) { this.bRMSPush = brmsPush; } - + + /* + * This Method is executed upon notification by the Policy Engine API Notification. + * (non-Javadoc) + * @see org.openecomp.policy.utils.BackUpHandler#notificationReceived(org.openecomp.policy.api.PDPNotification) + */ @Override public void notificationReceived(PDPNotification notification) { logger.info("Notification Recieved"); @@ -71,6 +76,9 @@ public class BRMSHandler implements BackUpHandler{ } } + /* + * Executed when a policy is removed from PDP. + */ private void removedPolicies(Collection<RemovedPolicy> removedPolicies){ Boolean removed = false; logger.info("Removed Policies"); @@ -87,44 +95,88 @@ public class BRMSHandler implements BackUpHandler{ } } } - if(removed){ - bRMSPush.pushRules(); - } + Boolean failureFlag = false; + int i = 0; + do{ + failureFlag = false; + if(removed){ + try{ + bRMSPush.pushRules(); + }catch(PolicyException e){ + //Upon Notification failure + failureFlag = true; + bRMSPush.rotateURLs(); + } + } + i++; + }while(failureFlag && i< bRMSPush.URLListSize()); } + /* + * This method is executed if BRMSGW is "MASTER" + * (non-Javadoc) + * @see org.openecomp.policy.utils.BackUpHandler#runOnNotification(org.openecomp.policy.api.PDPNotification) + */ public void runOnNotification(PDPNotification notification){ if(notification.getNotificationType().equals(NotificationType.REMOVE)){ removedPolicies(notification.getRemovedPolicies()); }else if(notification.getNotificationType().equals(NotificationType.UPDATE)|| notification.getNotificationType().equals(NotificationType.BOTH)){ logger.info("Updated Policies: \n"); - for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ - logger.info("policyName : " + updatedPolicy.getPolicyName()); - logger.info("policyVersion :" + updatedPolicy.getVersionNo()); - logger.info("Matches: " + updatedPolicy.getMatches()); - // Checking the Name is correct or not. - if(updatedPolicy.getPolicyName().contains("_BRMS_")){ - try{ - PolicyEngine policyEngine = getPolicyEngine(); - if(policyEngine!=null){ - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); - configRequestParameters.setPolicyName(updatedPolicy.getPolicyName()); - Collection<PolicyConfig> policyConfigs = policyEngine.getConfig(configRequestParameters); - for(PolicyConfig policyConfig: policyConfigs){ - if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ - logger.info("Policy Retrieved with this Name notified: " + policyConfig.getPolicyName()); - bRMSPush.addRule(policyConfig.getPolicyName(),policyConfig.toOther(),policyConfig.getResponseAttributes()); - }else{ - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Fail to retrieve policy so rule will not be pushed to PolicyRepo !!!!\n\n"); - } + ArrayList<PolicyConfig> brmsPolicies = addedPolicies(notification); + Boolean successFlag = false; + for(int i=0; !successFlag && i< bRMSPush.URLListSize(); i++){ + successFlag = false; + if(i!=0 && !successFlag){ + for(PolicyConfig policyConfig: brmsPolicies){ + logger.info("Policy Retry with this Name notified: " + policyConfig.getPolicyName()); + bRMSPush.addRule(policyConfig.getPolicyName(),policyConfig.toOther(),policyConfig.getResponseAttributes()); + } + } + try{ + bRMSPush.pushRules(); + successFlag = true; + }catch(PolicyException e){ + //Upon Notification failure + successFlag = false; + bRMSPush.rotateURLs(); + } + } + } + } + + /* + * Executed when a policy is added to PDP. + */ + private ArrayList<PolicyConfig> addedPolicies(PDPNotification notification) { + ArrayList<PolicyConfig> result = new ArrayList<PolicyConfig>(); + for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ + logger.info("policyName : " + updatedPolicy.getPolicyName()); + logger.info("policyVersion :" + updatedPolicy.getVersionNo()); + logger.info("Matches: " + updatedPolicy.getMatches()); + // Checking the Name is correct or not. + if(updatedPolicy.getPolicyName().contains("_BRMS_")){ + try{ + PolicyEngine policyEngine = getPolicyEngine(); + if(policyEngine!=null){ + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setPolicyName(updatedPolicy.getPolicyName()); + Collection<PolicyConfig> policyConfigs = policyEngine.getConfig(configRequestParameters); + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ + logger.info("Policy Retrieved with this Name notified: " + policyConfig.getPolicyName()); + result.add(policyConfig); + bRMSPush.addRule(policyConfig.getPolicyName(),policyConfig.toOther(),policyConfig.getResponseAttributes()); + }else{ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Fail to retrieve policy so rule will not be pushed to PolicyRepo !!!!\n\n"); } } - }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage()); } + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage()); } } - bRMSPush.pushRules(); } + return result; } public PolicyEngine getPolicyEngine() { diff --git a/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSPush.java b/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSPush.java index 60d764cb0..7e9b64c33 100644 --- a/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSPush.java +++ b/BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSPush.java @@ -36,6 +36,7 @@ import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; @@ -75,6 +76,7 @@ import org.openecomp.policy.brmsInterface.jpa.DependencyInfo; import org.openecomp.policy.common.im.AdministrativeStateException; import org.openecomp.policy.common.im.IntegrityMonitor; import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.utils.BackUpHandler; @@ -100,6 +102,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; * @version 0.9 */ +@SuppressWarnings("deprecation") public class BRMSPush { private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName()); private static final String PROJECTSLOCATION = "RuleProjects"; @@ -114,7 +117,7 @@ public class BRMSPush { private String defaultName = null; private String repID = null; private String repName = null; - private String repURL= null; + private ArrayList<String> repURLs= null; private String repUserName = null; private String repPassword = null; private String policyKeyID = null; @@ -132,6 +135,7 @@ public class BRMSPush { private Map<String, String> policyMap = new HashMap<String,String>(); private String brmsdependencyversion; private EntityManager em; + private boolean syncFlag = false; public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException{ Properties config = new Properties(); @@ -196,12 +200,17 @@ public class BRMSPush { throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryName property is missing from the property file "); } repName = repName.trim(); - repURL = config.getProperty("repositoryURL"); + String repURL = config.getProperty("repositoryURL"); if(repURL==null){ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file "); throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file "); } - repURL = repURL.trim(); + if(repURL.contains(",")){ + repURLs = new ArrayList<String>(Arrays.asList(repURL.trim().split(","))); + }else{ + repURLs = new ArrayList<>(); + repURLs.add(repURL); + } repUserName = config.getProperty("repositoryUsername"); repPassword = config.getProperty("repositoryPassword"); if(repUserName==null || repPassword==null){ @@ -216,6 +225,11 @@ public class BRMSPush { throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file "); } policyKeyID = policyKeyID.trim(); + String syncF = config.getProperty("sync", "false").trim(); + syncFlag = Boolean.parseBoolean(syncF); + if(syncFlag){ + PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority."); + } brmsdependencyversion = config.getProperty("brms.dependency.version"); if(brmsdependencyversion==null){ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "brmsdependencyversion property is missing from the property file, Using default Version."); @@ -440,6 +454,9 @@ public class BRMSPush { addToPolicy(name,selectedName); } + /* + * Add Policy to JMemory and DataBase. + */ private void addToPolicy(String policyName, String controllerName) { policyMap.put(policyName, controllerName); EntityTransaction et = em.getTransaction(); @@ -523,7 +540,11 @@ public class BRMSPush { String path = PROJECTSLOCATION+ File.separator + artifactId + File.separator + "src"+ File.separator+ "main" + File.separator + "resources" + File.separator+ "rules"; new File(path).mkdirs(); - f = new File(path + File.separator + fileName); + if(syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))){ + f = new File(path + File.separator + fileName); + }else{ + f = new File(path + File.separator + fileName); + } }else if(file.getName().endsWith("pom.xml")){ String path = PROJECTSLOCATION+ File.separator + artifactId; new File(path).mkdirs(); @@ -578,22 +599,35 @@ public class BRMSPush { private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) { final NexusClient client = new NexusRestClient(); - try { - client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName, repPassword); - final NexusArtifact template = new NexusArtifact(); - template.setGroupId(getGroupID(selectedName)); - template.setArtifactId(getArtifactID(selectedName)); - if(version!=null){ - template.setVersion(version); - } - return client.searchByGAV(template); - } catch (NexusClientException | NexusConnectionException | NullPointerException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. " +e.getMessage()); - } finally { + int i = 0 ; + boolean flag = false; + while(i<repURLs.size()){ try { - client.disconnect(); - } catch (NexusClientException | NexusConnectionException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus." +e.getMessage()); + String repURL = repURLs.get(0); + client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName, repPassword); + final NexusArtifact template = new NexusArtifact(); + template.setGroupId(getGroupID(selectedName)); + template.setArtifactId(getArtifactID(selectedName)); + if(version!=null){ + template.setVersion(version); + } + List<NexusArtifact> resultList = client.searchByGAV(template); + if(resultList!=null){ + flag = true; + return resultList; + } + } catch (NexusClientException | NexusConnectionException | NullPointerException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. " +e.getMessage()); + } finally { + try { + client.disconnect(); + } catch (NexusClientException | NexusConnectionException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus." +e.getMessage()); + } + if(!flag){ + Collections.rotate(repURLs, -1); + i++; + } } } return new ArrayList<NexusArtifact>(); @@ -637,8 +671,9 @@ public class BRMSPush { * Will Push policies to the PolicyRepo. * * @param notificationType <String> type of notification Type. + * @throws PolicyException */ - public void pushRules(){ + public void pushRules() throws PolicyException{ // Check how many groups have been updated. // Invoke their Maven process. try { @@ -651,6 +686,7 @@ public class BRMSPush { if(!modifiedGroups.isEmpty()){ Boolean flag = false; for(String group: modifiedGroups.keySet()){ + InvocationResult result = null; try{ InvocationRequest request = new DefaultInvocationRequest(); setVersion(group); @@ -658,24 +694,26 @@ public class BRMSPush { request.setPomFile(new File(PROJECTSLOCATION+File.separator+getArtifactID(group)+File.separator+"pom.xml")); request.setGoals(Arrays.asList(GOALS)); Invoker invoker = new DefaultInvoker(); - InvocationResult result = invoker.execute(request); + result = invoker.execute(request); if(result.getExecutionException()!=null){ LOGGER.error(result.getExecutionException()); }else if(result.getExitCode()!=0){ LOGGER.error("Maven Invocation failure..!"); } - if(result.getExitCode()==0){ - LOGGER.info("Build Completed..!"); - if (createFlag) { - addNotification(group, "create"); - }else{ - addNotification(group, modifiedGroups.get(group)); - } - flag = true; - } }catch(Exception e){ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Maven Invocation issue for "+getArtifactID(group) + e.getMessage()); } + if(result!=null && result.getExitCode()==0){ + LOGGER.info("Build Completed..!"); + if (createFlag) { + addNotification(group, "create"); + }else{ + addNotification(group, modifiedGroups.get(group)); + } + flag = true; + }else{ + throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!"); + } } if(flag){ sendNotification(controllers); @@ -799,10 +837,10 @@ public class BRMSPush { DeploymentRepository repository = new DeploymentRepository(); repository.setId(repID); repository.setName(repName); - repository.setUrl(repURL); + repository.setUrl(repURLs.get(0)); distributionManagement.setRepository(repository); model.setDistributionManagement(distributionManagement); - // Depenendency Mangement goes here. + // Dependency Management goes here. List<Dependency> dependencyList= new ArrayList<Dependency>(); if(groupMap.get(name).size()>1){ @SuppressWarnings("unchecked") @@ -1007,6 +1045,7 @@ public class BRMSPush { File file = new File(ruleFolder+File.separator+ policyName +".drl"); if(file.delete()){ LOGGER.info("Deleted File.. " + file.getAbsolutePath()); + removePolicyFromGroup(policyName, controllerName); } if(new File(ruleFolder).listFiles().length == 0) { removedRuleModifiedGroup(controllerName); @@ -1016,6 +1055,26 @@ public class BRMSPush { } } + // Removes Policy from Memory and Database. + private void removePolicyFromGroup(String policyName, String controllerName) { + policyMap.remove(policyName); + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn"); + query.setParameter("pn", policyName); + List<?> pList = query.getResultList(); + BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo(); + if(pList.size()>0){ + // Already exists. + brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0); + if(brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)){ + em.remove(brmsPolicyInfo); + em.flush(); + } + } + et.commit(); + } + private void setVersion(String newVersion, String controllerName) { PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0); userController.setVersion(newVersion); @@ -1026,4 +1085,16 @@ public class BRMSPush { public static BackUpMonitor getBackUpMonitor(){ return bm; } + + public void rotateURLs() { + if(repURLs!=null){ + Collections.rotate(repURLs, -1); + } + } + + public int URLListSize() { + if(repURLs!=null){ + return repURLs.size(); + }else return 0; + } } diff --git a/ECOMP-ControlloopPolicy/pom.xml b/ECOMP-ControlloopPolicy/pom.xml new file mode 100644 index 000000000..18b2c5ded --- /dev/null +++ b/ECOMP-ControlloopPolicy/pom.xml @@ -0,0 +1,33 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>ControlloopPolicy</artifactId> + <parent> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>PolicyEngineSuite</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.17</version> + </dependency> + <dependency> + <groupId>org.jgrapht</groupId> + <artifactId>jgrapht-core</artifactId> + <version>0.9.2</version> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>19.0</version> + </dependency> + </dependencies> +</project> diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java new file mode 100644 index 000000000..7c124d5fd --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.compiler; + +public class CompilerException extends Exception { + + private static final long serialVersionUID = -7262217239867898601L; + + public CompilerException() { + } + + public CompilerException(String message) { + super(message); + } + + public CompilerException(Throwable cause) { + super(cause); + } + + public CompilerException(String message, Throwable cause) { + super(message, cause); + } + + public CompilerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java new file mode 100644 index 000000000..fca229242 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java @@ -0,0 +1,618 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.compiler; + +import java.io.InputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.graph.ClassBasedEdgeFactory; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedMultigraph; +import org.openecomp.policy.controlloop.policy.ControlLoop; +import org.openecomp.policy.controlloop.policy.ControlLoopPolicy; +import org.openecomp.policy.controlloop.policy.FinalResult; +import org.openecomp.policy.controlloop.policy.Policy; +import org.openecomp.policy.controlloop.policy.PolicyResult; +import org.openecomp.policy.controlloop.policy.TargetType; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +public class ControlLoopCompiler { + + public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure the control loop is sane + // + validateControlLoop(policy.controlLoop, callback); + // + // Validate the policies + // + validatePolicies(policy, callback); + return policy; + } + + public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopPolicy)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object"); + } + return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback); + } + + private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException { + if (controlLoop == null) { + if (callback != null) { + callback.onError("controlLoop cannot be null"); + } + } + if (controlLoop.controlLoopName == null | controlLoop.controlLoopName.length() < 1) { + if (callback != null) { + callback.onError("Missing controlLoopName"); + } + } + if (! controlLoop.version.contentEquals(ControlLoop.VERSION)) { + if (callback != null) { + callback.onError("Unsupported version for this compiler"); + } + } + if (controlLoop.trigger_policy == null || controlLoop.trigger_policy.length() < 1) { + throw new CompilerException("trigger_policy is not valid"); + } + // + } + + private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + if (policy == null) { + throw new CompilerException("policy cannot be null"); + } + // + // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts + // + if (policy.policies == null) { + callback.onWarning("controlLoop is an open loop."); + } + else{ + int sum = 0; + for (Policy operPolicy : policy.policies) { + sum += operPolicy.timeout.intValue(); + } + if (policy.controlLoop.timeout.intValue() < sum) { + if (callback != null) { + callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); + } + } + // + // For this version we can use a directed multigraph, in the future we may not be able to + // + DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<NodeWrapper, LabeledEdge>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class)); + // + // Check to see if the trigger Event is for OpenLoop, we do so by + // attempting to create a FinalResult object from it. If its a policy id, this should + // return null. + // + FinalResult triggerResult = FinalResult.toResult(policy.controlLoop.trigger_policy); + TriggerNodeWrapper triggerNode; + // + // Did this turn into a FinalResult object? + // + if (triggerResult != null) { + // + // Ensure they didn't use some other FinalResult code + // + if (triggerResult != FinalResult.FINAL_OPENLOOP) { + throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + } + // + // They really shouldn't have any policies attached. + // + if (policy.policies != null || policy.policies.size() > 0) { + if (callback != null) { + callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); + } + } + return; + // + } else { + // + // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. + // + triggerNode = new TriggerNodeWrapper(policy.controlLoop.controlLoopName); + } + // + // Add in the trigger node + // + graph.addVertex(triggerNode); + // + // Add in our Final Result nodes. All paths should end to these nodes. + // + FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS); + FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE); + FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT); + FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES); + FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION); + FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD); + graph.addVertex(finalSuccess); + graph.addVertex(finalFailure); + graph.addVertex(finalFailureTimeout); + graph.addVertex(finalFailureRetries); + graph.addVertex(finalFailureException); + graph.addVertex(finalFailureGuard); + // + // Work through the policies and add them in as nodes. + // + Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<Policy, PolicyNodeWrapper>(); + for (Policy operPolicy : policy.policies) { + // + // Check the policy id and make sure its sane + // + boolean okToAdd = true; + if (operPolicy.id == null || operPolicy.id.length() < 1) { + if (callback != null) { + callback.onError("Operational Policy has an bad ID"); + } + okToAdd = false; + } + // + // Check if they decided to make the ID a result object + // + if (PolicyResult.toResult(operPolicy.id) != null) { + if (callback != null) { + callback.onError("Policy id is set to a PolicyResult " + operPolicy.id); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.id) != null) { + if (callback != null) { + callback.onError("Policy id is set to a FinalResult " + operPolicy.id); + } + okToAdd = false; + } + // + // Check that the actor/recipe/target are valid + // + if (operPolicy.actor == null) { + if (callback != null) { + callback.onError("Policy actor is null"); + } + okToAdd = false; + } + // + // Construct a list for all valid actors + // + ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI"); + // + if (operPolicy.actor != null && (!actors.contains(operPolicy.actor)) ) { + if (callback != null) { + callback.onError("Policy actor is invalid"); + } + okToAdd = false; + } + if (operPolicy.recipe == null) { + if (callback != null) { + callback.onError("Policy recipe is null"); + } + okToAdd = false; + } + // + // TODO: + // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) + // + ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>() + .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig")) + .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance")) + .put("MSO", ImmutableList.of("VF Module Create")) + .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes")) + .put("SDNR", ImmutableList.of("Restart", "Reboot")) + .build(); + // + if (operPolicy.recipe != null && (!recipes.getOrDefault(operPolicy.actor, Collections.emptyList()).contains(operPolicy.recipe))) { + if (callback != null) { + callback.onError("Policy recipe is invalid"); + } + okToAdd = false; + } + if (operPolicy.target == null) { + if (callback != null) { + callback.onError("Policy target is null"); + } + okToAdd = false; + } + if (operPolicy.target != null && operPolicy.target.type != TargetType.VM && operPolicy.target.type != TargetType.VFC && operPolicy.target.type != TargetType.PNF) { + if (callback != null) { + callback.onError("Policy target is invalid"); + } + okToAdd = false; + } + // + // Check that policy results are connected to either default final * or another policy + // + if (FinalResult.toResult(operPolicy.success) != null && operPolicy.success != FinalResult.FINAL_SUCCESS.toString()) { + if (callback != null) { + callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure) != null && operPolicy.failure != FinalResult.FINAL_FAILURE.toString()) { + if (callback != null) { + callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_retries) != null && operPolicy.failure_retries != FinalResult.FINAL_FAILURE_RETRIES.toString()) { + if (callback != null) { + callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_timeout) != null && operPolicy.failure_timeout != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { + if (callback != null) { + callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_exception) != null && operPolicy.failure_exception != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { + if (callback != null) { + callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_guard) != null && operPolicy.failure_guard != FinalResult.FINAL_FAILURE_GUARD.toString()) { + if (callback != null) { + callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); + } + okToAdd = false; + } + // + // Is it still ok to add? + // + if (okToAdd == false) { + // + // Do not add it in + // + continue; + } + // + // Create wrapper policy node and save it into our map so we can + // easily retrieve it. + // + PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); + mapNodes.put(operPolicy, node); + graph.addVertex(node); + // + // Is this the trigger policy? + // + if (operPolicy.id.equals(policy.controlLoop.trigger_policy)) { + // + // Yes add an edge from our trigger event node to this policy + // + graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); + } + } + // + // last sweep to connect remaining edges for policy results + // + for (Policy operPolicy : policy.policies) { + PolicyNodeWrapper node = mapNodes.get(operPolicy); + // + // Just ensure this has something + // + if (node == null) { + continue; + } + if (FinalResult.isResult(operPolicy.success, FinalResult.FINAL_SUCCESS)) { + graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.success); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " success is connected to unknown policy " + operPolicy.success); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); + } + } + if (FinalResult.isResult(operPolicy.failure, FinalResult.FINAL_FAILURE)) { + graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure is connected to unknown policy " + operPolicy.failure); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); + } + } + if (FinalResult.isResult(operPolicy.failure_timeout, FinalResult.FINAL_FAILURE_TIMEOUT)) { + graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_timeout); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_timeout is connected to unknown policy " + operPolicy.failure_timeout); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); + } + } + if (FinalResult.isResult(operPolicy.failure_retries, FinalResult.FINAL_FAILURE_RETRIES)) { + graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_retries); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_retries is connected to unknown policy " + operPolicy.failure_retries); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); + } + } + if (FinalResult.isResult(operPolicy.failure_exception, FinalResult.FINAL_FAILURE_EXCEPTION)) { + graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_exception); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_exception is connected to unknown policy " + operPolicy.failure_exception); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); + } + } + if (FinalResult.isResult(operPolicy.failure_guard, FinalResult.FINAL_FAILURE_GUARD)) { + graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_guard); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_guard is connected to unknown policy " + operPolicy.failure_guard); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); + } + } + } + // + // Now validate all the nodes/edges + // + for (NodeWrapper node : graph.vertexSet()) { + if (node instanceof TriggerNodeWrapper) { + System.out.println("Trigger Node " + node.toString()); + if (graph.inDegreeOf(node) > 0 ) { + // + // Really should NEVER get here unless someone messed up the code above. + // + throw new CompilerException("No inputs to event trigger"); + } + // + // Should always be 1, except in the future we may support multiple events + // + if (graph.outDegreeOf(node) > 1) { + throw new CompilerException("The event trigger should only go to ONE node"); + } + } else if (node instanceof FinalResultNodeWrapper) { + System.out.println("FinalResult Node " + node.toString()); + // + // FinalResult nodes should NEVER have an out edge + // + if (graph.outDegreeOf(node) > 0) { + throw new CompilerException("FinalResult nodes should never have any out edges."); + } + } else if (node instanceof PolicyNodeWrapper) { + System.out.println("Policy Node " + node.toString()); + // + // All Policy Nodes should have the 5 out degrees defined. + // + if (graph.outDegreeOf(node) != 6) { + throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); + } + // + // Chenfei: All Policy Nodes should have at least 1 in degrees + // + if (graph.inDegreeOf(node) == 0) { + if (callback != null) { + callback.onWarning("Policy " + node.getID() + " is not reachable."); + } + } + } + for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ + System.out.println(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); + } + } + } + } + + private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) { + for (Policy key : mapNodes.keySet()) { + if (key.id.equals(id)) { + return mapNodes.get(key); + } + } + return null; + } + + private interface NodeWrapper { + + public String getID(); + + } + + private static class TriggerNodeWrapper implements NodeWrapper { + public String closedLoopControlName; + + public TriggerNodeWrapper(String closedLoopControlName) { + this.closedLoopControlName = closedLoopControlName; + } + + @Override + public String toString() { + return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; + } + + @Override + public String getID() { + return closedLoopControlName; + } + + } + + private static class FinalResultNodeWrapper implements NodeWrapper { + + public FinalResult result; + + public FinalResultNodeWrapper(FinalResult result) { + this.result = result; + } + + @Override + public String toString() { + return "FinalResultNodeWrapper [result=" + result + "]"; + } + + @Override + public String getID() { + return result.toString(); + } + } + + private static class PolicyNodeWrapper implements NodeWrapper { + + public Policy policy; + + public PolicyNodeWrapper(Policy operPolicy) { + this.policy = operPolicy; + } + + @Override + public String toString() { + return "PolicyNodeWrapper [policy=" + policy + "]"; + } + + @Override + public String getID() { + return policy.id; + } + } + + private interface EdgeWrapper { + + public String getID(); + + } + + private static class TriggerEdgeWrapper implements EdgeWrapper { + + private String trigger; + + public TriggerEdgeWrapper(String trigger) { + this.trigger = trigger; + } + + @Override + public String getID() { + return trigger; + } + + @Override + public String toString() { + return "TriggerEdgeWrapper [trigger=" + trigger + "]"; + } + + } + + private static class PolicyResultEdgeWrapper implements EdgeWrapper { + public PolicyResult policyResult; + + public PolicyResultEdgeWrapper(PolicyResult policyResult) { + super(); + this.policyResult = policyResult; + } + + @Override + public String toString() { + return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; + } + + @Override + public String getID() { + return policyResult.toString(); + } + + + } + + private static class FinalResultEdgeWrapper implements EdgeWrapper { + + public FinalResult finalResult; + public FinalResultEdgeWrapper(FinalResult result) { + this.finalResult = result; + } + + @Override + public String toString() { + return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]"; + } + + @Override + public String getID() { + return finalResult.toString(); + } + } + + + private static class LabeledEdge extends DefaultEdge { + + /** + * + */ + private static final long serialVersionUID = 579384429573385524L; + + private NodeWrapper from; + private NodeWrapper to; + private EdgeWrapper edge; + + public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) { + this.from = from; + this.to = to; + this.edge = edge; + } + + @SuppressWarnings("unused") + public NodeWrapper from() { + return from; + } + + @SuppressWarnings("unused") + public NodeWrapper to() { + return to; + } + + @SuppressWarnings("unused") + public EdgeWrapper edge() { + return edge; + } + + @Override + public String toString() { + return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]"; + } + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java new file mode 100644 index 000000000..bb6cebde4 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.compiler; + +public interface ControlLoopCompilerCallback { + + public boolean onWarning(String message); + + public boolean onError(String message); + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java new file mode 100644 index 000000000..a40bc9d53 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.guard.compiler; + + +import java.io.InputStream; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.openecomp.policy.controlloop.compiler.CompilerException; +import org.openecomp.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.openecomp.policy.controlloop.policy.guard.Constraint; +import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; +import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class ControlLoopGuardCompiler { + + public static ControlLoopGuard compile(ControlLoopGuard CLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure ControlLoopGuard has at least one guard policies + // + validateControlLoopGuard(CLGuard, callback); + // + // Ensure each guard policy has at least one constraints and all guard policies are unique + // + validateGuardPolicies(CLGuard.guards, callback); + // + // Ensure constraints for each guard policy are unique + // + validateConstraints(CLGuard.guards, callback); + + return CLGuard; + } + + public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopGuard)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopGuard object"); + } + return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); + } + + private static void validateControlLoopGuard(ControlLoopGuard CLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + if (CLGuard == null) { + if (callback != null) { + callback.onError("ControlLoop Guard cannot be null"); + } + throw new CompilerException("ControlLoop Guard cannot be null"); + } + if (CLGuard.guard == null) { + if (callback != null) { + callback.onError("Guard version cannot be null"); + } + } + if (CLGuard.guards == null) { + if (callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } else if (CLGuard.guards.size() < 1) { + if (callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } + } + + private static void validateGuardPolicies(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + // + // Ensure all guard policies are unique + // + Set<GuardPolicy> newSet = new HashSet<GuardPolicy>(policies); + if (newSet.size() != policies.size()) { + if (callback != null) { + callback.onWarning("There are duplicate guard policies"); + } + } + // + // Ensure each guard policy has at least one constraints + // + for (GuardPolicy policy : policies) { + if (policy.limit_constraints == null || policy.limit_constraints.size() < 1) { + if (callback != null) { + callback.onError("Guard policy " + policy.name + " does not have any limit constraint"); + } + throw new CompilerException("Guard policy " + policy.name + " does not have any limit constraint"); + } + } + } + + private static void validateConstraints(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + for (GuardPolicy policy : policies) { + Set<Constraint> newSet = new HashSet<Constraint>(policy.limit_constraints); + if (newSet.size() != policy.limit_constraints.size()) { + if (callback != null) { + callback.onWarning("Guard policy " + policy.name + " has duplicate limit constraints"); + } + } + } + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java new file mode 100644 index 000000000..fa144156e --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +public class ControlLoop { + + public static String VERSION = "2.0.0"; + + public String controlLoopName; + public final String version = VERSION; + public String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + public Integer timeout; + public Boolean abatement = false; + + public ControlLoop() { + + } + + public ControlLoop(ControlLoop controlLoop) { + this.controlLoopName = controlLoop.controlLoopName; + this.trigger_policy = controlLoop.trigger_policy; + this.timeout = controlLoop.timeout; + this.abatement = controlLoop.abatement; + } + @Override + public String toString() { + return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + + ", trigger_policy=" + trigger_policy + ", timeout=" + + timeout + ", abatement=" + abatement + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + result = prime * result + ((abatement == null) ? 0 : abatement.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoop other = (ControlLoop) obj; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + if (trigger_policy == null) { + if (other.trigger_policy != null) + return false; + } else if (!trigger_policy.equals(other.trigger_policy)) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + if (abatement == null) { + if (other.abatement != null) + return false; + } else if (!abatement.equals(other.abatement)) + return false; + return true; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java new file mode 100644 index 000000000..f14229bce --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +import java.util.LinkedList; + +public class ControlLoopPolicy { + + public ControlLoop controlLoop; + + public LinkedList<Policy> policies; + + @Override + public String toString() { + return "ControlLoopPolicy [controlLoop=" + controlLoop + ", policies=" + policies + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoop == null) ? 0 : controlLoop.hashCode()); + result = prime * result + ((policies == null) ? 0 : policies.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoopPolicy other = (ControlLoopPolicy) obj; + if (controlLoop == null) { + if (other.controlLoop != null) + return false; + } else if (!controlLoop.equals(other.controlLoop)) + return false; + if (policies == null) { + if (other.policies != null) + return false; + } else if (!policies.equals(other.policies)) + return false; + return true; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.java new file mode 100644 index 000000000..86b174a85 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +public enum FinalResult { + /** + * The Control Loop Policy successfully completed its Operations. + */ + FINAL_SUCCESS("Final_Success"), + /** + * The Control Loop Policy was an Open Loop and is finished. + */ + FINAL_OPENLOOP("Final_OpenLoop"), + /** + * The Control Loop Policy failed in its last Operation Policy. NOTE: Previous Operation Policies may have been successful. + */ + FINAL_FAILURE("Final_Failure"), + /** + * The Control Loop Policy failed because the overall timeout was met. + */ + FINAL_FAILURE_TIMEOUT("Final_Failure_Timeout"), + /** + * The Control Loop Policy failed because an Operation Policy met its retry limit. + */ + FINAL_FAILURE_RETRIES("Final_Failure_Retries"), + /** + * The Control Loop Policy failed due to an exception. + */ + FINAL_FAILURE_EXCEPTION("Final_Failure_Exception"), + /** + * The Control Loop Policy failed due to guard denied + */ + FINAL_FAILURE_GUARD("Final_Failure_Guard") + ; + + String result; + + private FinalResult(String result) { + this.result = result; + } + + public static FinalResult toResult(String result) { + if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { + return FINAL_SUCCESS; + } + if (result.equalsIgnoreCase(FINAL_OPENLOOP.toString())) { + return FINAL_OPENLOOP; + } + if (result.equalsIgnoreCase(FINAL_FAILURE.toString())) { + return FINAL_FAILURE; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_TIMEOUT.toString())) { + return FINAL_FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_RETRIES.toString())) { + return FINAL_FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_EXCEPTION.toString())) { + return FINAL_FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_GUARD.toString())) { + return FINAL_FAILURE_GUARD; + } + return null; + } + + public static boolean isResult(String result, FinalResult finalResult) { + FinalResult toResult = FinalResult.toResult(result); + if (toResult == null) { + return false; + } + return (toResult.equals(finalResult)); + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.java new file mode 100644 index 000000000..6cf91ce05 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +import java.io.Serializable; + +public class OperationsAccumulateParams implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3597358159130168247L; + + public String period; + public Integer limit; + + public OperationsAccumulateParams() { + + } + + public OperationsAccumulateParams(OperationsAccumulateParams ops) { + this.period = ops.period; + this.limit = ops.limit; + } + + public OperationsAccumulateParams(String period, Integer limit) { + this.period = period; + this.limit = limit; + } + + @Override + public String toString() { + return "OperationsAccumulateParams [period=" + period + ", limit=" + limit + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((period == null) ? 0 : period.hashCode()); + result = prime * result + ((limit == null) ? 0 : limit.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OperationsAccumulateParams other = (OperationsAccumulateParams) obj; + if (period == null) { + if (other.period != null) + return false; + } else if (!period.equals(other.period)) + return false; + if (limit == null) { + if (other.limit != null) + return false; + } else if (!limit.equals(other.limit)) + return false; + return true; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java new file mode 100644 index 000000000..0af1eab68 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java @@ -0,0 +1,245 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +public class Policy { + + public String id = UUID.randomUUID().toString(); + public String name; + public String description; + public String actor; + public String recipe; + public Map<String, String> payload; + public Target target; + public OperationsAccumulateParams operationsAccumulateParams; + public Integer retry = 0; + public Integer timeout = 300; + public String success = FinalResult.FINAL_SUCCESS.toString(); + public String failure = FinalResult.FINAL_FAILURE.toString(); + public String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + public String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + public String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + public String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + + + public Policy() { + + } + + public Policy(String id) { + this.id = id; + } + + public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + this.target = target; + if (payload != null) { +// this.payload = new LinkedList<Map<String, String>>(); + this.payload = Collections.unmodifiableMap(payload); + } + } + + public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target); + this.retry = retries; + this.timeout = timeout; + } + + public Policy(String id, String name, String description, String actor, Map<String, String> payload, Target target, String recipe, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target, retries, timeout); + this.id = id; + this.description = description; + } + + public Policy(Policy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.actor = policy.actor; + this.recipe = policy.recipe; + if (policy.payload != null) { +// this.payload = new LinkedList<Map<String, String>>(); +// this.payload.addAll(policy.payload); + this.payload = Collections.unmodifiableMap(policy.payload); + } + this.target = policy.target; + this.operationsAccumulateParams = policy.operationsAccumulateParams; + this.retry = policy.retry; + this.timeout = policy.timeout; + this.success = policy.success; + this.failure = policy.failure; + this.failure_exception = policy.failure_exception; + this.failure_guard = policy.failure_guard; + this.failure_retries = policy.failure_retries; + this.failure_timeout = policy.failure_timeout; + } + + public boolean isValid() { + try { + if (id == null) { + throw new NullPointerException(); + } + if (name == null) { + throw new NullPointerException(); + } + if (actor == null) { + throw new NullPointerException(); + } + if (recipe == null) { + throw new NullPointerException(); + } + if (target == null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + + return true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout + + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries + + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((failure == null) ? 0 : failure.hashCode()); + result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); + result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); + result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); + result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((retry == null) ? 0 : retry.hashCode()); + result = prime * result + ((success == null) ? 0 : success.hashCode()); + result = prime * result + ((target == null) ? 0 : target.hashCode()); + result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Policy other = (Policy) obj; + if (actor != other.actor) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (failure == null) { + if (other.failure != null) + return false; + } else if (!failure.equals(other.failure)) + return false; + if (failure_exception == null) { + if (other.failure_exception != null) + return false; + } else if (!failure_exception.equals(other.failure_exception)) + return false; + if (failure_guard == null) { + if (other.failure_guard != null) + return false; + } else if (!failure_guard.equals(other.failure_guard)) + return false; + if (failure_retries == null) { + if (other.failure_retries != null) + return false; + } else if (!failure_retries.equals(other.failure_retries)) + return false; + if (failure_timeout == null) { + if (other.failure_timeout != null) + return false; + } else if (!failure_timeout.equals(other.failure_timeout)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + if (retry == null) { + if (other.retry != null) + return false; + } else if (!retry.equals(other.retry)) + return false; + if (success == null) { + if (other.success != null) + return false; + } else if (!success.equals(other.success)) + return false; + if (operationsAccumulateParams == null) { + if (other.operationsAccumulateParams != null) + return false; + } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) + return false; + if (target == null) { + if (other.target != null) + return false; + } else if (!target.equals(other.target)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + return true; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java new file mode 100644 index 000000000..cfcd624f3 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +public enum PolicyResult { + /** + * Operation was successful. + */ + SUCCESS("Success"), + /** + * Operation failed. + */ + FAILURE("Failure"), + /** + * Operation failed due to maximum retries being met. + */ + FAILURE_RETRIES("Failure_Retries"), + /** + * Operation failed due to timeout occurring. + */ + FAILURE_TIMEOUT("Failure_Timeout"), + /** + * Operation failed due to an exception. + */ + FAILURE_EXCEPTION("Failure_Exception"), + /** + * Operation failed since Guard did not permit. + */ + FAILURE_GUARD("Failure_Guard") + ; + + private String result; + + private PolicyResult(String result) { + this.result = result; + } + + public String toString() { + return this.result; + } + + public static PolicyResult toResult(String result) { + if (result.equalsIgnoreCase(SUCCESS.toString())) { + return SUCCESS; + } + if (result.equalsIgnoreCase(FAILURE.toString())) { + return FAILURE; + } + if (result.equalsIgnoreCase(FAILURE_RETRIES.toString())) { + return FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FAILURE_TIMEOUT.toString())) { + return FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FAILURE_EXCEPTION.toString())) { + return FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FAILURE_GUARD.toString())) { + return FAILURE_GUARD; + } + return null; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java new file mode 100644 index 000000000..9bccf0feb --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +import java.io.Serializable; + +public class Target implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 2180988443264988319L; + + public String resourceID; + public TargetType type; + + public Target() { + + } + + public Target(TargetType type) { + this.type = type; + } + + public Target(String resourceID) { + this.resourceID = resourceID; + } + + public Target(TargetType type, String resourceID) { + this.type = type; + this.resourceID = resourceID; + } + + public Target(Target target) { + this.type = target.type; + this.resourceID = target.resourceID; + } + + @Override + public String toString() { + return "Target [type=" + type + ", resourceID=" + resourceID + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((resourceID == null) ? 0 : resourceID.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Target other = (Target) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + if (resourceID == null) { + if (other.resourceID != null) + return false; + } else if (!resourceID.equals(other.resourceID)) + return false; + return true; + } +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java new file mode 100644 index 000000000..c5e4abce0 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy; + +public enum TargetType { + VM("VM"), + PNF("PNF"), + VFC("VFC") + ; + + private String targetType; + + private TargetType(String targetType) { + this.targetType = targetType; + } + + public String toString() { + return this.targetType; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java new file mode 100644 index 000000000..a087463b9 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder; + +public class BuilderException extends Exception { + + public BuilderException(String string) { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = 610064813684337895L; + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java new file mode 100644 index 000000000..fb10f292c --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder; + +import java.util.Map; + +import org.openecomp.policy.controlloop.policy.ControlLoop; +import org.openecomp.policy.controlloop.policy.OperationsAccumulateParams; +import org.openecomp.policy.controlloop.policy.Policy; +import org.openecomp.policy.controlloop.policy.PolicyResult; +import org.openecomp.policy.controlloop.policy.Target; +import org.openecomp.policy.controlloop.policy.builder.impl.ControlLoopPolicyBuilderImpl; + +public interface ControlLoopPolicyBuilder { + + /** + * @param abatement + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; + + + /** + * Sets the overall timeout value for the Control Loop. If any operational policies have retries and timeouts, + * then this overall timeout value should exceed all those values. + * + * @param timeout + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; + + /** + * Scans the operational policies and calculate an minimum overall timeout for the Control Loop. + * + * + * @return Integer + */ + public Integer calculateTimeout(); + + /** + * Sets the initial trigger policy when a DCAE Closed Loop Event arrives in the ECOMP Policy Platform. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @return Policy + * @throws BuilderException + */ + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException; + + /** + * + * Changes the trigger policy to point to another existing Policy. + * + * + * @param id + * @return ControlLoop + * @throws BuilderException + */ + public ControlLoop setTriggerPolicy(String id) throws BuilderException; + + /** + * @return + */ + public boolean isOpenLoop(); + + /** + * @return + * @throws BuilderException + */ + public Policy getTriggerPolicy() throws BuilderException; + + /** + * Simply returns a copy of the ControlLoop information. + * + * + * @return ControlLoop + */ + public ControlLoop getControlLoop(); + + /** + * Creates a policy that is chained to the result of another Policy. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException; + + + /** + * Sets the policy result(s) to an existing Operational Policy. + * + * + * @param policyResultID + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) throws BuilderException; + + /** + * Removes an Operational Policy. Be mindful that if any other Operational Policies have results that point to this policy, any + * policies that have results pointing to this policy will have their result reset to the appropriate default FINAL_* result. + * + * + * @param policyID + * @return + * @throws BuilderException + */ + public boolean removePolicy(String policyID) throws BuilderException; + + /** + * Resets a policy's results to defualt FINAL_* codes. + * + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy resetPolicyResults(String policyID) throws BuilderException; + + /** + * Removes all existing Operational Policies and reverts back to an Open Loop. + * + * @return + */ + public ControlLoopPolicyBuilder removeAllPolicies(); + + /** + * Adds an operationsAccumulateParams to an existing operational policy + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException; + + /** + * This will compile and build the YAML specification for the Control Loop Policy. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopPolicyBuilder implementation. + * + * @author pameladragosh + * + */ + public static class Factory { + + /** + * Builds a basic Control Loop with an overall timeout. Use this method if you wish to create an OpenLoop, or if you + * want to interactively build a Closed Loop. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); + + return builder; + } + + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java new file mode 100644 index 000000000..35aa3666f --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder; + +public interface Message { + + public String getMessage(); + + public MessageLevel getLevel(); + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java new file mode 100644 index 000000000..3c09d3813 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder; + +public enum MessageLevel { + INFO, + WARNING, + ERROR, + EXCEPTION + ; + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.java new file mode 100644 index 000000000..172524a78 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder; + +import java.util.List; + +public interface Results { + + public List<Message> getMessages(); + + public String getSpecification(); + + public boolean isValid(); + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java new file mode 100644 index 000000000..be34a0a24 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java @@ -0,0 +1,383 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder.impl; + +import java.util.LinkedList; +import java.util.Map; +import java.util.UUID; + +import org.openecomp.policy.controlloop.compiler.CompilerException; +import org.openecomp.policy.controlloop.compiler.ControlLoopCompiler; +import org.openecomp.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.openecomp.policy.controlloop.policy.ControlLoop; +import org.openecomp.policy.controlloop.policy.ControlLoopPolicy; +import org.openecomp.policy.controlloop.policy.FinalResult; +import org.openecomp.policy.controlloop.policy.OperationsAccumulateParams; +import org.openecomp.policy.controlloop.policy.Policy; +import org.openecomp.policy.controlloop.policy.PolicyResult; +import org.openecomp.policy.controlloop.policy.Target; +import org.openecomp.policy.controlloop.policy.builder.BuilderException; +import org.openecomp.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; +import org.openecomp.policy.controlloop.policy.builder.MessageLevel; +import org.openecomp.policy.controlloop.policy.builder.Results; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; + +public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { + + private ControlLoopPolicy policy; + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { + policy = new ControlLoopPolicy(); + policy.controlLoop = new ControlLoop(); + policy.controlLoop.controlLoopName = controlLoopName; + policy.controlLoop.timeout = timeout; + } + + @Override + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{ + if (abatement == null) { + throw new BuilderException("abatement must not be null"); + } + policy.controlLoop.abatement = abatement; + return this; + } + + @Override + public ControlLoopPolicyBuilder setTimeout(Integer timeout) { + policy.controlLoop.timeout = timeout; + return this; + } + + @Override + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, + Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException { + + Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + + policy.controlLoop.trigger_policy = trigger.id; + + this.addNewPolicy(trigger); + // + // Return a copy of the policy + // + return new Policy(trigger); + } + + @Override + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Create the new Policy + // + Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.failure = newPolicy.id; + break; + case FAILURE_EXCEPTION: + existingPolicy.failure_exception = newPolicy.id; + break; + case FAILURE_RETRIES: + existingPolicy.failure_retries = newPolicy.id; + break; + case FAILURE_TIMEOUT: + existingPolicy.failure_timeout = newPolicy.id; + break; + case FAILURE_GUARD: + existingPolicy.failure_guard = newPolicy.id; + break; + case SUCCESS: + existingPolicy.success = newPolicy.id; + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + // + // Add it to our list + // + this.policy.policies.add(newPolicy); + // + // Return a policy to them + // + return new Policy(newPolicy); + } + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + + public ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } + + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } + + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(policy); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopCompiler.compile(policy, callback); + } catch (CompilerException e) { + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + + private void addNewPolicy(Policy policy) { + if (this.policy.policies == null) { + this.policy.policies = new LinkedList<Policy>(); + } + this.policy.policies.add(policy); + } + + private Policy findPolicy(String id) { + for (Policy policy : this.policy.policies) { + if (policy.id.equals(id)) { + return policy; + } + } + return null; + } + + @Override + public Integer calculateTimeout() { + int sum = 0; + for (Policy policy : this.policy.policies) { + sum += policy.timeout.intValue(); + } + return new Integer(sum); + } + + @Override + public ControlLoop setTriggerPolicy(String id) throws BuilderException { + if (id == null) { + throw new BuilderException("Id must not be null"); + } + Policy trigger = this.findPolicy(id); + if (trigger == null) { + throw new BuilderException("Unknown policy " + id); + } + else { + this.policy.controlLoop.trigger_policy = id; + } + return new ControlLoop(this.policy.controlLoop); + } + + @Override + public boolean isOpenLoop() { + if (this.policy.controlLoop.trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())) { + return true; + } + else { + return false; + } + } + + @Override + public Policy getTriggerPolicy() throws BuilderException { + if (this.policy.controlLoop.trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())) { + return null; + } + else { + Policy trigger = new Policy(this.findPolicy(this.policy.controlLoop.trigger_policy)); + return trigger; + } + } + + @Override + public ControlLoop getControlLoop() { + ControlLoop loop = new ControlLoop(this.policy.controlLoop); + return loop; + } + + @Override + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) + throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException(policyID + " does not exist"); + } + if (this.findPolicy(policyResultID) == null) { + throw new BuilderException("Operational policy " + policyResultID + " does not exist"); + } + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.failure = policyResultID; + break; + case FAILURE_EXCEPTION: + existingPolicy.failure_exception = policyResultID; + break; + case FAILURE_RETRIES: + existingPolicy.failure_retries = policyResultID; + break; + case FAILURE_TIMEOUT: + existingPolicy.failure_timeout = policyResultID; + break; + case FAILURE_GUARD: + existingPolicy.failure_guard = policyResultID; + break; + case SUCCESS: + existingPolicy.success = policyResultID; + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + return new Policy(this.findPolicy(policyResultID)); + } + + @Override + public boolean removePolicy(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Check if the policy to remove is trigger_policy + // + if (this.policy.controlLoop.trigger_policy.equals(policyID)) { + this.policy.controlLoop.trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + } + else { + // + // Update policies + // + for (Policy policy : this.policy.policies) { + int index = this.policy.policies.indexOf(policy); + if (policy.success.equals(policyID)) { + policy.success = FinalResult.FINAL_SUCCESS.toString(); + } + if (policy.failure.equals(policyID)) { + policy.failure = FinalResult.FINAL_FAILURE.toString(); + } + if (policy.failure_retries.equals(policyID)) { + policy.failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + } + if (policy.failure_timeout.equals(policyID)) { + policy.failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + } + if (policy.failure_exception.equals(policyID)) { + policy.failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + } + if (policy.failure_guard.equals(policyID)) { + policy.failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + } + this.policy.policies.set(index, policy); + } + } + // + // remove the policy + // + boolean removed = this.policy.policies.remove(existingPolicy); + return removed; + } + + @Override + public Policy resetPolicyResults(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // reset policy results + // + existingPolicy.success = FinalResult.FINAL_SUCCESS.toString(); + existingPolicy.failure = FinalResult.FINAL_FAILURE.toString(); + existingPolicy.failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + existingPolicy.failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + existingPolicy.failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + existingPolicy.failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + return new Policy(existingPolicy); + } + + @Override + public ControlLoopPolicyBuilder removeAllPolicies() { + // + // Remove all existing operational policies + // + this.policy.policies.clear(); + // + // Revert controlLoop back to an open loop + // + this.policy.controlLoop.trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + return this; + } + + @Override + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Add operationsAccumulateParams to existingPolicy + // + existingPolicy.operationsAccumulateParams = operationsAccumulateParams; + return new Policy(existingPolicy); + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java new file mode 100644 index 000000000..3938aa899 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder.impl; + +import org.openecomp.policy.controlloop.policy.builder.Message; +import org.openecomp.policy.controlloop.policy.builder.MessageLevel; + +public class MessageImpl implements Message { + + private String message; + private MessageLevel level; + + public MessageImpl(String message, MessageLevel level) { + this.message = message; + this.level = level; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public MessageLevel getLevel() { + return level; + } + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java new file mode 100644 index 000000000..f7941533c --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.builder.impl; + +import java.util.LinkedList; +import java.util.List; + +import org.openecomp.policy.controlloop.policy.builder.Message; +import org.openecomp.policy.controlloop.policy.builder.Results; + +public class ResultsImpl implements Results { + + private String specification; + private List<Message> messages = new LinkedList<Message>(); + + @Override + public List<Message> getMessages() { + return messages; + } + + @Override + public String getSpecification() { + return specification; + } + + @Override + public boolean isValid() { + return (this.specification != null); + } + + public void addMessage(Message message) { + this.messages.add(message); + } + + public void setSpecification(String spec) { + this.specification = spec; + } +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java new file mode 100644 index 000000000..7d7991787 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.guard; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class Constraint { + + public Integer num; + public String duration; + public Map<String, String> time_in_range; + + public LinkedList<String> blacklist; + + public Constraint() { + + } + + public Constraint(Integer num, String duration) { + this.num = num; + this.duration = duration; + } + + public Constraint(List<String> blacklist) { + this.blacklist = new LinkedList<String>(blacklist); + + } + + public Constraint(Integer num, String duration, Map<String, String> time_in_range) { + this(num, duration); + if (time_in_range != null) { + this.time_in_range = Collections.unmodifiableMap(time_in_range); + } + } + + public Constraint(Integer num, String duration, List<String> blacklist) { + this.num = num; + this.duration = duration; + this.blacklist = new LinkedList<String>(blacklist); + } + + public Constraint(Integer num, String duration, Map<String, String> time_in_range, List<String> blacklist) { + this(num, duration); + if (time_in_range != null) { + this.time_in_range = Collections.unmodifiableMap(time_in_range); + } + this.blacklist = new LinkedList<String>(blacklist); + } + + public Constraint(Constraint constraint) { + this.num = constraint.num; + this.duration = constraint.duration; + if (constraint.time_in_range != null) { + this.time_in_range = Collections.unmodifiableMap(constraint.time_in_range); + } + this.blacklist = new LinkedList<String>(constraint.blacklist); + } + + public boolean isValid() { + try { + if (num == null && duration != null) { + throw new NullPointerException(); + } + if (duration == null && num != null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Constraint [num=" + num + ", duration=" + duration + ", time_in_range=" + time_in_range + ", blacklist=" + blacklist + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((num == null) ? 0 : num.hashCode()); + result = prime * result + ((duration == null) ? 0 : duration.hashCode()); + result = prime * result + ((time_in_range == null) ? 0 : time_in_range.hashCode()); + result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Constraint other = (Constraint) obj; + if (num == null) { + if (other.num != null) + return false; + } else if (!num.equals(other.num)) + return false; + if (duration == null) { + if (other.duration != null) + return false; + } else if (!duration.equals(other.duration)) + return false; + if (time_in_range == null) { + if (other.time_in_range != null) + return false; + } else if (!time_in_range.equals(other.time_in_range)) + return false; + if (blacklist == null) { + if (other.blacklist != null) + return false; + } else if (!blacklist.equals(other.blacklist)) + return false; + return true; + } +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java new file mode 100644 index 000000000..37fd431a0 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.guard; + +import java.util.LinkedList; + +public class ControlLoopGuard { + + public Guard guard; + + public LinkedList<GuardPolicy> guards; + + public ControlLoopGuard() { + + } + + public ControlLoopGuard(ControlLoopGuard CLGuard) { + this.guard = new Guard(); + this.guards = new LinkedList<GuardPolicy>(CLGuard.guards); + } + + @Override + public String toString() { + return "Guard [guard=" + guard + ", GuardPolicies=" + guards + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((guard == null) ? 0 : guard.hashCode()); + result = prime * result + ((guards == null) ? 0 : guards.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoopGuard other = (ControlLoopGuard) obj; + if (guard == null) { + if (other.guard != null) + return false; + } else if (!guard.equals(other.guard)) + return false; + if (guards == null) { + if (other.guards != null) + return false; + } else if (!guards.equals(other.guards)) + return false; + return true; + } + + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java new file mode 100644 index 000000000..f3e765107 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.guard; + +public class Guard { + + public static String VERSION = "2.0.0"; + + public final String version = VERSION; + + public Guard() { + + } + + @Override + public String toString() { + return "Guard [version=" + version + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Guard other = (Guard) obj; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java new file mode 100644 index 000000000..0195fac17 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.guard; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +public class GuardPolicy { + + public String id = UUID.randomUUID().toString(); + public String name; + public String description; + public String actor; + public String recipe; + public LinkedList<Constraint> limit_constraints; + + public GuardPolicy() { + + } + + public GuardPolicy(String id) { + this.id = id; + } + + public GuardPolicy(String name, String actor, String recipe) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + } + + public GuardPolicy(String id, String name, String description, String actor, String recipe) { + this(name, actor, recipe); + this.id = id; + this.description = description; + } + + public GuardPolicy(String name, String actor, String recipe, List<Constraint> limit_constraints) { + this(name, actor, recipe); + if (limit_constraints != null) { + this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(limit_constraints); + } + } + + public GuardPolicy(String name, String description, String actor, String recipe, List<Constraint> limit_constraints) { + this(name, actor, recipe, limit_constraints); + this.description = description; + } + + public GuardPolicy(String id, String name, String description, String actor, String recipe, List<Constraint> limit_constraints) { + this(name, description, actor, recipe, limit_constraints); + this.id = id; + } + + public GuardPolicy(GuardPolicy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.actor = policy.actor; + this.recipe = policy.recipe; + if (policy.limit_constraints != null) { + this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(policy.limit_constraints); + } + } + + public boolean isValid() { + try { + if (id == null) { + throw new NullPointerException(); + } + if (name == null) { + throw new NullPointerException(); + } + if (actor == null) { + throw new NullPointerException(); + } + if (recipe == null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + + recipe + ", limit_constraints=" + limit_constraints + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + GuardPolicy other = (GuardPolicy) obj; + if (actor == null) { + if (other.actor != null) + return false; + } else if (!actor.equals(other.actor)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (limit_constraints == null) { + if (other.limit_constraints != null) + return false; + } else if (!limit_constraints.equals(other.limit_constraints)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + return true; + } + + +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java new file mode 100644 index 000000000..c09757db6 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.guard.builder; + +import org.openecomp.policy.controlloop.policy.builder.BuilderException; +import org.openecomp.policy.controlloop.policy.builder.Results; +import org.openecomp.policy.controlloop.policy.guard.Constraint; +import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; +import org.openecomp.policy.controlloop.policy.guard.Guard; +import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; +import org.openecomp.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBuilderImpl; + +public interface ControlLoopGuardBuilder { + + /** + * Adds one or more guard policies to the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes one or more guard policies from the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes all guard policies from the Control Loop Guard + * + * + * @param + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; + + /** + * Adds one or more time limit constraints to the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes one or more time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes all time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; + + /** + * Simply return a copy of control loop guard + * + * @return ControlLoopGuard + */ + public ControlLoopGuard getControlLoopGuard(); + + /** + * This will compile and build the YAML specification for the Control Loop Guard. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopGuardBuilder implementation. + * + */ + public static class Factory { + + /** + * @param guard + * @return ControlLoopGuardBuilder object + * @throws BuilderException + */ + public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { + + ControlLoopGuardBuilder builder = new ControlLoopGuardBuilderImpl(guard); + + return builder; + } + } +} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java new file mode 100644 index 000000000..b119620e3 --- /dev/null +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.controlloop.policy.guard.builder.impl; + +import java.util.LinkedList; + +import org.openecomp.policy.controlloop.compiler.CompilerException; +import org.openecomp.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.openecomp.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; +import org.openecomp.policy.controlloop.policy.builder.BuilderException; +import org.openecomp.policy.controlloop.policy.builder.MessageLevel; +import org.openecomp.policy.controlloop.policy.builder.Results; +import org.openecomp.policy.controlloop.policy.builder.impl.MessageImpl; +import org.openecomp.policy.controlloop.policy.builder.impl.ResultsImpl; +import org.openecomp.policy.controlloop.policy.guard.Constraint; +import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; +import org.openecomp.policy.controlloop.policy.guard.Guard; +import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; +import org.openecomp.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; + +public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { + + private ControlLoopGuard CLGuard; + + public ControlLoopGuardBuilderImpl(Guard guard) { + CLGuard = new ControlLoopGuard(); + CLGuard.guard = guard; + } + + @Override + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException { + if (policies == null) { + throw new BuilderException("GuardPolicy must not be null"); + } + for (GuardPolicy policy : policies) { + if (!policy.isValid()) { + throw new BuilderException("Invalid guard policy - some required fields are missing"); + } + if (CLGuard.guards == null) { + CLGuard.guards = new LinkedList<GuardPolicy>(); + } + CLGuard.guards.add(policy); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException { + if (policies == null) { + throw new BuilderException("GuardPolicy must not be null"); + } + if (CLGuard.guards == null) { + throw new BuilderException("No existing guard policies to remove"); + } + for (GuardPolicy policy : policies) { + if (!policy.isValid()) { + throw new BuilderException("Invalid guard policy - some required fields are missing"); + } + boolean removed = CLGuard.guards.remove(policy); + if (!removed) { + throw new BuilderException("Unknown guard policy: " + policy.name); + } + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException { + CLGuard.guards.clear(); + return this; + } + + @Override + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException { + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + if (constraints == null) { + throw new BuilderException("Constraint much not be null"); + } + boolean exist = false; + for (GuardPolicy policy: CLGuard.guards) { + // + // We could have only one guard policy matching the id + // + if (policy.id.equals(id)) { + exist = true; + for (Constraint cons: constraints) { + if (!cons.isValid()) { + throw new BuilderException("Invalid guard constraint - some required fields are missing"); + } + if (policy.limit_constraints == null) { + policy.limit_constraints = new LinkedList<Constraint>(); + } + policy.limit_constraints.add(cons); + } + break; + } + } + if (exist == false) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException { + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + if (constraints == null) { + throw new BuilderException("Constraint much not be null"); + } + boolean exist = false; + for (GuardPolicy policy: CLGuard.guards) { + // + // We could have only one guard policy matching the id + // + if (policy.id.equals(id)) { + exist = true; + for (Constraint cons: constraints) { + if (!cons.isValid()) { + throw new BuilderException("Invalid guard constraint - some required fields are missing"); + } + boolean removed = policy.limit_constraints.remove(cons); + if (!removed) { + throw new BuilderException("Unknown guard constraint: " + cons); + } + } + break; + } + } + if (exist == false) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException { + if (CLGuard.guards == null || CLGuard.guards.isEmpty()) { + throw new BuilderException("No guard policies exist"); + } + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + boolean exist = false; + for (GuardPolicy policy: CLGuard.guards) { + if (policy.id.equals(id)) { + exist = true; + policy.limit_constraints.clear(); + } + } + if (exist == false) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + + public ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } + + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } + + @Override + public ControlLoopGuard getControlLoopGuard() { + ControlLoopGuard guard = new ControlLoopGuard(this.CLGuard); + return guard; + } + + + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(CLGuard); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopGuardCompiler.compile(CLGuard, callback); + } catch (CompilerException e) { + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + +} diff --git a/ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml b/ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml new file mode 100644 index 000000000..3a7f25008 --- /dev/null +++ b/ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:xacml:policy:id:d56af069-6cf1-430c-ba07-e26602e06a52" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"> + <Description>${description}</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${PolicyName}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="PolicyName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + <AllOf> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${ECOMPName}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="ECOMPName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="actor" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="recipe" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a" Effect="Permit"> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">DECIDE</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </Apply> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="org:openecomp:xacml:sql:${timeWindow}" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue> + </Apply> + </Apply> + </Condition> + </Rule> + <Rule RuleId="urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a" Effect="Deny"> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">DECIDE</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </Apply> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="org:openecomp:xacml:sql:${timeWindow}" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue> + </Apply> + </Apply> + </Apply> + </Condition> + <AdviceExpressions> + <AdviceExpression AdviceId="GUARD_YAML" AppliesTo="Deny"> + <AttributeAssignmentExpression AttributeId="guard.response" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Denied!</AttributeValue> + </AttributeAssignmentExpression> + </AdviceExpression> + </AdviceExpressions> + </Rule> +</Policy>
\ No newline at end of file diff --git a/ECOMP-PAP-REST/pom.xml b/ECOMP-PAP-REST/pom.xml index 5d35edaf6..f05729ebb 100644 --- a/ECOMP-PAP-REST/pom.xml +++ b/ECOMP-PAP-REST/pom.xml @@ -75,6 +75,18 @@ <groupId>org.json</groupId> <artifactId>json</artifactId> </exclusion> + <exclusion> + <groupId>com.att.nsa</groupId> + <artifactId>dmaapClient</artifactId> + </exclusion> + <exclusion> + <groupId>com.att.nsa</groupId> + <artifactId>cambriaClient</artifactId> + </exclusion> + <exclusion> + <groupId>com.att.cadi</groupId> + <artifactId>cadi-aaf</artifactId> + </exclusion> </exclusions> </dependency> <dependency> @@ -125,6 +137,11 @@ <version>1.3.1</version> </dependency> <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-core</artifactId> + <version>2.8.2</version> + </dependency> + <dependency> <groupId>log4j</groupId> <artifactId>apache-log4j-extras</artifactId> <version>1.2.17</version> @@ -192,6 +209,11 @@ <version>2.0.8</version> </dependency> <dependency> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>ControlloopPolicy</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> <groupId>com.mockrunner</groupId> <artifactId>mockrunner</artifactId> <version>0.3.1</version> diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java index b7b47cf28..4c67d798a 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java @@ -20,18 +20,44 @@ package org.openecomp.policy.pap.xacml.rest.components; +import java.io.ByteArrayInputStream; +import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.Query; +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.controlloop.policy.builder.BuilderException; +import org.openecomp.policy.controlloop.policy.builder.Results; +import org.openecomp.policy.controlloop.policy.guard.Constraint; +import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; +import org.openecomp.policy.controlloop.policy.guard.Guard; +import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; +import org.openecomp.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; +import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; +import org.openecomp.policy.pap.xacml.rest.util.JPAUtils; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.Datatype; +import org.openecomp.policy.rest.jpa.DecisionSettings; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; + +import com.att.research.xacml.std.IdentifierImpl; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -50,22 +76,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.util.JPAUtils; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.DecisionSettings; -import org.openecomp.policy.rest.jpa.FunctionDefinition; -import org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine; - -import com.att.research.xacml.std.IdentifierImpl; - public class DecisionPolicy extends Policy { public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; private static final String AAFProvider = "AAF"; + public static final String GUARD_YAML = "GUARD_YAML"; + private static final String XACMLTEMPLATE = "Decision_GuardPolicyTemplate.xml"; + List<String> dynamicLabelRuleAlgorithms = new LinkedList<String>(); List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<String>(); @@ -131,7 +148,25 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if (policyAdapter.getData() != null) { + if(policyAdapter.getRuleProvider().equals(GUARD_YAML)){ + Map<String, String> yamlParams = new HashMap<String, String>(); + yamlParams.put("description", (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy"); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + yamlParams.put("PolicyName", name); + yamlParams.put("ECOMPName", policyAdapter.getEcompName()); + Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes(); + yamlParams.putAll(params); + // Call YAML to XACML + PolicyType decisionPolicy = getGuardPolicy(yamlParams); + decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + decisionPolicy.setVersion(Integer.toString(version)); + policyAdapter.setPolicyData(decisionPolicy); + policyAdapter.setData(decisionPolicy); + }else if (policyAdapter.getData() != null) { PolicyType decisionPolicy = (PolicyType) policyAdapter.getData(); decisionPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -174,7 +209,7 @@ public class DecisionPolicy extends Policy { Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap(); //dynamicVariableList = policyAdapter.getDynamicVariableList(); - if(policyAdapter.getProviderComboBox()!=null && policyAdapter.getProviderComboBox().equals(AAFProvider)){ + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){ dynamicFieldDecisionSettings = new HashMap<String,String>(); } @@ -196,6 +231,47 @@ public class DecisionPolicy extends Policy { return true; } + public PolicyType getGuardPolicy(Map<String, String> yamlParams) { + try { + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); + GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get("PolicyName"), yamlParams.get("description"), yamlParams.get("actor"), yamlParams.get("recipe")); + builder = builder.addGuardPolicy(policy1); + Map<String, String> time_in_range = new HashMap<String, String>(); + time_in_range.put("arg2", yamlParams.get("guardActiveStart")); + time_in_range.put("arg3", yamlParams.get("guardActiveEnd")); + Constraint cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), yamlParams.get("timeWindow"), time_in_range); + builder = builder.addLimitConstraint(policy1.id, cons); + // Build the specification + Results results = builder.buildSpecification(); + // YAML TO XACML + ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification()); + Path xacmlTemplatePath = Paths.get(XACMLTEMPLATE); + String xacmlTemplateContent; + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + HashMap<String, String> yamlSpecs = new HashMap<String, String>(); + yamlSpecs.put("PolicyName", yamlParams.get("PolicyName")); + yamlSpecs.put("description", yamlParams.get("description")); + yamlSpecs.put("ECOMPName", yamlParams.get("ECOMPName")); + yamlSpecs.put("actor", yamlGuardObject.guards.getFirst().actor); + yamlSpecs.put("recipe", yamlGuardObject.guards.getFirst().recipe); + yamlSpecs.put("limit", yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num.toString()); + yamlSpecs.put("timeWindow", yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration); + yamlSpecs.put("guardActiveStart", yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg2")); + yamlSpecs.put("guardActiveEnd", yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg3")); + String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs); + // Convert the Policy into Stream input to Policy Adapter. + Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8))); + return (PolicyType) policy; + } catch (IOException e) { + PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage()); + } + } catch (BuilderException e) { + PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage()); + } + return null; + } + private DecisionSettings findDecisionSettingsBySettingId(String settingId) { DecisionSettings decisionSetting = null; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java new file mode 100644 index 000000000..7637719b1 --- /dev/null +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PAP-REST + * ================================================================================ + * 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.openecomp.policy.pap.xacml.rest.components; + +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class SafePolicyBuilder { + + public static ControlLoopGuard loadYamlGuard(String specification) { + // + // Read the yaml into our Java Object + // + PolicyLogger.info("Requested YAML to convert : " + specification); + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(specification); + return (ControlLoopGuard) obj; + } + + public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap) { + for(String key: generateMap.keySet()){ + Pattern p = Pattern.compile("\\$\\{" +key +"\\}"); + Matcher m = p.matcher(xacmlFileContent); + String finalInput = generateMap.get(key); + if(finalInput.contains("$")){ + finalInput = finalInput.replace("$", "\\$"); + } + xacmlFileContent=m.replaceAll(finalInput); + } + PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); + + return xacmlFileContent; + } +} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index 75a3c7fa0..876f380d4 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -55,6 +55,7 @@ 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.gson.Gson; @Controller public class MicroServiceDictionaryController { @@ -100,7 +101,7 @@ public class MicroServiceDictionaryController { response.getWriter().write(j.toString()); } catch (Exception e){ - e.printStackTrace(); + LOGGER.error(e); } } @@ -225,7 +226,7 @@ public class MicroServiceDictionaryController { return null; } catch (Exception e){ - System.out.println(e); + LOGGER.error(e); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -246,7 +247,7 @@ public class MicroServiceDictionaryController { response.getWriter().write(j.toString()); } catch (Exception e){ - e.printStackTrace(); + LOGGER.error(e); } } @@ -374,7 +375,7 @@ public class MicroServiceDictionaryController { return null; } catch (Exception e){ - System.out.println(e); + LOGGER.error(e); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -394,7 +395,7 @@ public class MicroServiceDictionaryController { response.getWriter().write(j.toString()); } catch (Exception e){ - e.printStackTrace(); + LOGGER.error(e); } } @@ -520,7 +521,7 @@ public class MicroServiceDictionaryController { return null; } catch (Exception e){ - System.out.println(e); + LOGGER.error(e); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -757,7 +758,7 @@ public class MicroServiceDictionaryController { catch (Exception e){ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", "dictionaryDBQuery"); - e.printStackTrace(); + LOGGER.error(e); } } @@ -785,74 +786,128 @@ public class MicroServiceDictionaryController { public ModelAndView saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ try { boolean duplicateflag = false; - boolean fromAPI = false; - this.newModel = new MicroServiceModels(); - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } + boolean fromAPI = false; + this.newModel = new MicroServiceModels(); + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - MicroServiceModels microServiceModels = new MicroServiceModels(); - String userId = null; - if (fromAPI) { - microServiceModels = (MicroServiceModels)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceModels.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter(OPERATION).equals("update")) { - String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); - int id = 0; - for (int i=0; i< duplicateData.size(); i++){ - MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); - id = data.getId(); - } - microServiceModels.setId(id); - microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); - - } - } else { - //microServiceModels = (MicroServiceModels)mapper.readValue(root.get("microServiceModelsDictionaryData").toString(), MicroServiceModels.class); - if (root.has("microServiceModelsDictionaryData")){ - if (root.get("microServiceModelsDictionaryData").has("description")){ - microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); - } - if (root.get("microServiceModelsDictionaryData").has("modelName")){ - microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); - this.newModel.setModelName(microServiceModels.getModelName()); - } - if (root.get("microServiceModelsDictionaryData").has("version")){ - microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); - this.newModel.setVersion(microServiceModels.getVersion()); - } - } - if(root.has("classMap")){ - classMap = new HashMap<String, MSAttributeObject>(); - JsonNode data = root.get("classMap"); - ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); - data1 = data1.replace("\\", ""); - JSONObject jsonObject = new JSONObject(data1); - Set<String> keys = jsonObject.keySet(); - for(String key : keys){ - String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); - classMap.put(key, msAttributeObject); - } - } - userId = root.get("userid").textValue(); - addValuesToNewModel(classMap); - } + MicroServiceModels microServiceModels = new MicroServiceModels(); + String userId = null; + + if(root.has("modelType")){ + JsonNode dataType = root.get("modelType"); + String modelType= dataType.toString(); + if(modelType.contains("yml")){ + if (root.has("microServiceModelsDictionaryData")){ + if (root.get("microServiceModelsDictionaryData").has("description")){ + microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); + } + if (root.get("microServiceModelsDictionaryData").has("modelName")){ + microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); + this.newModel.setModelName(microServiceModels.getModelName()); + } + if (root.get("microServiceModelsDictionaryData").has("version")){ + microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); + this.newModel.setVersion(microServiceModels.getVersion()); + } + } + + MSAttributeObject mainClass = null; + classMap = new HashMap<String, MSAttributeObject>(); + JsonNode data = root.get("classMap"); + ObjectMapper mapper1 = new ObjectMapper(); + String data1 = data.toString().substring(1, data.toString().length()-1); + data1 = data1.replace("\\", ""); + data1=data1.replace("\"{","{"); + data1=data1.replace("}\"","}"); + JSONObject jsonObject = new JSONObject(data1); + Set<String> keys = jsonObject.keySet(); + for(String key : keys){ + String value = jsonObject.get(key).toString(); + MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + classMap.put(key, msAttributeObject); + } + + userId = root.get("userid").textValue(); + mainClass = classMap.get(this.newModel.getModelName()); + this.newModel.setDependency("[]"); + String value = new Gson().toJson(mainClass.getSubClass()); + this.newModel.setSub_attributes(value); + String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes= attributes.indexOf("="); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + this.newModel.setAttributes(atttributesAfterFirstEquals); + String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex= refAttributes.indexOf("="); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + this.newModel.setRef_attributes(refAttributesAfterFirstEquals); + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + + }else{ + if (fromAPI) { + microServiceModels = (MicroServiceModels)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceModels.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter(OPERATION).equals("update")) { + String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); + int id = 0; + for (int i=0; i< duplicateData.size(); i++){ + MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); + id = data.getId(); + } + microServiceModels.setId(id); + microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); + + } + } else { + if (root.has("microServiceModelsDictionaryData")){ + if (root.get("microServiceModelsDictionaryData").has("description")){ + microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); + } + if (root.get("microServiceModelsDictionaryData").has("modelName")){ + microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); + this.newModel.setModelName(microServiceModels.getModelName()); + } + if (root.get("microServiceModelsDictionaryData").has("version")){ + microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); + this.newModel.setVersion(microServiceModels.getVersion()); + } + } + if(root.has("classMap")){ + classMap = new HashMap<String, MSAttributeObject>(); + JsonNode data = root.get("classMap"); + ObjectMapper mapper1 = new ObjectMapper(); + String data1 = data.toString().substring(1, data.toString().length()-1); + data1 = data1.replace("\\", ""); + JSONObject jsonObject = new JSONObject(data1); + Set<String> keys = jsonObject.keySet(); + for(String key : keys){ + String value = jsonObject.get(key).toString(); + MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + classMap.put(key, msAttributeObject); + } + } + userId = root.get("userid").textValue(); + addValuesToNewModel(classMap); + } + } + + } microServiceModels.setAttributes(this.newModel.getAttributes()); microServiceModels.setRef_attributes(this.newModel.getRef_attributes()); microServiceModels.setDependency(this.newModel.getDependency()); microServiceModels.setModelName(this.newModel.getModelName()); microServiceModels.setSub_attributes(this.newModel.getSub_attributes()); microServiceModels.setVersion(this.newModel.getVersion()); - microServiceModels.setEnumValues(this.newModel.getEnumValues()); - microServiceModels.setAnnotation(this.newModel.getAnnotation()); - + microServiceModels.setEnumValues(this.newModel.getEnumValues()); + microServiceModels.setAnnotation(this.newModel.getAnnotation()); + if(microServiceModels.getId() == 0){ String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); @@ -865,31 +920,31 @@ public class MicroServiceDictionaryController { }else{ commonClassDao.update(microServiceModels); } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -919,7 +974,7 @@ public class MicroServiceDictionaryController { return null; } catch (Exception e){ - System.out.println(e); + LOGGER.error(e); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -927,11 +982,7 @@ public class MicroServiceDictionaryController { } return null; } - - - - - + private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) { new MicroServiceModels(); //Loop through the classmap and pull out the required info for the new file. diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java index 1fd95abd4..2b94e44c7 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -20,7 +20,7 @@ package org.openecomp.policy.pap.xacml.rest.elk.client; -import java.util.ArrayList; +import java.util.Map; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; @@ -58,106 +58,43 @@ public interface ElkConnector { none, } - public JestResult policy(String policyId) - throws IllegalStateException, IllegalArgumentException; - public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException; - public ArrayList<PolicyLocator> policyLocators(PolicyIndexType type, String text,int connector) - throws IllegalStateException, IllegalArgumentException; - - public ArrayList<PolicyLocator> policyLocators(PolicyIndexType type, String text, - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s,int connector) - throws IllegalStateException, IllegalArgumentException; - public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException; public JestResult search(PolicyIndexType type, String text, - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) + Map<String, String> searchKeyValue) throws IllegalStateException, IllegalArgumentException; public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; public ElkConnector singleton = new ElkConnectorImpl(); - public static PolicyIndexType toPolicyIndexType(PolicyType type) - throws IllegalArgumentException { - if (type == null) - throw new IllegalArgumentException("Unsupported NULL type conversion"); - - switch(type) { - case Config: - return PolicyIndexType.config; - case Action: - return PolicyIndexType.action; - case Decision: - return PolicyIndexType.decision; - case Config_Fault: - return PolicyIndexType.closedloop; - case Config_PM: - return PolicyIndexType.closedloop; - case Config_FW: - return PolicyIndexType.config; - case Config_MS: - return PolicyIndexType.config; - case none: - return PolicyIndexType.all; - default: - throw new IllegalArgumentException("Unsupported type conversion to index: " + type.name()); - } - } - public static PolicyIndexType toPolicyIndexType(String policyName) - throws IllegalArgumentException { - if (policyName == null) - throw new IllegalArgumentException("Unsupported NULL policy name conversion"); - - if (policyName.startsWith("Config_Fault")) { - return PolicyIndexType.closedloop; - } else if (policyName.startsWith("Config_PM")) { - return PolicyIndexType.closedloop; - } else if (policyName.startsWith("Config_FW")) { - return PolicyIndexType.config; - } else if (policyName.startsWith("Config_MS")) { - return PolicyIndexType.config; - }else if (policyName.startsWith("Action")) { - return PolicyIndexType.action; - } else if (policyName.startsWith("Decision")) { - return PolicyIndexType.decision; - } else if (policyName.startsWith("Config")) { - return PolicyIndexType.config; - } else { - throw new IllegalArgumentException - ("Unsupported policy name conversion to index: " + - policyName); - } - } - - public static PolicyType toPolicyType(String policyName) - throws IllegalArgumentException { + throws IllegalArgumentException { if (policyName == null) - throw new IllegalArgumentException("Unsupported NULL policy name conversion to Policy Type"); - + throw new IllegalArgumentException("Unsupported NULL policy name conversion"); + if (policyName.startsWith("Config_Fault")) { - return PolicyType.Config_Fault; + return PolicyIndexType.closedloop; } else if (policyName.startsWith("Config_PM")) { - return PolicyType.Config_PM; + return PolicyIndexType.closedloop; } else if (policyName.startsWith("Config_FW")) { - return PolicyType.Config_FW; + return PolicyIndexType.config; } else if (policyName.startsWith("Config_MS")) { - return PolicyType.Config_MS; + return PolicyIndexType.config; }else if (policyName.startsWith("Action")) { - return PolicyType.Action; + return PolicyIndexType.action; } else if (policyName.startsWith("Decision")) { - return PolicyType.Decision; + return PolicyIndexType.decision; } else if (policyName.startsWith("Config")) { - return PolicyType.Config; + return PolicyIndexType.config; } else { throw new IllegalArgumentException - ("Unsupported policy name conversion to index: " + - policyName); + ("Unsupported policy name conversion to index: " + + policyName); } } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index 5a64ec2b7..5508ddc69 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -19,32 +19,25 @@ */ package org.openecomp.policy.pap.xacml.rest.elk.client; -import java.io.File; import java.io.IOException; -import java.util.ArrayList; +import java.util.Map; import java.util.Map.Entry; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryStringQueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.json.JSONObject; -import org.kohsuke.args4j.Option; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - import io.searchbox.action.Action; import io.searchbox.client.JestClient; import io.searchbox.client.JestClientFactory; import io.searchbox.client.JestResult; import io.searchbox.client.config.HttpClientConfig; import io.searchbox.core.Delete; -import io.searchbox.core.Get; import io.searchbox.core.Index; import io.searchbox.core.Search; import io.searchbox.core.Search.Builder; @@ -54,26 +47,6 @@ import io.searchbox.params.Parameters; public class ElkConnectorImpl implements ElkConnector{ - protected static class CLIOptions { - @Option(name="-s", usage="search", aliases={"-search", "--search"}, required=false, metaVar="<search text>") - protected String searchText; - - @Option(name="-e", usage="test and update policy if not exists", aliases={"-exist", "--exists"}, required=false, metaVar="<policy file>") - protected File testFile; - - @Option(name = "-h", aliases = {"-help", "--help"}, usage = "print this message") - private boolean help = false; - }; - - private static final String POLICY_RESULT_FIELDS = "[ \"Policy.PolicyType\", " + - "\"Policy.PolicyName\", " + - "\"Policy.Owner\", " + - "\"Policy.Scope\", " + - "\"Policy.PolicyId\", " + - "\"Policy.Version\" ]"; - - private static final String SOURCE_RESULT_FIELDS = "\"_source\": " + POLICY_RESULT_FIELDS; - private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); protected final JestClientFactory jestFactory = new JestClientFactory(); @@ -139,17 +112,10 @@ public class ElkConnectorImpl implements ElkConnector{ throw new IllegalArgumentException("No search string provided"); } - // MatchQueryBuilder mQ = QueryBuilders.matchQuery("_all", text); - QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery(text); + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); SearchSourceBuilder searchSourceBuilder = - new SearchSourceBuilder().query(mQ). - fetchSource(new String[]{"Policy.PolicyType", - "Policy.PolicyName", - "Policy.Owner", - "Policy.Scope", - "Policy.PolicyId", - "Policy.Version"}, - null); + new SearchSourceBuilder().query(mQ); + Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). addIndex(ELK_INDEX_POLICY). setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); @@ -219,191 +185,10 @@ public class ElkConnectorImpl implements ElkConnector{ return result; } - public JestResult searchKey(PolicyIndexType type, String text, - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s,int connector) - throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ - LOGGER.trace("ENTER: " + text); - } - if (filter_s == null || filter_s.size() <= 0) { - return search(type, text); - } - - String matches_s = ""; - - if(connector==0)// AND CONNECTOR - { - matches_s = "{\n" + - " " + SOURCE_RESULT_FIELDS + ",\n" + - " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + - " \"query\": {\n" + - " \"bool\" : {\n" + - " \"must\" : ["; - } - else if (connector ==1)//OR CONNECTOR - { - matches_s = "{\n" + - " " + SOURCE_RESULT_FIELDS + ",\n" + - " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + - " \"query\": {\n" + - " \"bool\" : {\n" + - " \"should\" : ["; - } - - for (Pair<ArrayList<String>,ArrayList<String>> p : filter_s) { - ArrayList<String> name_s = p.left(); - ArrayList<String> value_s = p.right(); - - if (name_s == null || name_s.size() <= 0) { - if (LOGGER.isWarnEnabled()){ - LOGGER.warn("Defaulting to text search: Empty field name array passed in"); - } - return search(type, text); - } - - if (LOGGER.isDebugEnabled()) { - for (String n: name_s) { - LOGGER.debug("Filter Name: " + n); - } - } - - if (value_s == null || value_s.size() <= 0) { - if (LOGGER.isWarnEnabled()){ - LOGGER.warn("Defaulting to text search: Empty field value array passed in"); - } - return search(type, text); - } - - if (LOGGER.isDebugEnabled()) { - for (String v: value_s) { - LOGGER.debug("Filter Value: " + v); - } - } - - /* common case: # filter names == # filter values */ - if (name_s.size() == value_s.size()) { - String match = ""; - for (int i=0; i<name_s.size(); i++) { - if (name_s.get(i).contains("*")) { - match = - "{ \"query_string\": { \"fields\": [ \"" + - name_s.get(i) + "\" ], " + - "\"query\" : \"" + - value_s.get(i) + "\" } },"; - } else { - match = - "{ \"match_phrase\": { \"" + - name_s.get(i) + "\" : \"" + - value_s.get(i) + "\" } },"; - } - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("Adding Match Line: " + match); - } - matches_s = matches_s + "\n " + match; - } - } - else if (name_s.size() > value_s.size() && (value_s.size() == 1)) { - String match = - "{ \"multi_match\": { \"query\": \"" + value_s.get(0) + "\", \"type\": \"phrase\", \"fields\": ["; - for (String n: name_s) { - match += " \"" + n + "\","; - } - match = match.substring(0, match.length()-1); - match += " ] } },";//debug - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("Adding Match Line: " + match); - } - matches_s = matches_s + "\n " + match; - } else { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("Defaulting to text search: different number of filter names and values"); - return search(type, text); - } - } - - matches_s = matches_s.substring(0, matches_s.length()-1); // remove last comma - - matches_s = matches_s + - " ]\n" + - " }\n" + - " }\n" + - "}"; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(matches_s); - } - - Builder searchBuilder = new Search.Builder(matches_s). - addIndex(ELK_INDEX_POLICY); - - if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { - if (pT != PolicyIndexType.all) { - searchBuilder.addType(pT.toString()); - } - } - } else { - searchBuilder.addType(type.toString()); - } - - Search search = searchBuilder.build(); - - JestResult result; - try { - result = jestClient.execute(search); - } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); - throw new IllegalStateException(ioe); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); - } - } else { - /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); - } - - String errorMessage = result.getErrorMessage(); - if (errorMessage != null && !errorMessage.isEmpty()) { - String xMessage = errorMessage; - if (errorMessage.contains("TokenMgrError")) { - int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("QueryParsingException")) { - int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("JsonParseException")) { - int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("Parse Failure")) { - int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("SearchParseException")) { - int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else { - xMessage = result.getErrorMessage(); - } - throw new IllegalStateException(xMessage); - } - } - return result; - } @Override public JestResult search(PolicyIndexType type, String text, - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) + Map<String, String> filter_s) throws IllegalStateException, IllegalArgumentException { if (LOGGER.isTraceEnabled()){ LOGGER.trace("ENTER: " + text); @@ -415,106 +200,41 @@ public class ElkConnectorImpl implements ElkConnector{ String matches_s = ""; matches_s = "{\n" + - " " + SOURCE_RESULT_FIELDS + ",\n" + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + " \"query\": {\n" + " \"bool\" : {\n" + " \"must\" : ["; - for (Pair<ArrayList<String>,ArrayList<String>> p : filter_s) { - ArrayList<String> name_s = p.left(); - ArrayList<String> value_s = p.right(); - - if (name_s == null || name_s.size() <= 0) { - if (LOGGER.isWarnEnabled()){ - LOGGER.warn("Defaulting to text search: Empty field name array passed in"); - } - return search(type, text); - } - - if (LOGGER.isDebugEnabled()) { - for (String n: name_s) { - LOGGER.debug("Filter Name: " + n); - } - } - - if (value_s == null || value_s.size() <= 0) { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("Defaulting to text search: Empty field value array passed in"); - return search(type, text); - } - - if (LOGGER.isDebugEnabled()) { - for (String v: value_s) { - LOGGER.debug("Filter Value: " + v); - } - } - - /* common case: # filter names == # filter values */ - if (name_s.size() == value_s.size()) { - String match = ""; - for (int i=0; i<name_s.size(); i++) { - if (name_s.get(i).contains("*")) { - match = - "{ \"query_string\": { \"fields\": [ \"" + - name_s.get(i) + "\" ], " + - "\"query\" : \"" + - value_s.get(i) + "\" } },"; - } else { - match = - "{ \"match_phrase\": { \"" + - name_s.get(i) + "\" : \"" + - value_s.get(i) + "\" } },"; - } - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("Adding Match Line: " + match); - } - matches_s = matches_s + "\n " + match; - } - } else if (name_s.size() > value_s.size() && (value_s.size() == 1)) { - String match = - "{ \"multi_match\": { \"query\": \"" + value_s.get(0) + "\", \"type\": \"phrase\", \"fields\": ["; - for (String n: name_s) { - match += " \"" + n + "\","; - } - match = match.substring(0, match.length()-1); - match += " ] } },"; - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("Adding Match Line: " + match); - } - matches_s = matches_s + "\n " + match; - } else { - if (LOGGER.isWarnEnabled()){ - LOGGER.warn("Defaulting to text search: different number of filter names and values"); - } - return search(type, text); + + String match_params = ""; + for(Entry<String, String> entry : filter_s.entrySet()){ + String key = entry.getKey(); + String value = entry.getValue(); + if(filter_s.size() == 1){ + match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }"; + }else{ + match_params = match_params + "match\" : { \""+key+"\" : \""+value+"\" } ,"; } } - if (text != null && !text.isEmpty()) { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("Adding Match Line for search text: " + text); - } - - final JsonObject jsonText = new JsonObject(); - jsonText.addProperty("_all", text); - String escapedText = jsonText.toString(); + if(match_params.endsWith(",")){ + match_params = match_params.substring(0, match_params.length()-1); + } - matches_s = matches_s + "\n " + - "{ \"match\": " + - escapedText + " },"; + matches_s = matches_s + "{\n" + match_params + "\n}" ; + + boolean query = false; + String query_String = ""; + if(text != null){ + query = true; + query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; } - matches_s = matches_s.substring(0, matches_s.length()-1); // remove last comma - matches_s = matches_s + "\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(matches_s); + + if(query){ + matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; + }else{ + matches_s = matches_s + "]\n}\n}\n}"; } - - Builder searchBuilder = new Search.Builder(matches_s). - addIndex(ELK_INDEX_POLICY); + + Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); if (type == null || type == PolicyIndexType.all) { for (PolicyIndexType pT: PolicyIndexType.values()) { @@ -582,155 +302,6 @@ public class ElkConnectorImpl implements ElkConnector{ return result; } - @Override - public JestResult policy(String policyId) - throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ - LOGGER.trace("ENTER: " + policyId); - } - - if (policyId == null || policyId.isEmpty()) { - throw new IllegalArgumentException("No policy id string provided"); - } - - Get policyRequest = new Get.Builder(ELK_INDEX_POLICY, policyId).build(); - - if (LOGGER.isInfoEnabled()){ - LOGGER.info("ELK Search body request: " + policyRequest.toString()); - } - - JestResult result; - try { - result = jestClient.execute(policyRequest); - } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - policyId + ": " + ioe.getMessage(), ioe); - throw new IllegalStateException(ioe); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + policyId + ":" + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); - } - - return result; - } - - /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()) - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + policyId + ":" + - result.getPathToResult() + ":" + - result.getErrorMessage()); - - return result; - } - - protected JsonObject getJsonObject(JsonObject jsonObject, String member) throws IllegalArgumentException { - if (jsonObject == null) { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("No JSON object provided to get " + member); - - throw new IllegalArgumentException("No JSON Object provided"); - } - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("ENTER: " + member); - for (Entry<String, JsonElement> entry: jsonObject.entrySet()) { - LOGGER.trace("JSONOBJECT: " + entry.getKey() + "->" + entry.getValue()); - } - } - - if (jsonObject.has(member)) { - JsonElement element = jsonObject.getAsJsonObject(member); - if (element.isJsonObject()) { - return (JsonObject) element; - } - } - - throw new IllegalArgumentException(member + " is not a JSON Object"); - } - - protected JsonArray getJsonArray(JsonObject jsonObject, String member) throws IllegalArgumentException { - if (jsonObject == null) { - throw new IllegalArgumentException("No JSON Object provided"); - } - - if (jsonObject.has(member)) { - if (jsonObject.get(member).isJsonArray()) { - return (JsonArray) jsonObject.get(member); - } - } - - throw new IllegalArgumentException(member + " is not a JSON Array"); - } - - protected String getJsonPolicyMember(JsonObject aHit, String member) throws IllegalArgumentException { - if (aHit == null) { - throw new IllegalArgumentException("No JSON Object provided"); - } - - JsonObject jSource = getJsonObject(aHit, "_source"); - JsonObject jPolicy = getJsonObject(jSource, "Policy"); - JsonElement jMember = jPolicy.get(member); - if (jMember == null) { - throw new IllegalArgumentException(member + " is not a JSON Object"); - } - return jMember.getAsString(); - } - - @Override - public ArrayList<PolicyLocator> policyLocators(PolicyIndexType indexType, String text, int connector) - throws IllegalStateException, IllegalArgumentException { - return policyLocators(indexType, text, new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(),connector); - } - - @Override - public ArrayList<PolicyLocator> policyLocators(PolicyIndexType indexType, - String text, - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s, int connector) - throws IllegalStateException, IllegalArgumentException { - final ArrayList<PolicyLocator> policyLocators = new ArrayList<PolicyLocator>(); - - JestResult results = searchKey(indexType, text, filter_s,connector); - if (!results.isSucceeded()) { - return policyLocators; - } - - JsonArray jsonHit_s = null; - try { - JsonObject jsonHits = getJsonObject(results.getJsonObject(), "hits"); - jsonHit_s = getJsonArray(jsonHits, "hits"); - } catch (IllegalArgumentException e) { - LOGGER.warn("SEARCH:" + text + " no valid element provided", e); - return policyLocators; - } - - for (JsonElement e : jsonHit_s) { - JsonObject elkSource = (JsonObject) e; - try { - String policyType = getJsonPolicyMember(elkSource,"PolicyType"); - String policyName = getJsonPolicyMember(elkSource,"PolicyName"); - String owner = getJsonPolicyMember(elkSource,"Owner"); - String scope = getJsonPolicyMember(elkSource,"Scope"); - String policyId = getJsonPolicyMember(elkSource,"PolicyId"); - String version = getJsonPolicyMember(elkSource,"Version"); - PolicyLocator policyLocator = - new PolicyLocator(policyType, policyName, owner, - scope, policyId, version); - policyLocators.add(policyLocator); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("SEARCH:" + text + "|FOUND:" + policyLocator); - } - } catch (IllegalArgumentException ex) { - LOGGER.warn("SEARCH:" + text + " missing locator information.", ex); - } - } - return policyLocators; - } - public boolean put(PolicyRestAdapter policyData) throws IOException, IllegalStateException { if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java index f0783529a..d4cf812a9 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java @@ -25,18 +25,26 @@ import java.util.List; import java.util.Map; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.adapter.YAMLParams; public class PolicyElasticData { private String scope; private String policyType; private String configPolicyType; + private String configBodyData; private String policyName; private String policyDescription; private String ecompName; private String configName; private String configType; private String jsonBody; + private Object jsonBodyData; + + private LinkedHashMap<?, ?> serviceTypePolicyName; + private LinkedHashMap<?, ?> verticaMetrics; + private LinkedHashMap<?, ?> description; + private LinkedHashMap<?, ?> attributeFields; //Safe Policy private String policyScope; @@ -102,17 +110,25 @@ public class PolicyElasticData { private String actionDictType; private String actionDictUrl; private String actionDictMethod; + private YAMLParams yamlparams; public PolicyElasticData(PolicyRestAdapter policyData) { this.scope = policyData.getDomain(); this.policyType = policyData.getPolicyType(); this.configPolicyType = policyData.getConfigPolicyType(); + this.configBodyData = policyData.getConfigBodyData(); this.policyName = policyData.getNewFileName(); this.policyDescription = policyData.getPolicyDescription(); this.ecompName = policyData.getEcompName(); this.configName = policyData.getConfigName(); this.configType = policyData.getConfigType(); this.jsonBody = policyData.getJsonBody(); + this.jsonBodyData = policyData.getJsonBodyData(); + + this.serviceTypePolicyName = policyData.getServiceTypePolicyName(); + this.verticaMetrics = policyData.getVerticaMetrics(); + this.description = policyData.getDescription(); + this.attributeFields = policyData.getAttributeFields(); //Safe Policy this.policyScope = policyData.getPolicyScope(); @@ -178,6 +194,7 @@ public class PolicyElasticData { this.actionDictType = policyData.getActionDictType(); this.actionDictUrl = policyData.getActionDictUrl(); this.actionDictMethod = policyData.getActionDictMethod(); + this.yamlparams = policyData.getYamlparams(); } public String getScope() { @@ -198,6 +215,13 @@ public class PolicyElasticData { public void setConfigPolicyType(String configPolicyType) { this.configPolicyType = configPolicyType; } + public String getConfigBodyData() { + return configBodyData; + } + + public void setConfigBodyData(String configBodyData) { + this.configBodyData = configBodyData; + } public String getPolicyName() { return policyName; } @@ -234,6 +258,37 @@ public class PolicyElasticData { public void setJsonBody(String jsonBody) { this.jsonBody = jsonBody; } + public LinkedHashMap<?, ?> getServiceTypePolicyName() { + return serviceTypePolicyName; + } + + public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + + public LinkedHashMap<?, ?> getVerticaMetrics() { + return verticaMetrics; + } + + public void setVerticaMetrics(LinkedHashMap<?, ?> verticaMetrics) { + this.verticaMetrics = verticaMetrics; + } + + public LinkedHashMap<?, ?> getDescription() { + return description; + } + + public void setDescription(LinkedHashMap<?, ?> description) { + this.description = description; + } + + public LinkedHashMap<?, ?> getAttributeFields() { + return attributeFields; + } + + public void setAttributeFields(LinkedHashMap<?, ?> attributeFields) { + this.attributeFields = attributeFields; + } public String getPolicyScope() { return policyScope; } @@ -546,5 +601,19 @@ public class PolicyElasticData { public void setActionDictMethod(String actionDictMethod) { this.actionDictMethod = actionDictMethod; } + public YAMLParams getYamlparams() { + return yamlparams; + } + + public void setYamlparams(YAMLParams yamlparams) { + this.yamlparams = yamlparams; + } + public Object getJsonBodyData() { + return jsonBodyData; + } + + public void setJsonBodyData(Object jsonBodyData) { + this.jsonBodyData = jsonBodyData; + } } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java index 9e512dab2..a067e9038 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -20,15 +20,14 @@ package org.openecomp.policy.pap.xacml.rest.elk.client; -import java.io.File; import java.io.PrintWriter; -import java.nio.file.Path; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; @@ -52,7 +51,6 @@ import org.openecomp.policy.rest.jpa.ClosedLoopD2Services; import org.openecomp.policy.rest.jpa.ClosedLoopSite; import org.openecomp.policy.rest.jpa.DCAEuuid; import org.openecomp.policy.rest.jpa.DecisionSettings; -import org.openecomp.policy.rest.jpa.DescriptiveScope; import org.openecomp.policy.rest.jpa.EcompName; import org.openecomp.policy.rest.jpa.EnforcingType; import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; @@ -74,12 +72,13 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.searchbox.client.JestResult; + @Controller @RequestMapping({"/"}) public class PolicyElasticSearchController{ private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); - private volatile HashMap<Path, String> filteredPolicies = new HashMap<Path, String>(); private List<JSONObject> policyNames = null; enum Mode{ @@ -90,8 +89,6 @@ public class PolicyElasticSearchController{ public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { private static final long serialVersionUID = 1L; }; - //For AND and OR logical connector AND=0 and OR=1 - private int connectorSelected; public static CommonClassDao commonClassDao; @@ -350,27 +347,17 @@ public class PolicyElasticSearchController{ public String searchElkDatabase(String value){ String policyType = ""; String searchText = value; - ArrayList<PolicyLocator> locators; - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + JestResult locators; + Map<String, String> filter_s = new HashMap<String, String>(); try { - locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0); + locators = ElkConnector.singleton.search(toPolicyIndexType(policyType), searchText, filter_s); } catch (Exception ise) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage()); value = "$notSuccess%"; return value; } policyNames = new ArrayList<JSONObject>(); - for (PolicyLocator p: locators) { - String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName + "." +p.version + ".xml"; - LOGGER.debug(dbPolicyName); - JSONObject el = new JSONObject(); - el.put("name", dbPolicyName); - policyNames.add(el); - } - if(!locators.isEmpty()){ - value = "$success%"; - return value; - } + System.out.println(locators); return value; } @@ -378,8 +365,8 @@ public class PolicyElasticSearchController{ public String searchElkDatabase(String key, String value){ String policyType = ""; String searchText = key+":"+value; - ArrayList<PolicyLocator> locators; - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + JestResult locators; + Map<String, String> filter_s = new HashMap<String, String>(); LOGGER.debug("Parameter value is"+value); String clSearchKey=null; @@ -387,13 +374,7 @@ public class PolicyElasticSearchController{ LOGGER.debug("Filter value is"+clSearchKey); - ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchKey); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchKey); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchKey); - //clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey); String clSearchValue=null; clSearchValue=value; @@ -403,15 +384,10 @@ public class PolicyElasticSearchController{ ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); clSearchBoxFilterValue_s.add(clSearchValue); - filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); try { - locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0); - LOGGER.debug("No Exceptions"); - for (PolicyLocator l: locators) { - LOGGER.debug(l.policyName); - } - LOGGER.debug("After for"); + locators = ElkConnector.singleton.search(toPolicyIndexType(policyType), searchText, filter_s); + System.out.println(locators); } catch (Exception ise) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage()); //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ise, "AttributeDictionary", " Exception while searching Elk database "); @@ -419,107 +395,14 @@ public class PolicyElasticSearchController{ value = "$notSuccess%"; return value; } - policyNames = new ArrayList<JSONObject>(); - for (PolicyLocator p: locators) { - String dbPolicyName = p.scope + File.separator + p.policyType + "_" + p.policyName + ".xml"; - LOGGER.debug(dbPolicyName); - JSONObject el = new JSONObject(); - el.put("name", dbPolicyName); - policyNames.add(el); - } - if(!locators.isEmpty()){ - value = "$success%"; - LOGGER.debug("Success"); - return value; - } return value; } - - //For AutoPush of policy using descriptive Scope. - //Returns string either "UnMatched" or "Matched" or "Search Unavailable". - public String searchDescriptiveScope(String scopeName, String policyNameToCheck) { - String searchText=null; - String status="UnMatched"; - ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = - new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); - //Finding the descriptive scope search tag. - LOGGER.warn("Entry into DS"); - DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", scopeName); - - searchText=dsSearch.getSearch(); - LOGGER.warn("Search text is " + searchText); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("DescriptiveScope Search String is " +searchText ); - } - - - if(searchText.contains(":")) - { - String connector="AND"; - - for (String retval: searchText.split(connector)){ - - int index= retval.indexOf(':'); - String filterKey=null; - String filterValue=null; - - filterKey=retval.substring(0,index).trim(); - filterValue= retval.substring(index+1).trim(); - - LOGGER.debug("Key is "+filterKey+" and value is "+filterValue); - String clSearchBoxFilter=filterKey; - - ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); - - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter); - clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter); - - - ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); - clSearchBoxFilterValue_s.add(filterValue); - - filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); - } - } - - ArrayList<PolicyLocator> locators=null; - try { - LOGGER.warn("Before calling search"); - locators = ElkConnector.singleton.policyLocators(ElkConnector.PolicyIndexType.all, - searchText, filter_s,connectorSelected); - LOGGER.warn("After calling search"); - } catch (Exception ise) { - //AdminNotification.warn("Search is unavailable: " + ise.getMessage()); - status= "Search Unavailable"; - LOGGER.warn("Search is unavailable"); - } - synchronized(filteredPolicies) { - if (locators.isEmpty()) { - LOGGER.debug("No match has been found"); - //AdminNotification.warn("No match has been found"); - status="UnMatched"; - } - - for (PolicyLocator p: locators) { - LOGGER.debug("Second String "+policyNameToCheck); - if(p.policyName.contains(policyNameToCheck)) - { - status="Matched"; - LOGGER.warn("Policies matched"); - break; - } - else - { - LOGGER.warn("Policies Unmatched"); - status="UnMatched"; - } - } - } - return status; - + + public JestResult search(PolicyIndexType type, String text, + Map<String, String> searchKeyValue) { + return ElkConnector.singleton.search(type, text, searchKeyValue); } + } class SearchData{ diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java index 91f97cae3..fc70e9a84 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicySearchController.java @@ -19,20 +19,33 @@ */ package org.openecomp.policy.pap.xacml.rest.elk.client; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.DescriptiveScope; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonArray; + +import io.searchbox.client.JestResult; @Controller @RequestMapping("/") @@ -40,23 +53,109 @@ public class PolicySearchController { private static final Logger LOGGER = FlexLogger.getLogger(PolicySearchController.class); + @Autowired + CommonClassDao commonClassDao; + @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) public void elkTransaction(HttpServletRequest request, HttpServletResponse response) { try{ boolean result = false; + boolean policyResult = false; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); PolicyRestAdapter policyData = new PolicyRestAdapter(); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + Map<String, String> searchKeyValue = new HashMap<String, String>(); + List<String> policyList = new ArrayList<String>(); if(request.getParameter("policyName") != null){ String policyName = request.getParameter("policyName"); policyData.setNewFileName(policyName); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); if("delete".equalsIgnoreCase(request.getParameter("action"))){ result = controller.deleteElk(policyData); }else{ result = controller.updateElk(policyData); } } + if("search".equalsIgnoreCase(request.getParameter("action"))){ + try { + JsonNode root = mapper.readTree(request.getReader()); + SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class); + + String policyType = searchData.getPolicyType(); + + String searchText = searchData.getQuery(); + String descriptivevalue = searchData.getDescriptiveScope(); + if(descriptivevalue != null){ + DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", searchData.getDescriptiveScope()); + if(dsSearch != null){ + String[] descriptiveList = dsSearch.getSearch().split("AND"); + for(String keyValue : descriptiveList){ + String[] entry = keyValue.split(":"); + searchKeyValue.put(entry[0], entry[1]); + } + } + } + + if(searchData.getClosedLooppolicyType() != null){ + String closedLoopType; + if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ + closedLoopType = "ClosedLoop_Fault"; + }else{ + closedLoopType = "ClosedLoop_PM"; + } + searchKeyValue.put("configPolicyType", closedLoopType); + } + if(searchData.getEcompName() != null){ + searchKeyValue.put("ecompName", searchData.getEcompName()); + } + if(searchData.getD2Service() != null){ + searchKeyValue.put("_all", searchData.getD2Service()); + } + if(searchData.getVnfType() != null){ + searchKeyValue.put("_all", searchData.getVnfType()); + } + if(searchData.getPolicyStatus() != null){ + searchKeyValue.put("_all", searchData.getPolicyStatus()); + } + if(searchData.getVproAction() != null){ + searchKeyValue.put("_all", searchData.getVproAction()); + } + if(searchData.getServiceType() != null){ + searchKeyValue.put("_all", searchData.getServiceType()); + } + if(searchData.getBindTextSearch() != null){ + searchKeyValue.put("_all", searchData.getBindTextSearch()); + } + PolicyIndexType type = null; + if(policyType != null){ + if(policyType.equalsIgnoreCase("action")){ + type = ElkConnector.PolicyIndexType.action; + }else if(policyType.equalsIgnoreCase("decision")){ + type = ElkConnector.PolicyIndexType.decision; + }else if(policyType.equalsIgnoreCase("config")){ + type = ElkConnector.PolicyIndexType.config; + }else { + type = ElkConnector.PolicyIndexType.closedloop; + } + }else{ + type = ElkConnector.PolicyIndexType.all; + } + JestResult policyResultList = controller.search(type, searchText, searchKeyValue); + if(policyResultList.isSucceeded()){ + result = true; + policyResult = true; + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for(int i =0; i < resultObject.size(); i++){ + String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); + policyList.add(policyName); + } + }else{ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } + }catch(Exception e){ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); + } + } String message=""; if(result){ message = "Elastic Server Transaction is success"; @@ -67,10 +166,15 @@ public class PolicySearchController { JSONObject j = new JSONObject(msg); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("success", "success"); - response.getWriter().write(j.toString()); + if(policyResult){ + JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); + response.getWriter().write(k.toString()); + }else{ + response.getWriter().write(j.toString()); + } }catch(Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage()); e.printStackTrace(); } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java index efaed9ffc..c1de11548 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -40,12 +40,6 @@ public class APIRequestHandler { dictionaryHandler.doDictionaryAPIGet(request, response); return; } - // Request from the API to get the gitPath - if ("gitPath".equalsIgnoreCase(apiflag)) { - PushPolicyHandler pushHandler = new PushPolicyHandler(); - pushHandler.getGitPath(request, response); - return; - } // Request from the API to get the ActiveVersion from the PolicyVersion table if ("version".equalsIgnoreCase(apiflag)){ PushPolicyHandler pushHandler = new PushPolicyHandler(); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java index 59fa60aec..009a2d601 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java @@ -21,9 +21,6 @@ package org.openecomp.policy.pap.xacml.rest.handler; import java.io.File; import java.net.URI; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import javax.persistence.EntityManager; @@ -34,17 +31,12 @@ import javax.servlet.http.HttpServletResponse; import org.openecomp.policy.common.logging.eelf.MessageCodes; import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.rest.XACMLRestProperties; import org.openecomp.policy.rest.jpa.PolicyVersion; import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.openecomp.policy.xacml.util.XACMLPolicyScanner; import com.att.research.xacml.util.XACMLProperties; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - public class PushPolicyHandler { /* @@ -94,85 +86,6 @@ public class PushPolicyHandler { } /* - * Get Git Path - */ - public void getGitPath(HttpServletRequest request, HttpServletResponse response) { - String policyScope = request.getParameter("policyScope"); - String filePrefix = request.getParameter("filePrefix"); - String policyName = request.getParameter("policyName"); - String activeVersion = request.getParameter("activeVersion"); - - Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin"); - Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY)); - Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString()); - - //getting the fullpath of the gitPath and convert to string - String fullGitPath = gitPath.toAbsolutePath().toString(); - String finalGitPath = null; - - //creating the parentPath directory for the Admin Console use - if(fullGitPath.contains("\\")){ - if(fullGitPath.contains("ECOMP-PAP-REST")){ - finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app"); - }else{ - finalGitPath = fullGitPath.replace("ATT-PAP-REST", "ATT-ecomp-sdk-app"); - } - }else{ - finalGitPath = fullGitPath.replace("pap", "console"); - } - - finalGitPath += File.separator + policyScope + File.separator + filePrefix + policyName + "." + activeVersion + ".xml"; - File file = new File(finalGitPath); - URI uri = file.toURI(); - - // - // Extract XACML policy information - // - Boolean isValid = false; - String policyId = null; - String description = null; - String version = null; - - URL url; - try { - url = uri.toURL(); - Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream()); - if (rootElement == null || - ( - ! (rootElement instanceof PolicySetType) && - ! (rootElement instanceof PolicyType) - ) ) { - PolicyLogger.warn("No root policy element in URI: " + uri.toString() + " : " + rootElement); - isValid = false; - } else { - if (rootElement instanceof PolicySetType) { - policyId = ((PolicySetType)rootElement).getPolicySetId(); - description = ((PolicySetType)rootElement).getDescription(); - isValid = true; - version = ((PolicySetType)rootElement).getVersion(); - } else if (rootElement instanceof PolicyType) { - policyId = ((PolicyType)rootElement).getPolicyId(); - description = ((PolicyType)rootElement).getDescription(); - version = ((PolicyType)rootElement).getVersion(); - isValid = true; - } else { - PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName()); - } - } - } catch (Exception e) { - PolicyLogger.error("Exception Occured While Extracting Policy Information"); - } - if (!finalGitPath.equalsIgnoreCase("") || policyId!=null || description!=null || version!=null || isValid!=null) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("gitPath", finalGitPath); - response.addHeader("policyId", policyId); - response.addHeader("description", description); - response.addHeader("version", version); - response.addHeader("isValid", isValid.toString()); - } - } - - /* * Get Selected URI path. */ public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) { diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java index 65402d5c2..ae75ad24c 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -127,7 +127,7 @@ public class SavePolicyHandler { policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2()); //Decision Policy Specific policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); - policyAdapter.setProviderComboBox(policy.getProviderComboBox()); + policyAdapter.setRuleProvider(policy.getProviderComboBox()); policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); policyAdapter.setDomain(policyAdapter.getPolicyScope()); return policyAdapter; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index a987e9abf..b9d6def5a 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -349,7 +349,7 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } } - if(policyData.getRuleAlgorithmschoices().size() > 0){ + if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ for(Object attribute : policyData.getRuleAlgorithmschoices()){ if(attribute instanceof LinkedHashMap<?, ?>){ String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); @@ -363,7 +363,14 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } } - + if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML) && policyData.getYamlparams()!=null){ + attributeMap.put("actor", policyData.getYamlparams().getActor()); + attributeMap.put("recipe", policyData.getYamlparams().getRecipe()); + attributeMap.put("limit", policyData.getYamlparams().getLimit()); + attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow()); + attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart()); + attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd()); + } policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); diff --git a/ECOMP-PAP-REST/xacml.pap.properties b/ECOMP-PAP-REST/xacml.pap.properties index 7ec9447b0..c25a81207 100644 --- a/ECOMP-PAP-REST/xacml.pap.properties +++ b/ECOMP-PAP-REST/xacml.pap.properties @@ -27,7 +27,7 @@ xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory # Dictionary and Policy Implementation Classes Properties dictionary.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DictionaryHandlerImpl savePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler -pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHander +pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler deletePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DeleteHandler #AutoPush Policy xacml.rest.pap.autopush.file=autopush.properties diff --git a/ECOMP-PAP-REST/xacml.pap.test.properties b/ECOMP-PAP-REST/xacml.pap.test.properties index 0f6f253e5..5b77fb18c 100644 --- a/ECOMP-PAP-REST/xacml.pap.test.properties +++ b/ECOMP-PAP-REST/xacml.pap.test.properties @@ -27,6 +27,8 @@ xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory # Dictionary and Policy Implementation Classes Properties dictionary.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DictionaryHandlerImpl savePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler +pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler +deletePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DeleteHandler #AutoPush Policy xacml.rest.pap.autopush.file=autopush.properties #=====================================================================================# diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java index b00346de6..5aa3360ca 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java @@ -611,19 +611,21 @@ public class PAPServices { response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") + " was successfully updated. "; if (connection.getHeaderField("safetyChecker")!=null) { - response = response + "\nPolicy Safety Checker Warning: This closedLoopControlName (" - + connection.getHeaderField("newCLName") + ") " + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") - + "that already exists." + "See detailed information on ClosedLoop Pairs below: " - +"\n"+connection.getHeaderField("safetyChecker"); + response = response + + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists." + " See detailed information on ClosedLoop Pairs below: " + +"\n\n"+connection.getHeaderField("safetyChecker"); } } else if ("create".equals(operation)) { response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") + " was successfully created."; if (connection.getHeaderField("safetyChecker")!=null) { - response = response + "\nPolicy Safety Checker Warning: This closedLoopControlName (" - + connection.getHeaderField("newCLName") + ") " + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") - + "that already exists." + "See detailed information on ClosedLoop Pairs below: " - +"\n"+connection.getHeaderField("safetyChecker"); + response = response + + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists. " + "See detailed information on ClosedLoop Pairs below: " + +"\n\n"+connection.getHeaderField("safetyChecker"); } } else if ("delete".equals(operation)) { response = "Transaction ID: " + requestID + " --The policy was successfully deleted."; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java index 5f62be3ac..1acc18eb0 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java @@ -41,6 +41,7 @@ import com.att.nsa.cambria.client.CambriaConsumer; import com.att.nsa.cambria.client.CambriaPublisher; import com.att.research.xacml.util.XACMLProperties; +@SuppressWarnings("deprecation") public class ManualNotificationUpdateThread implements Runnable { private static final Logger LOGGER = FlexLogger.getLogger(ManualNotificationUpdateThread.class); @@ -139,8 +140,7 @@ public class ManualNotificationUpdateThread implements Runnable { try { throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + LOGGER.error(e); } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java index fe295ebb8..cb1cf9f03 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java @@ -158,15 +158,12 @@ public class NotificationServer { // to succeed before giving up. If any messages are unsent after that time, // they're returned to your app. You could, for example, persist to disk // and try again later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); + final List<?> stuck = pub.close ( 20, TimeUnit.SECONDS ); - if ( stuck.size () > 0 ) - { - System.err.println ( stuck.size() + " messages unsent" ); - } - else - { - System.out.println ( "Clean exit; all messages sent: " + notification ); + if ( stuck.size () > 0 ){ + LOGGER.error( stuck.size() + " messages unsent" ); + }else{ + LOGGER.info( "Clean exit; all messages sent: " + notification ); } } else if (propNotificationType.equals("dmaap")) { diff --git a/ECOMP-PDP-REST/xacml.pdp.properties b/ECOMP-PDP-REST/xacml.pdp.properties index f9b564136..f87d5404e 100644 --- a/ECOMP-PDP-REST/xacml.pdp.properties +++ b/ECOMP-PDP-REST/xacml.pdp.properties @@ -47,7 +47,7 @@ xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinder # When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into # into one PolicySet and use the given Policy Algorithm. # -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides # # PDP RESTful API properties # diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java index 86c5c9b4b..ed1664f55 100644 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java +++ b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java @@ -63,6 +63,7 @@ import com.att.research.xacml.std.StdMutableResult; import com.att.research.xacml.std.StdObligation; import com.att.research.xacml.util.XACMLProperties; +@SuppressWarnings("deprecation") public class FindAction { private Logger LOGGER = FlexLogger.getLogger(this.getClass()); private Boolean changeIt = false; diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java index c823ec6ab..2cfacab85 100644 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java @@ -31,6 +31,14 @@ import org.openecomp.policy.rest.jpa.EcompName; public class PolicyRestAdapter { + /* + * + * Note : Make Sure if any variables are added in PolicyRestAdapter.java, add them to PolicyElasticData.java file + * + * + * */ + + //Common private Object data; private String policyName = null; @@ -117,6 +125,7 @@ public class PolicyRestAdapter { private String actionDictType = null; private String actionDictUrl = null; private String actionDictMethod = null; + private YAMLParams yamlparams; //MicroSerice private String serviceType = null; @@ -824,4 +833,10 @@ public class PolicyRestAdapter { public void setExistingCLName(String existingCLName) { this.existingCLName = existingCLName; } + public YAMLParams getYamlparams() { + return yamlparams; + } + public void setYamlparams(YAMLParams yamlparams) { + this.yamlparams = yamlparams; + } } diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java index 8fec46482..43bff884c 100644 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java @@ -28,6 +28,7 @@ public class Tags { String ruleName; List<TagDefines> tags; String tagPickerName; + String networkRole; public String getRuleName() { return ruleName; @@ -48,5 +49,11 @@ public class Tags { public void setTagPickerName(String tagPickerName) { this.tagPickerName = tagPickerName; } + public String getNetworkRole() { + return networkRole; + } + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } } diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java new file mode 100644 index 000000000..adcce2633 --- /dev/null +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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.openecomp.policy.rest.adapter; + +public class YAMLParams { + private String actor; + private String recipe; + private String limit; + private String timeWindow; + private String guardActiveStart; + private String guardActiveEnd; + + public String getActor() { + return actor; + } + public void setActor(String actor) { + this.actor = actor; + } + public String getRecipe() { + return recipe; + } + public void setRecipe(String recipe) { + this.recipe = recipe; + } + public String getLimit() { + return limit; + } + public void setLimit(String limit) { + this.limit = limit; + } + public String getTimeWindow() { + return timeWindow; + } + public void setTimeWindow(String timeWindow) { + this.timeWindow = timeWindow; + } + public String getGuardActiveStart() { + return guardActiveStart; + } + public void setGuardActiveStart(String guardActiveStart) { + this.guardActiveStart = guardActiveStart; + } + public String getGuardActiveEnd() { + return guardActiveEnd; + } + public void setGuardActiveEnd(String guardActiveEnd) { + this.guardActiveEnd = guardActiveEnd; + } +} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java index 129ad37df..032f77f3c 100644 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java @@ -59,6 +59,9 @@ public class FWTagPicker implements Serializable { @Column(name="description", nullable=true, length=2048) private String description; + + @Column(name="networkRole", nullable=true) + private String networkRole; @Column(name="tags", nullable=true) @OrderBy("asc") @@ -135,6 +138,14 @@ public class FWTagPicker implements Serializable { this.description = description; } + public String getNetworkRole() { + return networkRole; + } + + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } + public String getTagValues() { return tagValues; } diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java new file mode 100644 index 000000000..85c42ee48 --- /dev/null +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-REST + * ================================================================================ + * 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.openecomp.policy.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +@Entity +@Table(name="PolicyGroupEntity") +@NamedQuery(name="PolicyGroupEntity.findAll", query="SELECT p FROM PolicyGroupEntity p ") +public class PolicyGroupEntity implements Serializable{ + + private static final long serialVersionUID = 1L; + + @Id + @Column(name="groupKey") + private int groupKey; + + @Id + @Column(name="policyid") + private int policyid; + + public int getGroupKey() { + return groupKey; + } + + public void setGroupKey(int groupKey) { + this.groupKey = groupKey; + } + + public int getPolicyid() { + return policyid; + } + + public void setPolicyid(int policyid) { + this.policyid = policyid; + } +} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java index c912374ef..a04f77e7e 100644 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java @@ -28,7 +28,7 @@ public class MSAttributeObject { private String className; private HashMap<String, String> attribute = new HashMap<String, String>(); private HashMap<String, String> refAttribute = new HashMap<String, String>(); - private HashMap<String, String> subClass = new HashMap<String, String>(); + private HashMap<String, Object> subClass = new HashMap<String, Object>(); private String dependency; private HashMap<String, String> enumType = new HashMap<String, String>(); private HashMap<String, String> matchingSet = new HashMap<String, String>(); @@ -70,13 +70,13 @@ public class MSAttributeObject { public void addAllRefAttribute(Map<String, String> map){ this.refAttribute.putAll(map); } - public HashMap<String, String> getSubClass() { + public HashMap<String, Object> getSubClass() { return subClass; } - public void setSubClass(HashMap<String, String> subClass) { + public void setSubClass(HashMap<String, Object> subClass) { this.subClass = subClass; } - public void addAllSubClass(HashMap<String, String> subClass){ + public void addAllSubClass(HashMap<String, Object> subClass){ this.subClass.putAll(subClass); } public String getDependency() { diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java index 7276a19f8..057d8544e 100644 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java @@ -217,7 +217,7 @@ public class MSModelUtils { String extendClass = getSubTypes(root, className); HashMap<String, String> returnRefList = getRefAttributeList(root, className, extendClass); HashMap<String, String> returnAttributeList = getAttributeList(root, className, extendClass); - HashMap<String, String> returnSubList = getSubAttributeList(root, className, extendClass); + HashMap<String, Object> returnSubList = getSubAttributeList(root, className, extendClass); HashMap<String, String> returnAnnotation = getAnnotation(root, className, extendClass); msAttributeObject.setAttribute(returnAttributeList); msAttributeObject.setRefAttribute(returnRefList); @@ -285,10 +285,10 @@ public class MSModelUtils { return annotationSet; } - private HashMap<String, String> getSubAttributeList(EPackage root, String className , String superClass) { + private HashMap<String, Object> getSubAttributeList(EPackage root, String className , String superClass) { TreeIterator<EObject> treeItr = root.eAllContents(); boolean requiredAttribute = false; - HashMap<String, String> subAttribute = new HashMap<String, String>(); + HashMap<String, Object> subAttribute = new HashMap<String, Object>(); int rollingCount = 0; int processClass = 0; boolean annotation = false; @@ -622,7 +622,7 @@ public class MSModelUtils { } - public String createJson(HashMap<String, String> subClassAttributes, HashMap<String, MSAttributeObject> classMap, String className) { + public String createJson(HashMap<String, Object> subClassAttributes, HashMap<String, MSAttributeObject> classMap, String className) { boolean enumType; Map<String, HashMap<String, String>> myObject = new HashMap<String, HashMap<String, String>>(); for ( Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()){ @@ -660,7 +660,7 @@ public class MSModelUtils { public String createSubAttributes(ArrayList<String> dependency, HashMap<String, MSAttributeObject> classMap, String modelName) { - HashMap <String, String> workingMap = new HashMap<String,String>(); + HashMap <String, Object> workingMap = new HashMap<String,Object>(); MSAttributeObject tempObject = new MSAttributeObject(); if (dependency!=null){ if (dependency.size()==0){ diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/flexslider.css b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/flexslider.css deleted file mode 100644 index c459ef440..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/flexslider.css +++ /dev/null @@ -1,275 +0,0 @@ -/* - * jQuery FlexSlider v2.6.0 - * http://www.woothemes.com/flexslider/ - * - * Copyright 2012 WooThemes - * Free to use under the GPLv2 and later license. - * http://www.gnu.org/licenses/gpl-2.0.html - * - * Contributing author: Tyler Smith (@mbmufffin) - * - */ -/* ==================================================================================================================== - * FONT-FACE - * ====================================================================================================================*/ -@font-face { - font-family: 'flexslider-icon'; - src: url('fonts/flexslider-icon.eot'); - src: url('fonts/flexslider-icon.eot?#iefix') format('embedded-opentype'), url('fonts/flexslider-icon.woff') format('woff'), url('fonts/flexslider-icon.ttf') format('truetype'), url('fonts/flexslider-icon.svg#flexslider-icon') format('svg'); - font-weight: normal; - font-style: normal; -} -/* ==================================================================================================================== - * RESETS - * ====================================================================================================================*/ -.flex-container a:hover, -.flex-slider a:hover { - outline: none; -} -.slides, -.slides > li, -.flex-control-nav, -.flex-direction-nav { - margin: 0; - padding: 0; - list-style: none; -} -.flex-pauseplay span { - text-transform: capitalize; -} -/* ==================================================================================================================== - * BASE STYLES - * ====================================================================================================================*/ -.flexslider { - margin: 0; - padding: 0; -} -.flexslider .slides > li { - display: none; - -webkit-backface-visibility: hidden; -} -.flexslider .slides img { - width: 100%; - display: block; -} -.flexslider .slides:after { - content: "\0020"; - display: block; - clear: both; - visibility: hidden; - line-height: 0; - height: 0; -} -html[xmlns] .flexslider .slides { - display: block; -} -* html .flexslider .slides { - height: 1%; -} -.no-js .flexslider .slides > li:first-child { - display: block; -} -/* ==================================================================================================================== - * DEFAULT THEME - * ====================================================================================================================*/ -.flexslider { - margin: 0 0 60px; - background: #ffffff; - border: 4px solid #ffffff; - position: relative; - zoom: 1; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); - -moz-box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); - -o-box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); - box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); -} -.flexslider .slides { - zoom: 1; -} -.flexslider .slides img { - height: auto; - -moz-user-select: none; -} -.flex-viewport { - max-height: 2000px; - -webkit-transition: all 1s ease; - -moz-transition: all 1s ease; - -ms-transition: all 1s ease; - -o-transition: all 1s ease; - transition: all 1s ease; -} -.loading .flex-viewport { - max-height: 300px; -} -.carousel li { - margin-right: 5px; -} -.flex-direction-nav { - *height: 0; -} -.flex-direction-nav a { - text-decoration: none; - display: block; - width: 40px; - height: 40px; - margin: -20px 0 0; - position: absolute; - top: 50%; - z-index: 10; - overflow: hidden; - opacity: 0; - cursor: pointer; - color: rgba(0, 0, 0, 0.8); - text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3); - -webkit-transition: all 0.3s ease-in-out; - -moz-transition: all 0.3s ease-in-out; - -ms-transition: all 0.3s ease-in-out; - -o-transition: all 0.3s ease-in-out; - transition: all 0.3s ease-in-out; -} -.flex-direction-nav a:before { - font-family: "flexslider-icon"; - font-size: 40px; - display: inline-block; - content: '\f001'; - color: rgba(0, 0, 0, 0.8); - text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3); -} -.flex-direction-nav a.flex-next:before { - content: '\f002'; -} -.flex-direction-nav .flex-prev { - left: -50px; -} -.flex-direction-nav .flex-next { - right: -50px; - text-align: right; -} -.flexslider:hover .flex-direction-nav .flex-prev { - opacity: 0.7; - left: 10px; -} -.flexslider:hover .flex-direction-nav .flex-prev:hover { - opacity: 1; -} -.flexslider:hover .flex-direction-nav .flex-next { - opacity: 0.7; - right: 10px; -} -.flexslider:hover .flex-direction-nav .flex-next:hover { - opacity: 1; -} -.flex-direction-nav .flex-disabled { - opacity: 0!important; - filter: alpha(opacity=0); - cursor: default; - z-index: -1; -} -.flex-pauseplay a { - display: block; - width: 20px; - height: 20px; - position: absolute; - bottom: 5px; - left: 10px; - opacity: 0.8; - z-index: 10; - overflow: hidden; - cursor: pointer; - color: #000; -} -.flex-pauseplay a:before { - font-family: "flexslider-icon"; - font-size: 20px; - display: inline-block; - content: '\f004'; -} -.flex-pauseplay a:hover { - opacity: 1; -} -.flex-pauseplay a.flex-play:before { - content: '\f003'; -} -.flex-control-nav { - width: 100%; - position: absolute; - bottom: -40px; - text-align: center; -} -.flex-control-nav li { - margin: 0 6px; - display: inline-block; - zoom: 1; - *display: inline; -} -.flex-control-paging li a { - width: 11px; - height: 11px; - display: block; - background: #666; - background: rgba(0, 0, 0, 0.5); - cursor: pointer; - text-indent: -9999px; - -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); - -moz-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); - -o-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); - box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); - -webkit-border-radius: 20px; - -moz-border-radius: 20px; - border-radius: 20px; -} -.flex-control-paging li a:hover { - background: #333; - background: rgba(0, 0, 0, 0.7); -} -.flex-control-paging li a.flex-active { - background: #000; - background: rgba(0, 0, 0, 0.9); - cursor: default; -} -.flex-control-thumbs { - margin: 5px 0 0; - position: static; - overflow: hidden; -} -.flex-control-thumbs li { - width: 25%; - float: left; - margin: 0; -} -.flex-control-thumbs img { - width: 100%; - height: auto; - display: block; - opacity: .7; - cursor: pointer; - -moz-user-select: none; - -webkit-transition: all 1s ease; - -moz-transition: all 1s ease; - -ms-transition: all 1s ease; - -o-transition: all 1s ease; - transition: all 1s ease; -} -.flex-control-thumbs img:hover { - opacity: 1; -} -.flex-control-thumbs .flex-active { - opacity: 1; - cursor: default; -} -/* ==================================================================================================================== - * RESPONSIVE - * ====================================================================================================================*/ -@media screen and (max-width: 860px) { - .flex-direction-nav .flex-prev { - opacity: 1; - left: 10px; - } - .flex-direction-nav .flex-next { - opacity: 1; - right: 10px; - } -} diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.eot b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.eot Binary files differdeleted file mode 100644 index 97c4196f5..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.eot +++ /dev/null diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.svg b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.svg deleted file mode 100644 index 89fd1ab86..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.svg +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" standalone="no"?> -<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" > -<svg xmlns="http://www.w3.org/2000/svg"> -<metadata> -This is a custom SVG font generated by IcoMoon. -<iconset grid="14"></iconset> -</metadata> -<defs> -<font id="flexslider-icon" horiz-adv-x="448" > -<font-face units-per-em="448" ascent="384" descent="-64" /> -<missing-glyph horiz-adv-x="448" /> -<glyph unicode="" d="M 185.50-9.25l-163.00,162.75q-9.25,9.25 -9.25,22.625t 9.25,22.625l 163.00,162.75q 9.25,9.25 22.625,9.25t 22.625-9.25l 18.75-18.75q 9.25-9.25 9.25-22.625t-9.25-22.625l-121.50-121.50l 121.50-121.25q 9.25-9.50 9.25-22.75t-9.25-22.50l-18.75-18.75q-9.25-9.25 -22.625-9.25t-22.625,9.25z" horiz-adv-x="288" /> -<glyph unicode="" d="M 274.75,176.00q0.00-13.00 -9.25-22.75l-163.00-162.75q-9.25-9.25 -22.50-9.25t-22.50,9.25l-19.00,18.75q-9.25,9.75 -9.25,22.75q0.00,13.25 9.25,22.50l 121.50,121.50l-121.50,121.25q-9.25,9.75 -9.25,22.75q0.00,13.25 9.25,22.50l 19.00,18.75q 9.00,9.50 22.50,9.50t 22.50-9.50l 163.00-162.75q 9.25-9.25 9.25-22.50z" horiz-adv-x="288" /> -<glyph unicode="" d="M 346.00,152.25l-332.00-184.50q-5.75-3.25 -9.875-0.75t-4.125,9.00l0.00,368.00 q0.00,6.50 4.125,9.00t 9.875-0.75l 332.00-184.50q 5.75-3.25 5.75-7.75t-5.75-7.75z" horiz-adv-x="352" /> -<glyph unicode="" d="M 384.00,336.00l0.00-352.00 q0.00-6.50 -4.75-11.25t-11.25-4.75l-128.00,0.00 q-6.50,0.00 -11.25,4.75t-4.75,11.25l0.00,352.00 q0.00,6.50 4.75,11.25t 11.25,4.75l 128.00,0.00 q 6.50,0.00 11.25-4.75t 4.75-11.25zM 160.00,336.00l0.00-352.00 q0.00-6.50 -4.75-11.25t-11.25-4.75l-128.00,0.00 q-6.50,0.00 -11.25,4.75t-4.75,11.25l0.00,352.00 q0.00,6.50 4.75,11.25t 11.25,4.75l 128.00,0.00 q 6.50,0.00 11.25-4.75t 4.75-11.25z" horiz-adv-x="384" /> -<glyph unicode="" d="M 402.75,208.00q0.00-13.25 -9.25-22.50l-162.75-162.75q-9.50-9.50 -22.75-9.50q-13.50,0.00 -22.50,9.50l-162.75,162.75q-9.50,9.00 -9.50,22.50q0.00,13.25 9.50,22.75l 18.50,18.75q 9.75,9.25 22.75,9.25q 13.25,0.00 22.50-9.25l 121.50-121.50l 121.50,121.50q 9.25,9.25 22.50,9.25q 13.00,0.00 22.75-9.25l 18.75-18.75q 9.25-9.75 9.25-22.75z" horiz-adv-x="416" /> -<glyph unicode=" " horiz-adv-x="224" /> -<glyph class="hidden" unicode="" d="M0,384L 448 -64L0 -64 z" horiz-adv-x="0" /> -</font></defs></svg>
\ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.ttf b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.ttf Binary files differdeleted file mode 100644 index 05432986a..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.ttf +++ /dev/null diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.woff b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.woff Binary files differdeleted file mode 100644 index 10c4eeb83..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.woff +++ /dev/null diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/eye.js b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/eye.js deleted file mode 100644 index 8a281dc3b..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/eye.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * - * Zoomimage - * Author: Stefan Petre www.eyecon.ro - * - */ -(function($){ - var EYE = window.EYE = function() { - var _registered = { - init: [] - }; - return { - init: function() { - $.each(_registered.init, function(nr, fn){ - fn.call(); - }); - }, - extend: function(prop) { - for (var i in prop) { - if (prop[i] != undefined) { - this[i] = prop[i]; - } - } - }, - register: function(fn, type) { - if (!_registered[type]) { - _registered[type] = []; - } - _registered[type].push(fn); - } - }; - }(); - $(EYE.init); -})(jQuery); diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/utils.js b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/utils.js deleted file mode 100644 index d9be85326..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/utils.js +++ /dev/null @@ -1,252 +0,0 @@ -/** - * - * Utilities - * Author: Stefan Petre www.eyecon.ro - * - */ -(function($) { -EYE.extend({ - getPosition : function(e, forceIt) - { - var x = 0; - var y = 0; - var es = e.style; - var restoreStyles = false; - if (forceIt && jQuery.curCSS(e,'display') == 'none') { - var oldVisibility = es.visibility; - var oldPosition = es.position; - restoreStyles = true; - es.visibility = 'hidden'; - es.display = 'block'; - es.position = 'absolute'; - } - var el = e; - if (el.getBoundingClientRect) { // IE - var box = el.getBoundingClientRect(); - x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2; - y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2; - } else { - x = el.offsetLeft; - y = el.offsetTop; - el = el.offsetParent; - if (e != el) { - while (el) { - x += el.offsetLeft; - y += el.offsetTop; - el = el.offsetParent; - } - } - if (jQuery.browser.safari && jQuery.curCSS(e, 'position') == 'absolute' ) { - x -= document.body.offsetLeft; - y -= document.body.offsetTop; - } - el = e.parentNode; - while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML') - { - if (jQuery.curCSS(el, 'display') != 'inline') { - x -= el.scrollLeft; - y -= el.scrollTop; - } - el = el.parentNode; - } - } - if (restoreStyles == true) { - es.display = 'none'; - es.position = oldPosition; - es.visibility = oldVisibility; - } - return {x:x, y:y}; - }, - getSize : function(e) - { - var w = parseInt(jQuery.curCSS(e,'width'), 10); - var h = parseInt(jQuery.curCSS(e,'height'), 10); - var wb = 0; - var hb = 0; - if (jQuery.curCSS(e, 'display') != 'none') { - wb = e.offsetWidth; - hb = e.offsetHeight; - } else { - var es = e.style; - var oldVisibility = es.visibility; - var oldPosition = es.position; - es.visibility = 'hidden'; - es.display = 'block'; - es.position = 'absolute'; - wb = e.offsetWidth; - hb = e.offsetHeight; - es.display = 'none'; - es.position = oldPosition; - es.visibility = oldVisibility; - } - return {w:w, h:h, wb:wb, hb:hb}; - }, - getClient : function(e) - { - var h, w; - if (e) { - w = e.clientWidth; - h = e.clientHeight; - } else { - var de = document.documentElement; - w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; - h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; - } - return {w:w,h:h}; - }, - getScroll : function (e) - { - var t=0, l=0, w=0, h=0, iw=0, ih=0; - if (e && e.nodeName.toLowerCase() != 'body') { - t = e.scrollTop; - l = e.scrollLeft; - w = e.scrollWidth; - h = e.scrollHeight; - } else { - if (document.documentElement) { - t = document.documentElement.scrollTop; - l = document.documentElement.scrollLeft; - w = document.documentElement.scrollWidth; - h = document.documentElement.scrollHeight; - } else if (document.body) { - t = document.body.scrollTop; - l = document.body.scrollLeft; - w = document.body.scrollWidth; - h = document.body.scrollHeight; - } - if (typeof pageYOffset != 'undefined') { - t = pageYOffset; - l = pageXOffset; - } - iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0; - ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0; - } - return { t: t, l: l, w: w, h: h, iw: iw, ih: ih }; - }, - getMargins : function(e, toInteger) - { - var t = jQuery.curCSS(e,'marginTop') || ''; - var r = jQuery.curCSS(e,'marginRight') || ''; - var b = jQuery.curCSS(e,'marginBottom') || ''; - var l = jQuery.curCSS(e,'marginLeft') || ''; - if (toInteger) - return { - t: parseInt(t, 10)||0, - r: parseInt(r, 10)||0, - b: parseInt(b, 10)||0, - l: parseInt(l, 10) - }; - else - return {t: t, r: r, b: b, l: l}; - }, - getPadding : function(e, toInteger) - { - var t = jQuery.curCSS(e,'paddingTop') || ''; - var r = jQuery.curCSS(e,'paddingRight') || ''; - var b = jQuery.curCSS(e,'paddingBottom') || ''; - var l = jQuery.curCSS(e,'paddingLeft') || ''; - if (toInteger) - return { - t: parseInt(t, 10)||0, - r: parseInt(r, 10)||0, - b: parseInt(b, 10)||0, - l: parseInt(l, 10) - }; - else - return {t: t, r: r, b: b, l: l}; - }, - getBorder : function(e, toInteger) - { - var t = jQuery.curCSS(e,'borderTopWidth') || ''; - var r = jQuery.curCSS(e,'borderRightWidth') || ''; - var b = jQuery.curCSS(e,'borderBottomWidth') || ''; - var l = jQuery.curCSS(e,'borderLeftWidth') || ''; - if (toInteger) - return { - t: parseInt(t, 10)||0, - r: parseInt(r, 10)||0, - b: parseInt(b, 10)||0, - l: parseInt(l, 10)||0 - }; - else - return {t: t, r: r, b: b, l: l}; - }, - traverseDOM : function(nodeEl, func) - { - func(nodeEl); - nodeEl = nodeEl.firstChild; - while(nodeEl){ - EYE.traverseDOM(nodeEl, func); - nodeEl = nodeEl.nextSibling; - } - }, - getInnerWidth : function(el, scroll) { - var offsetW = el.offsetWidth; - return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth; - }, - getInnerHeight : function(el, scroll) { - var offsetH = el.offsetHeight; - return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight; - }, - getExtraWidth : function(el) { - if($.boxModel) - return (parseInt($.curCSS(el, 'paddingLeft'))||0) - + (parseInt($.curCSS(el, 'paddingRight'))||0) - + (parseInt($.curCSS(el, 'borderLeftWidth'))||0) - + (parseInt($.curCSS(el, 'borderRightWidth'))||0); - return 0; - }, - getExtraHeight : function(el) { - if($.boxModel) - return (parseInt($.curCSS(el, 'paddingTop'))||0) - + (parseInt($.curCSS(el, 'paddingBottom'))||0) - + (parseInt($.curCSS(el, 'borderTopWidth'))||0) - + (parseInt($.curCSS(el, 'borderBottomWidth'))||0); - return 0; - }, - isChildOf: function(parentEl, el, container) { - if (parentEl == el) { - return true; - } - if (!el || !el.nodeType || el.nodeType != 1) { - return false; - } - if (parentEl.contains && !$.browser.safari) { - return parentEl.contains(el); - } - if ( parentEl.compareDocumentPosition ) { - return !!(parentEl.compareDocumentPosition(el) & 16); - } - var prEl = el.parentNode; - while(prEl && prEl != container) { - if (prEl == parentEl) - return true; - prEl = prEl.parentNode; - } - return false; - }, - centerEl : function(el, axis) - { - var clientScroll = EYE.getScroll(); - var size = EYE.getSize(el); - if (!axis || axis == 'vertically') - $(el).css( - { - top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px' - } - ); - if (!axis || axis == 'horizontally') - $(el).css( - { - left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px' - } - ); - } -}); -if (!$.easing.easeout) { - $.easing.easeout = function(p, n, firstNum, delta, duration) { - return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum; - }; -} - -})(jQuery);
\ No newline at end of file diff --git a/POLICY-SDK-APP/pom.xml b/POLICY-SDK-APP/pom.xml index 1c0cb9100..6a6db1ac4 100644 --- a/POLICY-SDK-APP/pom.xml +++ b/POLICY-SDK-APP/pom.xml @@ -195,5 +195,17 @@ <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> + <!-- https://mvnrepository.com/artifact/com.esotericsoftware.yamlbeans/yamlbeans --> + <dependency> + <groupId>com.esotericsoftware.yamlbeans</groupId> + <artifactId>yamlbeans</artifactId> + <version>1.08</version> + </dependency> + <!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml --> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.16</version> + </dependency> </dependencies> </project>
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java index 86210cdef..6c60c58c2 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java @@ -18,11 +18,6 @@ * ============LICENSE_END========================================================= */ -/* - * - * - * - * */ package org.openecomp.policy.admin; import java.io.BufferedReader; @@ -63,6 +58,7 @@ import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.http.HttpStatus; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; @@ -96,7 +92,7 @@ public class PolicyManagerServlet extends HttpServlet { private static final long serialVersionUID = -8453502699403909016L; private enum Mode { - LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST } private static String CONTENTTYPE = "application/json"; @@ -120,6 +116,7 @@ public class PolicyManagerServlet extends HttpServlet { } private static List<String> serviceTypeNamesList = new ArrayList<String>(); + private List<Object> policyData; public static List<String> getServiceTypeNamesList() { return serviceTypeNamesList; @@ -276,6 +273,9 @@ public class PolicyManagerServlet extends HttpServlet { case SWITCHVERSION: responseJsonObject = switchVersion(params, request); break; + case SEARCHLIST: + responseJsonObject = searchPolicyList(params, request); + break; default: throw new ServletException("not implemented"); } @@ -292,6 +292,101 @@ public class PolicyManagerServlet extends HttpServlet { out.flush(); } + private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { + Set<String> scopes = null; + List<String> roles = null; + policyData = null; + JSONArray policyList = null; + if(params.has("policyList")){ + policyList = (JSONArray) params.get("policyList"); + } + PolicyController controller = new PolicyController(); + List<JSONObject> resultList = new ArrayList<JSONObject>(); + try { + //Get the Login Id of the User from Request + String userId = UserUtils.getUserSession(request).getOrgUserId(); + //Check if the Role and Scope Size are Null get the values from db. + List<Object> userRoles = PolicyController.getRoles(userId); + roles = new ArrayList<String>(); + scopes = new HashSet<String>(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + } + } + if(policyList!= null){ + for(int i = 0; i < policyList.length(); i++){ + String policyName = policyList.get(i).toString().replace(".xml", ""); + String version = policyName.substring(policyName.lastIndexOf(".")+1); + policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator); + if(policyName.contains("\\")){ + policyName = policyName.replace("\\", "\\\\"); + } + String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0"; + List<Object> activeData = controller.getDataByQuery(policyVersionQuery); + if(!activeData.isEmpty()){ + PolicyVersion policy = (PolicyVersion) activeData.get(0); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + }else{ + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ){ + policyData = controller.getData(PolicyVersion.class); + }else{ + List<Object> filterdatas = controller.getData(PolicyVersion.class); + for(Object filter : filterdatas){ + PolicyVersion filterdata = (PolicyVersion) filter; + String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + policyData.add(filterdata); + } + } + } + + if(!policyData.isEmpty()){ + for(int i =0; i < policyData.size(); i++){ + PolicyVersion policy = (PolicyVersion) policyData.get(i); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + } + }catch(Exception e){ + LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); + } + + return new JSONObject().put(RESULT, resultList); + } + //Switch Version Functionality private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ String path = params.getString("path"); @@ -387,7 +482,7 @@ public class PolicyManagerServlet extends HttpServlet { String[] split = path.split(":"); String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; List<Object> queryData = controller.getDataByQuery(query); - if(queryData != null){ + if(!queryData.isEmpty()){ PolicyEntity entity = (PolicyEntity) queryData.get(0); File temp = null; try { @@ -731,7 +826,7 @@ public class PolicyManagerServlet extends HttpServlet { //Check Policy Group Entity table if policy has been pushed or not String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'"; List<Object> object = controller.getDataByQuery(query); - if(object == null){ + if(object.isEmpty()){ String oldPolicyNameWithoutExtension = removeoldPolicyExtension; String newPolicyNameWithoutExtension = removenewPolicyExtension; if(removeoldPolicyExtension.endsWith(".xml")){ @@ -926,7 +1021,7 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(entityItem); } - LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); + LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); return success(); } catch (Exception e) { @@ -972,7 +1067,8 @@ public class PolicyManagerServlet extends HttpServlet { } List<Object> policyEntityobjects = controller.getDataByQuery(query); - boolean pdpCheck = true; + String activePolicyName = null; + boolean pdpCheck = false; if(path.endsWith(".xml")){ policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1)); @@ -982,38 +1078,43 @@ public class PolicyManagerServlet extends HttpServlet { policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; List<Object> groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject != null){ - pdpCheck = false; - break; + if(!groupobject.isEmpty()){ + pdpCheck = true; + activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); + }else{ + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } } } } + //Policy Notification + PolicyVersion versionEntity = new PolicyVersion(); + versionEntity.setPolicyName(policyNamewithoutExtension); + versionEntity.setModifiedBy(userId); + controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); if(pdpCheck){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; - //Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if(policyNamewithoutExtension.contains("Config_")){ - controller.deleteData(policyEntity.getConfigurationData()); - }else if(policyNamewithoutExtension.contains("Action_")){ - controller.deleteData(policyEntity.getActionBodyEntity()); - } - } - //Policy Notification - PolicyVersion versionEntity = new PolicyVersion(); - versionEntity.setPolicyName(policyNamewithoutExtension); - versionEntity.setModifiedBy(userId); - controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); //Delete from policyVersion table - String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); + getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1); + String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; if(policyVersionQuery != null){ controller.executeQuery(policyVersionQuery); } + return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName); }else{ - return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); + //No Active Policy in PDP. So, deleting all entries from policyVersion table + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } } }else if("CURRENT".equals(deleteVersion)){ String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); @@ -1024,9 +1125,9 @@ public class PolicyManagerServlet extends HttpServlet { policyEntity = (PolicyEntity) policyEntitys.get(0); } if(policyEntity != null){ - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0"; List<Object> groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject == null){ + if(groupobject.isEmpty()){ //Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); @@ -1040,7 +1141,7 @@ public class PolicyManagerServlet extends HttpServlet { if(version > 1){ int highestVersion = 0; - if(policyEntityobjects.isEmpty()){ + if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); @@ -1072,18 +1173,16 @@ public class PolicyManagerServlet extends HttpServlet { } } }else{ + List<String> activePoliciesInPDP = new ArrayList<String>(); if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; List<Object> groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject != null){ - pdpCheck = false; - } - } - if(pdpCheck){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; + if(!groupobject.isEmpty()){ + pdpCheck = true; + activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); + }else{ //Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); @@ -1096,17 +1195,35 @@ public class PolicyManagerServlet extends HttpServlet { controller.deleteData(policyEntity.getActionBodyEntity()); } } + } + //Delete from policyVersion and policyEditor Scope table + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyVersionQuery); + + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(path); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, path, "DeleteScope"); + if(pdpCheck){ + //Add Active Policies List to PolicyVersionTable + for(int i =0; i < activePoliciesInPDP.size(); i++){ + String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", ""); + int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1)); + activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator); + PolicyVersion insertactivePDPVersion = new PolicyVersion(); + insertactivePDPVersion.setPolicyName(activePDPPolicyName); + insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); + insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); + insertactivePDPVersion.setCreatedBy(userId); + insertactivePDPVersion.setModifiedBy(userId); + controller.saveData(insertactivePDPVersion); + } - //Delete from policyVersion and policyEditor Scope table - String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP); + }else{ String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; - controller.executeQuery(policyVersionQuery); - controller.executeQuery(policyScopeQuery); - //Policy Notification - PolicyVersion entity = new PolicyVersion(); - entity.setPolicyName(path); - entity.setModifiedBy(userId); - controller.watchPolicyFunction(entity, path, "DeleteScope"); + controller.executeQuery(policyScopeQuery); } } } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java index 2a1129cf6..c40f0da0c 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java @@ -92,10 +92,29 @@ public class PolicyRestController extends RestrictedBaseController{ JsonNode root = mapper.readTree(request.getReader()); PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ policyData.isEditPolicy = true; } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + if(policyData.isEditPolicy){ + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + }else{ + String domain = root.get("policyData").get("model").get("name").toString(); + if(domain.contains("/")){ + domain = domain.substring(0, domain.lastIndexOf("/")).replace("/", File.separator); + } + domain = domain.replace("\"", ""); + policyData.setDomainDir(domain); + } + if(policyData.getConfigPolicyType() != null){ if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){ CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController(); @@ -111,19 +130,6 @@ public class PolicyRestController extends RestrictedBaseController{ policyData.setUserId(userId); - if(root.get("policyData").get("model").get("path").size() != 0){ - String dirName = ""; - for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ - dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; - } - if(policyData.isEditPolicy){ - policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); - }else{ - policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", "")); - } - }else{ - policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); - } String result; String body = PolicyUtils.objectToJsonString(policyData); String uri = request.getRequestURI(); @@ -253,7 +259,8 @@ public class PolicyRestController extends RestrictedBaseController{ connection.setDoOutput(true); connection.setDoInput(true); - if(!uri.contains("searchPolicy")){ + if(!uri.contains("searchPolicy?action=delete&")){ + if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){ connection.setRequestProperty("Content-Type","application/json"); ObjectMapper mapper = new ObjectMapper(); @@ -371,6 +378,23 @@ public class PolicyRestController extends RestrictedBaseController{ return null; } + @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST}) + public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI()+"?action=search"; + String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim()); + JSONObject json = new JSONObject(body); + Object resultList = json.get("policyresult"); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + out.write(j.toString()); + return null; + } + public void deleteElasticData(String fileName){ String uri = "searchPolicy?action=delete&policyName='"+fileName+"'"; callPAP(null, null, "POST", uri.trim()); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java index 77bcea6ef..86d9920d9 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java @@ -106,7 +106,7 @@ public class AutoPushController extends RestrictedBaseController{ try{ Set<String> scopes = null; List<String> roles = null; - data = null; + data = new ArrayList<Object>(); String userId = UserUtils.getUserSession(request).getOrgUserId(); Map<String, Object> model = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); @@ -123,20 +123,29 @@ public class AutoPushController extends RestrictedBaseController{ scopes.add(multipleScopes[i]); } }else{ - scopes.add(userRole.getScope()); + if(!userRole.getScope().equals("")){ + scopes.add(userRole.getScope()); + } } } } - if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { data = commonClassDao.getData(PolicyVersion.class); }else{ - List<Object> filterdatas = commonClassDao.getData(PolicyVersion.class); - for(Object filter : filterdatas){ - PolicyVersion filterdata = (PolicyVersion) filter; - String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); - if(scopes.contains(scopeName)){ - data.add(filterdata); + if(!scopes.isEmpty()){ + for(String scope : scopes){ + String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0"; + List<Object> filterdatas = commonClassDao.getDataByQuery(query); + if(filterdatas != null){ + for(int i =0; i < filterdatas.size(); i++){ + data.add(filterdatas.get(i)); + } + } } + }else{ + PolicyVersion emptyPolicyName = new PolicyVersion(); + emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + data.add(emptyPolicyName); } } model.put("policydatas", mapper.writeValueAsString(data)); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java index 570ceac31..aeb5266c5 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java @@ -24,8 +24,11 @@ package org.openecomp.policy.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.file.Files; @@ -75,6 +78,7 @@ import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; +import org.yaml.snakeyaml.Yaml; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.core.JsonProcessingException; @@ -105,6 +109,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private List<String> modelList = new ArrayList<String>(); private List<String> dirDependencyList = new ArrayList<String>(); private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>(); + //Tosca Model related Datastructure. + String referenceAttributes; + String attributeString; + String listConstraints; + String subAttributeString; + HashMap<String, Object> retmap = new HashMap<String, Object>(); + Set<String> uniqueKeys= new HashSet<String>(); + Set<String> uniqueDataKeys= new HashSet<String>(); @Autowired private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ @@ -191,7 +203,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } catch (JsonProcessingException e) { logger.error("Error writing out the object"); } - System.out.println(json); + logger.info(json); String cleanJson = cleanUPJson(json); cleanJson = removeNullAttributes(cleanJson); policyAdapter.setJsonBody(cleanJson); @@ -223,8 +235,360 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } return cleanJson; } + + // Second index of dot should be returned. + public void stringBetweenDots(String str,String value){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + if(len>2){ + uniqueKeys.add(ss[2]); + } + } + } + + public void stringBetweenDotsForDataFields(String str,String value){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + if(len>2){ + uniqueDataKeys.add(ss[0]+"%"+ss[2]); + } + } + } + + public Map<String, String> load(String fileName) throws IOException { + File newConfiguration = new File(fileName); + InputStream is = null; + try { + is = new FileInputStream(newConfiguration); + } catch (FileNotFoundException e) { + logger.error(e); + } + + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(is); + StringBuilder sb = new StringBuilder(); + Map<String, String> settings = new HashMap<String, String>(); + if (yamlMap == null) { + return settings; + } + List<String> path = new ArrayList<String>(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + public Map<String, String> load(byte[] source) throws IOException { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<Object, Object> yamlMap = (Map<Object, Object>) yaml.load(source.toString()); + StringBuilder sb = new StringBuilder(); + Map<String, String> settings = new HashMap<String, String>(); + if (yamlMap == null) { + return settings; + } + List<String> path = new ArrayList<String>(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> yamlMap) { + for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) { + if (entry.getValue() instanceof Map) { + path.add((String) entry.getKey()); + serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue()); + path.remove(path.size() - 1); + } else if (entry.getValue() instanceof List) { + path.add((String) entry.getKey()); + serializeList(settings, sb, path, (List) entry.getValue()); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + private void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List<String> yamlList) { + int counter = 0; + for (Object listEle : yamlList) { + if (listEle instanceof Map) { + path.add(Integer.toString(counter)); + serializeMap(settings, sb, path, (Map<Object, Object>) listEle); + path.remove(path.size() - 1); + } else if (listEle instanceof List) { + path.add(Integer.toString(counter)); + serializeList(settings, sb, path, (List<String>) listEle); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, Integer.toString(counter), listEle); + } + counter++; + } + } + + private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) { + if (value == null) { + return; + } + sb.setLength(0); + for (String pathEle : path) { + sb.append(pathEle).append('.'); + } + sb.append(name); + settings.put(sb.toString(), value.toString()); + } + + + public void parseTosca (String fileName){ + Map<String,String> map= new HashMap<String, String>(); + try { + map=load(fileName); + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")) + { + continue; + } + else if(key.contains("policy.nodes")){ + String wordToFind = "policy.nodes."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+13, key.length()); + + stringBetweenDots(subNodeString,map.get(key)); + } + else if(key.contains("policy.data")){ + String wordToFind="policy.data."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+12, key.length()); + + stringBetweenDotsForDataFields(subNodeString,map.get(key)); + Iterator<String> itr= uniqueDataKeys.iterator(); + while(itr.hasNext()){ + logger.info(itr.next()); + } + } + } + + String attributeIndividualString=""; + String userDefinedIndividualString=""; + String referenceIndividualAttributes=""; + + String attributeString=""; + String userDefinedString=""; + String referenceAttributes=""; + String listConstraints=""; + + for(String uniqueDataKey: uniqueDataKeys){ + String[] uniqueDataKeySplit= uniqueDataKey.split("%"); + userDefinedIndividualString=userDefinedIndividualString+uniqueDataKey+"="; + userDefinedIndividualString=userDefinedIndividualString+"#A:defaultValue-#B:required-#C:MANY-false"; + for(String key:map.keySet()){ + if(key.contains("policy.data")){ + String containsKey= uniqueDataKeySplit[1]+".type"; + if(key.contains(uniqueDataKeySplit[0])){ + if(key.contains("default")){ + userDefinedIndividualString=userDefinedIndividualString.replace("#B", map.get(key)); + } + else if(key.contains("required")){ + userDefinedIndividualString=userDefinedIndividualString.replace("#C", map.get(key)); + } + else if(key.contains(containsKey)){ + String typeValue= map.get(key); + userDefinedIndividualString=userDefinedIndividualString.replace("#A", typeValue); + } + } + } + + } + if(userDefinedString!=""){ + userDefinedString=userDefinedString+","+userDefinedIndividualString; + }else{ + userDefinedString=userDefinedString+userDefinedIndividualString; + } + userDefinedIndividualString=""; + } + logger.info("userDefinedString :"+userDefinedString); + + HashMap<String,ArrayList<String>> mapKey= new HashMap<String,ArrayList<String>>(); + String secondPartString=""; + String firstPartString=""; + for(String value: userDefinedString.split(",")){ + String[] splitWithEquals= value.split("="); + secondPartString=splitWithEquals[0].substring(splitWithEquals[0].indexOf("%")+1); + firstPartString=splitWithEquals[0].substring(0, splitWithEquals[0].indexOf("%")); + ArrayList<String> list; + if(mapKey.containsKey(firstPartString)){ + list = mapKey.get(firstPartString); + list.add(secondPartString+"<"+splitWithEquals[1]); + } else { + list = new ArrayList<String>(); + list.add(secondPartString+"<"+splitWithEquals[1]); + mapKey.put(firstPartString, list); + } + } + + JSONObject mainObject= new JSONObject();; + JSONObject json; + for(String s: mapKey.keySet()){ + json= new JSONObject(); + List<String> value=mapKey.get(s); + for(String listValue:value){ + String[] splitValue=listValue.split("<"); + json.put(splitValue[0], splitValue[1]); + } + mainObject.put(s,json); + } + + logger.info(mainObject); + + Iterator<String> keysItr = mainObject.keys(); + while(keysItr.hasNext()) { + String key = keysItr.next(); + String value = mainObject.get(key).toString(); + retmap.put(key, value); + } + + for(String str:retmap.keySet()){ + logger.info(str+":"+retmap.get(str)); + } + + String typeValueFromKey=""; + boolean userDefinedDataType=false; + boolean isList=false; + for(String uniqueKey: uniqueKeys){ + List<String> constraints= new ArrayList<String>(); + logger.info("===================="); + attributeIndividualString=attributeIndividualString+uniqueKey+"="; + attributeIndividualString=attributeIndividualString+"#A:defaultValue-#B:required-#C:MANY-false"; + + logger.info("UniqueStrings: "+uniqueKey); + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")|| + key.contains("policy.data")) + { + continue; + } + else if(key.contains("policy.nodes")){ + if(key.contains(uniqueKey)){ + int p=key.lastIndexOf("."); + String firstLastOccurance=key.substring(0,p); + int p1=firstLastOccurance.lastIndexOf("."); + String secondLastOccurance= firstLastOccurance.substring(p1+1,firstLastOccurance.length()); + if(secondLastOccurance.equals(uniqueKey)){ + String checkTypeString= firstLastOccurance+".type"; + typeValueFromKey= map.get(checkTypeString); + }//Its a list. + else if (key.contains("entry_schema")){ + if(key.contains("constraints")){ + constraints.add(map.get(key)); + } + if(key.contains("type")){ + isList=true; + String value= map.get(key); + if(! (value.contains("string")) || + (value.contains("integer")) || + (value.contains("boolean")) ) + { + if(!key.contains("valid_values")){ + String trimValue=value.substring(value.lastIndexOf(".")+1); + referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+trimValue+":MANY-true"; + attributeIndividualString=""; + } + + } + } + } + + if(!(typeValueFromKey.equals("string")|| + typeValueFromKey.equals("integer") || + typeValueFromKey.equals("boolean"))) + { + if(typeValueFromKey.equals("list")){ + isList=true; + userDefinedDataType=false; + } + else{ + userDefinedDataType=true; + } + } + if(userDefinedDataType==false && isList==false){ + if(key.contains("default")){ + attributeIndividualString=attributeIndividualString.replace("#B", map.get(key)); + } + else if(key.contains("required")){ + attributeIndividualString=attributeIndividualString.replace("#C", map.get(key)); + } + else if(key.contains("type")){ + String typeValue= map.get(key); + attributeIndividualString=attributeIndividualString.replace("#A", typeValue); + } + } + else if(userDefinedDataType==true){ + String checkTypeAndUpdate=key.substring(p+1); + if(checkTypeAndUpdate.equals("type")){ + String value=map.get(key); + String trimValue=value.substring(value.lastIndexOf(".")+1); + referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+trimValue+":MANY-false"; + } + attributeIndividualString=""; + } + } + } + } + + if(constraints!=null &&constraints.isEmpty()==false){ + //List handling. + listConstraints=uniqueKey.toUpperCase()+"=["; + isList=true; + for(String str:constraints){ + listConstraints=listConstraints+str+","; + } + listConstraints+="],"; + logger.info(listConstraints); + attributeIndividualString=""; + referenceIndividualAttributes=referenceIndividualAttributes+uniqueKey+"="+uniqueKey.toUpperCase()+":MANY-false"; + constraints=null; + + } + if(userDefinedDataType==false && isList==false){ + if(attributeString!=""){ + attributeString=attributeString+","+attributeIndividualString; + }else{ + attributeString=attributeString+attributeIndividualString; + } + } + if(isList==true || userDefinedDataType==true){ + if(referenceAttributes!=""){ + referenceAttributes=referenceAttributes+","+referenceIndividualAttributes; + }else{ + referenceAttributes=referenceAttributes+referenceIndividualAttributes; + } + logger.info("ReferenceAttributes: "+referenceAttributes); + } + + logger.info("AttributeString: "+ attributeString); + logger.info("ListConstraints is: "+listConstraints); + + attributeIndividualString=""; + referenceIndividualAttributes=""; + userDefinedDataType=false; + isList=false; + + } + this.listConstraints=listConstraints; + this.referenceAttributes=referenceAttributes; + this.attributeString=attributeString; + } catch (IOException e) { + logger.error(e); + } + } + private String cleanUPJson(String json) { String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"}); @@ -269,7 +633,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { presKey = key; } // first check if we are different from old. - System.out.println(key+"\n"); + logger.info(key+"\n"); if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ jsonResult.put(oldValue, jsonArray); @@ -444,7 +808,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return null; } - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "rawtypes" }) private String createMicroSeriveJson(MicroServiceModels returnModel) { Map<String, String> attributeMap = new HashMap<String, String>(); Map<String, String> refAttributeMap = new HashMap<String, String>(); @@ -620,7 +984,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { response.getWriter().write(j.toString()); } catch (Exception e){ - e.printStackTrace(); + logger.error(e); } } @@ -755,7 +1119,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } catch (Exception e) { - e.printStackTrace(); + logger.error(e); } } @@ -852,8 +1216,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); boolean zip = false; + boolean yml= false; for (FileItem item : items) { - if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")){ + if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){ this.newModel = new MicroServiceModels(); try{ File file = new File(item.getName()); @@ -862,41 +1227,81 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { outputStream.close(); this.newFile = file.toString(); this.newModel.setModelName(this.newFile.toString().split("-v")[0]); + if (this.newFile.toString().contains("-v")){ if (item.getName().endsWith(".zip")){ this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", "")); zip = true; - }else { + }else if(item.getName().endsWith(".yml")){ + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", "")); + yml = true; + } + else { this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", "")); } } + }catch(Exception e){ logger.error("Upload error : " + e); } } + } List<File> fileList = new ArrayList<File>();; this.directory = "model"; if (zip){ extractFolder(this.newFile); fileList = listModelFiles(this.directory); + }else if (yml==true){ + parseTosca(this.newFile); }else { File file = new File(this.newFile); fileList.add(file); } - - //Process Main Model file first - classMap = new HashMap<String,MSAttributeObject>(); - for (File file : fileList) { - if(!file.isDirectory() && file.getName().endsWith(".xmi")){ - retreiveDependency(file.toString(), true); - } + String modelType= ""; + if(yml==false){ + modelType="xmi"; + //Process Main Model file first + classMap = new HashMap<String,MSAttributeObject>(); + for (File file : fileList) { + if(!file.isDirectory() && file.getName().endsWith(".xmi")){ + retreiveDependency(file.toString(), true); + } + } + + modelList = createList(); + + cleanUp(this.newFile); + cleanUp(directory); + }else{ + modelType="yml"; + modelList.add(this.newModel.getModelName()); + String className=this.newModel.getModelName(); + MSAttributeObject msAttributes= new MSAttributeObject(); + msAttributes.setClassName(className); + + HashMap<String, String> returnAttributeList =new HashMap<String, String>(); + returnAttributeList.put(className, this.attributeString); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(this.retmap); + + HashMap<String, String> returnReferenceList =new HashMap<String, String>(); + //String[] referenceArray=this.referenceAttributes.split("="); + returnReferenceList.put(className, this.referenceAttributes); + msAttributes.setRefAttribute(returnReferenceList); + + if(this.listConstraints!=""){ + HashMap<String, String> enumList =new HashMap<String, String>(); + String[] listArray=this.listConstraints.split("="); + enumList.put(listArray[0], listArray[1]); + msAttributes.setEnumType(enumList); + } + + classMap=new HashMap<String,MSAttributeObject>(); + classMap.put(className, msAttributes); + } - - modelList = createList(); - - cleanUp(this.newFile); - cleanUp(directory); PrintWriter out = response.getWriter(); @@ -908,6 +1313,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { JSONObject j = new JSONObject(); j.put("classListDatas", modelList); j.put("modelDatas", mapper.writeValueAsString(classMap)); + j.put("modelType", modelType); out.write(j.toString()); } @@ -969,7 +1375,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); classMap.putAll(tempMap); - System.out.println(tempMap); + logger.info(tempMap); return; diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java index ecc39cdb6..41c960680 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java @@ -19,8 +19,6 @@ */ package org.openecomp.policy.controller; - - import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; @@ -514,7 +512,7 @@ public class CreateFirewallController extends RestrictedBaseController { ServiceListJson targetSl=null; int i=0; try{ - + String networkRole=""; for(String tag:tagCollectorList){ tags= new Tags(); List<Object> tagListData = commonClassDao.getData(FWTagPicker.class); @@ -535,12 +533,14 @@ public class CreateFirewallController extends RestrictedBaseController { tagList.add(tagDefine); } - + networkRole=jpaTagPickerList.getNetworkRole(); + break; } } tags.setTags(tagList); tags.setTagPickerName(tag); tags.setRuleName(termCollectorList.get(i)); + tags.setNetworkRole(networkRole); tagsList.add(tags); i++; } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java index d21788e90..57e8821f4 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java @@ -29,14 +29,14 @@ import java.util.Map; import javax.xml.bind.JAXBElement; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.adapter.YAMLParams; import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; @@ -150,24 +150,47 @@ public class DecisionPolicyController extends RestrictedBaseController { decisionList.add(settings); } else if (object instanceof RuleType) { // get the condition data under the rule for rule Algorithms. - if (((RuleType) object).getEffect().equals(EffectType.PERMIT)) { - ConditionType condition = ((RuleType) object).getCondition(); - if (condition != null) { - ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList<Integer>(); - // Populating Rule Algorithms starting from compound. - prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - } - }else if(((RuleType) object).getEffect().equals(EffectType.DENY)) { + if(((RuleType) object).getEffect().equals(EffectType.DENY)) { if(((RuleType) object).getAdviceExpressions()!=null){ if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ policyAdapter.setRuleProvider("AAF"); break; + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){ + policyAdapter.setRuleProvider("GUARD_YAML"); } }else{ policyAdapter.setRuleProvider("Custom"); } + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); + ruleAlgoirthmTracker = new LinkedList<Integer>(); + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("GUARD_YAML")){ + YAMLParams yamlParams = new YAMLParams(); + for(int i=0; i<attributeList.size() ; i++){ + Map<String, String> map = (Map<String,String>)attributeList.get(i); + if(map.get("key").equals("actor")){ + yamlParams.setActor(map.get("value")); + }else if(map.get("key").equals("recipe")){ + yamlParams.setRecipe(map.get("value")); + } + } + ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue()); + yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); + yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); + yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1)); + policyAdapter.setYamlparams(yamlParams); + policyAdapter.setAttributes(new ArrayList<Object>()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>()); + break; + } + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } } } } @@ -244,6 +267,7 @@ public class DecisionPolicyController extends RestrictedBaseController { String keyValue = PolicyController.getDropDownMap().get(key); if (keyValue.equals(decisionApply.getFunctionId())) { rule.put("dynamicRuleAlgorithmCombo", key); + break; } } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java index 72dfb164b..7d8701ef4 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java @@ -361,6 +361,10 @@ public class PolicyController extends RestrictedBaseController { public void deleteData(Object entity) { commonClassDao.delete(entity); } + + public List<Object> getData(@SuppressWarnings("rawtypes") Class className){ + return commonClassDao.getData(className); + } public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java index 55bff24a0..eb144cc18 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java @@ -448,7 +448,44 @@ public class PolicyValidationController extends RestrictedBaseController { responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>"; valid = false; } - + if(policyData.getRuleProvider().equals("GUARD_YAML")){ + if(policyData.getYamlparams()==null){ + responseString = responseString + "<b> Guard Params are Required </b>" + "<br>"; + valid = false; + }else{ + if(policyData.getYamlparams().getActor()==null){ + responseString = responseString + "Guard Params <b>Actor</b> is Required " + "<br>"; + valid = false; + } + if(policyData.getYamlparams().getRecipe()==null){ + responseString = responseString + "Guard Params <b>Recipe</b> is Required " + "<br>"; + valid = false; + } + if(policyData.getYamlparams().getLimit()==null){ + responseString = responseString + " Guard Params <b>Limit</b> is Required " + "<br>"; + valid = false; + }else{ + try{ + Integer.parseInt(policyData.getYamlparams().getLimit()); + }catch(NumberFormatException e){ + responseString = responseString + " Guard Params <b>Limit</b> Should be Integer " + "<br>"; + valid = false; + } + } + if(policyData.getYamlparams().getTimeWindow()==null){ + responseString = responseString + "Guard Params <b>Time Window</b> is Required" + "<br>"; + valid = false; + } + if(policyData.getYamlparams().getGuardActiveStart()==null){ + responseString = responseString + "Guard Params <b>Guard Active Start/b>is Required " + "<br>"; + valid = false; + } + if(policyData.getYamlparams().getGuardActiveEnd()==null){ + responseString = responseString + "Guard Params <b>Guard Active End</b>is Required " + "<br>"; + valid = false; + } + } + } } if(policyData.getPolicyType().equals(ACTION_POLICY)){ diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java index 6ac4afbcf..9cb41eeab 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java @@ -264,8 +264,6 @@ public class CommonClassDaoImpl implements CommonClassDao{ @SuppressWarnings("rawtypes") @Override public Object getEntityItem(Class className, String columnName, String key) { - System.out.println(columnName); - System.out.println(key); Session session = sessionfactory.openSession(); Transaction tx = session.beginTransaction(); Object data = null; @@ -281,7 +279,6 @@ public class CommonClassDaoImpl implements CommonClassDao{ cr.add(Restrictions.eq(columnName, key)); } data = cr.list().get(0); - System.out.println(data); tx.commit(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html index 231ac0a33..5f403b104 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html @@ -48,7 +48,7 @@ <div class="form-group row"> <div class="form-group"> <div data-ng-repeat="choice in apchoices"> - <div class="form-group row"> + <div class="form-group row" style="margin-left: 2%"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> <select class="form-control" ng-model="choice.option" ng-options="option for option in prefixListDictionaryDatas track by option"></select> <p ng-show="formdata.option.$invalid && !formdata.option.$pristine" class="help-block">Key is required.</p> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html index 3f676938e..4fb043136 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html @@ -23,7 +23,7 @@ <div class="form-group row"> <div class="form-group"> <div data-ng-repeat="choice in slchoices"> - <div class="form-group row"> + <div class="form-group row" style="margin-left: 2%"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> <select class="form-control" ng-model="choice.option" name= "option" required ng-options="option for option in serviceListDictionaryDatas track by option"><option value = "">{{choice.option}}</option></select> <p ng-show="formdata.option.$invalid && !formdata.option.$pristine" class="help-block">ServiceList is required.</p> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceListDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceListDictionary.html index 130542326..8696f24f6 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceListDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWServiceListDictionary.html @@ -46,7 +46,7 @@ <div class="form-group row"> <div class="form-group"> <div data-ng-repeat="choice in tpchoices"> - <div class="form-group row"> + <div class="form-group row" style="margin-left: 2%"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> <select class="form-control" name= "option" required ng-model="choice.option" ng-options="option for option in protocolListDictionaryDatas track by option" > <option value="">{{choice.option}}</option></select> @@ -68,7 +68,7 @@ <div class="form-group row"> <div class="form-group"> <div data-ng-repeat="choice in apchoices"> - <div class="form-group row"> + <div class="form-group row" style="margin-left: 2%"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> <select class="form-control" name= "option" required ng-model="choice.option" ng-options="option for option in protocolListDictionaryDatas track by option" > <option value="">{{choice.option}}</option></select> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTagPicker.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTagPicker.html index 30c4e6372..96ba42f1b 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTagPicker.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTagPicker.html @@ -38,6 +38,12 @@ </div> </div> <div class="form-group row"> + <div class="form-group col-sm-6"> + <label>Network role:</label><br> + <input type="text" ng-model="editFWTagPicker.networkRole" class="form-control"/> + </div> + </div> + <div class="form-group row"> <div class="form-group col-sm-4"> <label>Select Tags:</label><br> <button type="button" class="btn btn-secondary btn-small" ng-click="addNewChoice()"><i class="fa fa-plus"></i></button> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTermListDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTermListDictionary.html index 412cce34e..2e7a064f3 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTermListDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/FWTermListDictionary.html @@ -91,7 +91,7 @@ <div data-ng-repeat="choice in sourceListchoices"> <div class="form-group row"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> - <select class="form-control" ng-model="choice.option" ng-options="option for option in addressGroupDictionaryDatas track by option"><option value = "" name= "option" required>{{choice.option}}</option></select> + <select class="form-control" ng-model="choice.option" ng-options="option for option in groupAddresses track by option"><option value = "" name= "option" required>{{choice.option}}</option></select> <p ng-show="formdata.option.$invalid && !formdata.option.$pristine" class="help-block">Source-List is required.</p> </div> <div class="form-group col-sm-1"> @@ -112,7 +112,7 @@ <div data-ng-repeat="choice in destinationListchoices"> <div class="form-group row"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> - <select class="form-control" ng-model="choice.option" ng-options="option for option in prefixListDictionaryDatas track by option"><option value = "" name= "option" required>{{choice.option}}</option></select> + <select class="form-control" ng-model="choice.option" ng-options="option for option in groupAddresses track by option"><option value = "" name= "option" required>{{choice.option}}</option></select> <p ng-show="formdata.option.$invalid && !formdata.option.$pristine" class="help-block">Destination-List is required.</p> </div> <div class="form-group col-sm-1"> @@ -133,7 +133,7 @@ <div data-ng-repeat="choice in sourceServicechoices"> <div class="form-group row"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> - <select class="form-control" ng-model="choice.option" ng-options="option for option in serviceListDictionaryDatas track by option" ng-options="option for option in serviceGroupDictionaryDatas track by option"><option value = "" name= "option" required>{{choice.option}}</option></select> + <select class="form-control" ng-model="choice.option" ng-options="option for option in groupServices track by option" ng-options="option for option in groupServices track by option"><option value = "" name= "option" required>{{choice.option}}</option></select> <p ng-show="formdata.option.$invalid && !formdata.option.$pristine" class="help-block">Source-Services is required.</p> </div> <div class="form-group col-sm-1"> @@ -154,7 +154,7 @@ <div data-ng-repeat="choice in destinationServicechoices"> <div class="form-group row"> <div class="form-group col-sm-5" ng-class="{ 'has-error' : formdata.option.$invalid && !formdata.option.$pristine }"> - <select class="form-control" ng-model="choice.option" ng-options="option for option in serviceListDictionaryDatas track by option" ng-options="option for option in serviceGroupDictionaryDatas track by option" name= "option" required><option value = "">{{choice.option}}</option></select> + <select class="form-control" ng-model="choice.option" ng-options="option for option in groupServices track by option" ng-options="option for option in groupServices track by option" name= "option" required><option value = "">{{choice.option}}</option></select> <p ng-show="formdata.option.$invalid && !formdata.option.$pristine" class="help-block">Destination-Services is required.</p> </div> <div class="form-group col-sm-1"> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/MSModelsDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/MSModelsDictionary.html index 0bc58fc1c..303f122cd 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/MSModelsDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/MSModelsDictionary.html @@ -49,8 +49,8 @@ <p ng-show="formdata.classList.$invalid && !formdata.classList.$pristine" class="help-block">Micro Service is required.</p> </div> <div class="form-group col-sm-6"> - <label>Verison:</label><br> - <input type="text" ng-model="editMSmodelName.version" class="form-control"/> + <label>Version:<sup><b>*</b></sup></label><br> + <input type="text" required ng-model="editMSmodelName.version" class="form-control"/> </div> </div> </div> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js index 4c3ddb4ab..be2f7449b 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js @@ -25,6 +25,8 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me $scope.sourceServicechoices = []; $scope.destinationServicechoices = []; $scope.actionListchoices = []; + $scope.groupAddresses=[]; + $scope.groupServices=[]; if(message.termListDictionaryData==null){ $scope.label='Add Term List Name' }else{ @@ -143,6 +145,10 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me console.log($scope.data); $scope.prefixListDictionaryDatas = JSON.parse($scope.data.prefixListDictionaryDatas); console.log($scope.prefixListDictionaryDatas); + for(i = 0; i < $scope.prefixListDictionaryDatas.length; i++){ + var key = $scope.prefixListDictionaryDatas[i]; + $scope.groupAddresses.push(key); + } }, function (error) { console.log("failed"); }); @@ -163,6 +169,10 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me console.log($scope.data); $scope.addressGroupDictionaryDatas = JSON.parse($scope.data.addressGroupDictionaryDatas); console.log($scope.addressGroupDictionaryDatas); + for(i = 0; i < $scope.addressGroupDictionaryDatas.length; i++){ + var key = $scope.addressGroupDictionaryDatas[i]; + $scope.groupAddresses.push(key); + } }, function (error) { console.log("failed"); }); @@ -173,6 +183,10 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me console.log($scope.data); $scope.serviceListDictionaryDatas = JSON.parse($scope.data.serviceListDictionaryDatas); console.log($scope.serviceListDictionaryDatas); + for(i = 0; i < $scope.serviceListDictionaryDatas.length; i++){ + var key = $scope.serviceListDictionaryDatas[i]; + $scope.groupServices.push(key); + } }, function (error) { console.log("failed"); }); @@ -183,6 +197,10 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me console.log($scope.data); $scope.serviceGroupDictionaryDatas = JSON.parse($scope.data.serviceGroupDictionaryDatas); console.log($scope.serviceGroupDictionaryDatas); + for(i = 0; i < $scope.serviceGroupDictionaryDatas.length; i++){ + var key = $scope.serviceGroupDictionaryDatas[i]; + $scope.groupServices.push(key); + } }, function (error) { console.log("failed"); }); diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSModelsDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSModelsDictController.js index 2e30523ad..67b68eca8 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSModelsDictController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSModelsDictController.js @@ -37,7 +37,7 @@ app.controller('editMSModelController' , function ($scope, $modalInstance, mess $scope.uploadFile = function(files) { var extn = files[0].name.substr(files[0].name.lastIndexOf('.')+1); - if(extn == 'zip' || extn == 'xmi'){ + if(extn == 'zip' || extn == 'xmi'|| extn == 'yml'){ valid = true; var fd = new FormData(); fd.append("file", files[0]); @@ -51,6 +51,7 @@ app.controller('editMSModelController' , function ($scope, $modalInstance, mess }else{ $scope.classListDatas=data.classListDatas; $scope.modalDatas = data.modelDatas; + $scope.modelType= data.modelType; console.log($scope.classListDatas); } }).error( ); @@ -64,7 +65,7 @@ app.controller('editMSModelController' , function ($scope, $modalInstance, mess $scope.saveMSModel = function(microServiceModelsDictionaryData) { if(valid){ var uuu = "saveDictionary/ms_dictionary/save_model"; - var postData={microServiceModelsDictionaryData: microServiceModelsDictionaryData, userid: userid, classMap: $scope.modalDatas}; + var postData={microServiceModelsDictionaryData: microServiceModelsDictionaryData, userid: userid, classMap: $scope.modalDatas,modelType:$scope.modelType}; $.ajax({ type : 'POST', url : uuu, diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyController.js index ec6a56c05..4699512be 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyController.js @@ -55,7 +55,7 @@ app.config(function($routeProvider) { }) .when('/policy_SearchFilter', { templateUrl: 'app/policyApp/policy-models/policy_SearchFilter.html', - controller : "PolicyManagerController" + controller : "PolicySearchController" }) .otherwise({ templateUrl:'app/policyApp/policy-models/Editor/templates/policyEditor.html', diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html index 55b3214d2..dedf4b414 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html @@ -90,6 +90,7 @@ <script src= "app/policyApp/policy-models/Editor/js/services/policynavigator.js"></script> <script src= "app/policyApp/policy-models/Editor/js/services/policyuploader.js"></script> <script src= "app/policyApp/policy-models/Editor/js/controllers/policyManager.js"></script> + <script src= "app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js"></script> <script src= "app/policyApp/policy-models/Editor/js/controllers/selector-controller.js"></script> <script src= "app/policyApp/controller/policyController.js"></script> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js index fde8d4e9e..6ca9dfd93 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js @@ -17,12 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('actionPolicyController', function ($scope, PolicyAppService, modalService, $modal, Notification) { +app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; - + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; + PolicyAppService.getData('getDictionary/get_ActionPolicyDictDataByName').then(function (data) { var j = data; $scope.data = JSON.parse(j.data); @@ -61,7 +73,11 @@ angular.module('abs').controller('actionPolicyController', function ($scope, Pol } $scope.saveActionPolicy = function(policy){ - console.log(policy); + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; var uuu = "policycreation/save_policy"; var postData={policyData: policy}; @@ -82,7 +98,6 @@ angular.module('abs').controller('actionPolicyController', function ($scope, Pol Notification.error("Policy Already Exists with Same Name in Scope."); } }); - console.log($scope.data); }, error : function(data){ Notification.error("Error Occured while saving Policy."); @@ -92,9 +107,8 @@ angular.module('abs').controller('actionPolicyController', function ($scope, Pol }; $scope.validatePolicy = function(policy){ - console.log(policy); document.getElementById("validate").innerHTML = ""; - var uuu = "policyController/validate_policy.htm"; + var uuu = "policyController/validate_policy.htm"; var postData={policyData: policy}; $.ajax({ type : 'POST', @@ -118,7 +132,6 @@ angular.module('abs').controller('actionPolicyController', function ($scope, Pol } }); - console.log($scope.data); }, error : function(data){ Notification.error("Validation Failed."); @@ -170,4 +183,4 @@ angular.module('abs').controller('actionPolicyController', function ($scope, Pol $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem); }; -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js index c5160e741..ebec3a526 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js @@ -17,11 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('brmsParamPolicyController', function ($scope, $window, PolicyAppService, modalService, $modal, Notification) { +angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; $scope.validateSuccess = true; var readValue = $scope.temp.policy.readOnly; @@ -129,7 +141,11 @@ angular.module('abs').controller('brmsParamPolicyController', function ($scope, }; $scope.saveBrmsParamPolicy = function(policy){ - console.log(policy); + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; var uuu = "policycreation/save_policy"; var postData={policyData: policy}; @@ -231,7 +247,7 @@ angular.module('abs').controller('brmsParamPolicyController', function ($scope, var lastItem = $scope.temp.policy.attributes.length-1; $scope.temp.policy.attributes.splice(lastItem); }; -}); +}]); app.controller('showrulecontroller' , function ($scope, $modalInstance, message){ if(message.datas!=null){ diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js index 5b78193ee..97f6d2997 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js @@ -17,11 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('brmsRawPolicyController', function ($scope, $window, PolicyAppService, modalService, $modal, Notification) { +angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; PolicyAppService.getData('getDictionary/get_BRMSControllerDataByName').then(function (data) { var j = data; @@ -54,7 +66,11 @@ angular.module('abs').controller('brmsRawPolicyController', function ($scope, $w }); $scope.saveBrmsRawPolicy = function(policy){ - console.log(policy); + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; var uuu = "policycreation/save_policy"; var postData={policyData: policy}; @@ -149,4 +165,4 @@ angular.module('abs').controller('brmsRawPolicyController', function ($scope, $w var lastItem = $scope.temp.policy.attributes.length-1; $scope.temp.policy.attributes.splice(lastItem); }; -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js index 9f2863579..20287baf1 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js @@ -17,11 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -app.controller('baseConfigController', function ($scope, PolicyAppService, modalService, $modal, Notification) { +app.controller('baseConfigController', ['$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + + $scope.policyNavigator; $scope.savebutton = true; - + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; + PolicyAppService.getData('getDictionary/get_EcompNameDataByName').then(function (data) { var j = data; $scope.data = JSON.parse(j.data); @@ -61,8 +75,12 @@ app.controller('baseConfigController', function ($scope, PolicyAppService, modal } $scope.savePolicy = function(policy){ + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; - console.log(policy); var uuu = "policycreation/save_policy"; var postData={policyData: policy}; $.ajax({ @@ -92,7 +110,7 @@ app.controller('baseConfigController', function ($scope, PolicyAppService, modal $scope.validatePolicy = function(policy){ - console.log(policy); + $scope.scope = policy.domain; document.getElementById("validate").innerHTML = ""; var uuu = "policyController/validate_policy.htm"; var postData={policyData: policy}; @@ -150,5 +168,4 @@ app.controller('baseConfigController', function ($scope, PolicyAppService, modal var lastItem = $scope.temp.policy.attributes.length-1; $scope.temp.policy.attributes.splice(lastItem); }; - -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js index a8dcd7b0a..11254742a 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js @@ -17,11 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module("abs").controller('clFaultController', function($scope, $window, PolicyAppService, modalService, $modal, Notification){ +angular.module("abs").controller('clFaultController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification){ $("#dialog").hide(); + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; if($scope.temp.policy.triggerTrapSignatures == undefined){ $scope.temp.policy.triggerTrapSignatures = []; @@ -501,7 +513,11 @@ angular.module("abs").controller('clFaultController', function($scope, $window, }; $scope.saveFaultPolicy = function(policy){ - console.log(policy); + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; var data = {}; var faultData = {}; @@ -780,4 +796,4 @@ angular.module("abs").controller('clFaultController', function($scope, $window, }; -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js index 2f709a716..393780705 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js @@ -17,11 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module("abs").controller('clPMController', function($scope, $window, $timeout, PolicyAppService, modalService, $modal, Notification){ +angular.module("abs").controller('clPMController', ['$scope', '$window', '$timeout', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function($scope, $window, $timeout, PolicyAppService, PolicyNavigator, modalService, $modal, Notification){ $("#dialog").hide(); + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; PolicyAppService.getData('getDictionary/get_EcompNameDataByName').then(function (data) { var j = data; @@ -88,7 +100,11 @@ angular.module("abs").controller('clPMController', function($scope, $window, $ti }; $scope.saveCLPMPolicy = function(policy){ - console.log(policy); + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; var uuu = "policycreation/save_policy"; var postData={policyData: policy}; @@ -160,4 +176,4 @@ angular.module("abs").controller('clPMController', function($scope, $window, $ti }); }; -})
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js index d0f44d46e..b87299cbd 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js @@ -17,13 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('dcaeMicroServiceController', function ($scope, $window, $compile, PolicyAppService, modalService, $modal, Notification) { +angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + + $scope.policyNavigator; $scope.isCheck = false; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; -// $scope.temp.policy.ttlDate = "2016-12-31"; if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){ if ($scope.temp.policy.configName == undefined){ $scope.isCheck = false; @@ -384,11 +396,17 @@ angular.module('abs').controller('dcaeMicroServiceController', function ($scope, } function getList(attribute) { - + var enumName = attribute; + console.log("In getList: attribute => " + attribute); + if(attribute){ + if(attribute.includes(":")){ + enumName = attribute.split(":")[0]; + } + } var baseEnum = $scope.dcaeModelData.enumValues; var enumList = baseEnum.split(splitEnum); var enumAttributes; - var patternTest = new RegExp(attribute); + var patternTest = new RegExp(enumName); for (k=0; k < enumList.length; k += 1){ if(patternTest.test(enumList[k]) == true){ enumAttributes = enumList[k].trim(); @@ -399,12 +417,9 @@ angular.module('abs').controller('dcaeMicroServiceController', function ($scope, enumAttributes = enumAttributes.replace("[", ""); enumAttributes = enumAttributes.replace("]", ""); enumAttributes = enumAttributes.replace(/ /g, ''); - var dropListAfterCommaSplit = enumAttributes.split(splitEqual); listemunerateValues = dropListAfterCommaSplit[1].split(splitComma); - - enumKeyList.push(attribute); - + //enumKeyList.push(attribute); return listemunerateValues; } @@ -704,7 +719,10 @@ angular.module('abs').controller('dcaeMicroServiceController', function ($scope, option.appendChild(document.createTextNode(listemunerateValues[i])); listField.appendChild(option); } - listField.setAttribute("id" , ''+ labelLevel + attributeName + '');; + listField.setAttribute("id" , ''+ labelLevel + attributeName + ''); + + enumKeyList.push(attributeName); + document.getElementById(divID).appendChild(label); document.getElementById(divID).appendChild(br); @@ -750,6 +768,11 @@ angular.module('abs').controller('dcaeMicroServiceController', function ($scope, } $scope.savePolicy = function(policy){ + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; var splitAt = '*'; var dot ='.'; @@ -926,4 +949,4 @@ angular.module('abs').controller('dcaeMicroServiceController', function ($scope, } return obj; } -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js index f5932e2f4..d0c72682b 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js @@ -17,10 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('decisionPolicyController', function ($scope, PolicyAppService, modalService, $modal, Notification) { +angular.module('abs').controller('decisionPolicyController', ['$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; if($scope.temp.policy.ruleProvider==undefined){ $scope.temp.policy.ruleProvider="Custom"; @@ -76,6 +89,11 @@ angular.module('abs').controller('decisionPolicyController', function ($scope, P } $scope.saveDecisionPolicy = function(policy){ + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; console.log(policy); var uuu = "policycreation/save_policy"; @@ -146,7 +164,7 @@ angular.module('abs').controller('decisionPolicyController', function ($scope, P $scope.temp.policy.attributes = []; $scope.temp.policy.settings = []; $scope.temp.policy.ruleAlgorithmschoices = []; - }else{ + }else if($scope.temp.policy.ruleProvider=="Custom"){ if($scope.temp.policy.attributes.length == 0){ $scope.temp.policy.attributes = []; } @@ -206,4 +224,4 @@ angular.module('abs').controller('decisionPolicyController', function ($scope, P $scope.temp.policy.attributes = []; } }; -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js index cc051769c..46b6711cd 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js @@ -17,11 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -angular.module('abs').controller('fwPolicyController', function ($scope, $window, PolicyAppService, modalService, $modal, Notification) { +angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) { $("#dialog").hide(); + $scope.policyNavigator; $scope.savebutton = true; - $scope.finalPath = null; + $scope.refreshCheck = false; + + $scope.refresh = function(){ + if($scope.refreshCheck){ + $scope.policyNavigator.refresh(); + } + $scope.modal('createNewPolicy', true); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; PolicyAppService.getData('getDictionary/get_SecurityZoneDataByName').then(function (data) { var j = data; @@ -113,6 +125,11 @@ angular.module('abs').controller('fwPolicyController', function ($scope, $window $scope.saveFWPolicy = function(policy){ + if(policy.itemContent != undefined){ + $scope.refreshCheck = true; + $scope.policyNavigator = policy.itemContent; + policy.itemContent = ""; + } $scope.savebutton = false; console.log(policy); var uuu = "policycreation/save_policy"; @@ -224,4 +241,4 @@ angular.module('abs').controller('fwPolicyController', function ($scope, $window $scope.temp.policy.fwattributes.splice(lastItem); }; -});
\ No newline at end of file +}]);
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html index 3b60c9b19..ffb0e972f 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html @@ -133,10 +133,7 @@ <button class="btn btn-success" ng-disabled="savebutton" herf="javascript:void(0)" ng-disabled="temp.policy.readOnly" ng-click="saveActionPolicy(temp);">Save</button> - <button class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" - ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </form> </div> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSParamPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSParamPolicyTemplate.html index 6989a8509..2aa3b23d9 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSParamPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSParamPolicyTemplate.html @@ -47,7 +47,7 @@ <div class="form-group row"> <div class="form-group col-sm-3"> <label>Time to Live Date:</label> <input type="date" - class="form-control" name="ttlDate" class="date" + class="form-control" name="ttlDate" ng-disabled="temp.policy.readOnly" class="date" ng-model="temp.policy.ttlDate" /> </div> <div class="form-group col-sm-3"> @@ -136,10 +136,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="savebutton" ng-disabled="temp.policy.readOnly" ng-click="saveBrmsParamPolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal" - ng-model="finalPath" - ng-controller="FileManagerCtrl" - ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </div> </form> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSRawPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSRawPolicyTemplate.html index 75b8c3ba2..a778b13fe 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSRawPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BRMSRawPolicyTemplate.html @@ -46,7 +46,7 @@ <div class="form-group row"> <div class="form-group col-sm-3"> <label>Time to Live Date:</label> <input type="date" - class="form-control" name="ttlDate" class="date" + class="form-control" name="ttlDate" ng-disabled="temp.policy.readOnly" class="date" ng-model="temp.policy.ttlDate" /> </div> <div class="form-group col-sm-3"> @@ -116,10 +116,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="savebutton" ng-disabled="temp.policy.readOnly" ng-click="saveBrmsRawPolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" - ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </div> </form> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BasePolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BasePolicyTemplate.html index 16b8cad9a..1ecfd2fbd 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BasePolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/BasePolicyTemplate.html @@ -31,7 +31,7 @@ </div> <div class="form-group col-sm-3"> <label>Time to Live Date:</label> <input type="date" - class="form-control" name="ttlDate" class="date" + class="form-control" ng-disabled="temp.policy.readOnly" name="ttlDate" class="date" ng-model="temp.policy.ttlDate" /> </div> </div> @@ -132,7 +132,7 @@ herf="javascript:void(0)" ng-click="validatePolicy(temp.policy);">Validate</button> <button class="btn btn-success" ng-disabled="savebutton" herf="javascript:void(0)" ng-click="savePolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </div> </form> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html index 6590d2690..e831bb40e 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html @@ -68,7 +68,7 @@ <option>InActive</option> </select> </div> - <div class="form-group col-sm-6"> + <div class="form-group col-sm-3"> <label>D2/Virtualized Services(s):<sup><b>*</b></sup></label><br> <input type="checkbox" ng-disabled="temp.policy.readOnly" ng-model="temp.policy.jsonBodyData.trinity"> Hosted Voice @@ -81,6 +81,11 @@ type="checkbox" ng-disabled="temp.policy.readOnly" ng-model="temp.policy.jsonBodyData.vDNS"> vDNS</input> </div> + <div class="form-group col-sm-3"> + <label>Time to Live Date:</label> <input type="date" + class="form-control" name="ttlDate" ng-disabled="temp.policy.readOnly" class="date" + ng-model="temp.policy.ttlDate" /> + </div> </div> </div> <div class="well"> @@ -492,9 +497,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="savebutton" ng-disabled="temp.policy.readOnly" ng-click="saveFaultPolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </form> </div>
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopPMPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopPMPolicyTemplate.html index e22070308..20781a369 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopPMPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopPMPolicyTemplate.html @@ -25,7 +25,7 @@ </div> <div class="form-group col-sm-3"> <label>Time to Live Date:</label> <input type="date" - class="form-control" name="ttlDate" class="date" + class="form-control" name="ttlDate" ng-disabled="temp.policy.readOnly" class="date" ng-model="temp.policy.ttlDate" /> </div> <div class="form-group col-sm-3"> @@ -148,10 +148,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="savebutton" ng-disabled="temp.policy.readOnly" ng-click="saveCLPMPolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" - ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </div> </form> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DCAEMicroServicePolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DCAEMicroServicePolicyTemplate.html index 945e8655a..a12300b97 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DCAEMicroServicePolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DCAEMicroServicePolicyTemplate.html @@ -25,7 +25,7 @@ </div> <div class="form-group col-sm-3"> <label>Time to Live Date:</label> <input type="date" - class="form-control" name="ttlDate" class="date" + class="form-control" name="ttlDate" ng-disabled="temp.policy.readOnly" class="date" ng-model="temp.policy.ttlDate" /> </div> <div class="form-group col-sm-3"> @@ -126,9 +126,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="savebutton" ng-disabled="temp.policy.readOnly" ng-click="savePolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </form> </div> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html index d386770b9..a98dbff1d 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html @@ -31,10 +31,93 @@ ng-click="providerListener(temp.policy.ruleProvider);"> <option>Custom</option> <option>AAF</option> + <option>GUARD_YAML</option> </select> </div> </div> </div> + + <div ng-if="temp.policy.ruleProvider == 'GUARD_YAML'"> + <div class="well"> + <div class="form-group row"> + <div class="form-group col-sm-1"> + <label>Guard YAML Attributes:</label><br> + </div> + </div> + <div class="form-group row"> + <div class="form-group row" style="margin-left: 2%"> + <div class="form-group col-sm-3"> + <label> actor: </label> + </div> + <div class="form-group col-sm-3"> + <input type="text" class="form-control" + ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.actor" + placeholder="Actor" /> + </div> + </div> + <div class="form-group row" style="margin-left: 2%"> + <div class="form-group col-sm-3"> + <label> recipe: </label> + </div> + <div class="form-group col-sm-3"> + <input type="text" class="form-control" + ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.recipe" + placeholder="Recipe" /> + </div> + </div> + <div class="form-group row" style="margin-left: 2%"> + <div class="form-group col-sm-3"> + <label> limit: </label> + </div> + <div class="form-group col-sm-3"> + <input type="text" class="form-control" + ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.limit" + placeholder="Limit" /> + </div> + </div> + <div class="form-group row" style="margin-left: 2%"> + <div class="form-group col-sm-3"> + <label> timeWindow: </label> + </div> + <div class="form-group col-sm-3"> + <select class="form-control" ng-disabled="temp.policy.readOnly" + ng-model="temp.policy.yamlparams.timeWindow"> + <option>tw5min</option> + <option>tw10min</option> + <option>tw30min</option> + <option>tw1h</option> + <option>tw12h</option> + <option>tw1d</option> + <option>tw5d</option> + <option>tw1w</option> + <option>tw1mon</option> + </select> + </div> + </div> + <div class="form-group row" style="margin-left: 2%"> + <div class="form-group col-sm-3"> + <label> guardActiveStart: </label> + </div> + <div class="form-group col-sm-3"> + <input type="text" class="form-control" + ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.guardActiveStart" + placeholder="00:00:00-05:00" /> + </div> + </div> + <div class="form-group row" style="margin-left: 2%"> + <div class="form-group col-sm-3"> + <label> guardActiveEnd: </label> + </div> + <div class="form-group col-sm-3"> + <input type="text" class="form-control" + ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.guardActiveEnd" + placeholder="00:00:00-05:00" /> + </div> + </div> + </div> + </div> + </div> + <div ng-if="temp.policy.ruleProvider == 'Custom'"> <div class="well"> @@ -179,9 +262,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="savebutton" ng-disabled="temp.policy.readOnly" ng-click="saveDecisionPolicy(temp);">Save</button> - <button class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </form> </div> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/FirewallPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/FirewallPolicyTemplate.html index 85ffbf7ab..2a4a6534f 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/FirewallPolicyTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/FirewallPolicyTemplate.html @@ -51,7 +51,7 @@ </div> <div class="form-group col-sm-3"> <label>Time to Live Date:</label> <input type="date" - class="form-control" name="ttlDate" class="date" + class="form-control" name="ttlDate" ng-disabled="temp.policy.readOnly" class="date" ng-model="temp.policy.ttlDate" /> </div> <div class="form-group col-sm-3"> @@ -111,9 +111,7 @@ <button class="btn btn-success" herf="javascript:void(0)" ng-disabled="temp.policy.readOnly" ng-disabled="savebutton" ng-click="saveFWPolicy(temp);">Save</button> - <button type="button" class="btn btn-default" data-dismiss="modal" - ng-disabled="temp.inprocess" ng-model="finalPath" - ng-controller="FileManagerCtrl" ng-click="closefunction(finalPath);">Close</button> + <button type="button" class="btn btn-default" ng-click="refresh();">Close</button> </div> </form> </div>
\ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html index 568387827..ada2428ed 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html @@ -26,7 +26,7 @@ <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">{{"close" + <span class="sr-only">{{"close" | translate}}</span> </button> <form> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js index 869d26ba3..d471f2763 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js @@ -208,55 +208,12 @@ app.controller('PolicyManagerController', [ } }); }; - - $scope.search = function(search){ - var deferred = $q.defer(); - var uuu = "searchPolicy"; - var postData = {searchdata : search}; - $.ajax({ - type : 'POST', - url : uuu, - dataType: 'json', - contentType: 'application/json', - data: JSON.stringify(postData), - success : function(data){ - $scope.$apply(function(){ - $scope.searchdata=data.result;}); - if($scope.searchdata[0].error != undefined){ - Notification.info($scope.searchdata[0].error); - }else{ - var j = data; - $scope.data = JSON.stringify(data.result); - $scope.searchDatas = JSON.parse($scope.data); - var searchString = "Policies List" + "<br>"; - var i; - for(i = 0 ; i < $scope.searchDatas.length; i++){ - searchString += $scope.searchDatas[i].name + ".xml" + "<br>"; - } - var myWindow = window.open("", "MsgWindow", "width=500,height=500"); - myWindow.document.write("<p>Search List</p>"); - myWindow.document.write("<p>"+searchString+"</p>"); - } - }, - error : function(data){ - alert("Error while Searching."); - } - }); - }; - - - /* $scope.describePolicy = function(item){ - item.describePolicy().then(function(){ - $scope.modal('describePolicy', true); - }); - }; - - $scope.exportPolicy = function(item){ - item.exportPolicy().then(function(){ - $scope.modal('exportPolicy', true); - }); - };*/ + + $scope.refresh = function(){ + $scope.policyNavigator.refresh(); + }; + $scope.switchVersion = function(item){ if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) { item.error = 'Invalid filename or already exists, specify another name'; @@ -268,13 +225,6 @@ app.controller('PolicyManagerController', [ }); }; - - /* $scope.viewPolicy = function(item){ - item.viewPolicy().then(function(){ - $scope.modal('createNewPolicy', true); - }); - };*/ - $scope.copy = function(item) { var samePath = item.tempModel.path.join() === item.model.path.join(); if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) { diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js new file mode 100644 index 000000000..83c3820a6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP 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========================================================= + */ +app.controller('PolicySearchController', [ + '$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService', + function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) { + + $scope.isDisabled = true; + $scope.superAdminId = false; + $scope.exportPolicyId = false; + $scope.importPolicyId = false; + $scope.createScopeId = false; + $scope.deleteScopeId = false; + $scope.renameId = false; + $scope.createPolicyId = false; + $scope.cloneId = false; + $scope.editPolicyId = false; + $scope.switchVersionId = false; + $scope.describePolicyId = false; + $scope.viewPolicyId = false; + $scope.deletePolicyId = false; + PolicyAppService.getData('get_LockDownData').then(function(data){ + var j = data; + $scope.data = JSON.parse(j.data); + $scope.lockdowndata = JSON.parse($scope.data.lockdowndata); + if($scope.lockdowndata[0].lockdown == true){ + $scope.isDisabled = true; + }else{ + $scope.isDisabled = false; + } + console.log($scope.data); + },function(error){ + console.log("failed"); + }); + + PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data){ + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas); + }, function (error) { + console.log("failed"); + }); + + PolicyAppService.getData('getDictionary/get_EcompNameDataByName').then(function(data){ + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.ecompNameDictionaryDatas = JSON.parse($scope.data.ecompNameDictionaryDatas); + }, function (error) { + console.log("failed"); + }); + + PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data){ + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas); + }, function (error) { + console.log("failed"); + }); + + PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data){ + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas); + }, function (error) { + console.log("failed"); + }); + + + PolicyAppService.getData('get_UserRolesData').then(function (data) { + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas); + console.log($scope.userRolesDatas); + if($scope.userRolesDatas[0] == 'super-admin'){ + $scope.superAdminId = true; + $scope.createPolicyId = true; + $scope.editPolicyId = true; + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin'){ + $scope.editPolicyId = true; + $scope.createPolicyId = true; + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){ + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + } + }, function (error) { + console.log("failed"); + }); + + $scope.config = policyManagerConfig; + $scope.reverse = false; + $scope.predicate = ['model.type', 'model.name']; + $scope.order = function(predicate) { + $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false; + $scope.predicate[1] = predicate; + }; + + $scope.query = ''; + $scope.temp = new Item(); + $scope.policyNavigator = new PolicyNavigator(); + + $scope.setTemplate = function(name) { + $scope.viewTemplate = $cookies.viewTemplate = name; + }; + + $scope.touch = function(item) { + item = item instanceof Item ? item : new Item(); + item.revert(); + $scope.temp = item; + }; + + $scope.smartClick = function(item) { + if (item.isFolder()) { + return $scope.policyNavigator.folderClick(item); + } + if (item.isEditable()) { + return $scope.openEditItem(item); + } + }; + + $scope.openEditItem = function(item) { + item.getContent(); + $scope.modal('createNewPolicy'); + return $scope.touch(item); + }; + + $scope.modal = function(id, hide) { + return $('#' + id).modal(hide ? 'hide' : 'show'); + }; + + $scope.isInThisPath = function(path) { + var currentPath = $scope.policyNavigator.currentPath.join('/'); + return currentPath.indexOf(path) !== -1; + }; + + $scope.searchPolicy = function(searchContent){ + var deferred = $q.defer(); + var uuu = "searchPolicy"; + var postData = {searchdata : searchContent}; + $.ajax({ + type : 'POST', + url : uuu, + dataType: 'json', + contentType: 'application/json', + data: JSON.stringify(postData), + success : function(data){ + $scope.$apply(function(){ + var searchdata = data.result; + if(searchdata.length > 0){ + $scope.policyNavigator.searchrefresh(searchdata); + }else{ + Notification.info("No Matches Found with your Search"); + } + }); + }, + error : function(data){ + alert("Error while Searching."); + } + }); + }; + + $scope.refresh = function(searchData){ + $scope.policyNavigator.searchrefresh(null); + }; + + $scope.getQueryParam = function(param) { + var found; + window.location.search.substr(1).split('&').forEach(function(item) { + if (param === item.split('=')[0]) { + found = item.split('=')[1]; + return false; + } + }); + return found; + }; + + $scope.isWindows = $scope.getQueryParam('server') === 'Windows'; + $scope.policyNavigator.searchrefresh(null); + $scope.policyNavigator.setSearchModalActiveStatus(); + }]); diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js index 2b1fd3469..21762ce77 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js @@ -170,7 +170,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun }; - Item.prototype.getContent = function() { + Item.prototype.getContent = function(policyNavigator) { var self = this; var deferred = $q.defer(); var data = {params: { @@ -185,6 +185,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun var json = data.result; var policy = JSON.parse(json); self.policy = policy; + self.itemContent = policyNavigator; console.log(policy); self.deferredHandler(data, deferred); }).error(function(data) { @@ -339,9 +340,5 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun return !this.isFolder() && policyManagerConfig.isEditableFilePattern.test(this.model.name); }; - /*Item.prototype.isImage = function() { - return policyManagerConfig.isImageFilePattern.test(this.model.name); - };*/ - return Item; }]); diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/providers/config.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/providers/config.js index 72fd84d53..6afabe136 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/providers/config.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/providers/config.js @@ -42,6 +42,7 @@ addSubScopeUrl : 'fm/addSubScopeUrl', switchVersionUrl : 'fm/switchVersionUrl', exportUrl : 'fm/exportUrl', + searchListUrl : 'fm/searchListUrl', sidebar: true, breadcrumb: true, diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/services/policynavigator.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/services/policynavigator.js index bb76dd9d5..1435afe8a 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/services/policynavigator.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/services/policynavigator.js @@ -30,8 +30,13 @@ this.currentPath = []; this.history = []; this.error = ''; + this.searchModalActive = false; }; + PolicyNavigator.prototype.setSearchModalActiveStatus = function(){ + this.searchModalActive = true; + }; + PolicyNavigator.prototype.deferredHandler = function(data, deferred, defaultMsg) { if (!data || typeof data !== 'object') { this.error = 'Bridge response error, please check the docs'; @@ -99,29 +104,49 @@ PolicyNavigator.prototype.refresh = function() { var self = this; var path = self.currentPath.join('/'); - return self.list().then(function(data) { - self.fileList = (data.result || []).map(function(file) { - return new Item(file, self.currentPath); - }); - self.buildTree(path); - }); + if(self.searchModalActive){ + return self.searchlist(null).then(function(data) { + self.fileList = (data.result || []).map(function(file) { + return new Item(file, self.currentPath); + }); + self.buildTree(path); + }); + }else{ + return self.list().then(function(data) { + self.fileList = (data.result || []).map(function(file) { + return new Item(file, self.currentPath); + }); + self.buildTree(path); + }); + } }; - PolicyNavigator.prototype.policylist = function(finalpath) { + PolicyNavigator.prototype.searchlist = function(policyList) { var self = this; var deferred = $q.defer(); - var path = finalpath; - var data = {params: { - mode: 'LIST', - onlyFolders: false, - path: '/' + path - }}; + var path = self.currentPath.join('/'); + var data; + if(policyList == null){ + data = {params: { + mode: 'SEARCHLIST', + onlyFolders: false, + path: '/' + path + }}; + }else{ + data = {params: { + mode: 'SEARCHLIST', + onlyFolders: false, + path: '/' + path, + policyList : policyList + }}; + } + self.requesting = true; self.fileList = []; self.error = ''; - $http.post(policyManagerConfig.listUrl, data).success(function(data) { + $http.post(policyManagerConfig.searchListUrl, data).success(function(data) { self.deferredHandler(data, deferred); }).error(function(data) { self.deferredHandler(data, deferred, 'Unknown error listing, check the response'); @@ -131,16 +156,15 @@ return deferred.promise; }; - PolicyNavigator.prototype.policyrefresh = function(finalpath) { - var self = this; - var path = finalpath; - self.currentPath = path; - return self.policylist(finalpath).then(function(data) { - self.fileList = (data.result || []).map(function(file) { - return new Item(file, self.currentPath); - }); - self.buildTree(path); - }); + PolicyNavigator.prototype.searchrefresh = function(policyList) { + var self = this; + var path = self.currentPath.join('/'); + return self.searchlist(policyList).then(function(data) { + self.fileList = (data.result || []).map(function(file) { + return new Item(file, self.currentPath); + }); + self.buildTree(path); + }); }; diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/item-context-menu.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/item-context-menu.html index 5ef11b219..3c41fbc1d 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/item-context-menu.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/item-context-menu.html @@ -47,7 +47,7 @@ </a> </li> <li ng-show="config.allowedActions.edit && !temp.isFolder()"> - <a href="" tabindex="-1" data-toggle="modal" data-target="#createNewPolicy" ng-show="editPolicyId" ng-click="temp.getContent();"> + <a href="" tabindex="-1" data-toggle="modal" data-target="#createNewPolicy" ng-show="editPolicyId" ng-click="temp.getContent(policyNavigator);"> <i class="glyphicon glyphicon-pencil"></i> Edit Policy </a> </li> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/modals.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/modals.html index f2b2b8d9d..6bd9587ef 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/modals.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/modals.html @@ -4,17 +4,16 @@ <form ng-submit="remove(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Confirm</h4> </div> - <div> + <div class="modal-body"> Are you Sure to delete <b>{{temp.model.name}}</b> ? <div ng-include data-src="'error-bar'" class="clearfix"></div> </div> <div class="modal-footer"> - <button type="button" class="btn btn-default" data-dismiss="modal" ng-disabled="temp.inprocess">Cancel</button> + <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="refresh();" ng-disabled="temp.inprocess">Cancel</button> <button type="submit" class="btn btn-primary" ng-disabled="temp.inprocess" autofocus="autofocus">Delete</button> </div> </form> @@ -28,12 +27,11 @@ <form ng-submit="removePolicy(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Confirm</h4> </div> - <div>Are you Sure to delete <b>{{temp.model.name}}</b> ? + <div class="modal-body">Are you Sure to delete <b>{{temp.model.name}}</b> ? <div> <p> <input type = "radio" ng-model ="temp.model.versions" name = "radSize" id = "sizeSmall" value = "CURRENT" checked = "checked" /><label for = "sizeSmall">Are you sure you want to delete Current Version of Policy</label> @@ -44,7 +42,7 @@ <div ng-include data-src="'error-bar'" class="clearfix"></div> </div> <div class="modal-footer"> - <button type="button" class="btn btn-default" data-dismiss="modal" ng-disabled="temp.inprocess">Cancel</button> + <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="refresh();" ng-disabled="temp.inprocess">Cancel</button> <button type="submit" class="btn btn-primary" ng-disabled="temp.inprocess" autofocus="autofocus">Delete</button> </div> </form> @@ -58,16 +56,14 @@ <form ng-submit="rename(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Rename</h4> </div> - <div> + <div class="modal-body"> <label class="radio">Enter New Name : <b>{{temp.model.name}}</b></label> <input class="form-control" ng-model="temp.tempModel.name" autofocus="autofocus"> - <div ng-include data-src="'path-selector'" class="clearfix"></div> <div ng-include data-src="'error-bar'" class="clearfix"></div> </div> <div class="modal-footer"> @@ -85,7 +81,6 @@ <form> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">List of Policies</h4> @@ -107,12 +102,11 @@ <form ng-submit="move(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Move Policy</h4> </div> - <div> + <div class="modal-body"> <div ng-include data-src="'path-selector'" class="clearfix"></div> <div ng-include data-src="'error-bar'" class="clearfix"></div> </div> @@ -131,16 +125,15 @@ <form ng-submit="switchVersion(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Switch Version</h4> </div> - <div> + <div class="modal-body"> <label class="radio">Highest Version <b></b></label> <input class="form-control" ng-disabled="true" ng-model="temp.tempModel.content.highestVersion" autofocus="autofocus"> </div> - <div> + <div class="modal-body"> <label class="radio">Active Version <b></b></label> <select class="form-control" ng-model="temp.tempModel.content.activeVersion" ng-options="option for option in temp.tempModel.content.availableVersions" autofocus="autofocus"></select> <div ng-include data-src="'error-bar'" class="clearfix"></div> @@ -160,12 +153,11 @@ <form ng-submit="copy(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Clone Policy</h4> </div> - <div> + <div class="modal-body"> <label class="radio">Enter new Policy Name to Clone <b>{{temp.model.name}}</b></label> <input class="form-control" ng-model="temp.tempModel.name" autofocus="autofocus"> @@ -187,12 +179,11 @@ <form ng-submit="createFolder(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Add Scope</h4> </div> - <div> + <div class="modal-body"> <label class="radio">Scope Name</label> <input class="form-control" ng-model="temp.tempModel.name" autofocus="autofocus"> <div ng-include data-src="'error-bar'" class="clearfix"></div> @@ -212,12 +203,11 @@ <form ng-submit="subScopeFolder(temp)"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Add Sub Scope</h4> </div> - <div> + <div class="modal-body"> <label class="radio">Scope Name</label> <input class="form-control" ng-model="temp.tempModel.subScopename" autofocus="autofocus"> <div ng-include data-src="'error-bar'" class="clearfix"></div> @@ -237,12 +227,11 @@ <form ng-submit="uploadFiles()"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Import</h4> </div> - <div> + <div class="modal-body"> <label class="radio">Upload to</label> <input type="file" class="form-control" ng-file="$parent.uploadFileList" autofocus="autofocus" multiple="multiple"/> <div ng-include data-src="'error-bar'" class="clearfix"></div> @@ -266,7 +255,6 @@ <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> - <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Select the Destination Scope</h4> diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/searchNavbar.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/searchNavbar.html index 43eb5148b..72985a190 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/searchNavbar.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/searchNavbar.html @@ -102,7 +102,7 @@ body { </div> </div> <div class="form-group row"> - <div class="form-group col-sm-6"> + <div class="form-group col-sm-6" ng-if="search.closedLooppolicyType == 'Config_PM'"> <label>D2 Service:</label><BR> <select class="form-control" ng-model="search.d2Service"> <option>Hosted Voice(Trinity)</option> @@ -112,18 +112,15 @@ body { <option>vDNS</option> </select> </div> - <div class="form-group col-sm-6"> - <label>Bind Text Search to:</label><BR> <select - class="form-control" ng-model="search.bindTextSearch"> - <option>Email Address</option> - <option>Trigger Signature</option> - <option>Connect All Traps</option> - <option>Verification Signature</option> - <option>Connect All Faults</option> - <option>Onset Message</option> - <option>Policy Name</option> - <option>Abatement Message</option> - <option>Geo Link</option> + <div class="form-group col-sm-6" + ng-if="search.closedLooppolicyType == 'Config_PM'"> + <label>Service Type:</label><BR> <select + class="form-control" ng-model="search.serviceType"> + <option>Registration Failure(Trinity)</option> + <option>International Fraud(Trinity)</option> + <option>No Dial Tone(Trinity)</option> + <option>Call Storm(Trinity)</option> + <option>Registration Storm(Trinity)</option> </select> </div> </div> @@ -150,15 +147,18 @@ body { class="form-control" ng-model="search.vproAction" ng-options="option for option in vsclActionDictionaryDatas track by option"></select> </div> - <div class="form-group col-sm-6" - ng-if="search.closedLooppolicyType == 'Config_PM'"> - <label>Service Type:</label><BR> <select - class="form-control" ng-model="search.serviceType"> - <option>Registration Failure(Trinity)</option> - <option>International Fraud(Trinity)</option> - <option>No Dial Tone(Trinity)</option> - <option>Call Storm(Trinity)</option> - <option>Registration Storm(Trinity)</option> + <div class="form-group col-sm-6" ng-if="search.closedLooppolicyType == 'Config_Fault'"> + <label>Bind Text Search to:</label><BR> <select + class="form-control" ng-model="search.bindTextSearch"> + <option>Email Address</option> + <option>Trigger Signature</option> + <option>Connect All Traps</option> + <option>Verification Signature</option> + <option>Connect All Faults</option> + <option>Onset Message</option> + <option>Policy Name</option> + <option>Abatement Message</option> + <option>Geo Link</option> </select> </div> </div> @@ -166,8 +166,12 @@ body { </form> </div> </div> + <button type="button" class="btn btn-default" + ng-click="refresh(search = null);"> + <span aria-hidden="true">Clear</span> + </button> <button type="button" class="btn btn-primary" - ng-click="search(search);"> + ng-click="searchPolicy(search);"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> </button> </div> diff --git a/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java b/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java index e263d5dfa..0bd8bd9e8 100644 --- a/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java +++ b/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java @@ -36,7 +36,11 @@ public enum RuleProvider { /** * Indicates AAF will be providing the Rule information. */ - AAF("AAF") + AAF("AAF"), + /** + * Indicates Guard YAML will be providing the Rule information. + */ + GUARD_YAML("GUARD_YAML") ; private String name; diff --git a/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientUEB.java b/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientUEB.java index 40bd8012a..91d81d043 100644 --- a/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientUEB.java +++ b/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientUEB.java @@ -30,22 +30,19 @@ import org.openecomp.policy.api.NotificationHandler; import org.openecomp.policy.api.NotificationScheme; import org.openecomp.policy.api.NotificationType; import org.openecomp.policy.api.PDPNotification; -import org.openecomp.policy.std.StdPDPNotification; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; import com.att.nsa.cambria.client.CambriaClientBuilders; -import com.att.nsa.cambria.client.CambriaClientFactory; -import com.att.nsa.cambria.client.CambriaConsumer; import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; +import com.att.nsa.cambria.client.CambriaConsumer; /** * Create a UEB Consumer to receive policy update notification. * * * */ -@SuppressWarnings("deprecation") public class AutoClientUEB implements Runnable { private static StdPDPNotification notification = null; private static NotificationScheme scheme = null; @@ -117,8 +114,6 @@ public class AutoClientUEB implements Runnable { } catch (MalformedURLException e) { topic = AutoClientUEB.url.replace("[:/]", ""); } - - //TODO create a loop to listen for messages from UEB cluster try { //CConsumer = CambriaClientFactory.createConsumer ( null, uebURLList, topic, group, id, 15*1000, 1000 ); @@ -147,7 +142,6 @@ public class AutoClientUEB implements Runnable { callHandler(); } } catch (Exception e) { - // TODO Auto-generated catch block logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error in processing UEB message" + e.getMessage()); } diff --git a/packages/base/src/files/install/mysql/data/170204_downgrade_script.sql b/packages/base/src/files/install/mysql/data/170204_downgrade_script.sql index d33fde5c6..8fead9cce 100644 --- a/packages/base/src/files/install/mysql/data/170204_downgrade_script.sql +++ b/packages/base/src/files/install/mysql/data/170204_downgrade_script.sql @@ -20,3 +20,4 @@ use ecomp_sdk; drop table if exists brmsgroup_info; drop table if exists brmsgroup_policy; +drop table if exists operationshistory10; diff --git a/packages/base/src/files/install/mysql/data/170204_upgrade_script.sql b/packages/base/src/files/install/mysql/data/170204_upgrade_script.sql index 87b24710d..c474f1b7e 100644 --- a/packages/base/src/files/install/mysql/data/170204_upgrade_script.sql +++ b/packages/base/src/files/install/mysql/data/170204_upgrade_script.sql @@ -36,6 +36,20 @@ controllerName VARCHAR(255) NOT NULL references brmsgroup_info(controllerName), PRIMARY KEY(policyname) ); +drop table if exists operationshistory10; + +create table operationshistory10( +CLNAME varchar(255) not null, +requestID varchar(100), +actor varchar(50) not null, +operation varchar(50) not null, +target varchar(50) not null, +starttime timestamp not null, +outcome varchar(50) not null, +message varchar(255) , +subrequestId varchar(100), +endtime timestamp not null default current_timestamp +); Insert into fn_role (ROLE_ID,ROLE_NAME,ACTIVE_YN,PRIORITY) values (5002,'Policy Super Admin','Y',10); Insert into fn_role (ROLE_ID,ROLE_NAME,ACTIVE_YN,PRIORITY) values (5003,'Policy Super Editor','Y',10); diff --git a/packages/base/src/files/install/servers/brmsgw/config.properties b/packages/base/src/files/install/servers/brmsgw/config.properties index 4f92a0ac7..30b14b1e2 100644 --- a/packages/base/src/files/install/servers/brmsgw/config.properties +++ b/packages/base/src/files/install/servers/brmsgw/config.properties @@ -26,14 +26,14 @@ PDP_URL = ${{REST_PDP_ID}} , ${{PDP_HTTP_USER_ID}} , ${{PDP_HTTP_PASSWORD}} PAP_URL = ${{REST_PAP_URL}} , ${{PDP_PAP_PDP_HTTP_USER_ID}} , ${{PDP_PAP_PDP_HTTP_PASSWORD}} #Notification Properties... type can be either websocket, ueb, or dmaap -NOTIFICATION_TYPE=websocket -NOTIFICATION_SERVERS=${{UEB_URL}} -NOTIFICATION_TOPIC=${{UEB_TOPIC}} -NOTIFICATION_DELAY= -CLIENT_ID=${{CLIENT_ID}} -CLIENT_KEY=${{CLIENT_KEY}} -UEB_API_KEY=${{UEB_API_KEY}} -UEB_API_SECRET=${{UEB_API_SECRET}} +NOTIFICATION_TYPE=${{BRMS_NOTIFICATION_TYPE}} +NOTIFICATION_SERVERS=${{BRMS_UEB_URL}} +NOTIFICATION_TOPIC=${{BRMS_UEB_TOPIC}} +NOTIFICATION_DELAY=${{BRMS_UEB_DELAY}} +CLIENT_ID=${{BRMS_CLIENT_ID}} +CLIENT_KEY=${{BRMS_CLIENT_KEY}} +UEB_API_KEY=${{BRMS_UEB_API_KEY}} +UEB_API_SECRET=${{BRMS_UEB_API_SECRET}} # Environment should be Set either DEV, TEST or PROD diff --git a/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml b/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml new file mode 100644 index 000000000..3a7f25008 --- /dev/null +++ b/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:xacml:policy:id:d56af069-6cf1-430c-ba07-e26602e06a52" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"> + <Description>${description}</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${PolicyName}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="PolicyName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + <AllOf> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${ECOMPName}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="ECOMPName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="actor" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="org.openecomp.function.regex-match"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="recipe" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a" Effect="Permit"> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">DECIDE</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </Apply> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="org:openecomp:xacml:sql:${timeWindow}" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue> + </Apply> + </Apply> + </Condition> + </Rule> + <Rule RuleId="urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a" Effect="Deny"> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">DECIDE</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </Apply> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="org:openecomp:xacml:sql:${timeWindow}" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue> + </Apply> + </Apply> + </Apply> + </Condition> + <AdviceExpressions> + <AdviceExpression AdviceId="GUARD_YAML" AppliesTo="Deny"> + <AttributeAssignmentExpression AttributeId="guard.response" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Denied!</AttributeValue> + </AttributeAssignmentExpression> + </AdviceExpression> + </AdviceExpressions> + </Rule> +</Policy>
\ No newline at end of file diff --git a/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties b/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties index 2a45ad32a..143aeabce 100644 --- a/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties +++ b/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties @@ -24,7 +24,7 @@ xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory dictionary.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DictionaryHandlerImpl savePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler -pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHander +pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler deletePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DeleteHandler # # Where we store our PAP PDP Group/Node information diff --git a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties index 676eeef31..3b0431958 100644 --- a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties +++ b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties @@ -47,13 +47,13 @@ xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinder # When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into # into one PolicySet and use the given Policy Algorithm. # -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides # # PDP RESTful API properties # -# Set this to the address where the XACML-PAP-REST servlet is running +# Set this to the address or list of addresses where the XACML-PAP-REST servlet is running # http://localhost:9090/pap/ -xacml.rest.pap.url=${{REST_PAP_URL}} +xacml.rest.pap.urls=${{REST_PAP_URL}} #if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: #xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ # @@ -67,14 +67,14 @@ xacml.jmx.port=${{TOMCAT_JMX_PORT}} # # Notification Properties # Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default -NOTIFICATION_TYPE=websocket,UEB -NOTIFICATION_SERVERS=${{UEB_CLUSTER}} -NOTIFICATION_TOPIC= -NOTIFICATION_DELAY= -UEB_API_KEY=${{UEB_API_KEY}} -UEB_API_SECRET=${{UEB_API_SECRET}} -DMAAP_AAF_LOGIN=${{DMAAP_AAF_LOGIN}} -DMAAP_AAF_PASSWORD=${{DMAAP_AAF_PASSWORD}} +NOTIFICATION_TYPE=${{PDP_NOTIFICATION_TYPE}} +NOTIFICATION_SERVERS=${{PDP_UEB_CLUSTER}} +NOTIFICATION_TOPIC=${{PDP_UEB_TOPIC}} +NOTIFICATION_DELAY=${{PDP_UEB_DELAY}} +UEB_API_KEY=${{PDP_UEB_API_KEY}} +UEB_API_SECRET=${{PDP_UEB_API_SECRET}} +DMAAP_AAF_LOGIN=${{PDP_DMAAP_AAF_LOGIN}} +DMAAP_AAF_PASSWORD=${{PDP_DMAAP_AAF_PASSWORD}} # # Set the directory where the PDP holds its Policy Cache and PIP Configuration # @@ -134,6 +134,6 @@ javax.persistence.jdbc.password=${{JDBC_PASSWORD}} ENVIRONMENT=${{ENVIRONMENT}} #AAF Policy Name space -#Not Mandatory for Open Ecomp +#Required only, when we use AAF policy.aaf.namespace = ${{POLICY_AAF_NAMESPACE}} policy.aaf.resource = ${{POLICY_AAF_RESOURCE}} diff --git a/packages/base/src/files/install/servers/pypdp/bin/client.properties b/packages/base/src/files/install/servers/pypdp/bin/client.properties deleted file mode 100644 index 0b8dc258e..000000000 --- a/packages/base/src/files/install/servers/pypdp/bin/client.properties +++ /dev/null @@ -1,22 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP 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========================================================= -### - -python=test,MASTER -PyPDPServer=test,MASTER
\ No newline at end of file diff --git a/packages/base/src/files/install/servers/pypdp/bin/config.properties b/packages/base/src/files/install/servers/pypdp/bin/config.properties deleted file mode 100644 index 93f7b5d41..000000000 --- a/packages/base/src/files/install/servers/pypdp/bin/config.properties +++ /dev/null @@ -1,51 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP 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========================================================= -### - -#pypdp properties - -PDP_URL=${{PDP_URL}} -PAP_URL=${{PAP_URL}} -PYPDP_ID=${{PYPDP_ID}} -PYPDP_PASSWORD=${{PYPDP_PASSWORD}} - -#Integrity Monitor values -#database driver for Integrity Monitor -javax.persistence.jdbc.driver=${{JDBC_DRIVER}} -#database URL for Integrity Monitor -javax.persistence.jdbc.url=${{JDBC_URL}} -#database username for Integrity Monitor -javax.persistence.jdbc.user=${{JDBC_USER}} -#database password for Integrity Monitor -javax.persistence.jdbc.password=${{JDBC_PASSWORD}} -#resource name -RESOURCE_NAME=${{resource_name}} -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** -site_name=${{site_name}} -node_type=${{node_type}} -fp_monitor_interval=${{fp_monitor_interval}} -failed_counter_threshold=${{failed_counter_threshold}} -test_trans_interval=${{test_trans_interval}} -write_fpc_interval=${{write_fpc_interval}} -max_fpc_update_interval=${{max_fpc_update_interval}} -test_via_jmx=${{test_via_jmx}} -# Environment should be Set either DEV, TEST or PROD -ENVIRONMENT=${{ENVIRONMENT}} - -CLIENT_FILE=${{CLIENT_FILE}} diff --git a/packages/base/src/files/install/servers/pypdp/bin/config/policyLogger.properties b/packages/base/src/files/install/servers/pypdp/bin/config/policyLogger.properties deleted file mode 100644 index 0deb1b3d6..000000000 --- a/packages/base/src/files/install/servers/pypdp/bin/config/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON @@ -41,6 +41,7 @@ <module>PolicyEngineUtils</module> <module>ECOMP-XACML</module> <module>ECOMP-REST</module> + <module>ECOMP-ControlloopPolicy</module> <module>PolicyEngineAPI</module> <module>ECOMP-PDP</module> <module>ECOMP-PDP-REST</module> |