diff options
Diffstat (limited to 'controlloop')
44 files changed, 3936 insertions, 3467 deletions
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<PIPRequest> attributesRequired() { - return Collections.emptySet(); - } - - @Override - public Collection<PIPRequest> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); - Set<String> setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator<AttributeValue<String>> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); - Set<String> setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator<AttributeValue<String>> 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<BigInteger> attributeValue = null; - try { - attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); - } catch (Exception ex) { - logger.error("Failed to convert {} to an AttributeValue<Boolean>",value, ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); - } - } - - private Set<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); - Set<String> setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator<AttributeValue<String>> 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<PIPRequest> attributesRequired() { + return Collections.emptySet(); + } + + @Override + public Collection<PIPRequest> 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<String> 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<Attribute> listAttUids = pipResponseAttUid.getAttributes(); + Set<String> setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator<AttributeValue<String>> 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<String> 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<Attribute> listAttUids = pipResponseAttUid.getAttributes(); + Set<String> setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator<AttributeValue<String>> 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<BigInteger> attributeValue = null; + try { + attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + } catch (Exception ex) { + logger.error("Failed to convert {} to an AttributeValue<Boolean>", value, ex); + } + if (attributeValue != null) { + stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, + pipRequest.getIssuer()/* this.getIssuer() */, false)); + } + } + + private Set<String> 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<Attribute> listAttUids = pipResponseAttUid.getAttributes(); + Set<String> setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator<AttributeValue<String>> 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<String, TargetLock> activeLocks = new HashMap<>(); - private static final Logger logger = LoggerFactory.getLogger(PolicyGuard.class); + private PolicyGuard() { + // Cannot instantiate this static class + } + + private static Map<String, TargetLock> activeLocks = new HashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(PolicyGuard.class); + + public static class LockResult<A, B> { + private A parameterA; + private B parameterB; + + public static <A, B> LockResult<A, B> 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<GuardResult, TargetLock> 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<A, B> { - private A a; - private B b; - - public static <A, B> LockResult<A, B> 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<GuardResult, TargetLock> 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 <code>true</code> if the target is successfully unlocked, <code>false</code> + * 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 <code>true</code> if the target is locked, <code>false</code> 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<Result> itRes = xacmlResponse.getResults().iterator(); - - Result res = itRes.next(); - String decisionFromXACMLResponse = res.getDecision().toString(); - Iterator<AttributeCategory> itAttrCat = res.getAttributes().iterator(); - UUID reqIDFromXACMLResponse = null; - String operationFromXACMLResponse = ""; - - while (itAttrCat.hasNext()) { - Iterator<Attribute> 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<AttributeValue<?>> 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<AttributeValue<?>> 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<URLEntry> 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<URLEntry> initEntries(Properties properties, StringBuilder sb) { - // now, see which numeric entries (1-9) exist - ArrayList<URLEntry> 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<Result> itRes = xacmlResponse.getResults().iterator(); + + Result res = itRes.next(); + String decisionFromXacmlResponse = res.getDecision().toString(); + Iterator<AttributeCategory> itAttrCat = res.getAttributes().iterator(); + UUID reqIdFromXacmlResponse = null; + String operationFromXacmlResponse = ""; + + while (itAttrCat.hasNext()) { + Iterator<Attribute> 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<AttributeValue<?>> 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<AttributeValue<?>> 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<UrlEntry> 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<UrlEntry> initEntries(Properties properties, StringBuilder sb) { + // now, see which numeric entries (1-9) exist + ArrayList<UrlEntry> 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<String> 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("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" - + target - + "</AttributeValue>" - + "\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<String> 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("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + target + + "</AttributeValue>" + "\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<A, B> { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } - - public static Pair<ControlLoopPolicy, String> 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<A, B> { + 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<ControlLoopPolicy, String> 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<ControlLoopPolicy, String> 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<ControlLoopPolicy, String> 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<Attribute> 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<String> valueIn0 = new StdAttributeValue<String>(dataTypeIdIn, "ActorDorothy"); - Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); - attributeList.add(attribute0); - - Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue<String> valueIn1 = new StdAttributeValue<String>(dataTypeIdIn, "OperationHomeFromOZ"); - Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); - attributeList.add(attribute1); - - Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue<String> valueIn2 = new StdAttributeValue<String>(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<PIPEngine> 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<PIPEngine> 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<PIPEngine> 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<Attribute> 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<PIPEngine> 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<Attribute> 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<String> valueIn0 = new StdAttributeValue<String>(dataTypeIdIn, "ActorDorothy"); + Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); + attributeList.add(attribute0); + + Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue<String> valueIn1 = new StdAttributeValue<String>(dataTypeIdIn, "OperationHomeFromOZ"); + Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); + attributeList.add(attribute1); + + Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue<String> valueIn2 = new StdAttributeValue<String>(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<PIPEngine> 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<PIPEngine> 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<PIPEngine> 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<Attribute> attributeList = new ArrayList<>(); + return new StdPIPResponse(attributeList); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection<PIPEngine> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<GuardResult, TargetLock> 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<Obligation> obligationsIn = null; - Collection<Advice> adviceIn = null; - Collection<IdReference> policyIdentifiersIn = null; - Collection<IdReference> policySetIdentifiersIn = null; - - Collection<AttributeCategory> attributesIn = new ArrayList<>(); - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow")); - Collection<Attribute> 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<String> valueIn = new StdAttributeValue<String>(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<Obligation> obligationsIn = null; + final Collection<Advice> adviceIn = null; + final Collection<IdReference> policyIdentifiersIn = null; + final Collection<IdReference> policySetIdentifiersIn = null; + + Collection<AttributeCategory> attributesIn = new ArrayList<>(); + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow")); + Collection<Attribute> 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<String> valueIn = new StdAttributeValue<String>(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<String> 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<String, String> timeWindow = new HashMap<>(); - timeWindow.put("value", "10"); - timeWindow.put("units", "hours"); - limitConstraint.setTime_window(timeWindow); - Map<String, String> activeTimeRange = new HashMap<>(); - activeTimeRange.put("start", "someStartTime"); - activeTimeRange.put("end", "someEndTime"); - limitConstraint.setActive_time_range(activeTimeRange ); - LinkedList<Constraint> limitConstraints = new LinkedList<>(); - limitConstraints.add(limitConstraint); - guardPolicy.setLimit_constraints(limitConstraints); - LinkedList<GuardPolicy> 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<String> 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<String> 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<String> 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<String> 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<String, String> timeWindow = new HashMap<>(); + timeWindow.put("value", "10"); + timeWindow.put("units", "hours"); + limitConstraint.setTime_window(timeWindow); + Map<String, String> activeTimeRange = new HashMap<>(); + activeTimeRange.put("start", "someStartTime"); + activeTimeRange.put("end", "someEndTime"); + limitConstraint.setActive_time_range(activeTimeRange); + LinkedList<Constraint> limitConstraints = new LinkedList<>(); + limitConstraints.add(limitConstraint); + guardPolicy.setLimit_constraints(limitConstraints); + LinkedList<GuardPolicy> 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<String> 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<String> 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<String> 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) */ diff --git a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceException.java b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceException.java deleted file mode 100644 index 2342e1695..000000000 --- a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceException.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright 2017 ZTE, Inc. and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ - -package org.onap.policy.msb.client; - -public class MSBServiceException extends Exception { - private static final long serialVersionUID = 5227416822833497317L; - - public MSBServiceException() { - super(); - } - - public MSBServiceException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - - public MSBServiceException(String message, Throwable cause) { - super(message, cause); - } - - public MSBServiceException(String message) { - super(message); - } - - public MSBServiceException(Throwable cause) { - super(cause); - } - -} diff --git a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceException.java b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceException.java new file mode 100644 index 000000000..ebd2e32ff --- /dev/null +++ b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceException.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright 2017-2018 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.msb.client; + +public class MsbServiceException extends Exception { + private static final long serialVersionUID = 5227416822833497317L; + + public MsbServiceException() { + super(); + } + + public MsbServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public MsbServiceException(String message, Throwable cause) { + super(message, cause); + } + + public MsbServiceException(String message) { + super(message); + } + + public MsbServiceException(Throwable cause) { + super(cause); + } + +} diff --git a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceFactory.java b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceFactory.java index 7ebb5d6dc..91e36c01d 100644 --- a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceFactory.java +++ b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceFactory.java @@ -1,106 +1,122 @@ -/*******************************************************************************
- * Copyright 2017 ZTE, Inc. and others.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- ******************************************************************************/
-package org.onap.policy.msb.client;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Properties;
-
-import org.onap.msb.sdk.discovery.common.RouteException;
-import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo;
-import org.onap.msb.sdk.discovery.entity.NodeInfo;
-import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class MSBServiceFactory implements Serializable {
- private static final long serialVersionUID = 4638414146278012425L;
- private static final Logger logger = LoggerFactory.getLogger(MSBServiceFactory.class);
- private static final String MSB_PROPERTY_FILE = "msb.policy.properties";
- private static final String MSB_IP = "msb.ip";
- private static final String MSB_PORT = "msb.port";
- private transient MSBServiceClient msbClient;
- private Properties properties;
-
- public MSBServiceFactory() throws MSBServiceException,IOException{
- this.init();
- this.msbClient = new MSBServiceClient(properties.getProperty(MSB_IP), Integer.parseInt(properties.getProperty(MSB_PORT)));
- }
- public MSBServiceFactory (MSBServiceClient msbClient) {
- this.msbClient = msbClient;
- }
-
- private void init() throws MSBServiceException,IOException {
- properties = new Properties();
- String propertyFilePath = System.getProperty(MSB_PROPERTY_FILE);
- if (propertyFilePath == null) {
- throw new MSBServiceException("No msb.policy.properties specified.");
- }
- Path file = Paths.get(propertyFilePath);
- if (!file.toFile().exists()) {
- throw new MSBServiceException("No msb.policy.properties specified.");
- }
-
- if (!Files.isReadable(file)) {
- throw new MSBServiceException ("Repository is NOT readable: " + file.toAbsolutePath());
- }
- try(InputStream is = new FileInputStream(file.toFile())){
- properties.load(is);
- }
- }
-
-
- public Node getNode(String serviceName,String version){
- return this.build(serviceName,version);
- }
-
- public Node getNode(String actor){
- Node node = null;
- switch (actor) {
- case "AAI":
- node = this.build("aai-search","v11");
- return node;
- case "SO":
- node = this.build("so","v2");
- return node;
- case "VFC":
- node = this.build("nfvo-nslcm","v1");
- return node;
- default:
- logger.info("MSBServiceManager: policy has an unknown actor.");
- }
- return node;
- }
-
- private Node build(String serviceName,String version){
- Node node = new Node();
- node.setName(serviceName);
- try {
- MicroServiceFullInfo serviceInfo = msbClient.queryMicroServiceInfo(serviceName,version);
- for (NodeInfo nodeInfo: serviceInfo.getNodes()){
- node.setIp(nodeInfo.getIp());
- node.setPort(nodeInfo.getPort());
- }
- } catch (RouteException e) {
- logger.info("MSBServiceManager:",e);
- }
- return node;
- }
-}
+/*- + * ============LICENSE_START======================================================= + * Copyright 2017-2018 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.msb.client; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; + +import org.onap.msb.sdk.discovery.common.RouteException; +import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo; +import org.onap.msb.sdk.discovery.entity.NodeInfo; +import org.onap.msb.sdk.httpclient.msb.MSBServiceClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MsbServiceFactory implements Serializable { + private static final long serialVersionUID = 4638414146278012425L; + private static final Logger logger = LoggerFactory.getLogger(MsbServiceFactory.class); + private static final String MSB_PROPERTY_FILE = "msb.policy.properties"; + private static final String MSB_IP = "msb.ip"; + private static final String MSB_PORT = "msb.port"; + private transient MSBServiceClient msbClient; + private Properties properties; + + /** + * Construct an instance. + * + * @throws MsbServiceException if an error occurs + * @throws IOException if an IO error occurs + */ + public MsbServiceFactory() throws MsbServiceException, IOException { + this.init(); + this.msbClient = new MSBServiceClient(properties.getProperty(MSB_IP), + Integer.parseInt(properties.getProperty(MSB_PORT))); + } + + public MsbServiceFactory(MSBServiceClient msbClient) { + this.msbClient = msbClient; + } + + private void init() throws MsbServiceException, IOException { + properties = new Properties(); + String propertyFilePath = System.getProperty(MSB_PROPERTY_FILE); + if (propertyFilePath == null) { + throw new MsbServiceException("No msb.policy.properties specified."); + } + Path file = Paths.get(propertyFilePath); + if (!file.toFile().exists()) { + throw new MsbServiceException("No msb.policy.properties specified."); + } + + if (!Files.isReadable(file)) { + throw new MsbServiceException("Repository is NOT readable: " + file.toAbsolutePath()); + } + try (InputStream is = new FileInputStream(file.toFile())) { + properties.load(is); + } + } + + + public Node getNode(String serviceName, String version) { + return this.build(serviceName, version); + } + + /** + * Get the node for the given actor. + * + * @param actor the actor + * @return the node + */ + public Node getNode(String actor) { + Node node = null; + switch (actor) { + case "AAI": + node = this.build("aai-search", "v11"); + return node; + case "SO": + node = this.build("so", "v2"); + return node; + case "VFC": + node = this.build("nfvo-nslcm", "v1"); + return node; + default: + logger.info("MSBServiceManager: policy has an unknown actor."); + } + return node; + } + + private Node build(String serviceName, String version) { + Node node = new Node(); + node.setName(serviceName); + try { + MicroServiceFullInfo serviceInfo = msbClient.queryMicroServiceInfo(serviceName, version); + for (NodeInfo nodeInfo : serviceInfo.getNodes()) { + node.setIp(nodeInfo.getIp()); + node.setPort(nodeInfo.getPort()); + } + } catch (RouteException e) { + logger.info("MSBServiceManager:", e); + } + return node; + } +} diff --git a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceManager.java b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceManager.java index ccb13ece4..aca3ff28f 100644 --- a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MSBServiceManager.java +++ b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/MsbServiceManager.java @@ -1,55 +1,60 @@ -/*******************************************************************************
- * Copyright 2017 ZTE, Inc. and others.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- ******************************************************************************/
-package org.onap.policy.msb.client;
-
-import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;
-
-import java.io.IOException;
-import java.io.Serializable;
-
-public class MSBServiceManager implements Serializable {
- private static final long serialVersionUID = -2517971308551895215L;
- private MSBServiceFactory factory;
-
- public MSBServiceManager() throws MSBServiceException,IOException {
- this.factory = new MSBServiceFactory();
- }
-
- public MSBServiceManager(MSBServiceClient msbClient){
-
- this.factory = new MSBServiceFactory(msbClient);
- }
-
- /**
- * Get the IP and port of the components registered in the MSB
- * @param actor AAI or SO or VFC
- * @return
- */
- public Node getNode(String actor){
-
- return factory.getNode(actor);
- }
-
- /**
- * Get the IP and port of the components registered in the MSB
- * @param serviceName the service name registered in the MSB
- * @param version the service version registered in the MSB
- * @return
- */
- public Node getNode(String serviceName,String version){
-
- return factory.getNode(serviceName,version);
- }
-
-}
+/*- + * ============LICENSE_START======================================================= + * Copyright 2017-2018 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.msb.client; + +import java.io.IOException; +import java.io.Serializable; + +import org.onap.msb.sdk.httpclient.msb.MSBServiceClient; + +public class MsbServiceManager implements Serializable { + private static final long serialVersionUID = -2517971308551895215L; + private MsbServiceFactory factory; + + public MsbServiceManager() throws MsbServiceException, IOException { + this.factory = new MsbServiceFactory(); + } + + public MsbServiceManager(MSBServiceClient msbClient) { + + this.factory = new MsbServiceFactory(msbClient); + } + + /** + * Get the IP and port of the components registered in the MSB. + * + * @param actor AAI or SO or VFC + * @return the node + */ + public Node getNode(String actor) { + + return factory.getNode(actor); + } + + /** + * Get the IP and port of the components registered in the MSB. + * + * @param serviceName the service name registered in the MSB + * @param version the service version registered in the MSB + * @return the node + */ + public Node getNode(String serviceName, String version) { + + return factory.getNode(serviceName, version); + } + +} diff --git a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/Node.java b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/Node.java index 5c06939bf..f42b82e3c 100644 --- a/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/Node.java +++ b/controlloop/common/msb/src/main/java/org/onap/policy/msb/client/Node.java @@ -1,5 +1,6 @@ -/*******************************************************************************
- * Copyright 2017 ZTE, Inc. and others.
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright 2017-2018 ZTE, Inc. and others.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
@@ -10,7 +11,9 @@ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
- ******************************************************************************/
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.policy.msb.client;
import java.io.Serializable;
@@ -47,10 +50,6 @@ public class Node implements Serializable { @Override
public String toString() {
- return "Node{" +
- "name='" + name + '\'' +
- ", ip='" + ip + '\'' +
- ", port='" + port + '\'' +
- '}';
+ return "Node{" + "name='" + name + '\'' + ", ip='" + ip + '\'' + ", port='" + port + '\'' + '}';
}
}
diff --git a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MSBServiceManagerTest.java b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MSBServiceManagerTest.java deleted file mode 100644 index 4edb168f0..000000000 --- a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MSBServiceManagerTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/*******************************************************************************
- * Copyright 2017 ZTE, Inc. and others.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- ******************************************************************************/
-package org.onap.policy.msb.client;
-
-import org.junit.*;
-import org.junit.rules.ExpectedException;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.msb.sdk.discovery.common.RouteException;
-import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo;
-import org.onap.msb.sdk.discovery.entity.NodeInfo;
-import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;
-import org.onap.policy.msb.client.MSBServiceManager;
-import org.onap.policy.msb.client.Node;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.HashSet;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-public class MSBServiceManagerTest {
- @Mock
- private MSBServiceClient msbClient;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- private MSBServiceManager msbManager;
-
- public MSBServiceManagerTest(){}
-
- @BeforeClass
- public static void setUpClass(){}
-
- @AfterClass
- public static void tearDownClass(){}
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- msbManager = new MSBServiceManager(msbClient);
- }
-
- @After
- public void tearDown() {
- }
-
- @Test
- public void testByActor () throws RouteException,UnknownHostException {
- MicroServiceFullInfo serviceInfo = MSBServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(),"8843");
- when(msbClient.queryMicroServiceInfo("aai-search","v11")).thenReturn(serviceInfo);
- Node node = msbManager.getNode("AAI");
- assertNotNull(node);
- serviceInfo = MSBServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(),"8840");
- when(msbClient.queryMicroServiceInfo("so","v2")).thenReturn(serviceInfo);
- node = msbManager.getNode("SO");
- assertNotNull(node);
-
- serviceInfo = MSBServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(),"8082");
- when(msbClient.queryMicroServiceInfo("nfvo-nslcm","v1")).thenReturn(serviceInfo);
- node = msbManager.getNode("VFC");
- assertNotNull(node);
-
- }
-
- @Test
- public void testByActor_when_actorNotExist_returnNull () throws RouteException,UnknownHostException {
- MicroServiceFullInfo serviceInfo = MSBServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(),"8843");
- when(msbClient.queryMicroServiceInfo("aai-search","v11")).thenReturn(serviceInfo);
- Node node = msbManager.getNode("DDD");
- assertNull(node);
- }
-
- @Test
- public void testByServiceNameAndVersion () throws RouteException,UnknownHostException {
- MicroServiceFullInfo serviceInfo = MSBServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(),"8843");
- when(msbClient.queryMicroServiceInfo("aai-search","v11")).thenReturn(serviceInfo);
- Node node = msbManager.getNode("aai-search","v11");
- assertNotNull(node);
- }
-
- @Test
- public void testByServiceNameAndVersion_when_serice_notRegistedToMSB () throws RouteException,UnknownHostException {
- MSBServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(),"8843");
- when(msbClient.queryMicroServiceInfo("aai-search","v11")).thenThrow(new RouteException());
- Node node = msbManager.getNode("aai-search","v11");
- assertNotNull(node);
- assertTrue(node.getName() == "aai-search");
- assertTrue(node.getIp() == null);
- assertTrue(node.getPort() == null);
- }
-
- @Test
- public void testReadMsbPolicyProperites_noPropertyFileSpecifed_throwsException() throws MSBServiceException, IOException {
- expectedException.expect(MSBServiceException.class);
- expectedException.expectMessage("No msb.policy.properties specified.");
- System.clearProperty("msb.policy.properties");
- msbManager = new MSBServiceManager();
- }
-
- @Test
- public void testReadMsbPolicyProperites_propertyFileDoesNotExist_throwsException() throws MSBServiceException, IOException {
- expectedException.expect(MSBServiceException.class);
- expectedException.expectMessage("No msb.policy.properties specified.");
- System.setProperty("msb.policy.properties", "nonExistingPropertyFile.txt");
- msbManager = new MSBServiceManager();
- System.clearProperty("msb.policy.properties");
- }
-
- @Test
- public void testReadMsbPolicyProperites_propertyFileExists() throws MSBServiceException, IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
- System.setProperty("msb.policy.properties", "src/test/resources/msbPropertyFile.properties");
- msbManager = new MSBServiceManager();
- System.clearProperty("msb.policy.properties");
-
- Field factoryField = msbManager.getClass().getDeclaredField("factory");
- factoryField.setAccessible(true);
- MSBServiceFactory msbServiceFactory = (MSBServiceFactory) factoryField.get(msbManager);
-
- Field msbClientField = msbServiceFactory.getClass().getDeclaredField("msbClient");
- msbClientField.setAccessible(true);
- MSBServiceClient msbClient = (MSBServiceClient) msbClientField.get(msbServiceFactory);
- assertEquals("127.0.0.1:20", msbClient.getMsbSvrAddress());
- }
-
- public static MicroServiceFullInfo build(String ip,String port){
- MicroServiceFullInfo serviceInfo = new MicroServiceFullInfo();
- Set<NodeInfo> nodes = new HashSet<NodeInfo>();
- NodeInfo node= new NodeInfo();
- node.setPort(port);
- node.setIp(ip);
- nodes.add(node);
- serviceInfo.setNodes(nodes);
- return serviceInfo;
- }
-}
diff --git a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MSBServiceExceptionTest.java b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MsbServiceExceptionTest.java index 80c453eff..059eecdee 100644 --- a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MSBServiceExceptionTest.java +++ b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MsbServiceExceptionTest.java @@ -15,16 +15,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.msb.client; import org.junit.Test; import org.onap.policy.common.utils.test.ExceptionsTester; -public class MSBServiceExceptionTest extends ExceptionsTester{ - - @Test - public void test() throws Exception { - test(MSBServiceException.class); - } +public class MsbServiceExceptionTest extends ExceptionsTester { + + @Test + public void test() throws Exception { + test(MsbServiceException.class); + } } diff --git a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MsbServiceManagerTest.java b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MsbServiceManagerTest.java new file mode 100644 index 000000000..32025fb3c --- /dev/null +++ b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/MsbServiceManagerTest.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright 2017-2018 ZTE, Inc. and others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.msb.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashSet; +import java.util.Set; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.msb.sdk.discovery.common.RouteException; +import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo; +import org.onap.msb.sdk.discovery.entity.NodeInfo; +import org.onap.msb.sdk.httpclient.msb.MSBServiceClient; + +public class MsbServiceManagerTest { + @Mock + private MSBServiceClient msbClient; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private MsbServiceManager msbManager; + + public MsbServiceManagerTest() {} + + @BeforeClass + public static void setUpClass() {} + + @AfterClass + public static void tearDownClass() {} + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + msbManager = new MsbServiceManager(msbClient); + } + + @After + public void tearDown() {} + + @Test + public void testByActor() throws RouteException, UnknownHostException { + MicroServiceFullInfo serviceInfo = + MsbServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(), "8843"); + when(msbClient.queryMicroServiceInfo("aai-search", "v11")).thenReturn(serviceInfo); + Node node = msbManager.getNode("AAI"); + assertNotNull(node); + serviceInfo = MsbServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(), "8840"); + when(msbClient.queryMicroServiceInfo("so", "v2")).thenReturn(serviceInfo); + node = msbManager.getNode("SO"); + assertNotNull(node); + + serviceInfo = MsbServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(), "8082"); + when(msbClient.queryMicroServiceInfo("nfvo-nslcm", "v1")).thenReturn(serviceInfo); + node = msbManager.getNode("VFC"); + assertNotNull(node); + + } + + @Test + public void testByActor_when_actorNotExist_returnNull() throws RouteException, UnknownHostException { + MicroServiceFullInfo serviceInfo = + MsbServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(), "8843"); + when(msbClient.queryMicroServiceInfo("aai-search", "v11")).thenReturn(serviceInfo); + Node node = msbManager.getNode("DDD"); + assertNull(node); + } + + @Test + public void testByServiceNameAndVersion() throws RouteException, UnknownHostException { + MicroServiceFullInfo serviceInfo = + MsbServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(), "8843"); + when(msbClient.queryMicroServiceInfo("aai-search", "v11")).thenReturn(serviceInfo); + Node node = msbManager.getNode("aai-search", "v11"); + assertNotNull(node); + } + + @Test + public void testByServiceNameAndVersion_when_serice_notRegistedToMsb() throws RouteException, UnknownHostException { + MsbServiceManagerTest.build(InetAddress.getLocalHost().getHostAddress(), "8843"); + when(msbClient.queryMicroServiceInfo("aai-search", "v11")).thenThrow(new RouteException()); + Node node = msbManager.getNode("aai-search", "v11"); + assertNotNull(node); + assertTrue(node.getName() == "aai-search"); + assertTrue(node.getIp() == null); + assertTrue(node.getPort() == null); + } + + @Test + public void testReadMsbPolicyProperites_noPropertyFileSpecifed_throwsException() + throws MsbServiceException, IOException { + expectedException.expect(MsbServiceException.class); + expectedException.expectMessage("No msb.policy.properties specified."); + System.clearProperty("msb.policy.properties"); + msbManager = new MsbServiceManager(); + } + + @Test + public void testReadMsbPolicyProperites_propertyFileDoesNotExist_throwsException() + throws MsbServiceException, IOException { + expectedException.expect(MsbServiceException.class); + expectedException.expectMessage("No msb.policy.properties specified."); + System.setProperty("msb.policy.properties", "nonExistingPropertyFile.txt"); + msbManager = new MsbServiceManager(); + System.clearProperty("msb.policy.properties"); + } + + @Test + public void testReadMsbPolicyProperites_propertyFileExists() throws MsbServiceException, IOException, + NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + System.setProperty("msb.policy.properties", "src/test/resources/msbPropertyFile.properties"); + msbManager = new MsbServiceManager(); + System.clearProperty("msb.policy.properties"); + + Field factoryField = msbManager.getClass().getDeclaredField("factory"); + factoryField.setAccessible(true); + MsbServiceFactory msbServiceFactory = (MsbServiceFactory) factoryField.get(msbManager); + + Field msbClientField = msbServiceFactory.getClass().getDeclaredField("msbClient"); + msbClientField.setAccessible(true); + MSBServiceClient msbClient = (MSBServiceClient) msbClientField.get(msbServiceFactory); + assertEquals("127.0.0.1:20", msbClient.getMsbSvrAddress()); + } + + /** + * Build a micro service info. + * + * @param ip the up address + * @param port the port number + * @return the MicroServiceFullInfo + */ + public static MicroServiceFullInfo build(String ip, String port) { + Set<NodeInfo> nodes = new HashSet<NodeInfo>(); + NodeInfo node = new NodeInfo(); + node.setPort(port); + node.setIp(ip); + nodes.add(node); + MicroServiceFullInfo serviceInfo = new MicroServiceFullInfo(); + serviceInfo.setNodes(nodes); + return serviceInfo; + } +} diff --git a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/NodeTest.java b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/NodeTest.java index ed1d55f2c..7419bbe34 100644 --- a/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/NodeTest.java +++ b/controlloop/common/msb/src/test/java/org/onap/policy/msb/client/NodeTest.java @@ -15,48 +15,49 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.msb.client; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; public class NodeTest { - @Test - public void testSetAndGetName() { - Node node = new Node(); - final String name = "myName"; - node.setName(name); - assertEquals(name, node.getName()); - } - - @Test - public void testSetAndGetIp() { - Node node = new Node(); - final String ip = "127.0.0.1"; - node.setIp(ip); - assertEquals(ip, node.getIp()); - } - - @Test - public void testSetAndGetPort() { - Node node = new Node(); - final String port = "1001"; - node.setPort(port); - assertEquals(port, node.getPort()); - } - - @Test - public void testToString() { - Node node = new Node(); - final String name = "myName"; - final String ip = "127.0.0.1"; - final String port = "1001"; - node.setName(name); - node.setIp(ip); - node.setPort(port); - assertEquals("Node{name='myName', ip='127.0.0.1', port='1001'}", node.toString()); - } + @Test + public void testSetAndGetName() { + Node node = new Node(); + final String name = "myName"; + node.setName(name); + assertEquals(name, node.getName()); + } + + @Test + public void testSetAndGetIp() { + Node node = new Node(); + final String ip = "127.0.0.1"; + node.setIp(ip); + assertEquals(ip, node.getIp()); + } + + @Test + public void testSetAndGetPort() { + Node node = new Node(); + final String port = "1001"; + node.setPort(port); + assertEquals(port, node.getPort()); + } + + @Test + public void testToString() { + Node node = new Node(); + final String name = "myName"; + final String ip = "127.0.0.1"; + final String port = "1001"; + node.setName(name); + node.setIp(ip); + node.setPort(port); + assertEquals("Node{name='myName', ip='127.0.0.1', port='1001'}", node.toString()); + } } diff --git a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/AaiSimulatorJaxRs.java b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/AaiSimulatorJaxRs.java index c6b22cf70..627e9311e 100644 --- a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/AaiSimulatorJaxRs.java +++ b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/AaiSimulatorJaxRs.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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. @@ -34,88 +34,294 @@ import org.onap.policy.aai.util.Serialization; @Path("/aai") public class AaiSimulatorJaxRs { - - @GET - @Path("/v8/network/generic-vnfs/generic-vnf/{vnfId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String aaiGetQuery (@PathParam("vnfID") String vnfId) - { - return "{\"relationship-list\": {\"relationship\":[{\"related-to-property\": [{\"property-key\": \"service-instance.service-instance-name\"}]},{\"related-to-property\": [ {\"property-key\": \"vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; - } - - @POST - @Path("/search/named-query") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String aaiPostQuery(String req) - { - AAINQRequest request = Serialization.gsonPretty.fromJson(req, AAINQRequest.class); - - if (request.getInstanceFilters().getInstanceFilter().get(0).containsKey("vserver")) - { - String vserverName = request.getInstanceFilters().getInstanceFilter().get(0).get("vserver").get("vserver-name"); - if ("error".equals(vserverName)) { - return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"POST Search\",\"getNamedQueryResponse\",\"Node Not Found:No Node of type vserver found for properties\",\"ERR.5.4.6114\"]}}}"; - } - else { - // vll format - new - // new aai response from Brian 11/13/2017 - return "{\"inventory-response-item\":[{\"vserver\":{\"vserver-id\":\"6ed3642c-f7a1-4a7c-9290-3d51fe1531eb\",\"vserver-name\":\"zdfw1lb01lb02\",\"vserver-name2\":\"zdfw1lb01lb02\",\"prov-status\":\"ACTIVE\",\"vserver-selflink\":\"http://10.12.25.2:8774/v2.1/41d6d38489bd40b09ea8a6b6b852dcbd/servers/6ed3642c-f7a1-4a7c-9290-3d51fe1531eb\",\"in-maint\":false,\"is-closed-loop-disabled\":false,\"resource-version\":\"1510606403522\"},\"extra-properties\":{},\"inventory-response-items\":{\"inventory-response-item\":[{\"model-name\":\"vLoadBalancer\",\"generic-vnf\":{\"vnf-id\":\"db373a8d-f7be-4d02-8ac8-6ca4c305d144\",\"vnf-name\":\"Vfmodule_vLB1113\",\"vnf-type\":\"vLoadBalancer-1106/vLoadBalancer 0\",\"service-id\":\"66f157fc-4148-4880-95f5-e120677e98d1\",\"prov-status\":\"PREPROV\",\"orchestration-status\":\"Created\",\"in-maint\":false,\"is-closed-loop-disabled\":false,\"resource-version\":\"1510604011851\",\"model-invariant-id\":\"cee050ed-92a5-494f-ab04-234307a846dc\",\"model-version-id\":\"fd65becc-6b2c-4fe8-ace9-cc29db9a3da2\",\"model-customization-id\":\"1983c783-444f-4e79-af3a-85e5d49628f3\",\"nf-type\":\"\",\"nf-function\":\"\",\"nf-role\":\"\",\"nf-naming-code\":\"\"},\"extra-properties\":{\"extra-property\":[{\"property-name\":\"model-ver.model-version-id\",\"property-value\":\"fd65becc-6b2c-4fe8-ace9-cc29db9a3da2\"},{\"property-name\":\"model-ver.model-name\",\"property-value\":\"vLoadBalancer\"},{\"property-name\":\"model.model-type\",\"property-value\":\"resource\"},{\"property-name\":\"model.model-invariant-id\",\"property-value\":\"cee050ed-92a5-494f-ab04-234307a846dc\"},{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1.0\"}]},\"inventory-response-items\":{\"inventory-response-item\":[{\"model-name\":\"vLoadBalancer-1106\",\"service-instance\":{\"service-instance-id\":\"3b12f31f-8f2d-4f5c-b875-61ff1194b941\",\"service-instance-name\":\"vLoadBalancer-1113\",\"model-invariant-id\":\"1321d60d-f7ff-4300-96c2-6bf0b3268b7a\",\"model-version-id\":\"732d4692-4b97-46f9-a996-0b3339e88c50\",\"resource-version\":\"1510603936425\"},\"extra-properties\":{\"extra-property\":[{\"property-name\":\"model-ver.model-version-id\",\"property-value\":\"732d4692-4b97-46f9-a996-0b3339e88c50\"},{\"property-name\":\"model-ver.model-name\",\"property-value\":\"vLoadBalancer-1106\"},{\"property-name\":\"model.model-type\",\"property-value\":\"service\"},{\"property-name\":\"model.model-invariant-id\",\"property-value\":\"1321d60d-f7ff-4300-96c2-6bf0b3268b7a\"},{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1.0\"}]}},{\"model-name\":\"Vloadbalancer..base_vlb..module-0\",\"vf-module\":{\"vf-module-id\":\"e6b3e3eb-34e1-4c00-b8c1-2a4fbe479b12\",\"vf-module-name\":\"Vfmodule_vLB1113-1\",\"heat-stack-id\":\"Vfmodule_vLB1113-1/3dd6d900-772f-4fcc-a0cb-e250ab2bb4db\",\"orchestration-status\":\"active\",\"is-base-vf-module\":true,\"resource-version\":\"1510604612557\",\"model-invariant-id\":\"6d760188-9a24-451a-b05b-e08b86cb94f2\",\"model-version-id\":\"93facad9-55f2-4fe0-9574-814c2bc2d071\",\"model-customization-id\":\"93fd5bd4-8051-4074-8530-c0c504604df5\",\"module-index\":0},\"extra-properties\":{\"extra-property\":[{\"property-name\":\"model-ver.model-version-id\",\"property-value\":\"93facad9-55f2-4fe0-9574-814c2bc2d071\"},{\"property-name\":\"model-ver.model-name\",\"property-value\":\"Vloadbalancer..base_vlb..module-0\"},{\"property-name\":\"model.model-type\",\"property-value\":\"resource\"},{\"property-name\":\"model.model-invariant-id\",\"property-value\":\"6d760188-9a24-451a-b05b-e08b86cb94f2\"},{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1\"}]}},{\"model-name\":\"Vloadbalancer..dnsscaling..module-1\",\"vf-module\":{\"vf-module-id\":\"dummy_db373a8d-f7be-4d02-8ac8-6ca4c305d144\",\"vf-module-name\":\"dummy_db373a8d-f7be-4d02-8ac8-6ca4c305d144\",\"is-base-vf-module\":false,\"resource-version\":\"1510610079687\",\"model-invariant-id\":\"356a1cff-71f2-4086-9980-a2927ce11c1c\",\"model-version-id\":\"6b93d804-cfc8-4be3-92cc-9336d135859a\"},\"extra-properties\":{\"extra-property\":[{\"property-name\":\"model-ver.model-version-id\",\"property-value\":\"6b93d804-cfc8-4be3-92cc-9336d135859a\"},{\"property-name\":\"model-ver.model-name\",\"property-value\":\"Vloadbalancer..dnsscaling..module-1\"},{\"property-name\":\"model.model-type\",\"property-value\":\"resource\"},{\"property-name\":\"model.model-invariant-id\",\"property-value\":\"356a1cff-71f2-4086-9980-a2927ce11c1c\"},{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1\"}]}}]}},{\"tenant\":{\"tenant-id\":\"41d6d38489bd40b09ea8a6b6b852dcbd\",\"tenant-name\":\"Integration-SB-00\",\"resource-version\":\"1509587770200\"},\"extra-properties\":{},\"inventory-response-items\":{\"inventory-response-item\":[{\"cloud-region\":{\"cloud-owner\":\"CloudOwner\",\"cloud-region-id\":\"RegionOne\",\"cloud-type\":\"SharedNode\",\"owner-defined-type\":\"OwnerType\",\"cloud-region-version\":\"v1\",\"cloud-zone\":\"CloudZone\",\"sriov-automation\":false,\"resource-version\":\"1509587770092\"},\"extra-properties\":{}}]}}]}}]}"; - } - } - else - { - String vnfID = request.getInstanceFilters().getInstanceFilter().get(0).get("generic-vnf").get("vnf-id"); - if ("error".equals(vnfID)) { - return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"POST Search\",\"getNamedQueryResponse\",\"Node Not Found:No Node of type generic-vnf found for properties\",\"ERR.5.4.6114\"]}}}"; - } - else { - return "{\"inventory-response-item\": [{\"model-name\": \"service-instance\",\"generic-vnf\": {\"vnf-id\": \""+ vnfID + "\",\"vnf-name\": \"ZRDM2MMEX39\",\"vnf-type\": \"vMME Svc Jul 14/vMME VF Jul 14 1\",\"service-id\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\",\"orchestration-status\": \"active\",\"in-maint\": false,\"is-closed-loop-disabled\": false,\"resource-version\": \"1503082370097\",\"model-invariant-id\": \"82194af1-3c2c-485a-8f44-420e22a9eaa4\",\"model-version-id\": \"46b92144-923a-4d20-b85a-3cbd847668a9\"},\"extra-properties\": {},\"inventory-response-items\": {\"inventory-response-item\": [{\"model-name\": \"service-instance\",\"service-instance\": {\"service-instance-id\": \"37b8cdb7-94eb-468f-a0c2-4e3c3546578e\",\"service-instance-name\": \"Changed Service Instance NAME\",\"model-invariant-id\": \"82194af1-3c2c-485a-8f44-420e22a9eaa4\",\"model-version-id\": \"46b92144-923a-4d20-b85a-3cbd847668a9\",\"resource-version\": \"1503082993532\",\"orchestration-status\": \"Active\"},\"extra-properties\": {},\"inventory-response-items\": {\"inventory-response-item\": [{\"model-name\": \"pnf\",\"generic-vnf\": {\"vnf-id\": \"jimmy-test\",\"vnf-name\": \"jimmy-test-vnf\",\"vnf-type\": \"vMME Svc Jul 14/vMME VF Jul 14 1\",\"service-id\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\",\"orchestration-status\": \"active\",\"in-maint\": false,\"is-closed-loop-disabled\": false,\"resource-version\": \"1504013830207\",\"model-invariant-id\": \"862b25a1-262a-4961-bdaa-cdc55d69785a\",\"model-version-id\": \"e9f1fa7d-c839-418a-9601-03dc0d2ad687\"},\"extra-properties\": {}},{\"model-name\": \"service-instance\",\"generic-vnf\": {\"vnf-id\": \"jimmy-test-vnf2\",\"vnf-name\": \"jimmy-test-vnf2-named\",\"vnf-type\": \"vMME Svc Jul 14/vMME VF Jul 14 1\",\"service-id\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\",\"orchestration-status\": \"active\",\"in-maint\": false,\"is-closed-loop-disabled\": false,\"resource-version\": \"1504014833841\",\"model-invariant-id\": \"Eace933104d443b496b8.nodes.heat.vpg\",\"model-version-id\": \"46b92144-923a-4d20-b85a-3cbd847668a9\"},\"extra-properties\": {}}]}}]}}]}"; - } - } - } - - @GET - @Path("/v11/network/generic-vnfs/generic-vnf") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String getByVnfName (@QueryParam("vnf-name") String vnfName) - { - if ("getFail".equals(vnfName)) { - return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",\"network/generic-vnfs/generic-vnf\",\"Node Not Found:No Node of type generic-vnf found at network/generic-vnfs/generic-vnf\",\"ERR.5.4.6114\"]}}}"; - } - boolean isDisabled = "disableClosedLoop".equals(vnfName); - if ("error".equals(vnfName)) { - return "{ \"vnf-id\": \"error\", \"vnf-name\": \"" + vnfName + "\", \"vnf-type\": \"RT\", \"service-id\": \"d7bb0a21-66f2-4e6d-87d9-9ef3ced63ae4\", \"equipment-role\": \"UCPE\", \"orchestration-status\": \"created\", \"management-option\": \"ATT\", \"ipv4-oam-address\": \"32.40.68.35\", \"ipv4-loopback0-address\": \"32.40.64.57\", \"nm-lan-v6-address\": \"2001:1890:e00e:fffe::1345\", \"management-v6-address\": \"2001:1890:e00e:fffd::36\", \"in-maint\": false, \"is-closed-loop-disabled\": " + isDisabled + ", \"resource-version\": \"1493389458092\", \"relationship-list\": {\"relationship\":[{ \"related-to\": \"service-instance\", \"related-link\": \"/aai/v11/business/customers/customer/1610_Func_Global_20160817084727/service-subscriptions/service-subscription/uCPE-VMS/service-instances/service-instance/USUCP0PCOIL0110UJZZ01\", \"relationship-data\":[{ \"relationship-key\": \"customer.global-customer-id\", \"relationship-value\": \"1610_Func_Global_20160817084727\"},{ \"relationship-key\": \"service-subscription.service-type\", \"relationship-value\": \"uCPE-VMS\"},{ \"relationship-key\": \"service-instance.service-instance-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01\"} ], \"related-to-property\": [{\"property-key\": \"service-instance.service-instance-name\"}]},{ \"related-to\": \"vserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USUCP0PCOIL0110UJZZ01%3A%3AuCPE-VMS/vservers/vserver/3b2558f4-39d8-40e7-bfc7-30660fb52c45\", \"relationship-data\":[{ \"relationship-key\": \"cloud-region.cloud-owner\", \"relationship-value\": \"att-aic\"},{ \"relationship-key\": \"cloud-region.cloud-region-id\", \"relationship-value\": \"AAIAIC25\"},{ \"relationship-key\": \"tenant.tenant-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01::uCPE-VMS\"},{ \"relationship-key\": \"vserver.vserver-id\", \"relationship-value\": \"3b2558f4-39d8-40e7-bfc7-30660fb52c45\"} ], \"related-to-property\": [ {\"property-key\": \"vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; - - } - return "{ \"vnf-id\": \"5e49ca06-2972-4532-9ed4-6d071588d792\", \"vnf-name\": \"" + vnfName + "\", \"vnf-type\": \"RT\", \"service-id\": \"d7bb0a21-66f2-4e6d-87d9-9ef3ced63ae4\", \"equipment-role\": \"UCPE\", \"orchestration-status\": \"created\", \"management-option\": \"ATT\", \"ipv4-oam-address\": \"32.40.68.35\", \"ipv4-loopback0-address\": \"32.40.64.57\", \"nm-lan-v6-address\": \"2001:1890:e00e:fffe::1345\", \"management-v6-address\": \"2001:1890:e00e:fffd::36\", \"in-maint\": false, \"is-closed-loop-disabled\": " + isDisabled + ", \"resource-version\": \"1493389458092\", \"relationship-list\": {\"relationship\":[{ \"related-to\": \"service-instance\", \"related-link\": \"/aai/v11/business/customers/customer/1610_Func_Global_20160817084727/service-subscriptions/service-subscription/uCPE-VMS/service-instances/service-instance/USUCP0PCOIL0110UJZZ01\", \"relationship-data\":[{ \"relationship-key\": \"customer.global-customer-id\", \"relationship-value\": \"1610_Func_Global_20160817084727\"},{ \"relationship-key\": \"service-subscription.service-type\", \"relationship-value\": \"uCPE-VMS\"},{ \"relationship-key\": \"service-instance.service-instance-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01\"} ], \"related-to-property\": [{\"property-key\": \"service-instance.service-instance-name\"}]},{ \"related-to\": \"vserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USUCP0PCOIL0110UJZZ01%3A%3AuCPE-VMS/vservers/vserver/3b2558f4-39d8-40e7-bfc7-30660fb52c45\", \"relationship-data\":[{ \"relationship-key\": \"cloud-region.cloud-owner\", \"relationship-value\": \"att-aic\"},{ \"relationship-key\": \"cloud-region.cloud-region-id\", \"relationship-value\": \"AAIAIC25\"},{ \"relationship-key\": \"tenant.tenant-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01::uCPE-VMS\"},{ \"relationship-key\": \"vserver.vserver-id\", \"relationship-value\": \"3b2558f4-39d8-40e7-bfc7-30660fb52c45\"} ], \"related-to-property\": [ {\"property-key\": \"vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; - } - - @GET - @Path("/v11/network/generic-vnfs/generic-vnf/{vnfId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String getByVnfId (@PathParam("vnfId") String vnfId) - { - if ("getFail".equals(vnfId)) { - return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",\"network/generic-vnfs/generic-vnf/getFail\",\"Node Not Found:No Node of type generic-vnf found at network/generic-vnfs/generic-vnf/getFail\",\"ERR.5.4.6114\"]}}}"; - } - boolean isDisabled = "disableClosedLoop".equals(vnfId); - return "{ \"vnf-id\": \"" + vnfId + "\", \"vnf-name\": \"USUCP0PCOIL0110UJRT01\", \"vnf-type\": \"RT\", \"service-id\": \"d7bb0a21-66f2-4e6d-87d9-9ef3ced63ae4\", \"equipment-role\": \"UCPE\", \"orchestration-status\": \"created\", \"management-option\": \"ATT\", \"ipv4-oam-address\": \"32.40.68.35\", \"ipv4-loopback0-address\": \"32.40.64.57\", \"nm-lan-v6-address\": \"2001:1890:e00e:fffe::1345\", \"management-v6-address\": \"2001:1890:e00e:fffd::36\", \"in-maint\": false, \"is-closed-loop-disabled\": " + isDisabled + ", \"resource-version\": \"1493389458092\", \"relationship-list\": {\"relationship\":[{ \"related-to\": \"service-instance\", \"related-link\": \"/aai/v11/business/customers/customer/1610_Func_Global_20160817084727/service-subscriptions/service-subscription/uCPE-VMS/service-instances/service-instance/USUCP0PCOIL0110UJZZ01\", \"relationship-data\":[{ \"relationship-key\": \"customer.global-customer-id\", \"relationship-value\": \"1610_Func_Global_20160817084727\"},{ \"relationship-key\": \"service-subscription.service-type\", \"relationship-value\": \"uCPE-VMS\"},{ \"relationship-key\": \"service-instance.service-instance-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01\"} ], \"related-to-property\": [{\"property-key\": \"service-instance.service-instance-name\"}]},{ \"related-to\": \"vserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USUCP0PCOIL0110UJZZ01%3A%3AuCPE-VMS/vservers/vserver/3b2558f4-39d8-40e7-bfc7-30660fb52c45\", \"relationship-data\":[{ \"relationship-key\": \"cloud-region.cloud-owner\", \"relationship-value\": \"att-aic\"},{ \"relationship-key\": \"cloud-region.cloud-region-id\", \"relationship-value\": \"AAIAIC25\"},{ \"relationship-key\": \"tenant.tenant-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01::uCPE-VMS\"},{ \"relationship-key\": \"vserver.vserver-id\", \"relationship-value\": \"3b2558f4-39d8-40e7-bfc7-30660fb52c45\"} ], \"related-to-property\": [ {\"property-key\": \"vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; - } - - @GET - @Path("/v11/nodes/vservers") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String getByVserverName (@QueryParam("vserver-name") String vserverName) - { - if ("getFail".equals(vserverName)) { - return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",\"nodes/vservers\",\"Node Not Found:No Node of type generic-vnf found at nodes/vservers\",\"ERR.5.4.6114\"]}}}"; - } - boolean isDisabled = "disableClosedLoop".equals(vserverName); - return "{\"vserver\": [{ \"vserver-id\": \"d0668d4f-c25e-4a1b-87c4-83845c01efd8\", \"vserver-name\": \"" + vserverName + "\", \"vserver-name2\": \"vjunos0\", \"vserver-selflink\": \"https://aai-ext1.test.att.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USMSO1SX7NJ0103UJZZ01%3A%3AuCPE-VMS/vservers/vserver/d0668d4f-c25e-4a1b-87c4-83845c01efd8\", \"in-maint\": false, \"is-closed-loop-disabled\": " + isDisabled + ", \"resource-version\": \"1494001931513\", \"relationship-list\": {\"relationship\":[{ \"related-to\": \"generic-vnf\", \"related-link\": \"/aai/v11/network/generic-vnfs/generic-vnf/e1a41e99-4ede-409a-8f9d-b5e12984203a\", \"relationship-data\": [ {\"relationship-key\": \"generic-vnf.vnf-id\",\"relationship-value\": \"e1a41e99-4ede-409a-8f9d-b5e12984203a\" }], \"related-to-property\": [ {\"property-key\": \"generic-vnf.vnf-name\",\"property-value\": \"USMSO1SX7NJ0103UJSW01\" }]},{ \"related-to\": \"pserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/pservers/pserver/USMSO1SX7NJ0103UJZZ01\", \"relationship-data\": [ {\"relationship-key\": \"pserver.hostname\",\"relationship-value\": \"USMSO1SX7NJ0103UJZZ01\" }], \"related-to-property\": [{\"property-key\": \"pserver.pserver-name2\"}]} ]}}]}"; - } + + /** + * A&AI get query. + * + * @param vnfId the VNF Id + * @return the result + */ + @GET + @Path("/v8/network/generic-vnfs/generic-vnf/{vnfId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String aaiGetQuery(@PathParam("vnfID") String vnfId) { + return "{\"relationship-list\": {\"relationship\":[{\"related-to-property\": [{\"property-key\": " + + "\"service-instance.service-instance-name\"}]},{\"related-to-property\": [ {\"property-key\": " + + "\"vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; + } + + /** + * A&AI post query. + * + * @param req the request + * @return the response + */ + @POST + @Path("/search/named-query") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String aaiPostQuery(String req) { + AAINQRequest request = Serialization.gsonPretty.fromJson(req, AAINQRequest.class); + + if (request.getInstanceFilters().getInstanceFilter().get(0).containsKey("vserver")) { + String vserverName = + request.getInstanceFilters().getInstanceFilter().get(0).get("vserver").get("vserver-name"); + if ("error".equals(vserverName)) { + return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not " + + "found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"POST Search\",\"" + + "getNamedQueryResponse\",\"Node Not Found:No Node of type vserver found for properties\"" + + ",\"ERR.5.4.6114\"]}}}"; + } else { + // vll format - new + // new aai response from Brian 11/13/2017 + return "{\"inventory-response-item\":[{\"vserver\":{\"vserver-id\":\"" + + "6ed3642c-f7a1-4a7c-9290-3d51fe1531eb\",\"vserver-name\":\"zdfw1lb01lb02\",\"vserver-name2\"" + + ":\"zdfw1lb01lb02\",\"prov-status\":\"ACTIVE\",\"vserver-selflink\":\"" + + "http://10.12.25.2:8774/v2.1/41d6d38489bd40b09ea8a6b6b852dcbd/servers/" + + "6ed3642c-f7a1-4a7c-9290-3d51fe1531eb\",\"in-maint\":false,\"is-closed-loop-disabled\":false" + + ",\"resource-version\":\"1510606403522\"},\"extra-properties\":{},\"inventory-response-items" + + "\":{\"inventory-response-item\":[{\"model-name\":\"vLoadBalancer\",\"generic-vnf\":{\"vnf-id" + + "\":\"db373a8d-f7be-4d02-8ac8-6ca4c305d144\",\"vnf-name\":\"Vfmodule_vLB1113\",\"vnf-type" + + "\":\"vLoadBalancer-1106/vLoadBalancer 0\",\"service-id\":\"" + + "66f157fc-4148-4880-95f5-e120677e98d1\",\"prov-status\":\"PREPROV\",\"orchestration-status\":" + + "\"Created\",\"in-maint\":false,\"is-closed-loop-disabled\":false,\"resource-version\":\"" + + "1510604011851\",\"model-invariant-id\":\"cee050ed-92a5-494f-ab04-234307a846dc\",\"" + + "model-version-id\":\"fd65becc-6b2c-4fe8-ace9-cc29db9a3da2\",\"model-customization-id\":\"" + + "1983c783-444f-4e79-af3a-85e5d49628f3\",\"nf-type\":\"\",\"nf-function\":\"\",\"nf-role" + + "\":\"\",\"nf-naming-code\":\"\"},\"extra-properties\":{\"extra-property\":[{\"property-name" + + "\":\"model-ver.model-version-id\",\"property-value\":\"fd65becc-6b2c-4fe8-ace9-cc29db9a3da2" + + "\"},{\"property-name\":\"model-ver.model-name\",\"property-value\":\"vLoadBalancer\"},{\"" + + "property-name\":\"model.model-type\",\"property-value\":\"resource\"},{\"property-name\":\"" + + "model.model-invariant-id\",\"property-value\":\"cee050ed-92a5-494f-ab04-234307a846dc\"},{\"" + + "property-name\":\"model-ver.model-version\",\"property-value\":\"1.0\"}]},\"" + + "inventory-response-items\":{\"inventory-response-item\":[{\"model-name\":\"" + + "vLoadBalancer-1106\",\"service-instance\":{\"service-instance-id\":\"" + + "3b12f31f-8f2d-4f5c-b875-61ff1194b941\",\"service-instance-name\":\"vLoadBalancer-1113\",\"" + + "model-invariant-id\":\"1321d60d-f7ff-4300-96c2-6bf0b3268b7a\",\"model-version-id\":\"" + + "732d4692-4b97-46f9-a996-0b3339e88c50\",\"resource-version\":\"1510603936425\"},\"" + + "extra-properties\":{\"extra-property\":[{\"property-name\":\"model-ver.model-version-id" + + "\",\"property-value\":\"732d4692-4b97-46f9-a996-0b3339e88c50\"},{\"property-name\":\"" + + "model-ver.model-name\",\"property-value\":\"vLoadBalancer-1106\"},{\"property-name\":\"" + + "model.model-type\",\"property-value\":\"service\"},{\"property-name\":\"" + + "model.model-invariant-id\",\"property-value\":\"1321d60d-f7ff-4300-96c2-6bf0b3268b7a" + + "\"},{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1.0\"}]}},{\"" + + "model-name\":\"Vloadbalancer..base_vlb..module-0\",\"vf-module\":{\"vf-module-id\":\"" + + "e6b3e3eb-34e1-4c00-b8c1-2a4fbe479b12\",\"vf-module-name\":\"Vfmodule_vLB1113-1\",\"" + + "heat-stack-id\":\"Vfmodule_vLB1113-1/3dd6d900-772f-4fcc-a0cb-e250ab2bb4db\",\"" + + "orchestration-status\":\"active\",\"is-base-vf-module\":true,\"resource-version\":\"" + + "1510604612557\",\"model-invariant-id\":\"6d760188-9a24-451a-b05b-e08b86cb94f2\",\"" + + "model-version-id\":\"93facad9-55f2-4fe0-9574-814c2bc2d071\",\"model-customization-id\":\"" + + "93fd5bd4-8051-4074-8530-c0c504604df5\",\"module-index\":0},\"extra-properties\":{\"" + + "extra-property\":[{\"property-name\":\"model-ver.model-version-id\",\"property-value" + + "\":\"93facad9-55f2-4fe0-9574-814c2bc2d071\"},{\"property-name\":\"model-ver.model-name" + + "\",\"property-value\":\"Vloadbalancer..base_vlb..module-0\"},{\"property-name\":\"" + + "model.model-type\",\"property-value\":\"resource\"},{\"property-name\":\"" + + "model.model-invariant-id\",\"property-value\":\"6d760188-9a24-451a-b05b-e08b86cb94f2\"}," + + "{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1\"}]}},{\"model-name" + + "\":\"Vloadbalancer..dnsscaling..module-1\",\"vf-module\":{\"vf-module-id\":\"" + + "dummy_db373a8d-f7be-4d02-8ac8-6ca4c305d144\",\"vf-module-name\":\"" + + "dummy_db373a8d-f7be-4d02-8ac8-6ca4c305d144\",\"is-base-vf-module\":false,\"resource-version" + + "\":\"1510610079687\",\"model-invariant-id\":\"356a1cff-71f2-4086-9980-a2927ce11c1c\",\"" + + "model-version-id\":\"6b93d804-cfc8-4be3-92cc-9336d135859a\"},\"extra-properties\":{\"" + + "extra-property\":[{\"property-name\":\"model-ver.model-version-id\",\"property-value\":\"" + + "6b93d804-cfc8-4be3-92cc-9336d135859a\"},{\"property-name\":\"model-ver.model-name\",\"" + + "property-value\":\"Vloadbalancer..dnsscaling..module-1\"},{\"property-name\":\"" + + "model.model-type\",\"property-value\":\"resource\"},{\"property-name\":\"" + + "model.model-invariant-id\",\"property-value\":\"356a1cff-71f2-4086-9980-a2927ce11c1c\"}," + + "{\"property-name\":\"model-ver.model-version\",\"property-value\":\"1\"}]}}]}},{\"tenant" + + "\":{\"tenant-id\":\"41d6d38489bd40b09ea8a6b6b852dcbd\",\"tenant-name\":\"Integration-SB-00" + + "\",\"resource-version\":\"1509587770200\"},\"extra-properties\":{},\"" + + "inventory-response-items\":{\"inventory-response-item\":[{\"cloud-region\":{\"cloud-owner" + + "\":\"CloudOwner\",\"cloud-region-id\":\"RegionOne\",\"cloud-type\":\"SharedNode\",\"" + + "owner-defined-type\":\"OwnerType\",\"cloud-region-version\":\"v1\",\"cloud-zone\":\"" + + "CloudZone\",\"sriov-automation\":false,\"resource-version\":\"1509587770092\"},\"" + + "extra-properties\":{}}]}}]}}]}"; + } + } else { + String vnfId = request.getInstanceFilters().getInstanceFilter().get(0).get("generic-vnf").get("vnf-id"); + if ("error".equals(vnfId)) { + return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not " + + "found for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"POST Search\",\"" + + "getNamedQueryResponse\",\"Node Not Found:No Node of type generic-vnf found for properties" + + "\",\"ERR.5.4.6114\"]}}}"; + } else { + return "{\"inventory-response-item\": [{\"model-name\": \"service-instance\",\"generic-vnf\": {\"" + + "vnf-id\": \"" + vnfId + "\",\"vnf-name\": \"ZRDM2MMEX39\",\"vnf-type\": \"vMME Svc Jul " + + "14/vMME VF Jul 14 1\",\"service-id\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\",\"" + + "orchestration-status\": \"active\",\"in-maint\": false,\"is-closed-loop-disabled\": false" + + ",\"resource-version\": \"1503082370097\",\"model-invariant-id\": \"" + + "82194af1-3c2c-485a-8f44-420e22a9eaa4\",\"model-version-id\": \"" + + "46b92144-923a-4d20-b85a-3cbd847668a9\"},\"extra-properties\": {},\"" + + "inventory-response-items\": {\"inventory-response-item\": [{\"model-name\": \"" + + "service-instance\",\"service-instance\": {\"service-instance-id\": \"" + + "37b8cdb7-94eb-468f-a0c2-4e3c3546578e\",\"service-instance-name\": \"Changed Service " + + "Instance NAME\",\"model-invariant-id\": \"82194af1-3c2c-485a-8f44-420e22a9eaa4\",\"" + + "model-version-id\": \"46b92144-923a-4d20-b85a-3cbd847668a9\",\"resource-version\": \"" + + "1503082993532\",\"orchestration-status\": \"Active\"},\"extra-properties\": {},\"" + + "inventory-response-items\": {\"inventory-response-item\": [{\"model-name\": \"pnf\",\"" + + "generic-vnf\": {\"vnf-id\": \"jimmy-test\",\"vnf-name\": \"jimmy-test-vnf\",\"vnf-type" + + "\": \"vMME Svc Jul 14/vMME VF Jul 14 1\",\"service-id\": \"" + + "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\",\"orchestration-status\": \"active\",\"in-maint\":" + + " false,\"is-closed-loop-disabled\": false,\"resource-version\": \"1504013830207\",\"" + + "model-invariant-id\": \"862b25a1-262a-4961-bdaa-cdc55d69785a\",\"model-version-id\": \"" + + "e9f1fa7d-c839-418a-9601-03dc0d2ad687\"},\"extra-properties\": {}},{\"model-name\": \"" + + "service-instance\",\"generic-vnf\": {\"vnf-id\": \"jimmy-test-vnf2\",\"vnf-name\": \"" + + "jimmy-test-vnf2-named\",\"vnf-type\": \"vMME Svc Jul 14/vMME VF Jul 14 1\",\"service-id" + + "\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\",\"orchestration-status\": \"active\",\"" + + "in-maint\": false,\"is-closed-loop-disabled\": false,\"resource-version\": \"" + + "1504014833841\",\"model-invariant-id\": \"Eace933104d443b496b8.nodes.heat.vpg\",\"" + + "model-version-id\": \"46b92144-923a-4d20-b85a-3cbd847668a9\"},\"extra-properties\": " + + "{}}]}}]}}]}"; + } + } + } + + /** + * Get by VNF name. + * + * @param vnfName the VNF name + * @return the response + */ + @GET + @Path("/v11/network/generic-vnfs/generic-vnf") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String getByVnfName(@QueryParam("vnf-name") String vnfName) { + if ("getFail".equals(vnfName)) { + return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found" + + " for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",\"network/generic-vnfs/" + + "generic-vnf\",\"Node Not Found:No Node of type generic-vnf found at network/generic-vnfs" + + "/generic-vnf\",\"ERR.5.4.6114\"]}}}"; + } + boolean isDisabled = "disableClosedLoop".equals(vnfName); + if ("error".equals(vnfName)) { + return "{ \"vnf-id\": \"error\", \"vnf-name\": \"" + vnfName + + "\", \"vnf-type\": \"RT\", \"service-id\": \"d7bb0a21-66f2-4e6d-87d9-9ef3ced63ae4\", \"" + + "equipment-role\": \"UCPE\", \"orchestration-status\": \"created\", \"management-option\": \"" + + "ATT\", \"ipv4-oam-address\": \"32.40.68.35\", \"ipv4-loopback0-address\": \"32.40.64.57\", \"" + + "nm-lan-v6-address\": \"2001:1890:e00e:fffe::1345\", \"management-v6-address\": \"" + + "2001:1890:e00e:fffd::36\", \"in-maint\": false, \"is-closed-loop-disabled\": " + isDisabled + + ", \"resource-version\": \"1493389458092\", \"relationship-list\": {\"relationship\":[{ \"" + + "related-to\": \"service-instance\", \"related-link\": \"/aai/v11/business/customers/customer/" + + "1610_Func_Global_20160817084727/service-subscriptions/service-subscription/uCPE-VMS/" + + "service-instances/service-instance/USUCP0PCOIL0110UJZZ01\", \"relationship-data\":[{ \"" + + "relationship-key\": \"customer.global-customer-id\", \"relationship-value\": \"" + + "1610_Func_Global_20160817084727\"},{ \"relationship-key\": \"service-subscription.service-type" + + "\", \"relationship-value\": \"uCPE-VMS\"},{ \"relationship-key\": \"" + + "service-instance.service-instance-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01" + + "\"} ], \"related-to-property\": [{\"property-key\": \"service-instance.service-instance-name" + + "\"}]},{ \"related-to\": \"vserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/" + + "cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/" + + "USUCP0PCOIL0110UJZZ01%3A%3AuCPE-VMS/vservers/vserver/3b2558f4-39d8-40e7-bfc7-30660fb52c45" + + "\", \"relationship-data\":[{ \"relationship-key\": \"cloud-region.cloud-owner\", \"" + + "relationship-value\": \"att-aic\"},{ \"relationship-key\": \"cloud-region.cloud-region-id" + + "\", \"relationship-value\": \"AAIAIC25\"},{ \"relationship-key\": \"tenant.tenant-id" + + "\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01::uCPE-VMS\"},{ \"relationship-key\": \"" + + "vserver.vserver-id\", \"relationship-value\": \"3b2558f4-39d8-40e7-bfc7-30660fb52c45\"} ], \"" + + "related-to-property\": [ {\"property-key\": \"vserver.vserver-name\",\"property-value\": \"" + + "USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; + + } + return "{ \"vnf-id\": \"5e49ca06-2972-4532-9ed4-6d071588d792\", \"vnf-name\": \"" + vnfName + + "\", \"vnf-type\": \"RT\", \"service-id\": \"d7bb0a21-66f2-4e6d-87d9-9ef3ced63ae4\", \"" + + "equipment-role\": \"UCPE\", \"orchestration-status\": \"created\", \"management-option\": \"ATT" + + "\", \"ipv4-oam-address\": \"32.40.68.35\", \"ipv4-loopback0-address\": \"32.40.64.57\", \"" + + "nm-lan-v6-address\": \"2001:1890:e00e:fffe::1345\", \"management-v6-address\": \"" + + "2001:1890:e00e:fffd::36\", \"in-maint\": false, \"is-closed-loop-disabled\": " + isDisabled + + ", \"resource-version\": \"1493389458092\", \"relationship-list\": {\"relationship\":[{ \"" + + "related-to\": \"service-instance\", \"related-link\": \"/aai/v11/business/customers/customer" + + "/1610_Func_Global_20160817084727/service-subscriptions/service-subscription/uCPE-VMS/" + + "service-instances/service-instance/USUCP0PCOIL0110UJZZ01\", \"relationship-data\":[{ \"" + + "relationship-key\": \"customer.global-customer-id\", \"relationship-value\": \"" + + "1610_Func_Global_20160817084727\"},{ \"relationship-key\": \"service-subscription.service-type" + + "\", \"relationship-value\": \"uCPE-VMS\"},{ \"relationship-key\": \"" + + "service-instance.service-instance-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01\"} ], \"" + + "related-to-property\": [{\"property-key\": \"service-instance.service-instance-name\"}]},{ \"" + + "related-to\": \"vserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/" + + "cloud-region/att-aic/AAIAIC25/tenants/tenant/USUCP0PCOIL0110UJZZ01%3A%3AuCPE-VMS/vservers/vserver" + + "/3b2558f4-39d8-40e7-bfc7-30660fb52c45\", \"relationship-data\":[{ \"relationship-key\": \"" + + "cloud-region.cloud-owner\", \"relationship-value\": \"att-aic\"},{ \"relationship-key\": \"" + + "cloud-region.cloud-region-id\", \"relationship-value\": \"AAIAIC25\"},{ \"relationship-key\": \"" + + "tenant.tenant-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01::uCPE-VMS\"},{ \"" + + "relationship-key\": \"vserver.vserver-id\", \"relationship-value\": \"" + + "3b2558f4-39d8-40e7-bfc7-30660fb52c45\"} ], \"related-to-property\": [ {\"property-key\": \"" + + "vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; + } + + /** + * Get by VNF Id. + * + * @param vnfId the VNF Id + * @return the response + */ + @GET + @Path("/v11/network/generic-vnfs/generic-vnf/{vnfId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String getByVnfId(@PathParam("vnfId") String vnfId) { + if ("getFail".equals(vnfId)) { + return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found" + + " for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",\"network/generic-vnfs/" + + "generic-vnf/getFail\",\"Node Not Found:No Node of type generic-vnf found at network/" + + "generic-vnfs/generic-vnf/getFail\",\"ERR.5.4.6114\"]}}}"; + } + boolean isDisabled = "disableClosedLoop".equals(vnfId); + return "{ \"vnf-id\": \"" + vnfId + + "\", \"vnf-name\": \"USUCP0PCOIL0110UJRT01\", \"vnf-type\": \"RT\", \"service-id\": \"" + + "d7bb0a21-66f2-4e6d-87d9-9ef3ced63ae4\", \"equipment-role\": \"UCPE\", \"orchestration-status" + + "\": \"created\", \"management-option\": \"ATT\", \"ipv4-oam-address\": \"32.40.68.35\", \"" + + "ipv4-loopback0-address\": \"32.40.64.57\", \"nm-lan-v6-address\": \"2001:1890:e00e:fffe::1345" + + "\", \"management-v6-address\": \"2001:1890:e00e:fffd::36\", \"in-maint\": false, \"" + "" + + "is-closed-loop-disabled\": " + isDisabled + ", \"resource-version\": \"1493389458092\", \"" + + "relationship-list\": {\"relationship\":[{ \"related-to\": \"service-instance\", \"related-link" + + "\": \"/aai/v11/business/customers/customer/1610_Func_Global_20160817084727/service-subscriptions" + + "/service-subscription/uCPE-VMS/service-instances/service-instance/USUCP0PCOIL0110UJZZ01\", \"" + + "relationship-data\":[{ \"relationship-key\": \"customer.global-customer-id\", \"" + + "relationship-value\": \"1610_Func_Global_20160817084727\"},{ \"relationship-key\": \"" + + "service-subscription.service-type\", \"relationship-value\": \"uCPE-VMS\"},{ \"relationship-key" + + "\": \"service-instance.service-instance-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01\"} " + + "], \"related-to-property\": [{\"property-key\": \"service-instance.service-instance-name\"}]}," + + "{ \"related-to\": \"vserver\", \"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/" + + "cloud-region/att-aic/AAIAIC25/tenants/tenant/USUCP0PCOIL0110UJZZ01%3A%3AuCPE-VMS/vservers/vserver" + + "/3b2558f4-39d8-40e7-bfc7-30660fb52c45\", \"relationship-data\":[{ \"relationship-key\": \"" + + "cloud-region.cloud-owner\", \"relationship-value\": \"att-aic\"},{ \"relationship-key\": \"" + + "cloud-region.cloud-region-id\", \"relationship-value\": \"AAIAIC25\"},{ \"relationship-key\": \"" + + "tenant.tenant-id\", \"relationship-value\": \"USUCP0PCOIL0110UJZZ01::uCPE-VMS\"},{ \"" + + "relationship-key\": \"vserver.vserver-id\", \"relationship-value\": \"" + + "3b2558f4-39d8-40e7-bfc7-30660fb52c45\"} ], \"related-to-property\": [ {\"property-key\": \"" + + "vserver.vserver-name\",\"property-value\": \"USUCP0PCOIL0110UJZZ01-vsrx\" }]} ]}}"; + } + + /** + * Get by VServer name. + * + * @param vserverName the VServer name + * @return the response + */ + @GET + @Path("/v11/nodes/vservers") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String getByVserverName(@QueryParam("vserver-name") String vserverName) { + if ("getFail".equals(vserverName)) { + return "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3001\",\"text\":\"Resource not found" + + " for %1 using id %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",\"nodes/vservers\",\"Node Not" + + " Found:No Node of type generic-vnf found at nodes/vservers\",\"ERR.5.4.6114\"]}}}"; + } + boolean isDisabled = "disableClosedLoop".equals(vserverName); + return "{\"vserver\": [{ \"vserver-id\": \"d0668d4f-c25e-4a1b-87c4-83845c01efd8\", \"vserver-name\": \"" + + vserverName + + "\", \"vserver-name2\": \"vjunos0\", \"vserver-selflink\": \"https://aai-ext1.test.att.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/USMSO1SX7NJ0103UJZZ01%3A%3AuCPE-VMS/vservers/vserver/d0668d4f-c25e-4a1b-87c4-83845c01efd8\", \"in-maint\": false, \"is-closed-loop-disabled\": " + + isDisabled + + ", \"resource-version\": \"1494001931513\", \"relationship-list\": {\"relationship\":[{ \"related-to" + + "\": \"generic-vnf\", \"related-link\": \"/aai/v11/network/generic-vnfs/generic-vnf/" + + "e1a41e99-4ede-409a-8f9d-b5e12984203a\", \"relationship-data\": [ {\"relationship-key\": \"" + + "generic-vnf.vnf-id\",\"relationship-value\": \"e1a41e99-4ede-409a-8f9d-b5e12984203a\" }], \"" + + "related-to-property\": [ {\"property-key\": \"generic-vnf.vnf-name\",\"property-value\": \"" + + "USMSO1SX7NJ0103UJSW01\" }]},{ \"related-to\": \"pserver\", \"related-link\": \"/aai/v11/" + + "cloud-infrastructure/pservers/pserver/USMSO1SX7NJ0103UJZZ01\", \"relationship-data\": [ {\"" + + "relationship-key\": \"pserver.hostname\",\"relationship-value\": \"USMSO1SX7NJ0103UJZZ01\" }], \"" + + "related-to-property\": [{\"property-key\": \"pserver.pserver-name2\"}]} ]}}]}"; + } } diff --git a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java index 4551cf246..90bec372b 100644 --- a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java +++ b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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. @@ -30,19 +30,24 @@ import org.json.JSONObject; @Path("/pdp/api") public class GuardSimulatorJaxRs { - public static final String DENY_CLNAME = "denyGuard"; + public static final String DENY_CLNAME = "denyGuard"; - @POST - @Path("/getDecision") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String getGuardDecision(String req){ - String clName = new JSONObject(req).getJSONObject("decisionAttributes").getString("clname"); - if (DENY_CLNAME.equals(clName)) - { - return "{\"decision\": \"DENY\", \"details\": \"Decision Deny. You asked for it\"}"; - } - else - return "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}"; - } + /** + * Get a guard decision. + * + * @param req the request + * @return the response + */ + @POST + @Path("/getDecision") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String getGuardDecision(String req) { + String clName = new JSONObject(req).getJSONObject("decisionAttributes").getString("clname"); + if (DENY_CLNAME.equals(clName)) { + return "{\"decision\": \"DENY\", \"details\": \"Decision Deny. You asked for it\"}"; + } else { + return "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}"; + } + } } diff --git a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/SoSimulatorJaxRs.java b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/SoSimulatorJaxRs.java index eb12362ee..1547fd41f 100644 --- a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/SoSimulatorJaxRs.java +++ b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/SoSimulatorJaxRs.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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,18 +29,26 @@ import javax.ws.rs.core.MediaType; @Path("/serviceInstances") public class SoSimulatorJaxRs { - - @POST - @Path("/v5/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String soPostQuery(@PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId) - { - // the requestID contained in the SO Response is a newly generated requestID - // with no relation to the requestID in Policy controlLoopEvent - return "{\"requestReferences\": {\"instanceId\": \"ff305d54-75b4-ff1b-bdb2-eb6b9e5460ff\", \"requestId\": \"rq1234d1-5a33-ffdf-23ab-12abad84e331\" }}"; + /** + * SO post query. + * + * @param serviceInstanceId the service instance Id + * @param vnfInstanceId the VNF Id + * @return the response + */ + @POST + @Path("/v5/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String soPostQuery(@PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("vnfInstanceId") String vnfInstanceId) { + + // the requestID contained in the SO Response is a newly generated requestID + // with no relation to the requestID in Policy controlLoopEvent + return "{\"requestReferences\": {\"instanceId\": \"ff305d54-75b4-ff1b-bdb2-eb6b9e5460ff\", \"requestId\": \"" + + "rq1234d1-5a33-ffdf-23ab-12abad84e331\" }}"; + + } - } - } diff --git a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/Util.java b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/Util.java index 05afd1179..fc9a9320e 100644 --- a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/Util.java +++ b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/Util.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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. @@ -26,56 +26,89 @@ import org.onap.policy.drools.http.server.HttpServletServer; import org.onap.policy.drools.utils.NetworkUtil; public class Util { - private Util() { - // Prevent instantiation of thic class - } + private Util() { + // Prevent instantiation of thic class + } - public static final String AAISIM_SERVER_NAME = "aaiSim"; - public static final String SOSIM_SERVER_NAME = "soSim"; - public static final String VFCSIM_SERVER_NAME = "vfcSim"; - public static final String GUARDSIM_SERVER_NAME = "guardSim"; + public static final String AAISIM_SERVER_NAME = "aaiSim"; + public static final String SOSIM_SERVER_NAME = "soSim"; + public static final String VFCSIM_SERVER_NAME = "vfcSim"; + public static final String GUARDSIM_SERVER_NAME = "guardSim"; - public static final int AAISIM_SERVER_PORT = 6666; - public static final int SOSIM_SERVER_PORT = 6667; - public static final int VFCSIM_SERVER_PORT = 6668; - public static final int GUARDSIM_SERVER_PORT = 6669; + public static final int AAISIM_SERVER_PORT = 6666; + public static final int SOSIM_SERVER_PORT = 6667; + public static final int VFCSIM_SERVER_PORT = 6668; + public static final int GUARDSIM_SERVER_PORT = 6669; - public static HttpServletServer buildAaiSim() throws InterruptedException, IOException { - final HttpServletServer testServer = HttpServletServer.factory.build(AAISIM_SERVER_NAME, - "localhost", AAISIM_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", AaiSimulatorJaxRs.class.getName()); - testServer.waitedStart(5000); - if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + testServer.getPort()); - return testServer; - } + /** + * Build an A&AI simulator. + * + * @return the simulator + * @throws InterruptedException if a thread is interrupted + * @throws IOException if an IO errror occurs + */ + public static HttpServletServer buildAaiSim() throws InterruptedException, IOException { + final HttpServletServer testServer = + HttpServletServer.factory.build(AAISIM_SERVER_NAME, "localhost", AAISIM_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", AaiSimulatorJaxRs.class.getName()); + testServer.waitedStart(5000); + if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) { + throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + } + return testServer; + } - public static HttpServletServer buildSoSim() throws InterruptedException, IOException { - final HttpServletServer testServer = HttpServletServer.factory.build(SOSIM_SERVER_NAME, - "localhost", SOSIM_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", SoSimulatorJaxRs.class.getName()); - testServer.waitedStart(5000); - if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + testServer.getPort()); - return testServer; - } + /** + * Build an SO simulator. + * + * @return the simulator + * @throws InterruptedException if a thread is interrupted + * @throws IOException if an IO errror occurs + */ + public static HttpServletServer buildSoSim() throws InterruptedException, IOException { + final HttpServletServer testServer = + HttpServletServer.factory.build(SOSIM_SERVER_NAME, "localhost", SOSIM_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", SoSimulatorJaxRs.class.getName()); + testServer.waitedStart(5000); + if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) { + throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + } + return testServer; + } - public static HttpServletServer buildVfcSim() throws InterruptedException, IOException { - final HttpServletServer testServer = HttpServletServer.factory.build(VFCSIM_SERVER_NAME, - "localhost", VFCSIM_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", VfcSimulatorJaxRs.class.getName()); - testServer.waitedStart(5000); - if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + testServer.getPort()); - return testServer; - } + /** + * Build a VFC simulator. + * + * @return the simulator + * @throws InterruptedException if a thread is interrupted + * @throws IOException if an IO errror occurs + */ + public static HttpServletServer buildVfcSim() throws InterruptedException, IOException { + final HttpServletServer testServer = + HttpServletServer.factory.build(VFCSIM_SERVER_NAME, "localhost", VFCSIM_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", VfcSimulatorJaxRs.class.getName()); + testServer.waitedStart(5000); + if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) { + throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + } + return testServer; + } - public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { - HttpServletServer testServer = HttpServletServer.factory.build(GUARDSIM_SERVER_NAME, "localhost", GUARDSIM_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", GuardSimulatorJaxRs.class.getName()); - testServer.waitedStart(5000); - if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + testServer.getPort()); - return testServer; - } + /** + * Build a guard simulator. + * + * @return the simulator + * @throws InterruptedException if a thread is interrupted + * @throws IOException if an IO errror occurs + */ + public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { + HttpServletServer testServer = HttpServletServer.factory.build(GUARDSIM_SERVER_NAME, "localhost", + GUARDSIM_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", GuardSimulatorJaxRs.class.getName()); + testServer.waitedStart(5000); + if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) { + throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + } + return testServer; + } } diff --git a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/VfcSimulatorJaxRs.java b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/VfcSimulatorJaxRs.java index b8c0683d5..101184d69 100644 --- a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/VfcSimulatorJaxRs.java +++ b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/VfcSimulatorJaxRs.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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,13 +20,13 @@ package org.onap.policy.simulators; +import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; -import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; @@ -36,32 +36,50 @@ import org.slf4j.LoggerFactory; @Path("/api/nslcm/v1") public class VfcSimulatorJaxRs { - @POST - @Path("/ns/{nsInstanceId}/heal") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String vfcPostQuery(@PathParam("nsInstanceId") String nsInstanceId, - @Context final HttpServletResponse response) - { - response.setStatus(HttpServletResponse.SC_ACCEPTED); - try { - response.flushBuffer(); - } catch(Exception e){ - final Logger logger = LoggerFactory.getLogger(VfcSimulatorJaxRs.class); - logger.error("flushBuffer threw: ", e); - return ""; - } + /** + * VFC post query. + * + * @param nsInstanceId the NS instance + * @param response the response + * @return the response + */ + @POST + @Path("/ns/{nsInstanceId}/heal") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String vfcPostQuery(@PathParam("nsInstanceId") String nsInstanceId, + @Context final HttpServletResponse response) { + response.setStatus(HttpServletResponse.SC_ACCEPTED); + try { + response.flushBuffer(); + } catch (Exception e) { + final Logger logger = LoggerFactory.getLogger(VfcSimulatorJaxRs.class); + logger.error("flushBuffer threw: ", e); + return ""; + } - return "{\"jobId\":\"1\"}"; - } + return "{\"jobId\":\"1\"}"; + } - @GET - @Path("/jobs/{jobId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces("application/json") - public String vfcGetQuery(@PathParam("jobId") String jobId) { - return "{\"jobId\" : "+jobId+",\"responseDescriptor\" : {\"progress\" : \"40\",\"status\" : \"finished\",\"statusDescription\" : \"OMC VMs are decommissioned in VIM\",\"errorCode\" : null,\"responseId\": 101 ,\"responseHistoryList\": [{\"progress\" : \"40\",\"status\" : \"proccessing\",\"statusDescription\" : \"OMC VMs are decommissioned in VIM\",\"errorCode\" : null,\"responseId\" : \"1\"}, {\"progress\" : \"41\",\"status\" : \"proccessing\",\"statusDescription\" : \"OMC VMs are decommissioned in VIM\",\"errorCode\" : null,\"responseId\" : \"2\"}]}}"; - } + /** + * VFC get query. + * + * @param jobId tthe job id + * @return the response + */ + @GET + @Path("/jobs/{jobId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces("application/json") + public String vfcGetQuery(@PathParam("jobId") String jobId) { + return "{\"jobId\" : " + jobId + + ",\"responseDescriptor\" : {\"progress\" : \"40\",\"status\" : \"finished\",\"statusDescription" + + "\" : \"OMC VMs are decommissioned in VIM\",\"errorCode\" : null,\"responseId\": 101 ,\"" + + "responseHistoryList\": [{\"progress\" : \"40\",\"status\" : \"proccessing\",\"statusDescription" + + "\" : \"OMC VMs are decommissioned in VIM\",\"errorCode\" : null,\"responseId\" : \"1\"}, {\"" + + "progress\" : \"41\",\"status\" : \"proccessing\",\"statusDescription\" : \"OMC VMs are " + + "decommissioned in VIM\",\"errorCode\" : null,\"responseId\" : \"2\"}]}}"; + } } diff --git a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/AaiSimulatorTest.java b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/AaiSimulatorTest.java index 86168e899..89208d2c6 100644 --- a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/AaiSimulatorTest.java +++ b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/AaiSimulatorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,70 +45,73 @@ import org.onap.policy.rest.RESTManager; public class AaiSimulatorTest { - @BeforeClass - public static void setUpSimulator() { - LoggerUtil.setLevel("ROOT", "INFO"); - LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - try { - Util.buildAaiSim(); - } catch (final Exception e) { - fail(e.getMessage()); + /** + * Set up test class. + */ + @BeforeClass + public static void setUpSimulator() { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + try { + Util.buildAaiSim(); + } catch (final Exception e) { + fail(e.getMessage()); + } } - } - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } - @Test - public void testGet() { - final AAIGETVnfResponse response = new AAIManager(new RESTManager()).getQueryByVnfID( - "http://localhost:6666/aai/v11/network/generic-vnfs/generic-vnf/", "testUser", "testPass", - UUID.randomUUID(), "5e49ca06-2972-4532-9ed4-6d071588d792"); - assertNotNull(response); - assertNotNull(response.getRelationshipList()); - } + @Test + public void testGet() { + final AAIGETVnfResponse response = new AAIManager(new RESTManager()).getQueryByVnfID( + "http://localhost:6666/aai/v11/network/generic-vnfs/generic-vnf/", "testUser", "testPass", + UUID.randomUUID(), "5e49ca06-2972-4532-9ed4-6d071588d792"); + assertNotNull(response); + assertNotNull(response.getRelationshipList()); + } - @Test - public void testPost() { - final AAINQRequest request = new AAINQRequest(); - final AAINQQueryParameters tempQueryParameters = new AAINQQueryParameters(); - final AAINQNamedQuery tempNamedQuery = new AAINQNamedQuery(); - tempNamedQuery.setNamedQueryUUID(UUID.fromString("4ff56a54-9e3f-46b7-a337-07a1d3c6b469")); - tempQueryParameters.setNamedQuery(tempNamedQuery); - request.setQueryParameters(tempQueryParameters); - Map<String, String> tempInnerMap = new HashMap<>(); - tempInnerMap.put("vserver-name", "vserver-name-16102016-aai3255-data-11-1"); - Map<String, Map<String, String>> tempOuterMap = new HashMap<>(); - tempOuterMap.put("vserver", tempInnerMap); - List<Map<String, Map<String, String>>> tempInstanceFilter = new LinkedList<>(); - tempInstanceFilter.add(tempOuterMap); - AAINQInstanceFilters tempInstanceFilters = new AAINQInstanceFilters(); - tempInstanceFilters.setInstanceFilter(tempInstanceFilter); - request.setInstanceFilters(tempInstanceFilters); + @Test + public void testPost() { + final AAINQRequest request = new AAINQRequest(); + final AAINQQueryParameters tempQueryParameters = new AAINQQueryParameters(); + final AAINQNamedQuery tempNamedQuery = new AAINQNamedQuery(); + tempNamedQuery.setNamedQueryUUID(UUID.fromString("4ff56a54-9e3f-46b7-a337-07a1d3c6b469")); + tempQueryParameters.setNamedQuery(tempNamedQuery); + request.setQueryParameters(tempQueryParameters); + Map<String, String> tempInnerMap = new HashMap<>(); + tempInnerMap.put("vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + Map<String, Map<String, String>> tempOuterMap = new HashMap<>(); + tempOuterMap.put("vserver", tempInnerMap); + List<Map<String, Map<String, String>>> tempInstanceFilter = new LinkedList<>(); + tempInstanceFilter.add(tempOuterMap); + AAINQInstanceFilters tempInstanceFilters = new AAINQInstanceFilters(); + tempInstanceFilters.setInstanceFilter(tempInstanceFilter); + request.setInstanceFilters(tempInstanceFilters); - AAINQResponse response = new AAIManager(new RESTManager()).postQuery("http://localhost:6666", "testUser", "testPass", - request, UUID.randomUUID()); - assertNotNull(response); - assertNotNull(response.getInventoryResponseItems()); + AAINQResponse response = new AAIManager(new RESTManager()).postQuery("http://localhost:6666", "testUser", + "testPass", request, UUID.randomUUID()); + assertNotNull(response); + assertNotNull(response.getInventoryResponseItems()); - tempNamedQuery.setNamedQueryUUID(UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087")); - tempQueryParameters.setNamedQuery(tempNamedQuery); - request.setQueryParameters(tempQueryParameters); - tempInnerMap = new HashMap<>(); - tempInnerMap.put("vnf-id", "de7cc3ab-0212-47df-9e64-da1c79234deb"); - tempOuterMap = new HashMap<>(); - tempOuterMap.put("generic-vnf", tempInnerMap); - tempInstanceFilter = new LinkedList<>(); - tempInstanceFilter.add(tempOuterMap); - tempInstanceFilters = new AAINQInstanceFilters(); - tempInstanceFilters.setInstanceFilter(tempInstanceFilter); - request.setInstanceFilters(tempInstanceFilters); + tempNamedQuery.setNamedQueryUUID(UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087")); + tempQueryParameters.setNamedQuery(tempNamedQuery); + request.setQueryParameters(tempQueryParameters); + tempInnerMap = new HashMap<>(); + tempInnerMap.put("vnf-id", "de7cc3ab-0212-47df-9e64-da1c79234deb"); + tempOuterMap = new HashMap<>(); + tempOuterMap.put("generic-vnf", tempInnerMap); + tempInstanceFilter = new LinkedList<>(); + tempInstanceFilter.add(tempOuterMap); + tempInstanceFilters = new AAINQInstanceFilters(); + tempInstanceFilters.setInstanceFilter(tempInstanceFilter); + request.setInstanceFilters(tempInstanceFilters); - response = new AAIManager(new RESTManager()).postQuery("http://localhost:6666", "testUser", "testPass", request, - UUID.randomUUID()); - assertNotNull(response); - assertNotNull(response.getInventoryResponseItems()); - } + response = new AAIManager(new RESTManager()).postQuery("http://localhost:6666", "testUser", "testPass", request, + UUID.randomUUID()); + assertNotNull(response); + assertNotNull(response.getInventoryResponseItems()); + } } diff --git a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java index ea13ec445..9522e55da 100644 --- a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java +++ b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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,10 @@ package org.onap.policy.simulators; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -28,48 +32,48 @@ import org.onap.policy.drools.utils.LoggerUtil; import org.onap.policy.rest.RESTManager; import org.onap.policy.rest.RESTManager.Pair; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - public class GuardSimulatorTest { - @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()); - } - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } - - @Test - public void testGuard() { - String request = makeRequest("test_actor_id", "test_op_id", "test_target", "test_clName"); - String url = "http://localhost:" + Util.GUARDSIM_SERVER_PORT + "/pdp/api/getDecision"; - Pair<Integer, String> response = new RESTManager().post(url, "testUname", "testPass", null, "application/json", request); - assertNotNull(response); - assertNotNull(response.a); - assertNotNull(response.b); - assertEquals("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}", response.b); - - request = makeRequest("test_actor_id", "test_op_id", "test_target", "denyGuard"); - response = new RESTManager().post(url, "testUname", "testPass", null, "application/json", request); - assertNotNull(response); + /** + * 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()); + } + } + + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } + + @Test + public void testGuard() { + String request = makeRequest("test_actor_id", "test_op_id", "test_target", "test_clName"); + String url = "http://localhost:" + Util.GUARDSIM_SERVER_PORT + "/pdp/api/getDecision"; + Pair<Integer, String> response = + new RESTManager().post(url, "testUname", "testPass", null, "application/json", request); + assertNotNull(response); + assertNotNull(response.a); + assertNotNull(response.b); + assertEquals("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}", response.b); + + request = makeRequest("test_actor_id", "test_op_id", "test_target", "denyGuard"); + response = new RESTManager().post(url, "testUname", "testPass", null, "application/json", request); + assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); assertEquals("{\"decision\": \"DENY\", \"details\": \"Decision Deny. You asked for it\"}", response.b); - } - - private static String makeRequest (String actor, String recipe, String target, String clName) { - return "{\"decisionAttributes\": {\"actor\": \"" + actor + "\", \"recipe\": \"" + recipe + "\"" + } + + private static String makeRequest(String actor, String recipe, String target, String clName) { + return "{\"decisionAttributes\": {\"actor\": \"" + actor + "\", \"recipe\": \"" + recipe + "\"" + ", \"target\": \"" + target + "\", \"clname\": \"" + clName + "\"}, \"onapName\": \"PDPD\"}"; - } + } } diff --git a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java index 8ea0062cc..edc942bbe 100644 --- a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java +++ b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/SoSimulatorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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. @@ -46,103 +46,104 @@ import org.onap.policy.so.util.Serialization; public class SoSimulatorTest { - @BeforeClass - public static void setUpSimulator() { - LoggerUtil.setLevel("ROOT", "INFO"); - LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - try { - Util.buildSoSim(); - } catch (final Exception e) { - fail(e.getMessage()); + /** + * Set up test class. + */ + @BeforeClass + public static void setUpSimulator() { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + try { + Util.buildSoSim(); + } catch (final Exception e) { + fail(e.getMessage()); + } } - } - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } - /** - * Create dummy SO request for TestResponse() junit - */ - private SORequest createTestRequest() { + /** + * Create dummy SO request for TestResponse() junit. + */ + private SORequest createTestRequest() { - // Construct SO Request - final SORequest request = new SORequest(); - request.setRequestId(UUID.randomUUID()); - request.setRequestDetails(new SORequestDetails()); - request.getRequestDetails().setModelInfo(new SOModelInfo()); - request.getRequestDetails().setCloudConfiguration(new SOCloudConfiguration()); - request.getRequestDetails().setRequestInfo(new SORequestInfo()); - request.getRequestDetails().setRequestParameters(new SORequestParameters()); - request.getRequestDetails().getRequestParameters().setUserParams(null); - // - // cloudConfiguration - // - request.getRequestDetails().getCloudConfiguration().setLcpCloudRegionId("DFW"); - request.getRequestDetails().getCloudConfiguration().setTenantId("1015548"); - // - // modelInfo - // - request.getRequestDetails().getModelInfo().setModelType("vfModule"); - request.getRequestDetails().getModelInfo().setModelInvariantId("f32568ec-2f1c-458a-864b-0593d53d141a"); - request.getRequestDetails().getModelInfo().setModelVersionId("69615025-879d-4f0d-afe3-b7d1a7eeed1f"); - request.getRequestDetails().getModelInfo().setModelName("C15ce9e1E9144c8fB8bb..dnsscaling..module-1"); - request.getRequestDetails().getModelInfo().setModelVersion("1.0"); - // - // requestInfo - // - request.getRequestDetails().getRequestInfo().setInstanceName( - "vDNS_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8"); - request.getRequestDetails().getRequestInfo().setSource("POLICY"); - request.getRequestDetails().getRequestInfo().setSuppressRollback(false); - request.getRequestDetails().getRequestInfo().setRequestorId("policy"); - // - // relatedInstanceList - // - final SORelatedInstanceListElement relatedInstanceListElement1 = - new SORelatedInstanceListElement(); - final SORelatedInstanceListElement relatedInstanceListElement2 = - new SORelatedInstanceListElement(); - relatedInstanceListElement1.setRelatedInstance(new SORelatedInstance()); - relatedInstanceListElement2.setRelatedInstance(new SORelatedInstance()); - // - relatedInstanceListElement1.getRelatedInstance().setInstanceId("cf8426a6-0b53-4e3d-bfa6-4b2f4d5913a5"); - relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SOModelInfo()); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service"); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelInvariantId( - "4fcbc1c0-7793-46d8-8aa1-fa1c2ed9ec7b"); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersionId( - "5c996219-b2e2-4c76-9b43-7e8672a33c1d"); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelName("8330e932-2a23-4943-8606"); - relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersion("1.0"); - // - relatedInstanceListElement2.getRelatedInstance().setInstanceId("594e2fe0-48b8-41ff-82e2-3d4bab69b192"); - relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SOModelInfo()); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf"); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelInvariantId( - "033a32ed-aa65-4764-a736-36f2942f1aa0"); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersionId( - "d4d072dc-4e21-4a03-9524-628985819a8e"); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelName("c15ce9e1-e914-4c8f-b8bb"); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersion("1"); - relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelCustomizationName( - "c15ce9e1-e914-4c8f-b8bb 1"); - // - request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1); - request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2); + // Construct SO Request + final SORequest request = new SORequest(); + request.setRequestId(UUID.randomUUID()); + request.setRequestDetails(new SORequestDetails()); + request.getRequestDetails().setModelInfo(new SOModelInfo()); + request.getRequestDetails().setCloudConfiguration(new SOCloudConfiguration()); + request.getRequestDetails().setRequestInfo(new SORequestInfo()); + request.getRequestDetails().setRequestParameters(new SORequestParameters()); + request.getRequestDetails().getRequestParameters().setUserParams(null); + // + // cloudConfiguration + // + request.getRequestDetails().getCloudConfiguration().setLcpCloudRegionId("DFW"); + request.getRequestDetails().getCloudConfiguration().setTenantId("1015548"); + // + // modelInfo + // + request.getRequestDetails().getModelInfo().setModelType("vfModule"); + request.getRequestDetails().getModelInfo().setModelInvariantId("f32568ec-2f1c-458a-864b-0593d53d141a"); + request.getRequestDetails().getModelInfo().setModelVersionId("69615025-879d-4f0d-afe3-b7d1a7eeed1f"); + request.getRequestDetails().getModelInfo().setModelName("C15ce9e1E9144c8fB8bb..dnsscaling..module-1"); + request.getRequestDetails().getModelInfo().setModelVersion("1.0"); + // + // requestInfo + // + request.getRequestDetails().getRequestInfo() + .setInstanceName("vDNS_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8"); + request.getRequestDetails().getRequestInfo().setSource("POLICY"); + request.getRequestDetails().getRequestInfo().setSuppressRollback(false); + request.getRequestDetails().getRequestInfo().setRequestorId("policy"); + // + // relatedInstanceList + // + final SORelatedInstanceListElement relatedInstanceListElement1 = new SORelatedInstanceListElement(); + final SORelatedInstanceListElement relatedInstanceListElement2 = new SORelatedInstanceListElement(); + relatedInstanceListElement1.setRelatedInstance(new SORelatedInstance()); + relatedInstanceListElement2.setRelatedInstance(new SORelatedInstance()); + // + relatedInstanceListElement1.getRelatedInstance().setInstanceId("cf8426a6-0b53-4e3d-bfa6-4b2f4d5913a5"); + relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SOModelInfo()); + relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service"); + relatedInstanceListElement1.getRelatedInstance().getModelInfo() + .setModelInvariantId("4fcbc1c0-7793-46d8-8aa1-fa1c2ed9ec7b"); + relatedInstanceListElement1.getRelatedInstance().getModelInfo() + .setModelVersionId("5c996219-b2e2-4c76-9b43-7e8672a33c1d"); + relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelName("8330e932-2a23-4943-8606"); + relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersion("1.0"); + // + relatedInstanceListElement2.getRelatedInstance().setInstanceId("594e2fe0-48b8-41ff-82e2-3d4bab69b192"); + relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SOModelInfo()); + relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf"); + relatedInstanceListElement2.getRelatedInstance().getModelInfo() + .setModelInvariantId("033a32ed-aa65-4764-a736-36f2942f1aa0"); + relatedInstanceListElement2.getRelatedInstance().getModelInfo() + .setModelVersionId("d4d072dc-4e21-4a03-9524-628985819a8e"); + relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelName("c15ce9e1-e914-4c8f-b8bb"); + relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersion("1"); + relatedInstanceListElement2.getRelatedInstance().getModelInfo() + .setModelCustomizationName("c15ce9e1-e914-4c8f-b8bb 1"); + // + request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1); + request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2); - return request; - } + return request; + } - @Test - public void testResponse() { - final String request = Serialization.gsonPretty.toJson(this.createTestRequest()); - final Pair<Integer, String> httpDetails = new RESTManager().post( - "http://localhost:6667/serviceInstances/v5/12345/vnfs/12345/vfModules", "username", - "password", new HashMap<>(), "application/json", request); - assertNotNull(httpDetails); - final SOResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, SOResponse.class); - assertNotNull(response); - } + @Test + public void testResponse() { + final String request = Serialization.gsonPretty.toJson(this.createTestRequest()); + final Pair<Integer, String> httpDetails = + new RESTManager().post("http://localhost:6667/serviceInstances/v5/12345/vnfs/12345/vfModules", + "username", "password", new HashMap<>(), "application/json", request); + assertNotNull(httpDetails); + final SOResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, SOResponse.class); + assertNotNull(response); + } } diff --git a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/VfcSimulatorTest.java b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/VfcSimulatorTest.java index 4c29331bf..d26cee321 100644 --- a/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/VfcSimulatorTest.java +++ b/controlloop/common/simulators/src/test/java/org/onap/policy/simulators/VfcSimulatorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * 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. @@ -38,42 +38,42 @@ import org.onap.policy.vfc.util.Serialization; public class VfcSimulatorTest { - @BeforeClass - public static void setUpSimulator() { - LoggerUtil.setLevel("ROOT", "INFO"); - LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - try { - Util.buildVfcSim(); - } catch (final Exception e) { - fail(e.getMessage()); + /** + * Set up test class. + */ + @BeforeClass + public static void setUpSimulator() { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + try { + Util.buildVfcSim(); + } catch (final Exception e) { + fail(e.getMessage()); + } } - } - @AfterClass - public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); - } + @AfterClass + public static void tearDownSimulator() { + HttpServletServer.factory.destroy(); + } - @Test - public void testPost() { - final Pair<Integer, String> httpDetails = - new RESTManager().post("http://localhost:6668/api/nslcm/v1/ns/1234567890/heal", "username", - "password", new HashMap<String, String>(), "application/json", "Some Request Here"); - assertNotNull(httpDetails); - assertTrue(httpDetails.a == 202); - final VFCResponse response = - Serialization.gsonPretty.fromJson(httpDetails.b, VFCResponse.class); - assertNotNull(response); - } + @Test + public void testPost() { + final Pair<Integer, String> httpDetails = + new RESTManager().post("http://localhost:6668/api/nslcm/v1/ns/1234567890/heal", "username", "password", + new HashMap<String, String>(), "application/json", "Some Request Here"); + assertNotNull(httpDetails); + assertTrue(httpDetails.a == 202); + final VFCResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, VFCResponse.class); + assertNotNull(response); + } - @Test - public void testGet() { - final Pair<Integer, String> httpDetails = - new RESTManager().get("http://localhost:6668/api/nslcm/v1/jobs/1234", "username", "password", - new HashMap<String, String>()); - assertNotNull(httpDetails); - final VFCResponse response = - Serialization.gsonPretty.fromJson(httpDetails.b, VFCResponse.class); - assertNotNull(response); - } + @Test + public void testGet() { + final Pair<Integer, String> httpDetails = new RESTManager().get("http://localhost:6668/api/nslcm/v1/jobs/1234", + "username", "password", new HashMap<String, String>()); + assertNotNull(httpDetails); + final VFCResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, VFCResponse.class); + assertNotNull(response); + } } |