From: ITSERVICES\rb7147 Date: Tue, 9 May 2017 02:20:44 +0000 (-0400) Subject: Policy 1707 Second commit X-Git-Tag: v1.1.0~133 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=dda032f8bb161d54eb1f59de2b4a3efb774fc4d1 Policy 1707 Second commit Change-Id: I18f5b142238733d17280cf17c3d1dd28204d34e9 Signed-off-by: ITSERVICES\rb7147 --- diff --git a/BRMSGateway/pom.xml b/BRMSGateway/pom.xml index bee9747f8..5512f7ae3 100644 --- a/BRMSGateway/pom.xml +++ b/BRMSGateway/pom.xml @@ -60,6 +60,11 @@ nexus-rest-client-java 2.3.1 + + com.thoughtworks.xstream + xstream + 1.3.1 + com.att.nsa cambriaClient 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 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 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 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 addedPolicies(PDPNotification notification) { + ArrayList result = new ArrayList(); + 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 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 repURLs= null; private String repUserName = null; private String repPassword = null; private String policyKeyID = null; @@ -132,6 +135,7 @@ public class BRMSPush { private Map policyMap = new HashMap(); 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(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 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 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(); @@ -637,8 +671,9 @@ public class BRMSPush { * Will Push policies to the PolicyRepo. * * @param notificationType 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 dependencyList= new ArrayList(); 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 @@ + + 4.0.0 + ControlloopPolicy + + org.openecomp.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + + junit + junit + 4.12 + provided + + + org.yaml + snakeyaml + 1.17 + + + org.jgrapht + jgrapht-core + 0.9.2 + + + com.google.guava + guava + 19.0 + + + 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 graph = new DirectedMultigraph(new ClassBasedEdgeFactory(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 mapNodes = new HashMap(); + 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 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> recipes = new ImmutableMap.Builder>() + .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 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 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 newSet = new HashSet(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 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 newSet = new HashSet(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 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 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 payload, Target target) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + this.target = target; + if (payload != null) { +// this.payload = new LinkedList>(); + this.payload = Collections.unmodifiableMap(payload); + } + } + + public Policy(String name, String actor, String recipe, Map 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 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>(); +// 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 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 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 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 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 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(); + } + 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 messages = new LinkedList(); + + @Override + public List 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 time_in_range; + + public LinkedList blacklist; + + public Constraint() { + + } + + public Constraint(Integer num, String duration) { + this.num = num; + this.duration = duration; + } + + public Constraint(List blacklist) { + this.blacklist = new LinkedList(blacklist); + + } + + public Constraint(Integer num, String duration, Map 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 blacklist) { + this.num = num; + this.duration = duration; + this.blacklist = new LinkedList(blacklist); + } + + public Constraint(Integer num, String duration, Map time_in_range, List blacklist) { + this(num, duration); + if (time_in_range != null) { + this.time_in_range = Collections.unmodifiableMap(time_in_range); + } + this.blacklist = new LinkedList(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(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 guards; + + public ControlLoopGuard() { + + } + + public ControlLoopGuard(ControlLoopGuard CLGuard) { + this.guard = new Guard(); + this.guards = new LinkedList(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 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 limit_constraints) { + this(name, actor, recipe); + if (limit_constraints != null) { + this.limit_constraints = (LinkedList) Collections.unmodifiableList(limit_constraints); + } + } + + public GuardPolicy(String name, String description, String actor, String recipe, List limit_constraints) { + this(name, actor, recipe, limit_constraints); + this.description = description; + } + + public GuardPolicy(String id, String name, String description, String actor, String recipe, List 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) 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(); + } + 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(); + } + 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 @@ + + + ${description} + + + + + ${PolicyName} + + + + + + ${ECOMPName} + + + + ${actor} + + + + ${recipe} + + + + + + + + + + + DECIDE + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + ${limit} + + + + + + + + + + DECIDE + + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + ${limit} + + + + + + + + Denied! + + + + + \ 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 @@ org.json json + + com.att.nsa + dmaapClient + + + com.att.nsa + cambriaClient + + + com.att.cadi + cadi-aaf + @@ -124,6 +136,11 @@ commons-fileupload 1.3.1 + + org.apache.logging.log4j + log4j-core + 2.8.2 + log4j apache-log4j-extras @@ -191,6 +208,11 @@ spring-mock 2.0.8 + + org.openecomp.policy.engine + ControlloopPolicy + ${project.version} + com.mockrunner mockrunner 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 dynamicLabelRuleAlgorithms = new LinkedList(); List dynamicFieldComboRuleAlgorithms = new LinkedList(); @@ -131,7 +148,25 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if (policyAdapter.getData() != null) { + if(policyAdapter.getRuleProvider().equals(GUARD_YAML)){ + Map yamlParams = new HashMap(); + 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 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 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(); } @@ -196,6 +231,47 @@ public class DecisionPolicy extends Policy { return true; } + public PolicyType getGuardPolicy(Map 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 time_in_range = new HashMap(); + 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 yamlSpecs = new HashMap(); + 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 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 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(); - 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 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(); + 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 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 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(); + 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 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 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 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 policyLocators(PolicyIndexType type, String text,int connector) - throws IllegalStateException, IllegalArgumentException; - - public ArrayList policyLocators(PolicyIndexType type, String text, - ArrayList,ArrayList>> 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,ArrayList>> filter_s) + Map 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="") - protected String searchText; - - @Option(name="-e", usage="test and update policy if not exists", aliases={"-exist", "--exists"}, required=false, metaVar="") - 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,ArrayList>> 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> p : filter_s) { - ArrayList name_s = p.left(); - ArrayList 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 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,ArrayList>> filter_s) + Map 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> p : filter_s) { - ArrayList name_s = p.left(); - ArrayList 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 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 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 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 policyLocators(PolicyIndexType indexType, String text, int connector) - throws IllegalStateException, IllegalArgumentException { - return policyLocators(indexType, text, new ArrayList,ArrayList>>(),connector); - } - - @Override - public ArrayList policyLocators(PolicyIndexType indexType, - String text, - ArrayList,ArrayList>> filter_s, int connector) - throws IllegalStateException, IllegalArgumentException { - final ArrayList policyLocators = new ArrayList(); - - 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 filteredPolicies = new HashMap(); private List policyNames = null; enum Mode{ @@ -90,8 +89,6 @@ public class PolicyElasticSearchController{ public static final HashMap name2jsonPath = new HashMap() { 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 locators; - ArrayList,ArrayList>> filter_s = new ArrayList,ArrayList>>(); + JestResult locators; + Map filter_s = new HashMap(); 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(); - 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 locators; - ArrayList,ArrayList>> filter_s = new ArrayList,ArrayList>>(); + JestResult locators; + Map filter_s = new HashMap(); LOGGER.debug("Parameter value is"+value); String clSearchKey=null; @@ -387,13 +374,7 @@ public class PolicyElasticSearchController{ LOGGER.debug("Filter value is"+clSearchKey); - ArrayList clSearchBoxFilterField_s = new ArrayList(); - 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 clSearchBoxFilterValue_s = new ArrayList(); clSearchBoxFilterValue_s.add(clSearchValue); - filter_s.add(new Pair,ArrayList>(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(); - 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,ArrayList>> filter_s = - new ArrayList,ArrayList>>(); - //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 clSearchBoxFilterField_s = new ArrayList(); - - 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 clSearchBoxFilterValue_s = new ArrayList(); - clSearchBoxFilterValue_s.add(filterValue); - - filter_s.add(new Pair,ArrayList>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); - } - } - - ArrayList 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 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 searchKeyValue = new HashMap(); + List policyList = new ArrayList(); 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 { /* @@ -93,85 +85,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. */ 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 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 attribute = new HashMap(); private HashMap refAttribute = new HashMap(); - private HashMap subClass = new HashMap(); + private HashMap subClass = new HashMap(); private String dependency; private HashMap enumType = new HashMap(); private HashMap matchingSet = new HashMap(); @@ -70,13 +70,13 @@ public class MSAttributeObject { public void addAllRefAttribute(Map map){ this.refAttribute.putAll(map); } - public HashMap getSubClass() { + public HashMap getSubClass() { return subClass; } - public void setSubClass(HashMap subClass) { + public void setSubClass(HashMap subClass) { this.subClass = subClass; } - public void addAllSubClass(HashMap subClass){ + public void addAllSubClass(HashMap 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 returnRefList = getRefAttributeList(root, className, extendClass); HashMap returnAttributeList = getAttributeList(root, className, extendClass); - HashMap returnSubList = getSubAttributeList(root, className, extendClass); + HashMap returnSubList = getSubAttributeList(root, className, extendClass); HashMap returnAnnotation = getAnnotation(root, className, extendClass); msAttributeObject.setAttribute(returnAttributeList); msAttributeObject.setRefAttribute(returnRefList); @@ -285,10 +285,10 @@ public class MSModelUtils { return annotationSet; } - private HashMap getSubAttributeList(EPackage root, String className , String superClass) { + private HashMap getSubAttributeList(EPackage root, String className , String superClass) { TreeIterator treeItr = root.eAllContents(); boolean requiredAttribute = false; - HashMap subAttribute = new HashMap(); + HashMap subAttribute = new HashMap(); int rollingCount = 0; int processClass = 0; boolean annotation = false; @@ -622,7 +622,7 @@ public class MSModelUtils { } - public String createJson(HashMap subClassAttributes, HashMap classMap, String className) { + public String createJson(HashMap subClassAttributes, HashMap classMap, String className) { boolean enumType; Map> myObject = new HashMap>(); for ( Entry map : classMap.get(className).getRefAttribute().entrySet()){ @@ -660,7 +660,7 @@ public class MSModelUtils { public String createSubAttributes(ArrayList dependency, HashMap classMap, String modelName) { - HashMap workingMap = new HashMap(); + HashMap workingMap = new HashMap(); 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 deleted file mode 100644 index 97c4196f5..000000000 Binary files a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.eot and /dev/null differ 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 @@ - - - - -This is a custom SVG font generated by IcoMoon. - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index 05432986a..000000000 Binary files a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.ttf and /dev/null differ 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 deleted file mode 100644 index 10c4eeb83..000000000 Binary files a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/fonts/flexslider-icon.woff and /dev/null differ 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 @@ poi-ooxml 3.15 + + + com.esotericsoftware.yamlbeans + yamlbeans + 1.08 + + + + org.yaml + snakeyaml + 1.16 + \ 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 serviceTypeNamesList = new ArrayList(); + private List policyData; public static List 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 scopes = null; + List roles = null; + policyData = null; + JSONArray policyList = null; + if(params.has("policyList")){ + policyList = (JSONArray) params.get("policyList"); + } + PolicyController controller = new PolicyController(); + List resultList = new ArrayList(); + 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 userRoles = PolicyController.getRoles(userId); + roles = new ArrayList(); + scopes = new HashSet(); + 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 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 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 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 = 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 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 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 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 activePoliciesInPDP = new ArrayList(); if(!policyEntityobjects.isEmpty()){ for(Object object : policyEntityobjects){ policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; List 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 scopes = null; List roles = null; - data = null; + data = new ArrayList(); String userId = UserUtils.getUserSession(request).getOrgUserId(); Map model = new HashMap(); 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 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 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 modelList = new ArrayList(); private List dirDependencyList = new ArrayList(); private HashMap classMap = new HashMap(); + //Tosca Model related Datastructure. + String referenceAttributes; + String attributeString; + String listConstraints; + String subAttributeString; + HashMap retmap = new HashMap(); + Set uniqueKeys= new HashSet(); + Set uniqueDataKeys= new HashSet(); @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 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 yamlMap = (Map) yaml.load(is); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + public Map load(byte[] source) throws IOException { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(source.toString()); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void serializeMap(Map settings, StringBuilder sb, List path, Map yamlMap) { + for (Map.Entry entry : yamlMap.entrySet()) { + if (entry.getValue() instanceof Map) { + path.add((String) entry.getKey()); + serializeMap(settings, sb, path, (Map) 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 settings, StringBuilder sb, List path, List yamlList) { + int counter = 0; + for (Object listEle : yamlList) { + if (listEle instanceof Map) { + path.add(Integer.toString(counter)); + serializeMap(settings, sb, path, (Map) listEle); + path.remove(path.size() - 1); + } else if (listEle instanceof List) { + path.add(Integer.toString(counter)); + serializeList(settings, sb, path, (List) listEle); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, Integer.toString(counter), listEle); + } + counter++; + } + } + + private void serializeValue(Map settings, StringBuilder sb, List 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 map= new HashMap(); + 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 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> mapKey= new HashMap>(); + 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 list; + if(mapKey.containsKey(firstPartString)){ + list = mapKey.get(firstPartString); + list.add(secondPartString+"<"+splitWithEquals[1]); + } else { + list = new ArrayList(); + list.add(secondPartString+"<"+splitWithEquals[1]); + mapKey.put(firstPartString, list); + } + } + + JSONObject mainObject= new JSONObject();; + JSONObject json; + for(String s: mapKey.keySet()){ + json= new JSONObject(); + List 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 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 constraints= new ArrayList(); + 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 attributeMap = new HashMap(); Map refAttributeMap = new HashMap(); @@ -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 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 fileList = new ArrayList();; 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(); - 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(); + 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 returnAttributeList =new HashMap(); + returnAttributeList.put(className, this.attributeString); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(this.retmap); + + HashMap returnReferenceList =new HashMap(); + //String[] referenceArray=this.referenceAttributes.split("="); + returnReferenceList.put(className, this.referenceAttributes); + msAttributes.setRefAttribute(returnReferenceList); + + if(this.listConstraints!=""){ + HashMap enumList =new HashMap(); + String[] listArray=this.listConstraints.split("="); + enumList.put(listArray[0], listArray[1]); + msAttributes.setEnumType(enumList); + } + + classMap=new HashMap(); + 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 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(); - // 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(); + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("GUARD_YAML")){ + YAMLParams yamlParams = new YAMLParams(); + for(int i=0; i map = (Map)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()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList()); + 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 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" + "
"; valid = false; } - + if(policyData.getRuleProvider().equals("GUARD_YAML")){ + if(policyData.getYamlparams()==null){ + responseString = responseString + " Guard Params are Required " + "
"; + valid = false; + }else{ + if(policyData.getYamlparams().getActor()==null){ + responseString = responseString + "Guard Params Actor is Required " + "
"; + valid = false; + } + if(policyData.getYamlparams().getRecipe()==null){ + responseString = responseString + "Guard Params Recipe is Required " + "
"; + valid = false; + } + if(policyData.getYamlparams().getLimit()==null){ + responseString = responseString + " Guard Params Limit is Required " + "
"; + valid = false; + }else{ + try{ + Integer.parseInt(policyData.getYamlparams().getLimit()); + }catch(NumberFormatException e){ + responseString = responseString + " Guard Params Limit Should be Integer " + "
"; + valid = false; + } + } + if(policyData.getYamlparams().getTimeWindow()==null){ + responseString = responseString + "Guard Params Time Window is Required" + "
"; + valid = false; + } + if(policyData.getYamlparams().getGuardActiveStart()==null){ + responseString = responseString + "Guard Params Guard Active Start/b>is Required " + "
"; + valid = false; + } + if(policyData.getYamlparams().getGuardActiveEnd()==null){ + responseString = responseString + "Guard Params Guard Active Endis Required " + "
"; + 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 @@
-
+

Key is required.

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 @@
-
+

ServiceList is required.

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 @@
-
+
@@ -68,7 +68,7 @@
-
+
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 @@
+
+
+ +
+
+

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 @@
- +

Source-List is required.

@@ -112,7 +112,7 @@
- +

Destination-List is required.

@@ -133,7 +133,7 @@
- +

Source-Services is required.

@@ -154,7 +154,7 @@
- +

Destination-Services is required.

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 @@

Micro Service is required.

-
- +
+
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 @@ + 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 @@ - +
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 @@
@@ -136,10 +136,7 @@ - +
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 @@
@@ -116,10 +116,7 @@ - +
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 @@
@@ -132,7 +132,7 @@ herf="javascript:void(0)" ng-click="validatePolicy(temp.policy);">Validate - +
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 @@
-
+

Hosted Voice @@ -81,6 +81,11 @@ type="checkbox" ng-disabled="temp.policy.readOnly" ng-model="temp.policy.jsonBodyData.vDNS"> vDNS
+
+ +
@@ -492,9 +497,7 @@ - +
\ 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 @@
@@ -148,10 +148,7 @@ - +
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 @@
@@ -126,9 +126,7 @@ - +
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);"> +
+ +
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+
+
@@ -179,9 +262,7 @@ - +
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 @@
@@ -111,9 +111,7 @@ - +
\ 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 @@