From 5c4675e5f6f7fe9b8d9e87976ac5f603ff61c268 Mon Sep 17 00:00:00 2001 From: mmis Date: Thu, 22 Mar 2018 14:20:46 +0000 Subject: Removed checkstyle warnings Removed checkstyle warnings in: policy/controlloop/common/guard policy/controlloop/common/msb policy/controlloop/simulators including renaming of the following classes: MSBServiceFactory -> MsbServiceFactory MSBServiceManager -> MsbServiceManager MSBServiceException -> MsbServiceException Issue-ID: POLICY-705 Change-Id: I11d62a74fcb77e764121df119cb0bd9b844b485b Signed-off-by: mmis --- .../java/org/onap/policy/guard/CallGuardTask.java | 160 ++--- .../java/org/onap/policy/guard/GuardResult.java | 8 +- .../java/org/onap/policy/guard/LockCallback.java | 11 +- .../org/onap/policy/guard/PIPEngineGetHistory.java | 734 ++++++++++--------- .../java/org/onap/policy/guard/PolicyGuard.java | 208 +++--- .../org/onap/policy/guard/PolicyGuardRequest.java | 94 +-- .../org/onap/policy/guard/PolicyGuardResponse.java | 82 ++- .../onap/policy/guard/PolicyGuardXacmlHelper.java | 779 +++++++++++---------- .../guard/PolicyGuardXacmlRequestAttributes.java | 151 ++-- .../onap/policy/guard/PolicyGuardYamlToXacml.java | 377 +++++----- .../java/org/onap/policy/guard/TargetLock.java | 16 +- .../src/main/java/org/onap/policy/guard/Util.java | 224 +++--- .../org/onap/policy/guard/impl/PNFTargetLock.java | 109 +-- .../org/onap/policy/guard/impl/VMTargetLock.java | 93 +-- .../org/onap/policy/guard/impl/VNFTargetLock.java | 109 +-- .../org/onap/policy/guard/CallGuardTaskTest.java | 61 +- .../org/onap/policy/guard/GuardResultTest.java | 25 +- .../java/org/onap/policy/guard/GuardUtilTest.java | 149 ++-- .../onap/policy/guard/PIPEngineGetHistoryTest.java | 706 ++++++++++--------- .../onap/policy/guard/PolicyGuardRequestTest.java | 47 +- .../onap/policy/guard/PolicyGuardResponseTest.java | 41 +- .../org/onap/policy/guard/PolicyGuardTest.java | 401 +++++------ .../policy/guard/PolicyGuardXacmlHelperTest.java | 398 ++++++----- .../PolicyGuardXacmlRequestAttributesTest.java | 69 +- .../policy/guard/PolicyGuardYamlToXacmlTest.java | 386 +++++----- .../java/org/onap/policy/guard/TextFileUtils.java | 4 +- 26 files changed, 2796 insertions(+), 2646 deletions(-) (limited to 'controlloop/common/guard') diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java index 9e3116dd8..4ac22600b 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,91 +20,93 @@ package org.onap.policy.guard; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.std.annotations.RequestParser; + import java.util.UUID; import org.drools.core.WorkingMemory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.std.annotations.RequestParser; - public class CallGuardTask implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class); - WorkingMemory workingMemory; - String restfulPdpUrl; - String clname; - String actor; - String recipe; - String target; - String requestId; - - /* - * Guard url is grabbed from PolicyEngine.manager properties - */ - public CallGuardTask(WorkingMemory wm, String cl, String act, String rec, String tar, String reqId) { - workingMemory = wm; - clname = cl; - actor = act; - recipe = rec; - requestId = reqId; - target = tar; - } - - @Override - public void run() { - long startTime = System.nanoTime(); - com.att.research.xacml.api.Request request = null; - - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId); - - try { - request = RequestParser.parseRequest(xacmlReq); - } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { - logger.error("CallGuardTask.run threw: {}", e); - } - - - logger.debug("\n********** XACML REQUEST START ********"); - logger.debug("{}", request); - logger.debug("********** XACML REQUEST END ********\n"); - - String guardDecision = null; - - // - // Make guard request - // - guardDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - - logger.debug("\n********** XACML RESPONSE START ********"); - logger.debug("{}", guardDecision); - logger.debug("********** XACML RESPONSE END ********\n"); - - // - // Check if the restful call was unsuccessful or property doesn't exist - // - if(guardDecision == null){ - logger.error("********** XACML FAILED TO CONNECT ********"); - guardDecision = Util.INDETERMINATE; - } - - PolicyGuardResponse guardResponse = new PolicyGuardResponse(guardDecision, UUID.fromString(this.requestId), this.recipe); - - - // - //Create an artificial Guard response in case we didn't get a clear Permit or Deny - // - if(guardResponse.getResult().equals("Indeterminate")){ - guardResponse.setOperation(recipe); - guardResponse.setRequestID(UUID.fromString(requestId)); - } - - long estimatedTime = System.nanoTime() - startTime; - logger.debug("\n\n============ Guard inserted with decision {} !!! =========== time took: {} mili sec \n\n", - guardResponse.getResult(), (double)estimatedTime/1000/1000); - workingMemory.insert(guardResponse); - - } + private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class); + WorkingMemory workingMemory; + String restfulPdpUrl; + String clname; + String actor; + String recipe; + String target; + String requestId; + + /** + * Guard url is grabbed from PolicyEngine.manager properties + */ + public CallGuardTask(WorkingMemory wm, String cl, String act, String rec, String tar, String reqId) { + workingMemory = wm; + clname = cl; + actor = act; + recipe = rec; + requestId = reqId; + target = tar; + } + + @Override + public void run() { + final long startTime = System.nanoTime(); + com.att.research.xacml.api.Request request = null; + + PolicyGuardXacmlRequestAttributes xacmlReq = + new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId); + + try { + request = RequestParser.parseRequest(xacmlReq); + } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { + logger.error("CallGuardTask.run threw: {}", e); + } + + + logger.debug("\n********** XACML REQUEST START ********"); + logger.debug("{}", request); + logger.debug("********** XACML REQUEST END ********\n"); + + String guardDecision = null; + + // + // Make guard request + // + guardDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + + logger.debug("\n********** XACML RESPONSE START ********"); + logger.debug("{}", guardDecision); + logger.debug("********** XACML RESPONSE END ********\n"); + + // + // Check if the restful call was unsuccessful or property doesn't exist + // + if (guardDecision == null) { + logger.error("********** XACML FAILED TO CONNECT ********"); + guardDecision = Util.INDETERMINATE; + } + + PolicyGuardResponse guardResponse = + new PolicyGuardResponse(guardDecision, UUID.fromString(this.requestId), this.recipe); + + + // + // Create an artificial Guard response in case we didn't get a clear Permit or Deny + // + if (guardResponse.getResult().equals("Indeterminate")) { + guardResponse.setOperation(recipe); + guardResponse.setRequestID(UUID.fromString(requestId)); + } + + long estimatedTime = System.nanoTime() - startTime; + logger.debug("\n\n============ Guard inserted with decision {} !!! =========== time took: {} mili sec \n\n", + guardResponse.getResult(), (double) estimatedTime / 1000 / 1000); + workingMemory.insert(guardResponse); + + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java index b2792858a..6b11c1afa 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; public enum GuardResult { - LOCK_ACQUIRED, - LOCK_DENIED, - LOCK_EXCEPTION - ; + LOCK_ACQUIRED, LOCK_DENIED, LOCK_EXCEPTION; } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java index 0a1255d33..2b33e0e57 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; public interface LockCallback { - - public boolean isActive(); - - public boolean releaseLock(); + + public boolean isActive(); + + public boolean releaseLock(); } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java index 21bdcd853..a9a984ade 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,21 @@ package org.onap.policy.guard; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.pip.StdMutablePIPResponse; +import com.att.research.xacml.std.pip.StdPIPRequest; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; + import java.math.BigInteger; import java.sql.Timestamp; import java.util.Collection; @@ -40,374 +55,351 @@ import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPRequest; -import com.att.research.xacml.api.pip.PIPResponse; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.pip.StdMutablePIPResponse; -import com.att.research.xacml.std.pip.StdPIPRequest; -import com.att.research.xacml.std.pip.StdPIPResponse; -import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; - -public class PIPEngineGetHistory extends StdConfigurableEngine{ - private static final Logger logger = LoggerFactory.getLogger(PIPEngineGetHistory.class); - - // - // Base issuer string. The issuer in the policy will also contain time window information - // E.g., "com:att:research:xacml:guard:historydb:tw:10:min" - // - public static final String DEFAULT_ISSUER = "com:att:research:xacml:guard:historydb"; - public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; - - private static final String XML_SCHEMA_STRING = "http://www.w3.org/2001/XMLSchema#string"; - - private static final String XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; - private static final String XACML_ACTOR_ACTOR_ID = "urn:oasis:names:tc:xacml:1.0:actor:actor-id"; - private static final String XACML_ATTRIBUTE_CATEGORY_ACTION ="urn:oasis:names:tc:xacml:3.0:attribute-category:action"; - private static final String XACML_OPERATION_OPERATION_ID ="urn:oasis:names:tc:xacml:1.0:operation:operation-id"; - private static final String XACML_ATTRIBUTE_CATEGORY_RESOURCE ="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; - private static final String XACML_TARGET_TARGET_ID ="urn:oasis:names:tc:xacml:1.0:target:target-id"; - private static final String XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT = "com:att:research:xacml:test:sql:resource:operations:count"; - - private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( - new IdentifierImpl(XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT), - new IdentifierImpl(XACML_ACTOR_ACTOR_ID), - new IdentifierImpl(XML_SCHEMA_STRING)); - - private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( - new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_ACTION), - new IdentifierImpl(XACML_OPERATION_OPERATION_ID), - new IdentifierImpl(XML_SCHEMA_STRING)); - - private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( - new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), - new IdentifierImpl(XACML_TARGET_TARGET_ID), - new IdentifierImpl(XML_SCHEMA_STRING)); - - public PIPEngineGetHistory() { - super(); - } - - @Override - public Collection attributesRequired() { - return Collections.emptySet(); - } - - @Override - public Collection attributesProvided() { - return Collections.emptySet(); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - logger.debug("Entering FeqLimiter PIP"); - - /* - * First check to see if the issuer is set and then match it - */ - String string; - if ((string = pipRequest.getIssuer()) == null) { - - logger.debug("No issuer in the request..."); - logger.debug("FeqLimiter PIP - No issuer in the request!"); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - else{ - //Notice, we are checking here for the base issuer prefix. - if (!string.contains(this.getIssuer())) { - logger.debug("Requested issuer '{}' does not match {}", string, getIssuer()); - logger.debug("FeqLimiter PIP - Issuer {} does not match with: ", string, this.getIssuer()); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - } - - String[] s1 = string.split("tw:"); - String[] s2 = s1[1].split(":"); - String timeWindowVal = s2[0];// number [of minutes, hours, days...] - String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year - - String actor = null; - String operation = null; - String target = null; - try { - actor = getActor(pipFinder).iterator().next(); - operation = getRecipe(pipFinder).iterator().next(); - target = getTarget(pipFinder).iterator().next(); - } catch (Exception e) { - logger.debug("could not retrieve actor, operation, or target from PIP finder", e); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - - String timeWindow = timeWindowVal + " " + timeWindowScale; - - logger.debug("Going to query DB about: {} {} {} {}", actor, operation, target, timeWindow); - int countFromDB = getCountFromDB(actor, operation, target, timeWindow); - - StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); - - this.addIntegerAttribute(stdPIPResponse, - new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), - new IdentifierImpl(XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT), - countFromDB, - pipRequest); - - return new StdPIPResponse(stdPIPResponse); - } - - @Override - public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - - if (this.getDescription() == null) { - this.setDescription(DEFAULT_DESCRIPTION); - } - if (this.getIssuer() == null) { - this.setIssuer(DEFAULT_ISSUER); - } - } - - private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { - PIPResponse pipResponse = null; - - try { - pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); - } catch (PIPException ex) { - logger.error("getAttribute threw:", ex); - return null; - } - if (pipResponse == null) { - return null; - } - if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { - if (logger.isWarnEnabled()) { - logger.warn("PIP response error {}: {}", pipRequest.getAttributeId().stringValue(), pipResponse.getStatus().toString()); - } - return null; - } - if (pipResponse.getAttributes() != null && pipResponse.getAttributes().isEmpty()) { - if (logger.isWarnEnabled()) { - logger.warn("No attributes in POP response {}: {}", pipRequest.getAttributeId().stringValue(), pipResponse.getStatus().toString()); - } - return null; - } - return pipResponse; - } - - private Set getActor(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - - return setATTUIDs; - } - - private Set getRecipe(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - - return setATTUIDs; - } - - private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) { - AttributeValue attributeValue = null; - try { - attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); - } catch (Exception ex) { - logger.error("Failed to convert {} to an AttributeValue",value, ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); - } - } - - private Set getTarget(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - - return setATTUIDs; - } - - private static int getCountFromDB(String actor, String operation, String target, String timeWindow){ - // DB Properties - Properties props = new Properties(); - props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL)); - props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER)); - props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); - - - EntityManager em = null; - String opsHistPU = System.getProperty("OperationsHistoryPU"); - if (opsHistPU == null || !opsHistPU.equals("TestOperationsHistoryPU")){ - opsHistPU = "OperationsHistoryPU"; - } - else { - props.clear(); - } - - try { - em = Persistence.createEntityManagerFactory(opsHistPU, props).createEntityManager(); - } catch(Exception ex){ - logger.error("PIP thread got Exception. Can't connect to Operations History DB -- {}", opsHistPU); - logger.error("getCountFromDB threw: ", ex); - return -1; - } - - long now = new Date().getTime(); - long diff; - try { - diff = now - getMSFromTimeWindow(timeWindow); - } catch (Exception ex) { - logger.error("PIP thread got Exception " + ex); - return -1; - } - - StringBuilder sqlBuilder = new StringBuilder(); - sqlBuilder.append("select count(*) as count from operationshistory10 where outcome<>'Failure_Guard'"); - sqlBuilder.append(" and actor= ?"); - sqlBuilder.append(" and operation= ?"); - sqlBuilder.append(" and target= ?"); - sqlBuilder.append(" and endtime between '"); - sqlBuilder.append(new Timestamp(diff)); - sqlBuilder.append("' and '"); - sqlBuilder.append(new Timestamp(now)); - sqlBuilder.append('\''); - - Query nq = em.createNativeQuery(sqlBuilder.toString()); - nq.setParameter(1, actor); - nq.setParameter(2, operation); - nq.setParameter(3, target); - - int ret = -1; - try { - ret = ((Number)nq.getSingleResult()).intValue(); - } - catch(NoResultException | NonUniqueResultException ex){ - logger.error("getCountFromDB threw: ", ex); - return -1; - } - - em.close(); - - return ret; - } - - /** - * Get the Millisecond time from a time window string - * @param timeWindow the time window string to parse - * @return the millisecond time from the time window string - * @throws PIPException On invalid time window strings - */ - private static long getMSFromTimeWindow(String timeWindowString) throws PIPException { - long ms = 0; - double multiplier = 0; - - String[] split = timeWindowString.split(" "); - if (split.length != 2) { - throw new PIPException("Invalid Value Unit pair for SQL"); - } - - ms = Long.parseLong(split[0]); - - if("SECOND".compareToIgnoreCase(split[1]) == 0){ - multiplier = 1000; - } - else if("MINUTE".compareToIgnoreCase(split[1]) == 0){ - multiplier = 60000; - } - else if("HOUR".compareToIgnoreCase(split[1]) == 0){ - multiplier = 3.6e+6; - } - else if("DAY".compareToIgnoreCase(split[1]) == 0){ - multiplier = 8.64e+7; - } - else if("WEEK".compareToIgnoreCase(split[1]) == 0){ - multiplier = 6.048e+8; - } - else if("MONTH".compareToIgnoreCase(split[1]) == 0){ - multiplier = 2.628e+9; - } - else if("QUARTER".compareToIgnoreCase(split[1]) == 0){ - multiplier = 2.628e+9 * 3; - } - else if("YEAR".compareToIgnoreCase(split[1]) == 0){ - multiplier = 3.154e+10; - } - else{ - logger.error("{} not supported", split[1]); - } - - ms *= multiplier; - return ms; - } +public class PIPEngineGetHistory extends StdConfigurableEngine { + private static final Logger logger = LoggerFactory.getLogger(PIPEngineGetHistory.class); + + // + // Base issuer string. The issuer in the policy will also contain time window information + // E.g., "com:att:research:xacml:guard:historydb:tw:10:min" + // + public static final String DEFAULT_ISSUER = "com:att:research:xacml:guard:historydb"; + public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; + + private static final String XML_SCHEMA_STRING = "http://www.w3.org/2001/XMLSchema#string"; + + private static final String XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT = + "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + private static final String XACML_ACTOR_ACTOR_ID = "urn:oasis:names:tc:xacml:1.0:actor:actor-id"; + private static final String XACML_ATTRIBUTE_CATEGORY_ACTION = + "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + private static final String XACML_OPERATION_OPERATION_ID = "urn:oasis:names:tc:xacml:1.0:operation:operation-id"; + private static final String XACML_ATTRIBUTE_CATEGORY_RESOURCE = + "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + private static final String XACML_TARGET_TARGET_ID = "urn:oasis:names:tc:xacml:1.0:target:target-id"; + private static final String XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT = + "com:att:research:xacml:test:sql:resource:operations:count"; + + private static final PIPRequest PIP_REQUEST_ACTOR = + new StdPIPRequest(new IdentifierImpl(XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT), + new IdentifierImpl(XACML_ACTOR_ACTOR_ID), new IdentifierImpl(XML_SCHEMA_STRING)); + + private static final PIPRequest PIP_REQUEST_RECIPE = + new StdPIPRequest(new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_ACTION), + new IdentifierImpl(XACML_OPERATION_OPERATION_ID), new IdentifierImpl(XML_SCHEMA_STRING)); + + private static final PIPRequest PIP_REQUEST_TARGET = + new StdPIPRequest(new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), + new IdentifierImpl(XACML_TARGET_TARGET_ID), new IdentifierImpl(XML_SCHEMA_STRING)); + + public PIPEngineGetHistory() { + super(); + } + + @Override + public Collection attributesRequired() { + return Collections.emptySet(); + } + + @Override + public Collection attributesProvided() { + return Collections.emptySet(); + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + logger.debug("Entering FeqLimiter PIP"); + + /* + * First check to see if the issuer is set and then match it + */ + String string; + if ((string = pipRequest.getIssuer()) == null) { + + logger.debug("No issuer in the request..."); + logger.debug("FeqLimiter PIP - No issuer in the request!"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } else { + // Notice, we are checking here for the base issuer prefix. + if (!string.contains(this.getIssuer())) { + logger.debug("Requested issuer '{}' does not match {}", string, getIssuer()); + logger.debug("FeqLimiter PIP - Issuer {} does not match with: ", string, this.getIssuer()); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + } + + String[] s1 = string.split("tw:"); + String[] s2 = s1[1].split(":"); + String timeWindowVal = s2[0];// number [of minutes, hours, days...] + String timeWindowScale = s2[1];// e.g., minute, hour, day, week, month, year + + String actor = null; + String operation = null; + String target = null; + try { + actor = getActor(pipFinder).iterator().next(); + operation = getRecipe(pipFinder).iterator().next(); + target = getTarget(pipFinder).iterator().next(); + } catch (Exception e) { + logger.debug("could not retrieve actor, operation, or target from PIP finder", e); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + + String timeWindow = timeWindowVal + " " + timeWindowScale; + + logger.debug("Going to query DB about: {} {} {} {}", actor, operation, target, timeWindow); + int countFromDb = getCountFromDb(actor, operation, target, timeWindow); + + StdMutablePIPResponse stdPipResponse = new StdMutablePIPResponse(); + + this.addIntegerAttribute(stdPipResponse, new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), + new IdentifierImpl(XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT), countFromDb, pipRequest); + + return new StdPIPResponse(stdPipResponse); + } + + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + } + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + } catch (PIPException ex) { + logger.error("getAttribute threw:", ex); + return null; + } + if (pipResponse == null) { + return null; + } + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + if (logger.isWarnEnabled()) { + logger.warn("PIP response error {}: {}", pipRequest.getAttributeId().stringValue(), + pipResponse.getStatus().toString()); + } + return null; + } + if (pipResponse.getAttributes() != null && pipResponse.getAttributes().isEmpty()) { + if (logger.isWarnEnabled()) { + logger.warn("No attributes in POP response {}: {}", pipRequest.getAttributeId().stringValue(), + pipResponse.getStatus().toString()); + } + return null; + } + return pipResponse; + } + + private Set getActor(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseAttUid = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listAttUids = pipResponseAttUid.getAttributes(); + Set setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + + return setAttUids; + } + + private Set getRecipe(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseAttUid = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listAttUids = pipResponseAttUid.getAttributes(); + Set setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + + return setAttUids; + } + + private void addIntegerAttribute(StdMutablePIPResponse stdPipResponse, Identifier category, Identifier attributeId, + int value, PIPRequest pipRequest) { + AttributeValue attributeValue = null; + try { + attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + } catch (Exception ex) { + logger.error("Failed to convert {} to an AttributeValue", value, ex); + } + if (attributeValue != null) { + stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, + pipRequest.getIssuer()/* this.getIssuer() */, false)); + } + } + + private Set getTarget(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseAttUid = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listAttUids = pipResponseAttUid.getAttributes(); + Set setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + + return setAttUids; + } + + private static int getCountFromDb(String actor, String operation, String target, String timeWindow) { + // DB Properties + Properties props = new Properties(); + props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL)); + props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER)); + props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); + + + EntityManager em = null; + String opsHistPu = System.getProperty("OperationsHistoryPU"); + if (opsHistPu == null || !opsHistPu.equals("TestOperationsHistoryPU")) { + opsHistPu = "OperationsHistoryPU"; + } else { + props.clear(); + } + + try { + em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager(); + } catch (Exception ex) { + logger.error("PIP thread got Exception. Can't connect to Operations History DB -- {}", opsHistPu); + logger.error("getCountFromDb threw: ", ex); + return -1; + } + + long now = new Date().getTime(); + long diff; + try { + diff = now - getMsFromTimeWindow(timeWindow); + } catch (Exception ex) { + logger.error("PIP thread got Exception " + ex); + return -1; + } + + StringBuilder sqlBuilder = new StringBuilder(); + sqlBuilder.append("select count(*) as count from operationshistory10 where outcome<>'Failure_Guard'"); + sqlBuilder.append(" and actor= ?"); + sqlBuilder.append(" and operation= ?"); + sqlBuilder.append(" and target= ?"); + sqlBuilder.append(" and endtime between '"); + sqlBuilder.append(new Timestamp(diff)); + sqlBuilder.append("' and '"); + sqlBuilder.append(new Timestamp(now)); + sqlBuilder.append('\''); + + Query nq = em.createNativeQuery(sqlBuilder.toString()); + nq.setParameter(1, actor); + nq.setParameter(2, operation); + nq.setParameter(3, target); + + int ret = -1; + try { + ret = ((Number) nq.getSingleResult()).intValue(); + } catch (NoResultException | NonUniqueResultException ex) { + logger.error("getCountFromDb threw: ", ex); + return -1; + } + + em.close(); + + return ret; + } + + /** + * Get the Millisecond time from a time window string. + * + * @param timeWindow the time window string to parse + * @return the millisecond time from the time window string + * @throws PIPException On invalid time window strings + */ + private static long getMsFromTimeWindow(String timeWindowString) throws PIPException { + long ms = 0; + double multiplier = 0; + + String[] split = timeWindowString.split(" "); + if (split.length != 2) { + throw new PIPException("Invalid Value Unit pair for SQL"); + } + + ms = Long.parseLong(split[0]); + + if ("SECOND".compareToIgnoreCase(split[1]) == 0) { + multiplier = 1000; + } else if ("MINUTE".compareToIgnoreCase(split[1]) == 0) { + multiplier = 60000; + } else if ("HOUR".compareToIgnoreCase(split[1]) == 0) { + multiplier = 3.6e+6; + } else if ("DAY".compareToIgnoreCase(split[1]) == 0) { + multiplier = 8.64e+7; + } else if ("WEEK".compareToIgnoreCase(split[1]) == 0) { + multiplier = 6.048e+8; + } else if ("MONTH".compareToIgnoreCase(split[1]) == 0) { + multiplier = 2.628e+9; + } else if ("QUARTER".compareToIgnoreCase(split[1]) == 0) { + multiplier = 2.628e+9 * 3; + } else if ("YEAR".compareToIgnoreCase(split[1]) == 0) { + multiplier = 3.154e+10; + } else { + logger.error("{} not supported", split[1]); + } + + ms *= multiplier; + return ms; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java index c23dc35cd..47faa88c2 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import java.util.HashMap; @@ -31,97 +32,122 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PolicyGuard { - private PolicyGuard() { - // Cannot instantiate this static class - } - - private static Map activeLocks = new HashMap<>(); - private static final Logger logger = LoggerFactory.getLogger(PolicyGuard.class); + private PolicyGuard() { + // Cannot instantiate this static class + } + + private static Map activeLocks = new HashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(PolicyGuard.class); + + public static class LockResult { + private A parameterA; + private B parameterB; + + public static LockResult createLockResult(A parameterA, B parameterB) { + return new LockResult<>(parameterA, parameterB); + } + + public LockResult(A parameterA, B parameterB) { + this.parameterA = parameterA; + this.parameterB = parameterB; + } + + public A getA() { + return parameterA; + } + + public B getB() { + return parameterB; + } + } + + /** + * Lock a target. + * + * @param targetType the target type + * @param targetInstance the target instance + * @param requestID the request Id + * @param callback the LockCallback + * @return the LockResult + */ + public static LockResult lockTarget(TargetType targetType, String targetInstance, + UUID requestID, LockCallback callback) { + + synchronized (activeLocks) { + // + // Is there a lock on this instance already? + // + if (activeLocks.containsKey(targetInstance)) { + return LockResult.createLockResult(GuardResult.LOCK_DENIED, null); + } + TargetLock lock = null; + switch (targetType) { + case PNF: + // + // Create the Lock object + // + lock = new PNFTargetLock(targetType, targetInstance, requestID, callback); + break; + case VM: + // + // Create the Lock object + // + lock = new VMTargetLock(targetType, targetInstance, requestID, callback); + break; + case VNF: + // + // Create the Lock object + // + lock = new VNFTargetLock(targetType, targetInstance, requestID, callback); + break; + + default: + return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null); + } + // + // Keep track of it + // + activeLocks.put(targetInstance, lock); + // + // Return result + // + logger.debug("Locking {}", lock); + return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock); + } + } - public static class LockResult { - private A a; - private B b; - - public static LockResult createLockResult(A a, B b) { - return new LockResult<>(a, b); - } - - public LockResult(A a, B b) { - this.a = a; - this.b = b; - } - - public A getA() { - return a; - } - - public B getB() { - return b; - } - } - - public static LockResult lockTarget(TargetType targetType, String targetInstance, UUID requestID, LockCallback callback) { - - synchronized(activeLocks) { - // - // Is there a lock on this instance already? - // - if (activeLocks.containsKey(targetInstance)) { - return LockResult.createLockResult(GuardResult.LOCK_DENIED, null); - } - TargetLock lock = null; - switch (targetType) { - case PNF: - // - // Create the Lock object - // - lock = new PNFTargetLock(targetType, targetInstance, requestID, callback); - break; - case VM: - // - // Create the Lock object - // - lock = new VMTargetLock(targetType, targetInstance, requestID, callback); - break; - case VNF: - // - // Create the Lock object - // - lock = new VNFTargetLock(targetType, targetInstance, requestID, callback); - break; + /** + * Unlock a target. + * + * @param lock the target lock to unlock + * @return true if the target is successfully unlocked, false + * otherwise + */ + public static boolean unlockTarget(TargetLock lock) { + synchronized (activeLocks) { + if (activeLocks.containsKey(lock.getTargetInstance())) { + logger.debug("Unlocking {}", lock); + return (activeLocks.remove(lock.getTargetInstance()) != null); + } + return false; + } + } - default: - return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null); - } - // - // Keep track of it - // - activeLocks.put(targetInstance, lock); - // - // Return result - // - logger.debug("Locking {}", lock); - return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock); - } - } - - public static boolean unlockTarget(TargetLock lock) { - synchronized(activeLocks) { - if (activeLocks.containsKey(lock.getTargetInstance())) { - logger.debug("Unlocking {}", lock); - return (activeLocks.remove(lock.getTargetInstance()) != null); - } - return false; - } - } - - public static boolean isLocked(TargetType targetType, String targetInstance, UUID requestID) { - synchronized(activeLocks) { - if (activeLocks.containsKey(targetInstance)) { - TargetLock lock = activeLocks.get(targetInstance); - return (lock.getTargetType().equals(targetType) && lock.getRequestID().equals(requestID)); - } - return false; - } - } + /** + * Check if a target is locked. + * + * @param targetType the target type + * @param targetInstance the target instance + * @param requestID the request Id + * @return true if the target is locked, false otherwise + */ + public static boolean isLocked(TargetType targetType, String targetInstance, UUID requestID) { + synchronized (activeLocks) { + if (activeLocks.containsKey(targetInstance)) { + TargetLock lock = activeLocks.get(targetInstance); + return (lock.getTargetType().equals(targetType) && lock.getRequestID().equals(requestID)); + } + return false; + } + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java index 20c9665ce..bca31d904 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java @@ -23,54 +23,62 @@ package org.onap.policy.guard; import java.util.UUID; public class PolicyGuardRequest { - private String actor; - private String target; - private UUID requestID; - private String operation; - - public PolicyGuardRequest(String actor, String target, UUID requestID, String operation) { - super(); - this.actor = actor; - this.target = target; - this.requestID = requestID; - this.operation = operation; - } - - @Override - public String toString() { - return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestID=" + requestID + ", operation=" - + operation + "]"; - } + private String actor; + private String target; + private UUID requestId; + private String operation; - public String getActor() { - return actor; - } + /** + * Construct an instance. + * + * @param actor the actor + * @param target the target + * @param requestID the request Id + * @param operation the operation + */ + public PolicyGuardRequest(String actor, String target, UUID requestID, String operation) { + super(); + this.actor = actor; + this.target = target; + this.requestId = requestID; + this.operation = operation; + } - public void setActor(String actor) { - this.actor = actor; - } + @Override + public String toString() { + return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestID=" + requestId + ", operation=" + + operation + "]"; + } - public String getTarget() { - return target; - } + public String getActor() { + return actor; + } - public void setTarget(String target) { - this.target = target; - } + public void setActor(String actor) { + this.actor = actor; + } - public UUID getRequestID() { - return requestID; - } + public String getTarget() { + return target; + } - public void setRequestID(UUID requestID) { - this.requestID = requestID; - } + public void setTarget(String target) { + this.target = target; + } - public String getOperation() { - return operation; - } + public UUID getRequestID() { + return requestId; + } - public void setOperation(String operation) { - this.operation = operation; - } -} \ No newline at end of file + public void setRequestID(UUID requestID) { + this.requestId = requestID; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java index 110fbe0ab..e9ff435f8 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java @@ -22,38 +22,50 @@ package org.onap.policy.guard; import java.util.UUID; -public class PolicyGuardResponse{ - private UUID requestID; - private String operation; - private String result; - - public PolicyGuardResponse(String result, UUID req, String op) { - this.result = result; - this.requestID = req; - this.operation = op; - } - - @Override - public String toString() { - return "PolicyGuardResponse [requestID=" + requestID + ", operation=" + operation + ", result=" + result + "]"; - } - - public UUID getRequestID() { - return requestID; - } - public void setRequestID(UUID requestID) { - this.requestID = requestID; - } - public String getResult() { - return result; - } - public void setResult(String result) { - this.result = result; - } - public String getOperation() { - return operation; - } - public void setOperation(String operation) { - this.operation = operation; - } -} \ No newline at end of file +public class PolicyGuardResponse { + private UUID requestId; + private String operation; + private String result; + + /** + * Create an instance. + * + * @param result the result + * @param req the request Id + * @param op the operation + */ + public PolicyGuardResponse(String result, UUID req, String op) { + this.result = result; + this.requestId = req; + this.operation = op; + } + + @Override + public String toString() { + return "PolicyGuardResponse [requestID=" + requestId + ", operation=" + operation + ", result=" + result + "]"; + } + + public UUID getRequestID() { + return requestId; + } + + public void setRequestID(UUID requestID) { + this.requestId = requestID; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java index a81da89d7..777240fea 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java @@ -20,6 +20,11 @@ package org.onap.policy.guard; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeCategory; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Result; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -40,391 +45,395 @@ import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeCategory; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Result; - public class PolicyGuardXacmlHelper { - private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class); - private static final Logger netLogger = LoggerFactory.getLogger(org.onap.policy.drools.event.comm.Topic.NETWORK_LOGGER); - - // Constant for the systme line separator - private static final String SYSTEM_LS = System.lineSeparator(); - - public PolicyGuardXacmlHelper() { - init(PolicyEngine.manager.getEnvironment()); - } - - // initialized from 'pdpx.url' property -- - // Each entry in 'restUrls' contains a destination URL, and an optional - // 'Authorization' header entry. 'restUrlIndex' indicates the next - // entry to try -- after each failure, the index is advanced to the - // next entry (wrapping to the beginning, if needed). - private static class URLEntry implements Serializable { - private static final long serialVersionUID = -8859237552195400518L; - - URL restURL; - String authorization = null; - String clientAuth = null; - String environment = null; - } - - private URLEntry[] restUrls = null; - private int restUrlIndex = 0; - - // REST timeout, initialized from 'pdpx.timeout' property - private int timeout = 20000; - - public String callPDP(PolicyGuardXacmlRequestAttributes xacmlReq) { - // - // Send it to the PDP - // - String response = null; - - // - // Build the json request - // - JSONObject attributes = new JSONObject(); - attributes.put("actor", xacmlReq.getActorID()); - attributes.put("recipe", xacmlReq.getOperationID()); - attributes.put("target", xacmlReq.getTargetID()); - if (xacmlReq.getClnameID() != null) { - attributes.put("clname", xacmlReq.getClnameID()); - } - JSONObject jsonReq = new JSONObject(); - jsonReq.put("decisionAttributes", attributes); - jsonReq.put("onapName", "PDPD"); - - - try { - // - // Call RESTful PDP - // - URLEntry urlEntry = restUrls[restUrlIndex]; - String jsonRequestString = jsonReq.toString(); - netLogger.info("[OUT|{}|{}|]{}{}", "GUARD", urlEntry.restURL, SYSTEM_LS, jsonRequestString); - response = callRESTfulPDP(new ByteArrayInputStream(jsonReq - .toString().getBytes()), urlEntry.restURL, - urlEntry.authorization, urlEntry.clientAuth, - urlEntry.environment); - netLogger.info("[IN|{}|{}|]{}{}", "GUARD", urlEntry.restURL, SYSTEM_LS, response); - } catch (Exception e) { - logger.error("Error in sending RESTful request: ", e); - } - - return response; - } - - /** - * This makes an HTTP POST call to a running PDP RESTful servlet to get a - * decision. - * - * @param file - * @return response from guard which contains "Permit" or "Deny" - */ - private String callRESTfulPDP(InputStream is, URL restURL, String authorization, String clientauth, String environment) { - HttpURLConnection connection = null; - - try { - // - // Open up the connection - // - connection = (HttpURLConnection) restURL.openConnection(); - connection.setRequestProperty("Content-Type", "application/json"); - // - // Setup our method and headers - // - connection.setRequestProperty("Accept", "application/json"); - if (authorization != null) { - connection.setRequestProperty("Authorization", authorization); - } - if (clientauth != null) { - connection.setRequestProperty("ClientAuth", clientauth); - } - if (environment != null) { - connection.setRequestProperty("Environment", environment); - } - connection.setConnectTimeout(timeout); - connection.setReadTimeout(timeout); - connection.setRequestMethod("POST"); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - // - // Send the request - // - try (OutputStream os = connection.getOutputStream()) { - IOUtils.copy(is, os); - } - - // - // Do the connect - // - connection.connect(); - - if (connection.getResponseCode() != 200) { - logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); - return Util.INDETERMINATE; - } - } catch (Exception e) { - logger.error("Exception in 'PolicyGuardXacmlHelper.callRESTfulPDP'", e); - return Util.INDETERMINATE; - } - - // - // Read the response - // - try { - ContentType contentType = ContentType.parse(connection.getContentType()); - - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - InputStream iStream = connection.getInputStream(); - int contentLength = connection.getContentLength(); - - return readResponseFromStream(iStream, contentLength); - } else { - logger.error("unknown content-type: {}", contentType); - return Util.INDETERMINATE; - } - - } catch (Exception e) { - String message = "Parsing Content-Type: " + connection.getContentType(); - logger.error(message, e); - return Util.INDETERMINATE; - } - } - - public static PolicyGuardResponse parseXACMLPDPResponse(com.att.research.xacml.api.Response xacmlResponse) { - if (xacmlResponse == null) { - // - // In case the actual XACML response was null, create an empty - // response object with decision "Indeterminate" - // - return new PolicyGuardResponse("Indeterminate", null, ""); - } - - Iterator itRes = xacmlResponse.getResults().iterator(); - - Result res = itRes.next(); - String decisionFromXACMLResponse = res.getDecision().toString(); - Iterator itAttrCat = res.getAttributes().iterator(); - UUID reqIDFromXACMLResponse = null; - String operationFromXACMLResponse = ""; - - while (itAttrCat.hasNext()) { - Iterator itAttr = itAttrCat.next().getAttributes() - .iterator(); - while (itAttr.hasNext()) { - Attribute currentAttr = itAttr.next(); - String s = currentAttr.getAttributeId().stringValue(); - if ("urn:oasis:names:tc:xacml:1.0:request:request-id".equals(s)) { - Iterator> itValues = currentAttr.getValues().iterator(); - reqIDFromXACMLResponse = UUID.fromString(itValues .next().getValue().toString()); - } - if ("urn:oasis:names:tc:xacml:1.0:operation:operation-id" .equals(s)) { - Iterator> itValues = currentAttr.getValues().iterator(); - operationFromXACMLResponse = itValues.next().getValue().toString(); - } - } - } - - return new PolicyGuardResponse(decisionFromXACMLResponse, - reqIDFromXACMLResponse, operationFromXACMLResponse); - - } - - private void init(Properties properties) { - // used to store error messages - StringBuilder sb = new StringBuilder(); - - // fetch these parameters, if they exist - String timeoutString = properties.getProperty("pdpx.timeout"); - String disabledString = properties.getProperty("guard.disabled"); - - if (disabledString != null && Boolean.parseBoolean(disabledString)) { - return; - } - - ArrayList entries = initEntries(properties, sb); - - if (entries.isEmpty()) { - sb.append("'pdpx.*' -- no URLs specified, "); - } else { - restUrls = entries.toArray(new URLEntry[0]); - } - - if (timeoutString != null) { - try { - // decode optional 'pdpx.timeout' parameter - timeout = Integer.valueOf(timeoutString); - } catch (NumberFormatException e) { - sb.append("'pdpx.timeout': " + e + ", "); - logger.trace(e.getLocalizedMessage()); - } - } - - - // if there are any errors, update 'errorMessage' & disable guard - // queries - if (sb.length() != 0) { - // remove the terminating ", ", and extract resulting error message - sb.setLength(sb.length() - 2); - String errorMessage = sb.toString(); - logger.error("Initialization failure: {}", errorMessage); - } - } - - private ArrayList initEntries(Properties properties, StringBuilder sb) { - // now, see which numeric entries (1-9) exist - ArrayList entries = new ArrayList<>(); - - for (int index = 0; index < 10; index += 1) { - String urlPrefix = "guard."; - if (index != 0) { - urlPrefix = urlPrefix + index + "."; - } - - // see if the associated URL exists - String restURLlist = properties.getProperty(urlPrefix + "url"); - if (nullOrEmpty(restURLlist)) { - // no entry for this index - continue; - } - - // support a list of entries separated by semicolons. Each entry - // can be: - // URL - // URL,user - // URL,user,password - for (String restURL : restURLlist.split("\\s*;\\s*")) { - URLEntry entry = initRestURL(properties, sb, restURL); - // include this URLEntry in the list - if (entry != null) { - entries.add(entry); - } - } - } - - return entries; - } - - private URLEntry initRestURL(Properties properties, StringBuilder sb, String restURL) { - String urlPrefix = "guard."; - String pdpxPrefix = "pdpx."; - - String[] segments = restURL.split("\\s*,\\s*"); - String user = null; - String password = null; - - if (segments.length >= 2) { - // user id is provided - restURL = segments[0]; - user = segments[1]; - if (segments.length >= 3) { - // password is also provided - password = segments[2]; - } - } - - // URL does exist -- create the entry - URLEntry urlEntry = new URLEntry(); - try { - urlEntry.restURL = new URL(restURL); - } catch (java.net.MalformedURLException e) { - // if we don't have a URL, - // don't bother with the rest on this one - sb.append("'").append(urlPrefix).append("url' '") - .append(restURL).append("': ").append(e) - .append(","); - return null; - } - - if (nullOrEmpty(user)) { - // user id was not provided on '*.url' line -- - // extract it from a separate property - user = properties.getProperty(pdpxPrefix + "username", properties.getProperty("pdpx.username")); - } - if (nullOrEmpty(password)) { - // password was not provided on '*.url' line -- - // extract it from a separate property - password = properties.getProperty(pdpxPrefix + "password", properties.getProperty("pdpx.password")); - } - - // see if 'user' and 'password' entries both exist - if (!nullOrEmpty(user) && !nullOrEmpty(password)) { - urlEntry.authorization = "Basic " - + Base64.getEncoder().encodeToString( - (user + ":" + password).getBytes()); - } - - // see if 'client.user' and 'client.password' entries both exist - String clientUser = properties.getProperty(pdpxPrefix + "client.username", properties.getProperty("pdpx.client.username")); - String clientPassword = properties.getProperty(pdpxPrefix + "client.password", properties.getProperty("pdpx.client.password")); - if (!nullOrEmpty(clientUser) && !nullOrEmpty(clientPassword)) { - urlEntry.clientAuth = "Basic " - + Base64.getEncoder().encodeToString( - (clientUser + ":" + clientPassword) - .getBytes()); - } - - // see if there is an 'environment' entry - String environment = properties.getProperty(pdpxPrefix + "environment", properties.getProperty("pdpx.environment")); - if (!nullOrEmpty(environment)) { - urlEntry.environment = environment; - } - - return urlEntry; - } - - /** - * Check if a string is null or an empty string - * - * @param value - * the string to be tested - * @return 'true' if the string is 'null' or has a length of 0, 'false' - * otherwise - */ - private static boolean nullOrEmpty(String value) { - return (value == null || value.isEmpty()); - } - - private static String readResponseFromStream(InputStream iStream, int contentLength) throws IOException { - // if content length is -1, response is chunked, and - // TCP connection will be dropped at the end - byte[] buf = new byte[contentLength < 0 ? 1024: contentLength]; - int offset = 0; - do { - int size = iStream.read(buf, offset, buf.length - offset); - if (size < 0) { - // In a chunked response a dropped connection is expected, but not if the response is not chunked - if (contentLength > 0) { - logger.error("partial input stream"); - } - break; - } - offset += size; - } while (offset != contentLength); - - String response = new String(buf, 0, offset); - - // - // Connection may have failed or not been 200 OK, return Indeterminate - // - if (response.isEmpty()) { - return Util.INDETERMINATE; - } - - return new JSONObject(response).getString("decision"); - - } + private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class); + private static final Logger netLogger = + LoggerFactory.getLogger(org.onap.policy.drools.event.comm.Topic.NETWORK_LOGGER); + + // Constant for the systme line separator + private static final String SYSTEM_LS = System.lineSeparator(); + + public PolicyGuardXacmlHelper() { + init(PolicyEngine.manager.getEnvironment()); + } + + // initialized from 'pdpx.url' property -- + // Each entry in 'restUrls' contains a destination URL, and an optional + // 'Authorization' header entry. 'restUrlIndex' indicates the next + // entry to try -- after each failure, the index is advanced to the + // next entry (wrapping to the beginning, if needed). + private static class UrlEntry implements Serializable { + private static final long serialVersionUID = -8859237552195400518L; + + URL restUrl; + String authorization = null; + String clientAuth = null; + String environment = null; + } + + private UrlEntry[] restUrls = null; + private int restUrlIndex = 0; + + // REST timeout, initialized from 'pdpx.timeout' property + private int timeout = 20000; + + /** + * Call PDP. + * + * @param xacmlReq the XACML request + * @return the response + */ + public String callPDP(PolicyGuardXacmlRequestAttributes xacmlReq) { + // + // Send it to the PDP + // + String response = null; + + // + // Build the json request + // + JSONObject attributes = new JSONObject(); + attributes.put("actor", xacmlReq.getActorID()); + attributes.put("recipe", xacmlReq.getOperationID()); + attributes.put("target", xacmlReq.getTargetID()); + if (xacmlReq.getClnameID() != null) { + attributes.put("clname", xacmlReq.getClnameID()); + } + JSONObject jsonReq = new JSONObject(); + jsonReq.put("decisionAttributes", attributes); + jsonReq.put("onapName", "PDPD"); + + + try { + // + // Call RESTful PDP + // + UrlEntry urlEntry = restUrls[restUrlIndex]; + String jsonRequestString = jsonReq.toString(); + netLogger.info("[OUT|{}|{}|]{}{}", "GUARD", urlEntry.restUrl, SYSTEM_LS, jsonRequestString); + response = callRESTfulPDP(new ByteArrayInputStream(jsonReq.toString().getBytes()), urlEntry.restUrl, + urlEntry.authorization, urlEntry.clientAuth, urlEntry.environment); + netLogger.info("[IN|{}|{}|]{}{}", "GUARD", urlEntry.restUrl, SYSTEM_LS, response); + } catch (Exception e) { + logger.error("Error in sending RESTful request: ", e); + } + + return response; + } + + /** + * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. + * + * @param is the InputStream + * @param authorization the Authorization + * @param clientauth the ClientAuth + * @param environment the Environment + * @return response from guard which contains "Permit" or "Deny" + */ + private String callRESTfulPDP(InputStream is, URL restURL, String authorization, String clientauth, + String environment) { + HttpURLConnection connection = null; + + try { + // + // Open up the connection + // + connection = (HttpURLConnection) restURL.openConnection(); + connection.setRequestProperty("Content-Type", "application/json"); + // + // Setup our method and headers + // + connection.setRequestProperty("Accept", "application/json"); + if (authorization != null) { + connection.setRequestProperty("Authorization", authorization); + } + if (clientauth != null) { + connection.setRequestProperty("ClientAuth", clientauth); + } + if (environment != null) { + connection.setRequestProperty("Environment", environment); + } + connection.setConnectTimeout(timeout); + connection.setReadTimeout(timeout); + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // + // Send the request + // + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy(is, os); + } + + // + // Do the connect + // + connection.connect(); + + if (connection.getResponseCode() != 200) { + logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); + return Util.INDETERMINATE; + } + } catch (Exception e) { + logger.error("Exception in 'PolicyGuardXacmlHelper.callRESTfulPDP'", e); + return Util.INDETERMINATE; + } + + // + // Read the response + // + try { + ContentType contentType = ContentType.parse(connection.getContentType()); + + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + InputStream inputStream = connection.getInputStream(); + int contentLength = connection.getContentLength(); + + return readResponseFromStream(inputStream, contentLength); + } else { + logger.error("unknown content-type: {}", contentType); + return Util.INDETERMINATE; + } + + } catch (Exception e) { + String message = "Parsing Content-Type: " + connection.getContentType(); + logger.error(message, e); + return Util.INDETERMINATE; + } + } + + /** + * Parse XACML PDP response. + * + * @param xacmlResponse the XACML response + * @return the PolicyGuardResponse + */ + public static PolicyGuardResponse parseXACMLPDPResponse(com.att.research.xacml.api.Response xacmlResponse) { + if (xacmlResponse == null) { + // + // In case the actual XACML response was null, create an empty + // response object with decision "Indeterminate" + // + return new PolicyGuardResponse("Indeterminate", null, ""); + } + + Iterator itRes = xacmlResponse.getResults().iterator(); + + Result res = itRes.next(); + String decisionFromXacmlResponse = res.getDecision().toString(); + Iterator itAttrCat = res.getAttributes().iterator(); + UUID reqIdFromXacmlResponse = null; + String operationFromXacmlResponse = ""; + + while (itAttrCat.hasNext()) { + Iterator itAttr = itAttrCat.next().getAttributes().iterator(); + while (itAttr.hasNext()) { + Attribute currentAttr = itAttr.next(); + String attributeId = currentAttr.getAttributeId().stringValue(); + if ("urn:oasis:names:tc:xacml:1.0:request:request-id".equals(attributeId)) { + Iterator> itValues = currentAttr.getValues().iterator(); + reqIdFromXacmlResponse = UUID.fromString(itValues.next().getValue().toString()); + } + if ("urn:oasis:names:tc:xacml:1.0:operation:operation-id".equals(attributeId)) { + Iterator> itValues = currentAttr.getValues().iterator(); + operationFromXacmlResponse = itValues.next().getValue().toString(); + } + } + } + + return new PolicyGuardResponse(decisionFromXacmlResponse, reqIdFromXacmlResponse, operationFromXacmlResponse); + + } + + private void init(Properties properties) { + // used to store error messages + StringBuilder sb = new StringBuilder(); + + // fetch these parameters, if they exist + String timeoutString = properties.getProperty("pdpx.timeout"); + String disabledString = properties.getProperty("guard.disabled"); + + if (disabledString != null && Boolean.parseBoolean(disabledString)) { + return; + } + + ArrayList entries = initEntries(properties, sb); + + if (entries.isEmpty()) { + sb.append("'pdpx.*' -- no URLs specified, "); + } else { + restUrls = entries.toArray(new UrlEntry[0]); + } + + if (timeoutString != null) { + try { + // decode optional 'pdpx.timeout' parameter + timeout = Integer.valueOf(timeoutString); + } catch (NumberFormatException e) { + sb.append("'pdpx.timeout': " + e + ", "); + logger.trace(e.getLocalizedMessage()); + } + } + + + // if there are any errors, update 'errorMessage' & disable guard + // queries + if (sb.length() != 0) { + // remove the terminating ", ", and extract resulting error message + sb.setLength(sb.length() - 2); + String errorMessage = sb.toString(); + logger.error("Initialization failure: {}", errorMessage); + } + } + + private ArrayList initEntries(Properties properties, StringBuilder sb) { + // now, see which numeric entries (1-9) exist + ArrayList entries = new ArrayList<>(); + + for (int index = 0; index < 10; index += 1) { + String urlPrefix = "guard."; + if (index != 0) { + urlPrefix = urlPrefix + index + "."; + } + + // see if the associated URL exists + String restUrllist = properties.getProperty(urlPrefix + "url"); + if (nullOrEmpty(restUrllist)) { + // no entry for this index + continue; + } + + // support a list of entries separated by semicolons. Each entry + // can be: + // URL + // URL,user + // URL,user,password + for (String restUrl : restUrllist.split("\\s*;\\s*")) { + UrlEntry entry = initRestUrl(properties, sb, restUrl); + // include this URLEntry in the list + if (entry != null) { + entries.add(entry); + } + } + } + + return entries; + } + + private UrlEntry initRestUrl(Properties properties, StringBuilder sb, String restUrl) { + String urlPrefix = "guard."; + String pdpxPrefix = "pdpx."; + + String[] segments = restUrl.split("\\s*,\\s*"); + String user = null; + String password = null; + + if (segments.length >= 2) { + // user id is provided + restUrl = segments[0]; + user = segments[1]; + if (segments.length >= 3) { + // password is also provided + password = segments[2]; + } + } + + // URL does exist -- create the entry + UrlEntry urlEntry = new UrlEntry(); + try { + urlEntry.restUrl = new URL(restUrl); + } catch (java.net.MalformedURLException e) { + // if we don't have a URL, + // don't bother with the rest on this one + sb.append("'").append(urlPrefix).append("url' '").append(restUrl).append("': ").append(e).append(","); + return null; + } + + if (nullOrEmpty(user)) { + // user id was not provided on '*.url' line -- + // extract it from a separate property + user = properties.getProperty(pdpxPrefix + "username", properties.getProperty("pdpx.username")); + } + if (nullOrEmpty(password)) { + // password was not provided on '*.url' line -- + // extract it from a separate property + password = properties.getProperty(pdpxPrefix + "password", properties.getProperty("pdpx.password")); + } + + // see if 'user' and 'password' entries both exist + if (!nullOrEmpty(user) && !nullOrEmpty(password)) { + urlEntry.authorization = "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes()); + } + + // see if 'client.user' and 'client.password' entries both exist + String clientUser = + properties.getProperty(pdpxPrefix + "client.username", properties.getProperty("pdpx.client.username")); + String clientPassword = + properties.getProperty(pdpxPrefix + "client.password", properties.getProperty("pdpx.client.password")); + if (!nullOrEmpty(clientUser) && !nullOrEmpty(clientPassword)) { + urlEntry.clientAuth = + "Basic " + Base64.getEncoder().encodeToString((clientUser + ":" + clientPassword).getBytes()); + } + + // see if there is an 'environment' entry + String environment = + properties.getProperty(pdpxPrefix + "environment", properties.getProperty("pdpx.environment")); + if (!nullOrEmpty(environment)) { + urlEntry.environment = environment; + } + + return urlEntry; + } + + /** + * Check if a string is null or an empty string. + * + * @param value the string to be tested + * @return 'true' if the string is 'null' or has a length of 0, 'false' otherwise + */ + private static boolean nullOrEmpty(String value) { + return (value == null || value.isEmpty()); + } + + private static String readResponseFromStream(InputStream inputStream, int contentLength) throws IOException { + // if content length is -1, response is chunked, and + // TCP connection will be dropped at the end + byte[] buf = new byte[contentLength < 0 ? 1024 : contentLength]; + int offset = 0; + do { + int size = inputStream.read(buf, offset, buf.length - offset); + if (size < 0) { + // In a chunked response a dropped connection is expected, but not if the response + // is not chunked + if (contentLength > 0) { + logger.error("partial input stream"); + } + break; + } + offset += size; + } + while (offset != contentLength); + + String response = new String(buf, 0, offset); + + // + // Connection may have failed or not been 200 OK, return Indeterminate + // + if (response.isEmpty()) { + return Util.INDETERMINATE; + } + + return new JSONObject(response).getString("decision"); + + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java index 70291001a..5e69d6435 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -20,82 +20,91 @@ package org.onap.policy.guard; - import com.att.research.xacml.std.annotations.XACMLAction; import com.att.research.xacml.std.annotations.XACMLRequest; import com.att.research.xacml.std.annotations.XACMLResource; import com.att.research.xacml.std.annotations.XACMLSubject; -@XACMLRequest(ReturnPolicyIdList=true,CombinedDecision=true) +@XACMLRequest(ReturnPolicyIdList = true, CombinedDecision = true) public class PolicyGuardXacmlRequestAttributes { - public PolicyGuardXacmlRequestAttributes(String clnameID, String actorID, String operationID, String targetID, String requestID) { - super(); - this.clnameID = clnameID; - this.actorID = actorID; - this.operationID = operationID; - this.targetID = targetID; - this.requestID = requestID; - } - - @Override - public String toString() { - return "PolicyGuardXacmlRequestAttributes [actorID=" + actorID + ", operationID=" + operationID - + ", targetID=" + targetID + ", requestID=" + requestID + "]"; - } - - @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:clname:clname-id") - String clnameID; - - @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id") - String actorID; - - @XACMLAction(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id") - String operationID; - - @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:target:target-id") - String targetID; - - @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:request:request-id") - String requestID; - - public String getActorID() { - return actorID; - } - - public void setActorID(String actorID) { - this.actorID = actorID; - } - - public String getOperationID() { - return operationID; - } - - public void setOperationID(String operationID) { - this.operationID = operationID; - } - - public String getTargetID() { - return targetID; - } - - public void setTargetID(String targetID) { - this.targetID = targetID; - } - - public String getRequestID() { - return requestID; - } - - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - public String getClnameID() { - return clnameID; - } - - public void setClnameID(String clnameID) { - this.clnameID = clnameID; - } + /** + * Construct an instance. + * + * @param clnameID the control loop Id + * @param actorID the actor Id + * @param operationID the operation Id + * @param targetID the target Id + * @param requestID the request Id + */ + public PolicyGuardXacmlRequestAttributes(String clnameID, String actorID, String operationID, String targetID, + String requestID) { + super(); + this.clnameID = clnameID; + this.actorID = actorID; + this.operationID = operationID; + this.targetID = targetID; + this.requestID = requestID; + } + + @Override + public String toString() { + return "PolicyGuardXacmlRequestAttributes [actorID=" + actorID + ", operationID=" + operationID + ", targetID=" + + targetID + ", requestID=" + requestID + "]"; + } + + @XACMLSubject(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:clname:clname-id") + String clnameID; + + @XACMLSubject(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:actor:actor-id") + String actorID; + + @XACMLAction(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:operation:operation-id") + String operationID; + + @XACMLResource(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:target:target-id") + String targetID; + + @XACMLResource(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:request:request-id") + String requestID; + + public String getActorID() { + return actorID; + } + + public void setActorID(String actorID) { + this.actorID = actorID; + } + + public String getOperationID() { + return operationID; + } + + public void setOperationID(String operationID) { + this.operationID = operationID; + } + + public String getTargetID() { + return targetID; + } + + public void setTargetID(String targetID) { + this.targetID = targetID; + } + + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + public String getClnameID() { + return clnameID; + } + + public void setClnameID(String clnameID) { + this.clnameID = clnameID; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java index bb6ae49c8..b493fff38 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -35,174 +35,211 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PolicyGuardYamlToXacml { - private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class); - - private PolicyGuardYamlToXacml() { - // Construction of this static class is not allowed - } - - public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { - ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); - logger.debug("clname: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); - logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); - logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); - logger.debug("num: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); - logger.debug("duration: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); - logger.debug("time_in_range: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); - - Path xacmlTemplatePath = Paths.get(xacmlTemplate); - String xacmlTemplateContent; - - try { - xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - - String xacmlPolicyContent = generateXACMLGuard(xacmlTemplateContent, - yamlGuardObject.getGuards().getFirst().getMatch_parameters(), - yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() - ); - - Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); - - } catch (IOException e) { - logger.error("fromYamlToXacml threw: ", e); - } - } - - private static String generateXACMLGuard(String xacmlTemplateContent, MatchParameters matchParameters, Constraint constraint) { - Pattern p = Pattern.compile("\\$\\{clname\\}"); - Matcher m = p.matcher(xacmlTemplateContent); - if (isNullOrEmpty(matchParameters.getControlLoopName())) matchParameters.setControlLoopName(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getControlLoopName()); - - p = Pattern.compile("\\$\\{actor\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getActor())) matchParameters.setActor(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getActor()); - - p = Pattern.compile("\\$\\{recipe\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getRecipe())) matchParameters.setRecipe(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getRecipe()); - - p = Pattern.compile("\\$\\{targets\\}"); - m = p.matcher(xacmlTemplateContent); - String targetsRegex = ""; - if(isNullOrEmptyList(matchParameters.getTargets())) { - targetsRegex = ".*"; - } - else { - StringBuilder targetsRegexSB = new StringBuilder(); - boolean addBarChar = false; - for (String t : matchParameters.getTargets()){ - targetsRegexSB.append(t); - if (addBarChar) { - targetsRegexSB.append("|"); - } - else { - addBarChar = true; - } - } - targetsRegex = targetsRegexSB.toString(); - } - xacmlTemplateContent = m.replaceAll(targetsRegex); - - p = Pattern.compile("\\$\\{limit\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getFreq_limit_per_target().toString()); - - p = Pattern.compile("\\$\\{twValue\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getTime_window().get("value")); - - p = Pattern.compile("\\$\\{twUnits\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getTime_window().get("units")); - - - p = Pattern.compile("\\$\\{guardActiveStart\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("start")); - - p = Pattern.compile("\\$\\{guardActiveEnd\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("end")); - logger.debug(xacmlTemplateContent); - - return xacmlTemplateContent; - } - - public static boolean isNullOrEmpty(String s) { - return s == null || s.trim().isEmpty(); - } - - public static boolean isNullOrEmptyList(List list){ - return list == null || list.isEmpty(); - } - - public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){ - ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); - logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); - logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); - logger.debug("freq_limit_per_target: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); - logger.debug("time_window: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); - logger.debug("active_time_range: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); - - Path xacmlTemplatePath = Paths.get(xacmlTemplate); - String xacmlTemplateContent; - - try { - xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, - yamlGuardObject.getGuards().getFirst().getMatch_parameters(), - yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() - ); - - Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); - - } catch (IOException e) { - logger.error("fromYamlToXacmlBlacklist threw: ", e); - } - } - - private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters, Constraint constraint) { - Pattern p = Pattern.compile("\\$\\{clname\\}"); - Matcher m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getControlLoopName())) matchParameters.setControlLoopName(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getControlLoopName()); - - p = Pattern.compile("\\$\\{actor\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getActor())) matchParameters.setActor(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getActor()); - - p = Pattern.compile("\\$\\{recipe\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getRecipe())) matchParameters.setRecipe(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getRecipe()); - - p = Pattern.compile("\\$\\{guardActiveStart\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("start")); - - p = Pattern.compile("\\$\\{guardActiveEnd\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("end")); - logger.debug(xacmlTemplateContent); - - for(String target : constraint.getBlacklist()){ - p = Pattern.compile("\\$\\{blackListElement\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll("" - + target - + "" - + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); - } - - p = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(""); - - - return xacmlTemplateContent; - } + private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class); + + private PolicyGuardYamlToXacml() { + // Construction of this static class is not allowed + } + + /** + * Convert from Yaml to Xacml. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + */ + public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + logger.debug("clname: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); + logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); + logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); + logger.debug("num: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); + logger.debug("duration: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); + logger.debug("time_in_range: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent, + yamlGuardObject.getGuards().getFirst().getMatch_parameters(), + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()); + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + logger.error("fromYamlToXacml threw: ", e); + } + } + + /** + * Generate a Xacml guard. + * + * @param xacmlTemplateContent the Xacml template content + * @param matchParameters the paremeters to use + * @param constraint the constraint to use + * @return the guard + */ + private static String generateXacmlGuard(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + Pattern pattern = Pattern.compile("\\$\\{clname\\}"); + Matcher matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getControlLoopName())) { + matchParameters.setControlLoopName(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getControlLoopName()); + + pattern = Pattern.compile("\\$\\{actor\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getActor())) { + matchParameters.setActor(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getActor()); + + pattern = Pattern.compile("\\$\\{recipe\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getRecipe())) { + matchParameters.setRecipe(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getRecipe()); + + pattern = Pattern.compile("\\$\\{targets\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + String targetsRegex = ""; + if (isNullOrEmptyList(matchParameters.getTargets())) { + targetsRegex = ".*"; + } else { + StringBuilder targetsRegexSb = new StringBuilder(); + boolean addBarChar = false; + for (String t : matchParameters.getTargets()) { + targetsRegexSb.append(t); + if (addBarChar) { + targetsRegexSb.append("|"); + } else { + addBarChar = true; + } + } + targetsRegex = targetsRegexSb.toString(); + } + xacmlTemplateContent = matcher.replaceAll(targetsRegex); + + pattern = Pattern.compile("\\$\\{limit\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getFreq_limit_per_target().toString()); + + pattern = Pattern.compile("\\$\\{twValue\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getTime_window().get("value")); + + pattern = Pattern.compile("\\$\\{twUnits\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getTime_window().get("units")); + + + pattern = Pattern.compile("\\$\\{guardActiveStart\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("start")); + + pattern = Pattern.compile("\\$\\{guardActiveEnd\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("end")); + logger.debug(xacmlTemplateContent); + + return xacmlTemplateContent; + } + + public static boolean isNullOrEmpty(String string) { + return string == null || string.trim().isEmpty(); + } + + public static boolean isNullOrEmptyList(List list) { + return list == null || list.isEmpty(); + } + + /** + * Convert from Yaml to Xacml blacklist. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + */ + public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); + logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); + logger.debug("freq_limit_per_target: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); + logger.debug("time_window: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); + logger.debug("active_time_range: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, + yamlGuardObject.getGuards().getFirst().getMatch_parameters(), + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()); + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + logger.error("fromYamlToXacmlBlacklist threw: ", e); + } + } + + private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + Pattern pattern = Pattern.compile("\\$\\{clname\\}"); + Matcher matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getControlLoopName())) { + matchParameters.setControlLoopName(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getControlLoopName()); + + pattern = Pattern.compile("\\$\\{actor\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getActor())) { + matchParameters.setActor(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getActor()); + + pattern = Pattern.compile("\\$\\{recipe\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getRecipe())) { + matchParameters.setRecipe(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getRecipe()); + + pattern = Pattern.compile("\\$\\{guardActiveStart\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("start")); + + pattern = Pattern.compile("\\$\\{guardActiveEnd\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("end")); + logger.debug(xacmlTemplateContent); + + for (String target : constraint.getBlacklist()) { + pattern = Pattern.compile("\\$\\{blackListElement\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = + matcher.replaceAll("" + target + + "" + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); + } + + pattern = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(""); + + + return xacmlTemplateContent; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java index f2e4f0ae2..1e3064abd 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java @@ -25,13 +25,13 @@ import java.util.UUID; import org.onap.policy.controlloop.policy.TargetType; public interface TargetLock { - - public UUID getLockID(); - - public TargetType getTargetType(); - - public String getTargetInstance(); - - public UUID getRequestID(); + + public UUID getLockID(); + + public TargetType getTargetType(); + + public String getTargetInstance(); + + public UUID getRequestID(); } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java index 53e7a5e50..233fc0b49 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java @@ -36,110 +36,122 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public final class Util { - private Util() { - // This static class cannot be instantiated - } - - /* - * Keys for guard properties - */ - public static final String PROP_GUARD_URL = "guard.url"; - public static final String PROP_GUARD_USER = "pdpx.username"; - public static final String PROP_GUARD_PASS = "pdpx.password"; - public static final String PROP_GUARD_CLIENT_USER = "pdpx.client.username"; - public static final String PROP_GUARD_CLIENT_PASS = "pdpx.client.password"; - public static final String PROP_GUARD_ENV = "pdpx.environment"; - public static final String PROP_GUARD_DISABLED = "guard.disabled"; - - /* - * Keys for eclipse link and ONAP properties - */ - public static final String ECLIPSE_LINK_KEY_URL = "javax.persistence.jdbc.url"; - public static final String ECLIPSE_LINK_KEY_USER = "javax.persistence.jdbc.user"; - public static final String ECLIPSE_LINK_KEY_PASS = "javax.persistence.jdbc.password"; - - public static final String ONAP_KEY_URL = "guard.jdbc.url"; - public static final String ONAP_KEY_USER = "sql.db.username"; - public static final String ONAP_KEY_PASS = "sql.db.password"; - - /* - * Guard responses - */ - public static final String INDETERMINATE = "Indeterminate"; - public static final String PERMIT = "Permit"; - public static final String DENY = "Deny"; - - /* - * Junit props - */ - protected static final String PU_KEY = "OperationsHistoryPU"; - protected static final String JUNITPU = "TestOperationsHistoryPU"; - - private static final Logger logger = LoggerFactory.getLogger(Util.class); - - public static class Pair { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } - - public static Pair loadYaml(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(contents); - - logger.debug(contents); - - return new Pair<>((ControlLoopPolicy) obj, contents); - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - return null; - } - - public static ControlLoopGuard loadYamlGuard(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(contents); - return (ControlLoopGuard) obj; - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - return null; - } - - /** - * Sets Guard Properties. - * - * @see /guard/src/test/java/org/onap/policy/guard/UtilTest.java - * for setting test properties - */ - public static void setGuardEnvProps(String url, String username, String password, String clientName, String clientPassword, String environment) { - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, url); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, username); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, password); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, clientName); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, clientPassword); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, environment); - } - - public static void setGuardEnvProp(String key, String value){ - PolicyEngine.manager.setEnvironmentProperty(key, value); - } - - public static String getGuardProp(String propName){ - return PolicyEngine.manager.getEnvironmentProperty(propName); - } + private Util() { + // This static class cannot be instantiated + } + + /* + * Keys for guard properties + */ + public static final String PROP_GUARD_URL = "guard.url"; + public static final String PROP_GUARD_USER = "pdpx.username"; + public static final String PROP_GUARD_PASS = "pdpx.password"; + public static final String PROP_GUARD_CLIENT_USER = "pdpx.client.username"; + public static final String PROP_GUARD_CLIENT_PASS = "pdpx.client.password"; + public static final String PROP_GUARD_ENV = "pdpx.environment"; + public static final String PROP_GUARD_DISABLED = "guard.disabled"; + + /* + * Keys for eclipse link and ONAP properties + */ + public static final String ECLIPSE_LINK_KEY_URL = "javax.persistence.jdbc.url"; + public static final String ECLIPSE_LINK_KEY_USER = "javax.persistence.jdbc.user"; + public static final String ECLIPSE_LINK_KEY_PASS = "javax.persistence.jdbc.password"; + + public static final String ONAP_KEY_URL = "guard.jdbc.url"; + public static final String ONAP_KEY_USER = "sql.db.username"; + public static final String ONAP_KEY_PASS = "sql.db.password"; + + /* + * Guard responses + */ + public static final String INDETERMINATE = "Indeterminate"; + public static final String PERMIT = "Permit"; + public static final String DENY = "Deny"; + + /* + * Junit props + */ + protected static final String PU_KEY = "OperationsHistoryPU"; + protected static final String JUNITPU = "TestOperationsHistoryPU"; + + private static final Logger logger = LoggerFactory.getLogger(Util.class); + + public static class Pair { + public final A parameterA; + public final B parameterB; + + public Pair(A parameterA, B parameterB) { + this.parameterA = parameterA; + this.parameterB = parameterB; + } + } + + /** + * Load a Yaml file. + * + * @param testFile the Yaml file + * @return the policies + */ + public static Pair loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + + logger.debug(contents); + + return new Pair<>((ControlLoopPolicy) obj, contents); + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + return null; + } + + /** + * Load a Yaml guard. + * + * @param testFile the Yaml file + * @return the guard + */ + public static ControlLoopGuard loadYamlGuard(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(contents); + return (ControlLoopGuard) obj; + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + return null; + } + + /** + * Sets Guard Properties. + * + * @see /guard/src/test/java/org/onap/policy/guard/UtilTest.java for setting test properties + */ + public static void setGuardEnvProps(String url, String username, String password, String clientName, + String clientPassword, String environment) { + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, url); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, username); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, password); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, clientName); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, clientPassword); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, environment); + } + + public static void setGuardEnvProp(String key, String value) { + PolicyEngine.manager.setEnvironmentProperty(key, value); + } + + public static String getGuardProp(String propName) { + return PolicyEngine.manager.getEnvironmentProperty(propName); + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java index d9335ea3d..06bd9fb89 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,56 +29,61 @@ import org.onap.policy.guard.TargetLock; public class PNFTargetLock implements TargetLock, Serializable { - /** - * - */ - private static final long serialVersionUID = 2335897394577202732L; - - private final UUID lockID; - private final TargetType targetType; - private final String target; - private final UUID requestID; - private final transient LockCallback callback; - - public PNFTargetLock (TargetType type, String target, UUID requestID, LockCallback callback) { - this.lockID = UUID.randomUUID(); - this.targetType = type; - this.target = target; - this.requestID = requestID; - this.callback = callback; - } - - @Override - public UUID getLockID() { - return this.lockID; - } - - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestID() { - return this.requestID; - } - - public LockCallback getCallback() { - return this.callback; - } - - @Override - public String toString() { - return "PNFTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" - + requestID + "]"; - } - - + private static final long serialVersionUID = 2335897394577202732L; + + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; + + /** + * Construct an instance. + * + * @param type the target type + * @param target the target + * @param requestID the request Id + * @param callback the callback + */ + public PNFTargetLock(TargetType type, String target, UUID requestID, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = type; + this.target = target; + this.requestId = requestID; + this.callback = callback; + } + + @Override + public UUID getLockID() { + return this.lockId; + } + + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "PNFTargetLock [lockID=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestId + "]"; + } + + } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java index 0a7556bc9..dc81712cd 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,53 +28,58 @@ import org.onap.policy.guard.LockCallback; import org.onap.policy.guard.TargetLock; public class VMTargetLock implements TargetLock, Serializable { - - /** - * - */ - private static final long serialVersionUID = -8795145054334409724L; - private final UUID lockID; - private final TargetType targetType; - private final String target; - private final UUID requestID; - private final transient LockCallback callback; - public VMTargetLock(TargetType targetType, String target, UUID requestID, LockCallback callback) { - this.lockID = UUID.randomUUID(); - this.targetType = targetType; - this.target = target; - this.requestID = requestID; - this.callback = callback; - } + private static final long serialVersionUID = -8795145054334409724L; + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; - @Override - public UUID getLockID() { - return this.lockID; - } - - @Override - public TargetType getTargetType() { - return targetType; - } + /** + * Create an instance. + * + * @param targetType the target type + * @param target the target + * @param requestID the request Id + * @param callback the callback + */ + public VMTargetLock(TargetType targetType, String target, UUID requestID, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = targetType; + this.target = target; + this.requestId = requestID; + this.callback = callback; + } - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestID() { - return this.requestID; - } + @Override + public UUID getLockID() { + return this.lockId; + } - public LockCallback getCallback() { - return this.callback; - } + @Override + public TargetType getTargetType() { + return targetType; + } - @Override - public String toString() { - return "VMTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" - + requestID + "]"; - } + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "VMTargetLock [lockID=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestId + "]"; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java index b6e49b578..307c11acf 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,56 +29,61 @@ import org.onap.policy.guard.TargetLock; public class VNFTargetLock implements TargetLock, Serializable { - /** - * - */ - private static final long serialVersionUID = 2335897394577202732L; - - private final UUID lockID; - private final TargetType targetType; - private final String target; - private final UUID requestID; - private final transient LockCallback callback; - - public VNFTargetLock (TargetType type, String target, UUID requestID, LockCallback callback) { - this.lockID = UUID.randomUUID(); - this.targetType = type; - this.target = target; - this.requestID = requestID; - this.callback = callback; - } - - @Override - public UUID getLockID() { - return this.lockID; - } - - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestID() { - return this.requestID; - } - - public LockCallback getCallback() { - return this.callback; - } - - @Override - public String toString() { - return "VNFTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" - + requestID + "]"; - } - - + private static final long serialVersionUID = 2335897394577202732L; + + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; + + /** + * Create an instance. + * + * @param type the type + * @param target the target + * @param requestID the request Id + * @param callback the callback + */ + public VNFTargetLock(TargetType type, String target, UUID requestID, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = type; + this.target = target; + this.requestId = requestID; + this.callback = callback; + } + + @Override + public UUID getLockID() { + return this.lockId; + } + + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "VNFTargetLock [lockID=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestId + "]"; + } + + } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java index 362931657..3255aec77 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.mockito.ArgumentMatchers.argThat; @@ -28,34 +29,34 @@ import static org.mockito.Mockito.when; import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.junit.Test; -public class CallGuardTaskTest{ - - static final String REQ_ID = "1-2-3-4-5"; - static final String REQ_MATCHER = "0+1-0+2-0+3-0+4-0+5"; - - @Test - /** - * Tests that the run method inserts guard response into working memory - */ - public void testRun() { - // Create mock working session - StatefulKnowledgeSessionImpl mockWorkingSession = mock(StatefulKnowledgeSessionImpl.class); - when(mockWorkingSession.insert(isNotNull())).thenReturn(null); - // Create CallGuardTask and run - CallGuardTask cgt = new CallGuardTask(mockWorkingSession, "cl", "act", "rec", "tar", REQ_ID); - cgt.run(); - verify(mockWorkingSession).insert(argThat( - (Object o) -> { - if(!(o instanceof PolicyGuardResponse)){ - return false; - } - // Check if the inserted response is PolicyGuardResponse, is Indeterminate, and has same reqID - PolicyGuardResponse response = (PolicyGuardResponse) o; - return Util.INDETERMINATE.equals(response.getResult()) && - // req ID has form 00000001-0002-0003-0004-000000000005 - response.getRequestID().toString().matches(REQ_MATCHER); - })); - - } +public class CallGuardTaskTest { + + static final String REQ_ID = "1-2-3-4-5"; + static final String REQ_MATCHER = "0+1-0+2-0+3-0+4-0+5"; + + @Test + /** + * Tests that the run method inserts guard response into working memory. + */ + public void testRun() { + // Create mock working session + StatefulKnowledgeSessionImpl mockWorkingSession = mock(StatefulKnowledgeSessionImpl.class); + when(mockWorkingSession.insert(isNotNull())).thenReturn(null); + // Create CallGuardTask and run + CallGuardTask cgt = new CallGuardTask(mockWorkingSession, "cl", "act", "rec", "tar", REQ_ID); + cgt.run(); + verify(mockWorkingSession).insert(argThat((Object obj) -> { + if (!(obj instanceof PolicyGuardResponse)) { + return false; + } + // Check if the inserted response is PolicyGuardResponse, is Indeterminate, and has same + // reqID + PolicyGuardResponse response = (PolicyGuardResponse) obj; + // req ID has form 00000001-0002-0003-0004-000000000005 + return Util.INDETERMINATE.equals(response.getResult()) + && response.getRequestID().toString().matches(REQ_MATCHER); + })); + + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java index b4d417e35..a491d74cc 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java @@ -20,21 +20,22 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.Test; public class GuardResultTest { - @Test - public void guardResultTest() { - assertEquals(3, GuardResult.values().length); - assertNotNull(GuardResult.LOCK_ACQUIRED); - assertNotNull(GuardResult.LOCK_DENIED); - assertNotNull(GuardResult.LOCK_EXCEPTION); - - assertEquals(GuardResult.LOCK_ACQUIRED, GuardResult.valueOf("LOCK_ACQUIRED")); - assertEquals(GuardResult.LOCK_DENIED, GuardResult.valueOf("LOCK_DENIED")); - assertEquals(GuardResult.LOCK_EXCEPTION, GuardResult.valueOf("LOCK_EXCEPTION")); - } + @Test + public void guardResultTest() { + assertEquals(3, GuardResult.values().length); + assertNotNull(GuardResult.LOCK_ACQUIRED); + assertNotNull(GuardResult.LOCK_DENIED); + assertNotNull(GuardResult.LOCK_EXCEPTION); + + assertEquals(GuardResult.LOCK_ACQUIRED, GuardResult.valueOf("LOCK_ACQUIRED")); + assertEquals(GuardResult.LOCK_DENIED, GuardResult.valueOf("LOCK_DENIED")); + assertEquals(GuardResult.LOCK_EXCEPTION, GuardResult.valueOf("LOCK_EXCEPTION")); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java index 9e1d1b29e..8fc5a83da 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java @@ -20,7 +20,10 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.att.aft.dme2.internal.google.common.io.Files; import java.io.File; import java.io.IOException; @@ -32,78 +35,76 @@ import org.onap.policy.guard.Util.Pair; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; -import com.att.aft.dme2.internal.google.common.io.Files; - public class GuardUtilTest { - @Test - public void testLoadYamlOK() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - - ControlLoopPolicy clPolicy = new ControlLoopPolicy(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - String clYamlString = clYaml.dump(clPolicy); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - - Pair result = Util.loadYaml(tempYAMLFile.getCanonicalPath()); - - assertEquals(clPolicy, result.a); - assertEquals(clYamlString, result.b); - - tempYAMLFile.delete(); - } - - @Test - public void testLoadYamlError() throws IOException { - File tempDir = Files.createTempDir(); - - // Read from a directory forces an IO exception - assertNull(Util.loadYaml(tempDir.getCanonicalPath())); - - tempDir.delete(); - } - - @Test - public void testLoadGuardYamlOK() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - - ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - String clYamlString = clYaml.dump(clGuardPolicy); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - - ControlLoopGuard result = Util.loadYamlGuard(tempYAMLFile.getCanonicalPath()); - - assertEquals(clGuardPolicy, result); - - tempYAMLFile.delete(); - } - - @Test - public void testLoadGuardYamlError() throws IOException { - File tempDir = Files.createTempDir(); - - // Read from a directory forces an IO exception - assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); - - tempDir.delete(); - } - - @Test - public void testMisc() { - Util.setGuardEnvProp("Actor", "Judy Garland"); - assertEquals("Judy Garland", Util.getGuardProp("Actor")); - - Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto", "Wizard", "Emerald", "Oz"); - - assertEquals("http://somewhere.over.the.rainbow", Util.getGuardProp(Util.PROP_GUARD_URL)); - assertEquals("Dorothy", Util.getGuardProp(Util.PROP_GUARD_USER)); - assertEquals("Toto", Util.getGuardProp(Util.PROP_GUARD_PASS)); - assertEquals("Wizard", Util.getGuardProp(Util.PROP_GUARD_CLIENT_USER)); - assertEquals("Emerald", Util.getGuardProp(Util.PROP_GUARD_CLIENT_PASS)); - assertEquals("Oz", Util.getGuardProp(Util.PROP_GUARD_ENV)); - } + @Test + public void testLoadYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + + ControlLoopPolicy clPolicy = new ControlLoopPolicy(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clPolicy); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + Pair result = Util.loadYaml(tempYamlFile.getCanonicalPath()); + + assertEquals(clPolicy, result.parameterA); + assertEquals(clYamlString, result.parameterB); + + tempYamlFile.delete(); + } + + @Test + public void testLoadYamlError() throws IOException { + File tempDir = Files.createTempDir(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYaml(tempDir.getCanonicalPath())); + + tempDir.delete(); + } + + @Test + public void testLoadGuardYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + + ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clGuardPolicy); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + ControlLoopGuard result = Util.loadYamlGuard(tempYamlFile.getCanonicalPath()); + + assertEquals(clGuardPolicy, result); + + tempYamlFile.delete(); + } + + @Test + public void testLoadGuardYamlError() throws IOException { + File tempDir = Files.createTempDir(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); + + tempDir.delete(); + } + + @Test + public void testMisc() { + Util.setGuardEnvProp("Actor", "Judy Garland"); + assertEquals("Judy Garland", Util.getGuardProp("Actor")); + + Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto", "Wizard", "Emerald", "Oz"); + + assertEquals("http://somewhere.over.the.rainbow", Util.getGuardProp(Util.PROP_GUARD_URL)); + assertEquals("Dorothy", Util.getGuardProp(Util.PROP_GUARD_USER)); + assertEquals("Toto", Util.getGuardProp(Util.PROP_GUARD_PASS)); + assertEquals("Wizard", Util.getGuardProp(Util.PROP_GUARD_CLIENT_USER)); + assertEquals("Emerald", Util.getGuardProp(Util.PROP_GUARD_CLIENT_PASS)); + assertEquals("Oz", Util.getGuardProp(Util.PROP_GUARD_ENV)); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java index 0c34d62b1..f1fd59961 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertEquals; @@ -26,24 +27,6 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import javax.persistence.Query; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.drools.system.PolicyEngine; - import com.att.research.xacml.api.Attribute; import com.att.research.xacml.api.AttributeValue; import com.att.research.xacml.api.Identifier; @@ -63,331 +46,364 @@ import com.att.research.xacml.std.pip.StdPIPResponse; import com.att.research.xacml.std.pip.finders.EngineFinder; import com.att.research.xacml.util.FactoryException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.drools.system.PolicyEngine; + public class PIPEngineGetHistoryTest { - static PIPEngineGetHistory pegh; - private static final String ISSUER = "issuerIntw:mid:end"; - - @BeforeClass - public static void testPIPEngineGetHistory(){ - pegh = null; - try{ - pegh = new PIPEngineGetHistory(); - } catch(Exception e){ - fail("PIPEngineGetHistory constructor failed"); - } - } - - @Test - public void testAttributesRequired() { - assertTrue(pegh.attributesRequired().isEmpty()); - } - - @Test - public void testAttributesProvided() { - assertTrue(pegh.attributesProvided().isEmpty()); - } - - @Test - public void testGetAttributes() { - StdPIPRequest mockPIPRequest = mock(StdPIPRequest.class); - EngineFinder mockPIPFinder = mock(EngineFinder.class); - - // Test issuer null - when(mockPIPRequest.getIssuer()).thenReturn(null); - try { - assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPIPRequest, mockPIPFinder)); - } catch (Exception e) { - fail("getAttributes failed"); - } - - // Test issuer not equal to our issuer - pegh.setIssuer(ISSUER); - when(mockPIPRequest.getIssuer()).thenReturn("something else"); - try { - assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPIPRequest, mockPIPFinder)); - } catch (Exception e) { - fail("getAttributes failed"); - } - - // Test issuer equal to our issuer - when(mockPIPRequest.getIssuer()).thenReturn(ISSUER); - try { - assertNotNull(pegh.getAttributes(mockPIPRequest, mockPIPFinder)); - } catch (Exception e) { - // Normal to catch exception - } - } - - @Test - public void testGetCountFromDB(){ - // Set PU - System.setProperty(Util.PU_KEY, Util.JUNITPU); - - //Enter dummy props to avoid nullPointerException - PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_URL, "a"); - PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_USER, "b"); - PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_PASS, "c"); - - // Connect to in-mem db - EntityManager em = null; - try{ - em = Persistence.createEntityManagerFactory(Util.JUNITPU).createEntityManager(); - } catch(Exception e){ - fail(e.getLocalizedMessage()); - } - - String sql = "CREATE TABLE `operationshistory10` (" + - "`CLNAME` varchar(255)," + - "`requestID` varchar(100)," + - "`actor` varchar(50) ," + - "`operation` varchar(50)," + - "`target` varchar(50)," + - "`starttime` timestamp," + - "`outcome` varchar(50)," + - "`message` varchar(255)," + - "`subrequestId` varchar(100)," + - "`endtime` timestamp"+ - ")"; - // Create necessary table - Query nq = em.createNativeQuery(sql); - em.getTransaction().begin(); - nq.executeUpdate(); - em.getTransaction().commit(); - - // Use reflection to run getCountFromDB - Method method = null; - int count = -1; - try { - method = PIPEngineGetHistory.class.getDeclaredMethod("getCountFromDB", String.class, String.class, String.class, String.class); - method.setAccessible(true); - count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { - fail(e.getLocalizedMessage()); - } - // No entries yet - assertEquals(0, count); - - // Add an entry - String addEntry = "insert into operationshistory10 (outcome, CLNAME, actor, operation, target, endtime)" + - "values('success','testcl', 'actor', 'op', 'target', CURRENT_TIMESTAMP())"; - Query nq2 = em.createNativeQuery(addEntry); - em.getTransaction().begin(); - nq2.executeUpdate(); - em.getTransaction().commit(); - em.close(); - - try { - count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - fail(e.getLocalizedMessage()); - } - // Should count 1 entry now - assertEquals(1, count); - } - - @Test - public void testConfigure() throws PIPException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.configure("Dorothy", new Properties()); - - pegh.setDescription(null); - pegh.setIssuer(null); - pegh.configure("Dorothy", new Properties()); - } - - @Test - public void getAttributesTest() throws URISyntaxException, PIPException, FactoryException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.setIssuer("Dorothy"); - - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; - Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; - Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; - PIPRequest pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:1000:SECOND"); - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNOK())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); - } - - @Test - public void timeWindowTest() throws URISyntaxException, PIPException, FactoryException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.setIssuer("Dorothy"); - - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; - Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; - Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; - - PIPRequest pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:SECOND"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:MINUTE"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:HOUR"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:DAY"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:WEEK"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:MONTH"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:QUARTER"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:YEAR"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:FORTNIGHT"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:FORT NIGHT"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNOK())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); - } - - private class DummyPipFinder implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - try { - List attributeList = new ArrayList<>(); - Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); - Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://www.w3.org/2001/XMLSchema#string")); - - Identifier attributeIdIn0 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue valueIn0 = new StdAttributeValue(dataTypeIdIn, "ActorDorothy"); - Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); - attributeList.add(attribute0); - - Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue valueIn1 = new StdAttributeValue(dataTypeIdIn, "OperationHomeFromOZ"); - Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); - attributeList.add(attribute1); - - Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue valueIn2 = new StdAttributeValue(dataTypeIdIn, "TargetWickedWitch"); - Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn2); - attributeList.add(attribute2); - - return new StdPIPResponse(attributeList); - } - catch (Exception e) { - return null; - } - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } - - private class DummyPipFinderPipException implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - throw new PIPException(); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } - - private class DummyPipFinderResponseStatusNOK implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - Status status = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Processing Error"); - return new StdPIPResponse(status); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } - - private class DummyPipFinderResponseEmptyAttrs implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - List attributeList = new ArrayList<>(); - return new StdPIPResponse(attributeList); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection getPIPEngines() { - return null; - } - } + static PIPEngineGetHistory pegh; + private static final String ISSUER = "issuerIntw:mid:end"; + + /** + * Set up test class. + */ + @BeforeClass + public static void testPipEngineGetHistory() { + pegh = null; + try { + pegh = new PIPEngineGetHistory(); + } catch (Exception e) { + fail("PIPEngineGetHistory constructor failed"); + } + } + + @Test + public void testAttributesRequired() { + assertTrue(pegh.attributesRequired().isEmpty()); + } + + @Test + public void testAttributesProvided() { + assertTrue(pegh.attributesProvided().isEmpty()); + } + + @Test + public void testGetAttributes() { + StdPIPRequest mockPipRequest = mock(StdPIPRequest.class); + EngineFinder mockPipFinder = mock(EngineFinder.class); + + // Test issuer null + when(mockPipRequest.getIssuer()).thenReturn(null); + try { + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + fail("getAttributes failed"); + } + + // Test issuer not equal to our issuer + pegh.setIssuer(ISSUER); + when(mockPipRequest.getIssuer()).thenReturn("something else"); + try { + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + fail("getAttributes failed"); + } + + // Test issuer equal to our issuer + when(mockPipRequest.getIssuer()).thenReturn(ISSUER); + try { + assertNotNull(pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + // Normal to catch exception + } + } + + @Test + public void testGetCountFromDb() { + // Set PU + System.setProperty(Util.PU_KEY, Util.JUNITPU); + + // Enter dummy props to avoid nullPointerException + PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_URL, "a"); + PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_USER, "b"); + PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_PASS, "c"); + + // Connect to in-mem db + EntityManager em = null; + try { + em = Persistence.createEntityManagerFactory(Util.JUNITPU).createEntityManager(); + } catch (Exception e) { + fail(e.getLocalizedMessage()); + } + + String sql = "CREATE TABLE `operationshistory10` (" + "`CLNAME` varchar(255)," + "`requestID` varchar(100)," + + "`actor` varchar(50) ," + "`operation` varchar(50)," + "`target` varchar(50)," + + "`starttime` timestamp," + "`outcome` varchar(50)," + "`message` varchar(255)," + + "`subrequestId` varchar(100)," + "`endtime` timestamp" + ")"; + // Create necessary table + Query nq = em.createNativeQuery(sql); + em.getTransaction().begin(); + nq.executeUpdate(); + em.getTransaction().commit(); + + // Use reflection to run getCountFromDB + Method method = null; + int count = -1; + try { + method = PIPEngineGetHistory.class.getDeclaredMethod("getCountFromDb", String.class, String.class, + String.class, String.class); + method.setAccessible(true); + count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException e) { + fail(e.getLocalizedMessage()); + } + // No entries yet + assertEquals(0, count); + + // Add an entry + String addEntry = "insert into operationshistory10 (outcome, CLNAME, actor, operation, target, endtime)" + + "values('success','testcl', 'actor', 'op', 'target', CURRENT_TIMESTAMP())"; + Query nq2 = em.createNativeQuery(addEntry); + em.getTransaction().begin(); + nq2.executeUpdate(); + em.getTransaction().commit(); + em.close(); + + try { + count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE"); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + fail(e.getLocalizedMessage()); + } + // Should count 1 entry now + assertEquals(1, count); + } + + @Test + public void testConfigure() throws PIPException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.configure("Dorothy", new Properties()); + + pegh.setDescription(null); + pegh.setIssuer(null); + pegh.configure("Dorothy", new Properties()); + } + + @Test + public void getAttributesTest() throws URISyntaxException, PIPException, FactoryException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.setIssuer("Dorothy"); + + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; + Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; + Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; + PIPRequest pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:1000:SECOND"); + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); + } + + @Test + public void timeWindowTest() throws URISyntaxException, PIPException, FactoryException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.setIssuer("Dorothy"); + + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; + Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; + Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; + + PIPRequest pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:SECOND"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MINUTE"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:HOUR"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:DAY"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:WEEK"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MONTH"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:QUARTER"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:YEAR"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:FORTNIGHT"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:FORT NIGHT"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); + } + + private class DummyPipFinder implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + try { + List attributeList = new ArrayList<>(); + Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); + Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://www.w3.org/2001/XMLSchema#string")); + + Identifier attributeIdIn0 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue valueIn0 = new StdAttributeValue(dataTypeIdIn, "ActorDorothy"); + Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); + attributeList.add(attribute0); + + Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue valueIn1 = new StdAttributeValue(dataTypeIdIn, "OperationHomeFromOZ"); + Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); + attributeList.add(attribute1); + + Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue valueIn2 = new StdAttributeValue(dataTypeIdIn, "TargetWickedWitch"); + Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn2); + attributeList.add(attribute2); + + return new StdPIPResponse(attributeList); + } catch (Exception e) { + return null; + } + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } + + private class DummyPipFinderPipException implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + throw new PIPException(); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } + + private class DummyPipFinderResponseStatusNok implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + Status status = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Processing Error"); + return new StdPIPResponse(status); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } + + private class DummyPipFinderResponseEmptyAttrs implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + List attributeList = new ArrayList<>(); + return new StdPIPResponse(attributeList); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection getPIPEngines() { + return null; + } + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java index fa4acf7ec..7c9aae7b4 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java @@ -20,7 +20,8 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.UUID; @@ -28,26 +29,26 @@ import org.junit.Test; public class PolicyGuardRequestTest { - @Test - public void policyGuardRequestTest() { - UUID requestId = UUID.randomUUID(); - - assertNotNull(new PolicyGuardRequest(null, null, null, null)); - - PolicyGuardRequest request = new PolicyGuardRequest("Dorothy", "Kansas", requestId, "GetBackHome"); - - request.setRequestID(requestId); - assertEquals(requestId, request.getRequestID()); - - request.setActor("Dorothy"); - assertEquals("Dorothy", request.getActor()); - - request.setTarget("Kansas"); - assertEquals("Kansas", request.getTarget()); - - request.setOperation("GetBackHome"); - assertEquals("GetBackHome", request.getOperation()); - - assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); - } + @Test + public void policyGuardRequestTest() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardRequest(null, null, null, null)); + + PolicyGuardRequest request = new PolicyGuardRequest("Dorothy", "Kansas", requestId, "GetBackHome"); + + request.setRequestID(requestId); + assertEquals(requestId, request.getRequestID()); + + request.setActor("Dorothy"); + assertEquals("Dorothy", request.getActor()); + + request.setTarget("Kansas"); + assertEquals("Kansas", request.getTarget()); + + request.setOperation("GetBackHome"); + assertEquals("GetBackHome", request.getOperation()); + + assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java index fe0155541..f9bd94795 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java @@ -20,7 +20,8 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.UUID; @@ -28,23 +29,23 @@ import org.junit.Test; public class PolicyGuardResponseTest { - @Test - public void policyGuardResponseTest() { - UUID requestId = UUID.randomUUID(); - - assertNotNull(new PolicyGuardResponse(null, null, null)); - - PolicyGuardResponse response = new PolicyGuardResponse("BackHome", requestId, "GetBackHome"); - - response.setRequestID(requestId); - assertEquals(requestId, response.getRequestID()); - - response.setResult("BackHome"); - assertEquals("BackHome", response.getResult()); - - response.setOperation("GetBackHome"); - assertEquals("GetBackHome", response.getOperation()); - - assertEquals("PolicyGuardResponse [requestID=", response.toString().substring(0, 31)); - } + @Test + public void policyGuardResponseTest() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardResponse(null, null, null)); + + PolicyGuardResponse response = new PolicyGuardResponse("BackHome", requestId, "GetBackHome"); + + response.setRequestID(requestId); + assertEquals(requestId, response.getRequestID()); + + response.setResult("BackHome"); + assertEquals("BackHome", response.getResult()); + + response.setOperation("GetBackHome"); + assertEquals("GetBackHome", response.getOperation()); + + assertEquals("PolicyGuardResponse [requestID=", response.toString().substring(0, 31)); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java index 82656fa09..9c85845b5 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertEquals; @@ -35,201 +36,205 @@ import org.onap.policy.guard.impl.VMTargetLock; import org.onap.policy.guard.impl.VNFTargetLock; public class PolicyGuardTest { - private static final String INSTANCENAME = "targetInstance"; - - private class DummyLockCallback implements LockCallback { - @Override - public boolean isActive() { - return false; - } - @Override - public boolean releaseLock() { - return false; - } - } - - private class DummyTargetLock implements TargetLock { - @Override - public UUID getLockID() { - return null; - } - @Override - public TargetType getTargetType() { - return null; - } - @Override - public String getTargetInstance() { - return INSTANCENAME; - } - @Override - public UUID getRequestID() { - return null; - } - } - - @Test - public void testLockVM() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VM; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VMTargetLock.class, result.getB().getClass()); - - VMTargetLock vtl = (VMTargetLock) result.getB(); - assertNotNull(vtl.getLockID()); - assertEquals(INSTANCENAME, vtl.getTargetInstance()); - assertEquals(TargetType.VM, vtl.getTargetType()); - assertNotNull(vtl.getRequestID()); - assertEquals(dlcb, vtl.getCallback()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testLockPNF() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.PNF; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(PNFTargetLock.class, result.getB().getClass()); - - PNFTargetLock ptl = (PNFTargetLock) result.getB(); - assertNotNull(ptl.getLockID()); - assertEquals(INSTANCENAME, ptl.getTargetInstance()); - assertEquals(TargetType.PNF, ptl.getTargetType()); - assertNotNull(ptl.getRequestID()); - assertEquals(dlcb, ptl.getCallback()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - - @Test - public void testLockVNF() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VNF; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VNFTargetLock.class, result.getB().getClass()); - - VNFTargetLock vtl = (VNFTargetLock) result.getB(); - assertNotNull(vtl.getLockID()); - assertEquals(INSTANCENAME, vtl.getTargetInstance()); - assertEquals(TargetType.VNF, vtl.getTargetType()); - assertNotNull(vtl.getRequestID()); - assertEquals(dlcb, vtl.getCallback()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testLockVFC() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VFC; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_EXCEPTION, result.getA()); - assertNull(result.getB()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testUnLockNotLocked() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VM; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VMTargetLock.class, result.getB().getClass()); - - result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_DENIED, result.getA()); - assertNull(result.getB()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - // Test unlock after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testLockAlreadyLocked() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VM; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VMTargetLock.class, result.getB().getClass()); - - result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_DENIED, result.getA()); - assertNull(result.getB()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testInnards() { - - DummyLockCallback dlcb = new DummyLockCallback(); - assertFalse(dlcb.isActive()); - assertFalse(dlcb.releaseLock()); - - DummyTargetLock dtl = new DummyTargetLock(); - assertNull(dtl.getLockID()); - assertNull(dtl.getRequestID()); - assertEquals(INSTANCENAME, dtl.getTargetInstance()); - assertNull(dtl.getTargetType()); - } + private static final String INSTANCENAME = "targetInstance"; + + private class DummyLockCallback implements LockCallback { + @Override + public boolean isActive() { + return false; + } + + @Override + public boolean releaseLock() { + return false; + } + } + + private class DummyTargetLock implements TargetLock { + @Override + public UUID getLockID() { + return null; + } + + @Override + public TargetType getTargetType() { + return null; + } + + @Override + public String getTargetInstance() { + return INSTANCENAME; + } + + @Override + public UUID getRequestID() { + return null; + } + } + + @Test + public void testLockVm() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VM; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VMTargetLock.class, result.getB().getClass()); + + VMTargetLock vtl = (VMTargetLock) result.getB(); + assertNotNull(vtl.getLockID()); + assertEquals(INSTANCENAME, vtl.getTargetInstance()); + assertEquals(TargetType.VM, vtl.getTargetType()); + assertNotNull(vtl.getRequestID()); + assertEquals(dlcb, vtl.getCallback()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testLockPnf() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.PNF; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(PNFTargetLock.class, result.getB().getClass()); + + PNFTargetLock ptl = (PNFTargetLock) result.getB(); + assertNotNull(ptl.getLockID()); + assertEquals(INSTANCENAME, ptl.getTargetInstance()); + assertEquals(TargetType.PNF, ptl.getTargetType()); + assertNotNull(ptl.getRequestID()); + assertEquals(dlcb, ptl.getCallback()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + + @Test + public void testLockVnf() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VNF; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VNFTargetLock.class, result.getB().getClass()); + + VNFTargetLock vtl = (VNFTargetLock) result.getB(); + assertNotNull(vtl.getLockID()); + assertEquals(INSTANCENAME, vtl.getTargetInstance()); + assertEquals(TargetType.VNF, vtl.getTargetType()); + assertNotNull(vtl.getRequestID()); + assertEquals(dlcb, vtl.getCallback()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testLockVfc() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VFC; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_EXCEPTION, result.getA()); + assertNull(result.getB()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testUnLockNotLocked() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VM; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VMTargetLock.class, result.getB().getClass()); + + result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_DENIED, result.getA()); + assertNull(result.getB()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + // Test unlock after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testLockAlreadyLocked() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VM; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VMTargetLock.class, result.getB().getClass()); + + result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_DENIED, result.getA()); + assertNull(result.getB()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testInnards() { + + DummyLockCallback dlcb = new DummyLockCallback(); + assertFalse(dlcb.isActive()); + assertFalse(dlcb.releaseLock()); + + DummyTargetLock dtl = new DummyTargetLock(); + assertNull(dtl.getLockID()); + assertNull(dtl.getRequestID()); + assertEquals(INSTANCENAME, dtl.getTargetInstance()); + assertNull(dtl.getTargetType()); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java index 10c6d7239..40123a4bb 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertEquals; @@ -24,20 +25,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.drools.http.server.HttpServletServer; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.LoggerUtil; - import com.att.research.xacml.api.Advice; import com.att.research.xacml.api.Attribute; import com.att.research.xacml.api.AttributeCategory; @@ -57,193 +44,200 @@ import com.att.research.xacml.std.StdResponse; import com.att.research.xacml.std.StdResult; import com.att.research.xacml.std.StdStatus; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.drools.http.server.HttpServletServer; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.LoggerUtil; + public class PolicyGuardXacmlHelperTest { - @BeforeClass - public static void setupSimulator() { - LoggerUtil.setLevel("ROOT", "INFO"); - LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - try { - org.onap.policy.simulators.Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - // - // Set guard properties - // - org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", - "python", - "test", - "python", - "test", - "DEVL"); - } - - @AfterClass - /** - * Shuts down simulator and performs 1 more test for the case where the connection fails - */ - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - - // Null/ Bad Connection Case - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); - String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - assertEquals(0, Util.INDETERMINATE.compareToIgnoreCase(rawDecision)); - } - - @Test - public void testSimulator() { - PolicyGuardXacmlRequestAttributes request = new PolicyGuardXacmlRequestAttributes("clname_id", "actor_id", "operation_id", "target_id", "request_id"); - String xacmlResponse = new PolicyGuardXacmlHelper().callPDP(request); - assertNotNull(xacmlResponse); - } - - @Test - /** - * Tests PolicyGuardXacmlHelper.callPDP method to determine if it returns DENY, PERMIT, or INDETERMINATE - * as expected. - */ - public void testCallPDP() { - // Deny Case - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); - String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - assertTrue(0 == Util.DENY.compareToIgnoreCase(rawDecision)); - - // Permit Case - xacmlReq = new PolicyGuardXacmlRequestAttributes( - "clname", "actor", "recipe", "target", "requestId"); - rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - assertEquals(0, Util.PERMIT.compareToIgnoreCase(rawDecision)); - - // Indeterminate case is in tearDown for efficiency - } - - @Test - /** - * Tests PolicyGuardXacmlHelper.callPDP method to exercise all branches - */ - public void testCallPDPExtra() { - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); - - xacmlReq.setClnameID(null); - String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - assertEquals(-5, Util.DENY.compareToIgnoreCase(rawDecision)); - - org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", - "", - "", - "", - "", - ""); - - rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - - org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", - "python", - "test", - "python", - "test", - "DEVL"); - - } - - @Test - public void testParseXACMLPDPResponse() throws URISyntaxException { - PolicyGuardResponse pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(null); - assertEquals("Indeterminate", pgResponse.getResult()); - - Decision decision = Decision.PERMIT; - Status status = new StdStatus(StdStatus.STATUS_OK); - Result result = new StdResult(decision, status); - Response xacmlResponse = new StdResponse(result); - pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(xacmlResponse); - assertEquals("Permit", pgResponse.getResult()); - - - Collection obligationsIn = null; - Collection adviceIn = null; - Collection policyIdentifiersIn = null; - Collection policySetIdentifiersIn = null; - - Collection attributesIn = new ArrayList<>(); - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow")); - Collection listAttributes = new ArrayList<>(); - Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); - Identifier attributeIdIn0 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:request:request-id")); - Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow.dataType")); - AttributeValue valueIn = new StdAttributeValue(dataTypeIdIn, UUID.randomUUID().toString()); - Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn); - listAttributes.add(attribute0); - - Identifier attributeIdIn1 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:operation:operation-id")); - Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn); - listAttributes.add(attribute1); - attributesIn.add(new StdAttributeCategory(identifierCategory , listAttributes)); - - Identifier attributeIdIn2 = new IdentifierImpl(new URI("Http://somewhere.over.the.rainbow/attributeId")); - Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn); - listAttributes.add(attribute2); - attributesIn.add(new StdAttributeCategory(identifierCategory , listAttributes)); - - Result fullResult = new StdResult(Decision.DENY, obligationsIn, adviceIn, attributesIn, policyIdentifiersIn, policySetIdentifiersIn); - Response fullXacmlResponse = new StdResponse(fullResult); - PolicyGuardResponse fullPGResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(fullXacmlResponse); - assertEquals("Deny", fullPGResponse.getResult()); - } - - @Test - public void testInit() { - Properties savedEnvironment = (Properties) PolicyEngine.manager.getEnvironment().clone(); - - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision,Dorothy"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision"); - - PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "1000"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().remove("pdpx.password"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("pdpx.username", "python"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().remove("pdpx.client.password"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().remove("pdpx.client.username"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "///"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", ""); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", "true"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().clear(); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.setEnvironment(savedEnvironment); - } + /** + * Set up test class. + */ + @BeforeClass + public static void setupSimulator() { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + try { + org.onap.policy.simulators.Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + // + // Set guard properties + // + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", "python", "test", + "python", "test", "DEVL"); + } + + /** + * Shuts down simulator and performs 1 more test for the case where the connection fails. + */ + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + + // Null/ Bad Connection Case + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); + String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + assertEquals(0, Util.INDETERMINATE.compareToIgnoreCase(rawDecision)); + } + + @Test + public void testSimulator() { + PolicyGuardXacmlRequestAttributes request = new PolicyGuardXacmlRequestAttributes("clname_id", "actor_id", + "operation_id", "target_id", "request_id"); + String xacmlResponse = new PolicyGuardXacmlHelper().callPDP(request); + assertNotNull(xacmlResponse); + } + + @Test + /** + * Tests PolicyGuardXacmlHelper.callPDP method to determine if it returns DENY, PERMIT, or + * INDETERMINATE as expected. + */ + public void testCallPdp() { + // Deny Case + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); + String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + assertTrue(0 == Util.DENY.compareToIgnoreCase(rawDecision)); + + // Permit Case + xacmlReq = new PolicyGuardXacmlRequestAttributes("clname", "actor", "recipe", "target", "requestId"); + rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + assertEquals(0, Util.PERMIT.compareToIgnoreCase(rawDecision)); + + // Indeterminate case is in tearDown for efficiency + } + + @Test + /** + * Tests PolicyGuardXacmlHelper.callPDP method to exercise all branches + */ + public void testCallPdpExtra() { + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); + + xacmlReq.setClnameID(null); + String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + assertEquals(-5, Util.DENY.compareToIgnoreCase(rawDecision)); + + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", "", "", "", "", ""); + + rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", "python", "test", + "python", "test", "DEVL"); + + } + + @Test + public void testParseXacmlPdpResponse() throws URISyntaxException { + PolicyGuardResponse pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(null); + assertEquals("Indeterminate", pgResponse.getResult()); + + Decision decision = Decision.PERMIT; + Status status = new StdStatus(StdStatus.STATUS_OK); + Result result = new StdResult(decision, status); + Response xacmlResponse = new StdResponse(result); + pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(xacmlResponse); + assertEquals("Permit", pgResponse.getResult()); + + + final Collection obligationsIn = null; + final Collection adviceIn = null; + final Collection policyIdentifiersIn = null; + final Collection policySetIdentifiersIn = null; + + Collection attributesIn = new ArrayList<>(); + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow")); + Collection listAttributes = new ArrayList<>(); + Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); + Identifier attributeIdIn0 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:request:request-id")); + Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow.dataType")); + AttributeValue valueIn = new StdAttributeValue(dataTypeIdIn, UUID.randomUUID().toString()); + Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn); + listAttributes.add(attribute0); + + Identifier attributeIdIn1 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:operation:operation-id")); + Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn); + listAttributes.add(attribute1); + attributesIn.add(new StdAttributeCategory(identifierCategory, listAttributes)); + + Identifier attributeIdIn2 = new IdentifierImpl(new URI("Http://somewhere.over.the.rainbow/attributeId")); + Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn); + listAttributes.add(attribute2); + attributesIn.add(new StdAttributeCategory(identifierCategory, listAttributes)); + + Result fullResult = new StdResult(Decision.DENY, obligationsIn, adviceIn, attributesIn, policyIdentifiersIn, + policySetIdentifiersIn); + Response fullXacmlResponse = new StdResponse(fullResult); + PolicyGuardResponse fullPgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(fullXacmlResponse); + assertEquals("Deny", fullPgResponse.getResult()); + } + + @Test + public void testInit() { + final Properties savedEnvironment = (Properties) PolicyEngine.manager.getEnvironment().clone(); + + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", + "http://localhost:6669/pdp/api/getDecision,Dorothy"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", + "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision"); + + PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "1000"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().remove("pdpx.password"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("pdpx.username", "python"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().remove("pdpx.client.password"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().remove("pdpx.client.username"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", "///"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", ""); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", "true"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().clear(); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.setEnvironment(savedEnvironment); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java index d07a97a67..a61f5200b 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java @@ -20,7 +20,8 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.UUID; @@ -28,37 +29,37 @@ import org.junit.Test; public class PolicyGuardXacmlRequestAttributesTest { - @Test - public void policyGuardXacmlRequestAttributesTest() { - assertNotNull(new PolicyGuardXacmlRequestAttributes(null, null, null, null, null)); - - UUID controlLoopID = UUID.randomUUID(); - UUID operationID = UUID.randomUUID(); - UUID requestID = UUID.randomUUID(); - UUID actorID = UUID.randomUUID(); - UUID targetID = UUID.randomUUID(); - - PolicyGuardXacmlRequestAttributes attributes = new PolicyGuardXacmlRequestAttributes( - controlLoopID.toString(), actorID.toString(), operationID.toString(), targetID.toString(), requestID.toString()); - - attributes.setRequestID(requestID.toString()); - assertEquals(requestID.toString(), attributes.getRequestID()); - - attributes.setOperationID(operationID.toString()); - assertEquals(operationID.toString(), attributes.getOperationID()); - - attributes.setActorID(actorID.toString()); - assertEquals(actorID.toString(), attributes.getActorID()); - - attributes.setTargetID(targetID.toString()); - assertEquals(targetID.toString(), attributes.getTargetID()); - - attributes.setTargetID(targetID.toString()); - assertEquals(targetID.toString(), attributes.getTargetID()); - - attributes.setClnameID(controlLoopID.toString()); - assertEquals(controlLoopID.toString(), attributes.getClnameID()); - - assertEquals("PolicyGuardXacmlRequestAttributes [actorID=", attributes.toString().substring(0, 43)); - } + @Test + public void policyGuardXacmlRequestAttributesTest() { + assertNotNull(new PolicyGuardXacmlRequestAttributes(null, null, null, null, null)); + + UUID controlLoopId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID actorId = UUID.randomUUID(); + UUID targetId = UUID.randomUUID(); + + PolicyGuardXacmlRequestAttributes attributes = new PolicyGuardXacmlRequestAttributes(controlLoopId.toString(), + actorId.toString(), operationId.toString(), targetId.toString(), requestId.toString()); + + attributes.setRequestID(requestId.toString()); + assertEquals(requestId.toString(), attributes.getRequestID()); + + attributes.setOperationID(operationId.toString()); + assertEquals(operationId.toString(), attributes.getOperationID()); + + attributes.setActorID(actorId.toString()); + assertEquals(actorId.toString(), attributes.getActorID()); + + attributes.setTargetID(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetID()); + + attributes.setTargetID(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetID()); + + attributes.setClnameID(controlLoopId.toString()); + assertEquals(controlLoopId.toString(), attributes.getClnameID()); + + assertEquals("PolicyGuardXacmlRequestAttributes [actorID=", attributes.toString().substring(0, 43)); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java index b35356438..3b517bcc1 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertFalse; @@ -40,192 +41,199 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class PolicyGuardYamlToXacmlTest { - private ControlLoopGuard clGuard; - - @Before - public void createControlLoopGuard() { - clGuard = new ControlLoopGuard(); - GuardPolicy guardPolicy = new GuardPolicy(); - MatchParameters matchParameters = new MatchParameters(); - matchParameters.setControlLoopName("WizardOfOz"); - matchParameters.setActor("Dorothy"); - matchParameters.setRecipe("GoToOz"); - List targets = new ArrayList<>(); - targets.add("Wizard"); - targets.add("WickedWitchOfTheWest"); - matchParameters.setTargets(targets ); - guardPolicy.setMatch_parameters(matchParameters ); - Constraint limitConstraint = new Constraint(); - limitConstraint.setFreq_limit_per_target(5); - Map timeWindow = new HashMap<>(); - timeWindow.put("value", "10"); - timeWindow.put("units", "hours"); - limitConstraint.setTime_window(timeWindow); - Map activeTimeRange = new HashMap<>(); - activeTimeRange.put("start", "someStartTime"); - activeTimeRange.put("end", "someEndTime"); - limitConstraint.setActive_time_range(activeTimeRange ); - LinkedList limitConstraints = new LinkedList<>(); - limitConstraints.add(limitConstraint); - guardPolicy.setLimit_constraints(limitConstraints); - LinkedList guardList = new LinkedList<>(); - guardList.add(guardPolicy); - clGuard.setGuards(guardList); - } - - @Test - public void testGenerateXacmlGuardFull() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacml(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("cl")); - assertTrue(result.contains("actor")); - assertTrue(result.contains("GoToOz")); - assertTrue(result.contains("Wizard")); - assertTrue(result.contains("WickedWitchOfTheWest")); - assertTrue(result.contains("10")); - assertTrue(result.contains("hours")); - assertTrue(result.contains("someStartTime")); - assertTrue(result.contains("someEndTime")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } - - @Test - public void testGenerateXacmlGuardPartial() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); - clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); - clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); - clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacml(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("cl")); - assertTrue(result.contains("actor")); - assertFalse(result.contains("GoToOz")); - assertFalse(result.contains("Wizard")); - assertFalse(result.contains("WickedWitchOfTheWest")); - assertTrue(result.contains("10")); - assertTrue(result.contains("hours")); - assertTrue(result.contains("someStartTime")); - assertTrue(result.contains("someEndTime")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } - - @Test - public void testIsNullOrEmpty() { - assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty("")); - assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(null)); - assertFalse(PolicyGuardYamlToXacml.isNullOrEmpty("hello")); - } - - @Test - public void testIsNullOrEmptyList() { - List l = new ArrayList<>(); - assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(null)); - assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(l)); - - l.add("hello"); - assertFalse(PolicyGuardYamlToXacml.isNullOrEmptyList(l)); - } - - @Test - public void testFromYamlToXacmlBlacklist() { - //fail("Not yet implemented"); - } - - @Test - public void testGenerateXacmlGuardBlacklist() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/blacklist_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - List blacklist = new ArrayList<>(); - blacklist.add("WestWitches"); - blacklist.add("EastWitches"); - clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist ); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - System.err.println(result); - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("WestWitches")); - assertTrue(result.contains("EastWitches")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } - - @Test - public void testGenerateXacmlGuardBlacklistPartial() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/blacklist_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - List blacklist = new ArrayList<>(); - blacklist.add("WestWitches"); - blacklist.add("EastWitches"); - clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist ); - - clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); - clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); - clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); - clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - System.err.println(result); - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("WestWitches")); - assertTrue(result.contains("EastWitches")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } + private ControlLoopGuard clGuard; + + /** + * Set up test cases. + */ + @Before + public void createControlLoopGuard() { + clGuard = new ControlLoopGuard(); + MatchParameters matchParameters = new MatchParameters(); + matchParameters.setControlLoopName("WizardOfOz"); + matchParameters.setActor("Dorothy"); + matchParameters.setRecipe("GoToOz"); + List targets = new ArrayList<>(); + targets.add("Wizard"); + targets.add("WickedWitchOfTheWest"); + matchParameters.setTargets(targets); + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setMatch_parameters(matchParameters); + Constraint limitConstraint = new Constraint(); + limitConstraint.setFreq_limit_per_target(5); + Map timeWindow = new HashMap<>(); + timeWindow.put("value", "10"); + timeWindow.put("units", "hours"); + limitConstraint.setTime_window(timeWindow); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("start", "someStartTime"); + activeTimeRange.put("end", "someEndTime"); + limitConstraint.setActive_time_range(activeTimeRange); + LinkedList limitConstraints = new LinkedList<>(); + limitConstraints.add(limitConstraint); + guardPolicy.setLimit_constraints(limitConstraints); + LinkedList guardList = new LinkedList<>(); + guardList.add(guardPolicy); + clGuard.setGuards(guardList); + } + + @Test + public void testGenerateXacmlGuardFull() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("cl")); + assertTrue(result.contains("actor")); + assertTrue(result.contains("GoToOz")); + assertTrue(result.contains("Wizard")); + assertTrue(result.contains("WickedWitchOfTheWest")); + assertTrue(result.contains("10")); + assertTrue(result.contains("hours")); + assertTrue(result.contains("someStartTime")); + assertTrue(result.contains("someEndTime")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } + + @Test + public void testGenerateXacmlGuardPartial() throws IOException { + final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); + clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); + clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); + clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("cl")); + assertTrue(result.contains("actor")); + assertFalse(result.contains("GoToOz")); + assertFalse(result.contains("Wizard")); + assertFalse(result.contains("WickedWitchOfTheWest")); + assertTrue(result.contains("10")); + assertTrue(result.contains("hours")); + assertTrue(result.contains("someStartTime")); + assertTrue(result.contains("someEndTime")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } + + @Test + public void testIsNullOrEmpty() { + assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty("")); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(null)); + assertFalse(PolicyGuardYamlToXacml.isNullOrEmpty("hello")); + } + + @Test + public void testIsNullOrEmptyList() { + List list = new ArrayList<>(); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(null)); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); + + list.add("hello"); + assertFalse(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); + } + + @Test + public void testFromYamlToXacmlBlacklist() { + // fail("Not yet implemented"); + } + + @Test + public void testGenerateXacmlGuardBlacklist() throws IOException { + final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + List blacklist = new ArrayList<>(); + blacklist.add("WestWitches"); + blacklist.add("EastWitches"); + clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + System.err.println(result); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("WestWitches")); + assertTrue(result.contains("EastWitches")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } + + @Test + public void testGenerateXacmlGuardBlacklistPartial() throws IOException { + final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + List blacklist = new ArrayList<>(); + blacklist.add("WestWitches"); + blacklist.add("EastWitches"); + clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist); + + clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); + clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); + clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); + clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + System.err.println(result); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("WestWitches")); + assertTrue(result.contains("EastWitches")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java index 21b75ed20..46a2762cc 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java @@ -26,8 +26,8 @@ import java.io.FileOutputStream; import java.io.IOException; /** - * The Class TextFileUtils is class that provides useful functions for handling text files. Functions to read and wrtie text files to strings and strings are - * provided. + * The Class TextFileUtils is class that provides useful functions for handling text files. + * Functions to read and wrtie text files to strings and strings are provided. * * @author Liam Fallon (liam.fallon@ericsson.com) */ -- cgit 1.2.3-korg