aboutsummaryrefslogtreecommitdiffstats
path: root/applications
diff options
context:
space:
mode:
Diffstat (limited to 'applications')
-rw-r--r--applications/common/pom.xml6
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java19
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java4
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java21
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java64
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java8
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java6
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java8
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java6
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java5
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java4
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java65
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java21
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java21
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java47
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java23
-rw-r--r--applications/common/src/main/resources/persistence.xml12
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java73
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java11
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java80
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java25
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java40
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java82
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java26
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java65
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java44
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java117
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java31
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java56
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java27
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java124
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java100
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java78
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java115
-rw-r--r--applications/common/src/test/resources/META-INF/persistence.xml10
-rw-r--r--applications/guard/pom.xml2
-rw-r--r--applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java52
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java25
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java162
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java13
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java73
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java94
-rw-r--r--applications/guard/src/test/resources/META-INF/persistence.xml9
-rw-r--r--applications/match/pom.xml9
-rw-r--r--applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java66
-rw-r--r--applications/monitoring/pom.xml2
-rw-r--r--applications/monitoring/src/test/java/cucumber/RunCucumberTest.java32
-rw-r--r--applications/monitoring/src/test/java/cucumber/Stepdefs.java223
-rw-r--r--applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java60
-rw-r--r--applications/naming/pom.xml9
-rw-r--r--applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java87
-rw-r--r--applications/native/pom.xml2
-rw-r--r--applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java56
-rw-r--r--applications/optimization/pom.xml9
-rw-r--r--applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java20
-rw-r--r--applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java105
-rw-r--r--applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java21
-rw-r--r--applications/pom.xml2
63 files changed, 1221 insertions, 1401 deletions
diff --git a/applications/common/pom.xml b/applications/common/pom.xml
index c4ddeb2b..c9254911 100644
--- a/applications/common/pom.xml
+++ b/applications/common/pom.xml
@@ -27,7 +27,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>common</artifactId>
@@ -79,8 +79,8 @@
<version>4.0.0</version>
</dependency>
<dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core-jakarta</artifactId>
+ <groupId>org.hibernate.orm</groupId>
+ <artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java
index 2ccc694a..b8e1aa67 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory;
* Methods to access policy-api via REST service calls.
*/
public class PolicyApiCaller {
- private static Logger logger = LoggerFactory.getLogger(PolicyApiCaller.class);
+ private static final Logger logger = LoggerFactory.getLogger(PolicyApiCaller.class);
private static final String POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
private static final String POLICY_TYPE_VERSION_URI = "/versions/";
@@ -60,18 +60,19 @@ public class PolicyApiCaller {
try {
Response resp = httpClient
- .get(POLICY_TYPE_URI + type.getName() + POLICY_TYPE_VERSION_URI + type.getVersion());
+ .get(POLICY_TYPE_URI + type.getName() + POLICY_TYPE_VERSION_URI + type.getVersion());
- switch (resp.getStatus()) {
- case HttpURLConnection.HTTP_OK:
- return resp.readEntity(ToscaServiceTemplate.class);
- case HttpURLConnection.HTTP_NOT_FOUND:
+ return switch (resp.getStatus()) {
+ case HttpURLConnection.HTTP_OK -> resp.readEntity(ToscaServiceTemplate.class);
+ case HttpURLConnection.HTTP_NOT_FOUND -> {
logger.warn("policy-api not found {}", resp);
throw new NotFoundException(type.toString());
- default:
+ }
+ default -> {
logger.warn("policy-api request error {}", resp);
throw new PolicyApiException(type.toString());
- }
+ }
+ };
} catch (RuntimeException e) {
logger.warn("policy-api connection error, client info: {} ", httpClient);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java
index 071a14e1..bf25707f 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +23,11 @@
package org.onap.policy.pdp.xacml.application.common;
+import java.io.Serial;
+
public class ToscaPolicyConversionException extends Exception {
+ @Serial
private static final long serialVersionUID = 1L;
public ToscaPolicyConversionException() {
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java
index 0d23bc1c..9573a1b3 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -172,8 +173,8 @@ public final class ToscaPolicyTranslatorUtils {
theInt = Integer.parseInt(strInteger);
} catch (NumberFormatException e) {
try {
- Double dblLimit = Double.parseDouble(strInteger);
- theInt = dblLimit.intValue();
+ double dblLimit = Double.parseDouble(strInteger);
+ theInt = (int) dblLimit;
} catch (NumberFormatException e1) {
return null;
}
@@ -190,18 +191,18 @@ public final class ToscaPolicyTranslatorUtils {
* @return returns the given anyOf or new AnyTypeOf if null
*/
public static AnyOfType buildAndAppendAllof(AnyOfType anyOf, Object type) {
- if (type instanceof MatchType) {
+ if (type instanceof MatchType matchType) {
var allOf = new AllOfType();
- allOf.getMatch().add((MatchType) type);
+ allOf.getMatch().add(matchType);
if (anyOf == null) {
anyOf = new AnyOfType();
}
anyOf.getAllOf().add(allOf);
- } else if (type instanceof AllOfType) {
+ } else if (type instanceof AllOfType allOfType) {
if (anyOf == null) {
anyOf = new AnyOfType();
}
- anyOf.getAllOf().add((AllOfType) type);
+ anyOf.getAllOf().add(allOfType);
}
return anyOf;
@@ -215,11 +216,11 @@ public final class ToscaPolicyTranslatorUtils {
* @return TargetType
*/
public static TargetType buildAndAppendTarget(TargetType target, Object object) {
- if (object instanceof AnyOfType) {
- target.getAnyOf().add((AnyOfType) object);
- } else if (object instanceof MatchType) {
+ if (object instanceof AnyOfType anyOfType) {
+ target.getAnyOf().add(anyOfType);
+ } else if (object instanceof MatchType matchType) {
var allOf = new AllOfType();
- allOf.getMatch().add((MatchType) object);
+ allOf.getMatch().add(matchType);
var anyOf = new AnyOfType();
anyOf.getAllOf().add(allOf);
target.getAnyOf().add(anyOf);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
index 596a3cc6..ccd4d0de 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,7 +39,6 @@ import java.util.Properties;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Function;
-import java.util.stream.Collectors;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.IdReferenceType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
@@ -62,9 +62,9 @@ public final class XacmlPolicyUtils {
* file name. Does nothing for other OSs.
*/
private static final Function<String, String> SANITIZE_FILE_NAME =
- System.getProperty("os.name").startsWith("Windows")
- ? filename -> filename.replace(':', '_')
- : filename -> filename;
+ System.getProperty("os.name").startsWith("Windows")
+ ? filename -> filename.replace(':', '_')
+ : filename -> filename;
private XacmlPolicyUtils() {
super();
@@ -74,7 +74,7 @@ public final class XacmlPolicyUtils {
* Creates an empty PolicySetType object given the id and combining algorithm. Note,there
* will also be an empty Target created. You can easily override that if need be.
*
- * @param policyId Policy Id
+ * @param policyId Policy Id
* @param policyCombiningAlgorithm Policy Combining Algorithm
* @return PolicySetType object
*/
@@ -90,7 +90,7 @@ public final class XacmlPolicyUtils {
* Creates an empty PolicySetType object given the id and combining algorithm. Note,there
* will also be an empty Target created. You can easily override that if need be.
*
- * @param policyId Policy Id
+ * @param policyId Policy Id
* @param ruleCombiningAlgorithm Rule Combining Algorithm
* @return PolicyType object
*/
@@ -106,12 +106,12 @@ public final class XacmlPolicyUtils {
* This method adds a list of PolicyType objects to a root PolicySetType as
* referenced policies.
*
- * @param rootPolicy Root PolicySet being updated
+ * @param rootPolicy Root PolicySet being updated
* @param referencedPolicies A list of PolicyType being added as a references
* @return the rootPolicy PolicySet object
*/
public static PolicySetType addPoliciesToXacmlRootPolicy(PolicySetType rootPolicy,
- PolicyType... referencedPolicies) {
+ PolicyType... referencedPolicies) {
var factory = new ObjectFactory();
//
// Iterate each policy
@@ -133,12 +133,12 @@ public final class XacmlPolicyUtils {
/**
* This method updates a root PolicySetType by adding in a PolicyType as a reference.
*
- * @param rootPolicy Root PolicySet being updated
+ * @param rootPolicy Root PolicySet being updated
* @param referencedPolicySets A list of PolicySetType being added as a references
* @return the rootPolicy PolicySet object
*/
public static PolicySetType addPolicySetsToXacmlRootPolicy(PolicySetType rootPolicy,
- PolicySetType... referencedPolicySets) {
+ PolicySetType... referencedPolicySets) {
var factory = new ObjectFactory();
//
// Iterate each policy
@@ -160,7 +160,7 @@ public final class XacmlPolicyUtils {
/**
* Adds in the root policy to the PDP properties object.
*
- * @param properties Input properties
+ * @param properties Input properties
* @param rootPolicyPath Path to the root policy file
* @return Properties object
*/
@@ -187,14 +187,14 @@ public final class XacmlPolicyUtils {
// Set the new comma separated list
//
properties.setProperty(XACMLProperties.PROP_ROOTPOLICIES,
- rootPolicies.stream().collect(Collectors.joining(",")));
+ String.join(",", rootPolicies));
return properties;
}
/**
* Adds in the referenced policy to the PDP properties object.
*
- * @param properties Input properties
+ * @param properties Input properties
* @param refPolicyPath Path to the referenced policy file
* @return Properties object
*/
@@ -221,7 +221,7 @@ public final class XacmlPolicyUtils {
// Set the new comma separated list
//
properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES,
- referencedPolicies.stream().collect(Collectors.joining(",")));
+ String.join(",", referencedPolicies));
return properties;
}
@@ -229,7 +229,7 @@ public final class XacmlPolicyUtils {
* Removes a root policy from the Properties object. Both in the line
* that identifies the policy and the .file property that points to the path.
*
- * @param properties Input Properties object to remove
+ * @param properties Input Properties object to remove
* @param rootPolicyPath The policy file path
* @return Properties object
*/
@@ -273,7 +273,7 @@ public final class XacmlPolicyUtils {
* Removes a referenced policy from the Properties object. Both in the line
* that identifies the policy and the .file property that points to the path.
*
- * @param properties Input Properties object to remove
+ * @param properties Input Properties object to remove
* @param refPolicyPath The policy file path
* @return Properties object
*/
@@ -317,7 +317,7 @@ public final class XacmlPolicyUtils {
* Does a debug dump of referenced and root policy values.
*
* @param properties Input Properties object
- * @param logger Logger object to use
+ * @param logger Logger object to use
*/
public static void debugDumpPolicyProperties(Properties properties, Logger logger) {
//
@@ -356,18 +356,18 @@ public final class XacmlPolicyUtils {
* <P>How do we track that in case we need to know what policies we have loaded?
*
* @param policy PolicyType object
- * @param path Path for policy
+ * @param path Path for policy
* @return Path unique file path for the Policy
*/
public static Path constructUniquePolicyFilename(Object policy, Path path) {
String id;
String version;
- if (policy instanceof PolicyType) {
- id = ((PolicyType) policy).getPolicyId();
- version = ((PolicyType) policy).getVersion();
- } else if (policy instanceof PolicySetType) {
- id = ((PolicySetType) policy).getPolicySetId();
- version = ((PolicySetType) policy).getVersion();
+ if (policy instanceof PolicyType policyType) {
+ id = policyType.getPolicyId();
+ version = policyType.getVersion();
+ } else if (policy instanceof PolicySetType policySetType) {
+ id = policySetType.getPolicySetId();
+ version = policySetType.getVersion();
} else {
throw new IllegalArgumentException("Must pass a PolicyType or PolicySetType");
}
@@ -435,13 +435,13 @@ public final class XacmlPolicyUtils {
* Copies a xacml.properties file to another location and all the policies defined within it.
*
* @param propertiesPath Path to an existing properties file
- * @param properties Properties object
- * @param creator A callback that can create files. Allows JUnit test to pass Temporary folder
+ * @param properties Properties object
+ * @param creator A callback that can create files. Allows JUnit test to pass Temporary folder
* @return File object that points to new Properties file
* @throws IOException Could not read/write files
*/
public static File copyXacmlPropertiesContents(String propertiesPath, Properties properties,
- FileCreator creator) throws IOException {
+ FileCreator creator) throws IOException {
//
// Open the properties file
//
@@ -516,15 +516,15 @@ public final class XacmlPolicyUtils {
/**
* Wraps the call to XACMLPolicyWriter.
*
- * @param path Path to file to be written to.
+ * @param path Path to file to be written to.
* @param policy PolicyType or PolicySetType
* @return Path - the same path passed in most likely from XACMLPolicyWriter. Or NULL if an error occurs.
*/
public static Path writePolicyFile(Path path, Object policy) {
- if (policy instanceof PolicyType) {
- return XACMLPolicyWriter.writePolicyFile(path, (PolicyType) policy);
- } else if (policy instanceof PolicySetType) {
- return XACMLPolicyWriter.writePolicyFile(path, (PolicySetType) policy);
+ if (policy instanceof PolicyType policyType) {
+ return XACMLPolicyWriter.writePolicyFile(path, policyType);
+ } else if (policy instanceof PolicySetType policySetType) {
+ return XACMLPolicyWriter.writePolicyFile(path, policySetType);
} else {
throw new IllegalArgumentException("Expecting PolicyType or PolicySetType");
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java
index ca29c96a..f4011bd0 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -69,8 +69,8 @@ public class MatchablePolicyType {
);
//@formatter:on
- private ToscaConceptIdentifier policyId;
- private Map<String, MatchableProperty> matchables = new HashMap<>();
+ private final ToscaConceptIdentifier policyId;
+ private final Map<String, MatchableProperty> matchables = new HashMap<>();
public MatchablePolicyType(@NonNull ToscaPolicyType policyType, @NonNull MatchableCallback callback) {
this.policyId = new ToscaConceptIdentifier(policyType.getName(), policyType.getVersion());
@@ -119,7 +119,7 @@ public class MatchablePolicyType {
final String property = entrySet.getKey();
final var toscaProperty = entrySet.getValue();
//
- // Most likely case is its a primitive
+ // Most likely case is it's a primitive
//
if (isPrimitive(toscaProperty.getType())) {
MatchableProperty primitiveProperty = handlePrimitive(property, toscaProperty);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java
index 8ea65307..048d6185 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,8 @@ public class MatchablePropertyTypeBoolean extends MatchablePropertyTypeBase<Bool
@Override
public Boolean validate(Object value) throws ToscaPolicyConversionException {
- if (value instanceof Boolean) {
- return (Boolean) value;
+ if (value instanceof Boolean bolValue) {
+ return bolValue;
}
return Boolean.parseBoolean(value.toString());
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java
index bc702c1c..cac7d041 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,13 +45,13 @@ public class MatchablePropertyTypeFloat extends MatchablePropertyTypeBase<Float>
//
// Most likely it isn't because Gson does not recognize floats
//
- if (value instanceof Float) {
- return (Float) value;
+ if (value instanceof Float floatValue) {
+ return floatValue;
}
try {
return Float.parseFloat(value.toString());
} catch (NumberFormatException e) {
- throw new ToscaPolicyConversionException("Bad float value" + value.toString(), e);
+ throw new ToscaPolicyConversionException("Bad float value" + value, e);
}
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java
index b23d344f..fc5b7fdb 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,8 @@ public class MatchablePropertyTypeInteger extends MatchablePropertyTypeBase<Inte
@Override
public Integer validate(Object value) throws ToscaPolicyConversionException {
- if (value instanceof Integer) {
- return (Integer) value;
+ if (value instanceof Integer intValue) {
+ return intValue;
}
try {
return Integer.valueOf(value.toString());
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java
index 0c42d357..24af9973 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,8 @@ import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionExcepti
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
public class MatchablePropertyTypeList extends MatchablePropertyTypeBase<List<MatchablePropertyType<?>>> {
- private MatchableProperty primitiveProperty;
+
+ private final MatchableProperty primitiveProperty;
/**
* constructor.
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java
index 71ea55e8..b79d48ea 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,7 +47,7 @@ public class MatchablePropertyTypeTimestamp extends MatchablePropertyTypeBase<IS
try {
return ISO8601DateTime.fromISO8601DateTimeString(value.toString());
} catch (ParseException e) {
- throw new ToscaPolicyConversionException("bad ISO8601 timevalue " + value.toString(), e);
+ throw new ToscaPolicyConversionException("bad ISO8601 time value " + value, e);
}
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
index d1c6d38c..c1c0f15c 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,16 +60,14 @@ import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Setter
+@Getter
public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
private static final Logger LOGGER = LoggerFactory.getLogger(StdBaseTranslator.class);
private static final ObjectFactory factory = new ObjectFactory();
- @Getter
- @Setter
protected boolean booleanReturnAttributes = false;
- @Getter
- @Setter
protected boolean booleanReturnSingleValueAttributesAsCollection = false;
public static final String POLICY_ID = "policy-id";
@@ -131,7 +130,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* obligations. This method must be overridden and be implemented for the specific application as
* obligations may have different expected attributes per application.
*
- * @param obligations Collection of obligation objects
+ * @param obligations Collection of obligation objects
* @param decisionResponse DecisionResponse object used to store any results from obligations.
*/
protected abstract void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse);
@@ -141,7 +140,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* can be overridden for each specific application as advice may have different expected attributes per
* application.
*
- * @param advice Collection of Advice objects
+ * @param advice Collection of Advice objects
* @param decisionResponse DecisionResponse object used to store any results from advice.
*/
protected abstract void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse);
@@ -151,10 +150,10 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* DecisionResponse object.
*
* @param attributeCategories Collection of AttributeCategory objects
- * @param decisionResponse DecisionResponse object used to store any attributes
+ * @param decisionResponse DecisionResponse object used to store any attributes
*/
protected void scanAttributes(Collection<AttributeCategory> attributeCategories,
- DecisionResponse decisionResponse) {
+ DecisionResponse decisionResponse) {
var returnedAttributes = new HashMap<String, Object>();
for (AttributeCategory attributeCategory : attributeCategories) {
var mapCategory = new HashMap<String, Object>();
@@ -163,7 +162,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
// Most attributes have a single value, thus the collection is not necessary to
// return. However, we will allow this to be configurable.
//
- if (! booleanReturnSingleValueAttributesAsCollection && attribute.getValues().size() == 1) {
+ if (!booleanReturnSingleValueAttributesAsCollection && attribute.getValues().size() == 1) {
var iterator = attribute.getValues().iterator();
var value = iterator.next();
mapCategory.put(attribute.getAttributeId().stringValue(), value.getValue().toString());
@@ -173,7 +172,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
}
returnedAttributes.put(attributeCategory.getCategory().stringValue(), mapCategory);
}
- if (! returnedAttributes.isEmpty()) {
+ if (!returnedAttributes.isEmpty()) {
decisionResponse.setAttributes(returnedAttributes);
}
}
@@ -182,25 +181,25 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* From the TOSCA metadata section, pull in values that are needed into the XACML policy.
*
* @param policy Policy Object to store the metadata
- * @param map The Metadata TOSCA Map
+ * @param map The Metadata TOSCA Map
* @return Same Policy Object
* @throws ToscaPolicyConversionException If there is something missing from the metadata
*/
- protected PolicyType fillMetadataSection(PolicyType policy,
- Map<String, Object> map) throws ToscaPolicyConversionException {
+ protected PolicyType fillMetadataSection(PolicyType policy, Map<String, Object> map)
+ throws ToscaPolicyConversionException {
//
// Ensure the policy-id exists - we don't use it here. It
// is saved in the TOSCA Policy Name field.
//
- if (! map.containsKey(POLICY_ID)) {
+ if (!map.containsKey(POLICY_ID)) {
throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata " + POLICY_ID);
}
//
// Ensure the policy-version exists
//
- if (! map.containsKey(POLICY_VERSION)) {
+ if (!map.containsKey(POLICY_VERSION)) {
throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata "
- + POLICY_VERSION);
+ + POLICY_VERSION);
}
//
// Add in the Policy Version
@@ -214,20 +213,20 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* return the obligation only instead of adding it directly to a rule/policy/policyset.
* But this is fine for now.
*
- * @param <T> RuleType, PolicyType, PolicySetType object
- * @Param policyId The policy-id
+ * @param <T> RuleType, PolicyType, PolicySetType object
+ * @param policyId The policy-id
* @param ruleOrPolicy Incoming RuleType, PolicyType, PolicySetType object
- * @param jsonPolicy JSON String representation of policy.
- * @param weight Weighting for the policy (optional)
+ * @param jsonPolicy JSON String representation of policy.
+ * @param weight Weighting for the policy (optional)
* @return Return the Incoming RuleType, PolicyType, PolicySetType object for convenience.
*/
protected <T> T addObligation(T ruleOrPolicy, String policyId, String jsonPolicy, Integer weight,
- String policyType) {
+ String policyType) {
//
// Creating obligation for returning policy
//
LOGGER.info("Obligation Policy id: {} type: {} weight: {} policy:{}{}", policyId, policyType, weight,
- XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
+ XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
//
// Create our OnapObligation
//
@@ -241,12 +240,12 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
//
var obligations = new ObligationExpressionsType();
obligations.getObligationExpression().add(obligation);
- if (ruleOrPolicy instanceof RuleType) {
- ((RuleType) ruleOrPolicy).setObligationExpressions(obligations);
- } else if (ruleOrPolicy instanceof PolicyType) {
- ((PolicyType) ruleOrPolicy).setObligationExpressions(obligations);
- } else if (ruleOrPolicy instanceof PolicySetType) {
- ((PolicySetType) ruleOrPolicy).setObligationExpressions(obligations);
+ if (ruleOrPolicy instanceof RuleType ruleType) {
+ ruleType.setObligationExpressions(obligations);
+ } else if (ruleOrPolicy instanceof PolicyType policyType1) {
+ policyType1.setObligationExpressions(obligations);
+ } else if (ruleOrPolicy instanceof PolicySetType policySetType) {
+ policySetType.setObligationExpressions(obligations);
} else {
LOGGER.error("Unsupported class for adding obligation {}", ruleOrPolicy.getClass());
}
@@ -268,11 +267,11 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
// Create the match for the policy type
//
var match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_STRING_EQUAL,
- type,
- XACML3.ID_DATATYPE_STRING,
- ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
- XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
+ XACML3.ID_FUNCTION_STRING_EQUAL,
+ type,
+ XACML3.ID_DATATYPE_STRING,
+ ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
+ XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
//
// Add it to an AnyOfType object
//
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java
index 3e7c10af..ab32caef 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -52,7 +53,7 @@ public class StdCombinedPolicyRequest {
@XACMLSubject(attributeId = "urn:org:onap:onap-component", includeInResults = true)
private String onapComponent;
- @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
+ @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
private String onapInstance;
@XACMLAction()
@@ -92,18 +93,18 @@ public class StdCombinedPolicyRequest {
Map<String, Object> resources = decisionRequest.getResource();
for (Entry<String, Object> entrySet : resources.entrySet()) {
if (POLICY_ID_KEY.equals(entrySet.getKey())) {
- if (entrySet.getValue() instanceof Collection) {
- addPolicyIds(request, (Collection) entrySet.getValue());
- } else if (entrySet.getValue() instanceof String) {
- request.resource.add(entrySet.getValue().toString());
+ if (entrySet.getValue() instanceof Collection collection) {
+ addPolicyIds(request, collection);
+ } else if (entrySet.getValue() instanceof String stringValue) {
+ request.resource.add(stringValue);
}
continue;
}
if (POLICY_TYPE_KEY.equals(entrySet.getKey())) {
- if (entrySet.getValue() instanceof Collection) {
- addPolicyTypes(request, (Collection) entrySet.getValue());
- } else if (entrySet.getValue() instanceof String) {
- request.resourcePolicyType.add(entrySet.getValue().toString());
+ if (entrySet.getValue() instanceof Collection collection) {
+ addPolicyTypes(request, collection);
+ } else if (entrySet.getValue() instanceof String stringValue) {
+ request.resourcePolicyType.add(stringValue);
}
}
}
@@ -118,7 +119,7 @@ public class StdCombinedPolicyRequest {
}
protected static StdCombinedPolicyRequest addPolicyTypes(StdCombinedPolicyRequest request,
- Collection<Object> types) {
+ Collection<Object> types) {
for (Object type : types) {
request.resourcePolicyType.add(type.toString());
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java
index 42e3d43e..a084ec24 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,8 +39,8 @@ import com.att.research.xacml.std.annotations.XACMLRequest;
import com.att.research.xacml.std.annotations.XACMLSubject;
import com.att.research.xacml.util.FactoryException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import lombok.Getter;
@@ -69,13 +70,13 @@ public class StdMatchablePolicyRequest {
@XACMLSubject(attributeId = "urn:org:onap:onap-component", includeInResults = true)
private String onapComponent;
- @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
+ @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
private String onapInstance;
@XACMLAction()
private String action;
- protected static DataTypeFactory dataTypeFactory = null;
+ protected static DataTypeFactory dataTypeFactory = null;
protected static synchronized DataTypeFactory getDataTypeFactory() {
try {
@@ -148,10 +149,11 @@ public class StdMatchablePolicyRequest {
// and use that to validate the fields that are matchable.
//
try {
- if (entrySet.getValue() instanceof Collection) {
- addResources(resourceAttributes, (Collection) entrySet.getValue(), attributeId);
+ if (entrySet.getValue() instanceof Collection collection) {
+ addResources(resourceAttributes, collection, attributeId);
} else {
- addResources(resourceAttributes, Arrays.asList(entrySet.getValue().toString()), attributeId);
+ addResources(resourceAttributes,
+ Collections.singletonList(entrySet.getValue().toString()), attributeId);
}
} catch (DataTypeException e) {
throw new XacmlApplicationException("Failed to add resource ", e);
@@ -162,19 +164,20 @@ public class StdMatchablePolicyRequest {
}
protected static StdMutableRequestAttributes addResources(StdMutableRequestAttributes attributes,
- Collection<Object> values, String id) throws DataTypeException {
+ Collection<Object> values, String id)
+ throws DataTypeException {
var factory = getDataTypeFactory();
if (factory == null) {
return null;
}
for (Object value : values) {
- var mutableAttribute = new StdMutableAttribute();
+ var mutableAttribute = new StdMutableAttribute();
mutableAttribute.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
mutableAttribute.setAttributeId(new IdentifierImpl(id));
mutableAttribute.setIncludeInResults(true);
- DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
+ DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
AttributeValue<?> attributeValue = dataTypeExtended.createAttributeValue(value);
Collection<AttributeValue<?>> attributeValues = new ArrayList<>();
attributeValues.add(attributeValue);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
index 732542a2..a58b8c47 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -82,10 +82,9 @@ import org.slf4j.LoggerFactory;
* to translate policies.
*
* @author pameladragosh
- *
*/
@NoArgsConstructor
-public class StdMatchableTranslator extends StdBaseTranslator implements MatchableCallback {
+public class StdMatchableTranslator extends StdBaseTranslator implements MatchableCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
@@ -112,7 +111,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* scanObligations - scans the list of obligations and make appropriate method calls to process
* obligations.
*
- * @param obligations Collection of obligation objects
+ * @param obligations Collection of obligation objects
* @param decisionResponse DecisionResponse object used to store any results from obligations.
*/
@Override
@@ -165,10 +164,10 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* contents and their details.
*
* @param closestMatches Map holding the current set of highest weight policy types
- * @param obligation Obligation object
+ * @param obligation Obligation object
*/
protected void scanClosestMatchObligation(
- Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches, Obligation obligation) {
+ Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches, Obligation obligation) {
//
// Create our OnapObligation object
//
@@ -177,7 +176,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// All 4 *should* be there
//
if (onapObligation.getPolicyId() == null || onapObligation.getPolicyContent() == null
- || onapObligation.getPolicyType() == null || onapObligation.getWeight() == null) {
+ || onapObligation.getPolicyType() == null || onapObligation.getWeight() == null) {
LOGGER.error("Missing an expected attribute in obligation.");
return;
}
@@ -197,13 +196,13 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Only need to check first one - as we will ensure there is only one weight
//
Entry<Integer, List<Pair<String, Map<String, Object>>>> firstEntry =
- weightMap.entrySet().iterator().next();
+ weightMap.entrySet().iterator().next();
if (policyWeight < firstEntry.getKey()) {
//
// Existing policies have a greater weight, so we will not add it
//
LOGGER.info("{} is lesser weight {} than current policies, will not return it", policyWeight,
- firstEntry.getKey());
+ firstEntry.getKey());
} else if (firstEntry.getKey().equals(policyWeight)) {
//
// Same weight - we will add it
@@ -246,7 +245,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
//
if (toscaPolicyTypeTemplate == null) {
throw new ToscaPolicyConversionException(
- "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
+ "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
}
//
// Policy name should be at the root
@@ -340,14 +339,8 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
return null;
}
- private class MyMatchableCallback implements MatchableCallback {
- private StdMatchableTranslator translator;
- private ToscaServiceTemplate template;
-
- public MyMatchableCallback(StdMatchableTranslator translator, ToscaServiceTemplate template) {
- this.translator = translator;
- this.template = template;
- }
+ private record MyMatchableCallback(StdMatchableTranslator translator, ToscaServiceTemplate template)
+ implements MatchableCallback {
@Override
public ToscaPolicyType retrievePolicyType(String derivedFrom) {
@@ -369,7 +362,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* For generating target type, we scan for matchable properties
* and use those to build the policy.
*
- * @param policy the policy
+ * @param policy the policy
* @param template template containing the policy
* @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
*/
@@ -394,7 +387,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Create the matchable
//
matchablePolicyType = new MatchablePolicyType(
- template.getPolicyTypes().get(policy.getType()), myCallback);
+ template.getPolicyTypes().get(policy.getType()), myCallback);
//
// Cache it
//
@@ -422,7 +415,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
@SuppressWarnings("unchecked")
protected void fillTargetTypeWithMatchables(TargetType target, MatchablePolicyType matchablePolicyType,
- Map<String, Object> properties) throws ToscaPolicyConversionException {
+ Map<String, Object> properties) throws ToscaPolicyConversionException {
for (Entry<String, Object> entrySet : properties.entrySet()) {
String propertyName = entrySet.getKey();
Object propertyValue = entrySet.getValue();
@@ -436,7 +429,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Depending on what type it is, add it into the target
//
ToscaPolicyTranslatorUtils.buildAndAppendTarget(target,
- matchable.getType().generate(propertyValue, id));
+ matchable.getType().generate(propertyValue, id));
continue;
}
@@ -480,7 +473,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Is it loaded in memory?
//
ToscaServiceTemplate policyTemplate = this.matchablePolicyTypes.get(policyTypeId);
- if (policyTemplate == null) {
+ if (policyTemplate == null) {
//
// Load the policy
//
@@ -540,7 +533,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Decode the template
//
ToscaServiceTemplate template = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
- ToscaServiceTemplate.class);
+ ToscaServiceTemplate.class);
//
// Ensure all the fields are setup correctly
//
@@ -561,12 +554,12 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* pullPolicyType - pulls the given ToscaConceptIdentifier from the Policy Lifecycle API.
* If successful, will store it locally given the policyTypePath.
*
- * @param policyTypeId ToscaConceptIdentifier
+ * @param policyTypeId ToscaConceptIdentifier
* @param policyTypePath Path object to store locally
* @return ToscaPolicyType object. Null if failure.
*/
protected synchronized ToscaServiceTemplate pullPolicyType(ToscaConceptIdentifier policyTypeId,
- Path policyTypePath) {
+ Path policyTypePath) {
//
// This is what we return
//
@@ -603,6 +596,6 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
*/
protected Path constructLocalFilePath(ToscaConceptIdentifier policyTypeId) {
return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
- + policyTypeId.getVersion() + ".yaml");
+ + policyTypeId.getVersion() + ".yaml");
}
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
index 466aae12..5036b5a6 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,7 +30,6 @@ import com.att.research.xacml.api.pdp.PDPEngineFactory;
import com.att.research.xacml.api.pdp.PDPException;
import com.att.research.xacml.util.FactoryException;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -70,7 +69,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
private HttpClient policyApiClient;
private Properties pdpProperties = null;
private PDPEngine pdpEngine = null;
- private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
+ private final Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
@Override
public String applicationName() {
@@ -84,7 +83,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
@Override
public void initialize(Path pathForData, HttpClient policyApiClient)
- throws XacmlApplicationException {
+ throws XacmlApplicationException {
//
// Save our path
//
@@ -146,7 +145,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
- new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
+ Files.readString(refPath));
}
//
// Add root policy to properties object
@@ -156,7 +155,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
// Write the properties to disk
//
XacmlPolicyUtils.storeXacmlProperties(newProperties,
- XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
+ XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
//
// Reload the engine
//
@@ -175,14 +174,14 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
}
@Override
- public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
+ public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) {
//
// Find it in our map
//
Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
if (refPolicy == null) {
LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
- this.mapLoadedPolicies.size());
+ this.mapLoadedPolicies.size());
return false;
}
//
@@ -200,14 +199,14 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
Files.delete(refPolicy);
} catch (IOException e) {
LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
- refPolicy.toAbsolutePath(), e);
+ refPolicy.toAbsolutePath(), e);
}
//
// Write the properties to disk
//
try {
XacmlPolicyUtils.storeXacmlProperties(newProperties,
- XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
+ XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
} catch (IOException e) {
LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
}
@@ -224,7 +223,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
//
if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
- this.mapLoadedPolicies.size());
+ this.mapLoadedPolicies.size());
}
//
// Not sure if any of the errors above warrant returning false
@@ -234,7 +233,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
@Override
public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
- Map<String, String[]> requestQueryParams) {
+ Map<String, String[]> requestQueryParams) {
//
// Convert to a XacmlRequest
//
diff --git a/applications/common/src/main/resources/persistence.xml b/applications/common/src/main/resources/persistence.xml
index 037ba7bc..47efee24 100644
--- a/applications/common/src/main/resources/persistence.xml
+++ b/applications/common/src/main/resources/persistence.xml
@@ -4,7 +4,7 @@
ONAP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -20,16 +20,16 @@
============LICENSE_END=========================================================
-->
-<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
+<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd">
<persistence-unit name="OperationsHistoryPU" transaction-type="RESOURCE_LOCAL">
<class>org.onap.policy.guard.OperationsHistory</class>
-
<properties>
- <property name="jakarta.persistence.schema-generation.database.action" value="create" />
+ <property name="jakarta.persistence.schema-generation.database.action" value="none"/>
<property name="jakarta.persistence.schema-generation.create-source" value="metadata"/>
- <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
- <property name="hibernate.show_sql" value="false" />
+ <property name="hibernate.show_sql" value="false"/>
</properties>
</persistence-unit>
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java
index 63c6b246..086bfc88 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,15 +21,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class ExceptionTest {
+class ExceptionTest {
@Test
- public void test() {
+ void test() {
ExceptionsTester tester = new ExceptionsTester();
assertEquals(3, tester.test(PolicyApiException.class));
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java
index c02d7fb3..8a54da21 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,18 +24,18 @@
package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.att.research.xacml.api.AttributeAssignment;
import com.att.research.xacml.api.Obligation;
import com.att.research.xacml.api.XACML3;
import java.util.Arrays;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.resources.ResourceUtils;
-public class OnapObligationTest {
+class OnapObligationTest {
String policyJson;
String policyBadJson;
@@ -51,55 +52,55 @@ public class OnapObligationTest {
/**
* setup - create test data.
*/
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
policyJson = ResourceUtils.getResourceAsString("test.policy.json");
policyBadJson = ResourceUtils.getResourceAsString("test.policy.bad.json");
assignmentPolicyId = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentBadPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyBadJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyBadJson
+ );
assignmentWeight = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
- 0
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
+ 0
+ );
assignmentPolicyType = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
- "onap.policies.Test"
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
+ "onap.policies.Test"
+ );
assignmentUnknown = TestUtilsCommon.createAttributeAssignment(
- "foo:bar",
- XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
- 10.2
- );
+ "foo:bar",
+ XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
+ 10.2
+ );
obligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType,
- assignmentUnknown));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType,
+ assignmentUnknown));
}
@Test
- public void testObligation() {
+ void testObligation() {
OnapObligation onapObligation = new OnapObligation(obligation);
assertNotNull(onapObligation);
assertThat(onapObligation.getPolicyId()).isEqualTo(assignmentPolicyId.getAttributeValue().getValue());
@@ -109,7 +110,7 @@ public class OnapObligationTest {
}
@Test
- public void testSimplePolicy() {
+ void testSimplePolicy() {
OnapObligation onapObligation = new OnapObligation("my.policy.id", policyJson);
assertNotNull(onapObligation);
assertThat(onapObligation.getPolicyId()).isEqualTo("my.policy.id");
@@ -126,7 +127,7 @@ public class OnapObligationTest {
@Test
- public void testWeightedPolicy() {
+ void testWeightedPolicy() {
OnapObligation onapObligation = new OnapObligation("my.policy.id", policyJson, "onap.policies.Test", 5);
assertNotNull(onapObligation);
assertThat(onapObligation.getPolicyId()).isEqualTo("my.policy.id");
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java
index 86708284..ac6d89b5 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,15 +21,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class OnapPolicyFinderFactoryExceptionTest {
+class OnapPolicyFinderFactoryExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(5, new ExceptionsTester().test(OnapPolicyFinderFactoryException.class));
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java
index 5df2552d..8f7de199 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,12 +27,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.FileInputStream;
import java.util.Properties;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class OnapPolicyFinderFactoryTest {
+class OnapPolicyFinderFactoryTest {
@Test
- public void testFinder() throws Exception {
+ void testFinder() throws Exception {
//
// Load our test properties to use
//
@@ -47,7 +48,7 @@ public class OnapPolicyFinderFactoryTest {
}
@Test
- public void testFinderWithCombiningAlgorithm() throws Exception {
+ void testFinderWithCombiningAlgorithm() throws Exception {
//
// Load our test properties to use
//
@@ -59,7 +60,7 @@ public class OnapPolicyFinderFactoryTest {
// Set a combining algorithm
//
properties.put("xacml.att.policyFinderFactory.combineRootPolicies",
- "urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides");
+ "urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides");
OnapPolicyFinderFactory finder = new OnapPolicyFinderFactory(properties);
assertThat(finder).isNotNull();
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java
index bd42933c..a5a7b7c1 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,9 @@
package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,10 +38,10 @@ import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
@@ -55,7 +55,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class PolicyApiCallerTest {
+class PolicyApiCallerTest {
private static final String MY_TYPE = "my-type";
private static final String MY_VERSION = "1.0.0";
@@ -80,8 +80,8 @@ public class PolicyApiCallerTest {
*
* @throws IOException if an error occurs
*/
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
+ @BeforeAll
+ static void setUpBeforeClass() throws Exception {
port = NetworkUtil.allocPort();
clientParams = mock(RestClientParameters.class);
@@ -93,17 +93,17 @@ public class PolicyApiCallerTest {
props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
final String svcpfx =
- PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
+ PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
- Integer.toString(clientParams.getPort()));
+ Integer.toString(clientParams.getPort()));
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
- ApiRestController.class.getName());
+ ApiRestController.class.getName());
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- GsonMessageBodyHandler.class.getName());
+ GsonMessageBodyHandler.class.getName());
HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
@@ -111,8 +111,8 @@ public class PolicyApiCallerTest {
assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
}
- @AfterClass
- public static void tearDownAfterClass() {
+ @AfterAll
+ static void tearDownAfterClass() {
HttpServletServerFactoryInstance.getServerFactory().destroy();
}
@@ -121,26 +121,26 @@ public class PolicyApiCallerTest {
*
* @throws PolicyApiException if an error occurs
*/
- @Before
- public void setUp() throws PolicyApiException {
+ @BeforeEach
+ void setUp() throws PolicyApiException {
when(clientParams.getPort()).thenReturn(port);
api = new PolicyApiCaller(apiClient);
}
@Test
- public void testGetPolicyType() throws Exception {
+ void testGetPolicyType() throws Exception {
assertNotNull(api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)));
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(INVALID_TYPE, MY_VERSION)))
- .isInstanceOf(PolicyApiException.class);
+ .isInstanceOf(PolicyApiException.class);
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(UNKNOWN_TYPE, MY_VERSION)))
- .isInstanceOf(NotFoundException.class);
+ .isInstanceOf(NotFoundException.class);
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(NOT_A_TYPE, MY_VERSION)))
- .isInstanceOf(PolicyApiException.class);
+ .isInstanceOf(PolicyApiException.class);
// connect to a port that has no server
RestClientParameters params2 = mock(RestClientParameters.class);
@@ -152,7 +152,7 @@ public class PolicyApiCallerTest {
api = new PolicyApiCaller(apiClient2);
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)))
- .isInstanceOf(PolicyApiException.class);
+ .isInstanceOf(PolicyApiException.class);
}
/**
@@ -168,32 +168,36 @@ public class PolicyApiCallerTest {
* Retrieves the specified version of a particular policy type.
*
* @param policyTypeId ID of desired policy type
- * @param versionId version of desired policy type
- * @param requestId optional request ID
- *
+ * @param versionId version of desired policy type
+ * @param requestId optional request ID
* @return the Response object containing the results of the API operation
*/
@GET
@Path("/policytypes/{policyTypeId}/versions/{versionId}")
public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
- @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
+ @PathParam("versionId") String versionId,
+ @HeaderParam("X-ONAP-RequestID") UUID requestId) {
assertEquals(MY_VERSION, versionId);
- switch (policyTypeId) {
- case UNKNOWN_TYPE:
+ return switch (policyTypeId) {
+ case UNKNOWN_TYPE -> {
logger.info("request for unknown policy type");
- return Response.status(Response.Status.NOT_FOUND).build();
- case INVALID_TYPE:
+ yield Response.status(Response.Status.NOT_FOUND).build();
+ }
+ case INVALID_TYPE -> {
logger.info("invalid request for policy type");
- return Response.status(Response.Status.BAD_REQUEST).build();
- case NOT_A_TYPE:
+ yield Response.status(Response.Status.BAD_REQUEST).build();
+ }
+ case NOT_A_TYPE -> {
logger.info("invalid request for policy type");
- return Response.status(Response.Status.OK).entity("string-type").build();
- default:
+ yield Response.status(Response.Status.OK).entity("string-type").build();
+ }
+ default -> {
logger.info("request for policy type={} version={}", policyTypeId, versionId);
- return Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();
- }
+ yield Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();
+ }
+ };
}
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java
index 026bea9e..884e1cae 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,10 +51,10 @@ public class TestUtilsCommon {
/**
* createAttributeAssignment.
*
- * @param <T> Object can be String, Integer, Double, Boolean
- * @param id String attribute id
+ * @param <T> Object can be String, Integer, Double, Boolean
+ * @param id String attribute id
* @param category String for the attribute category
- * @param value Object containing a value
+ * @param value Object containing a value
* @return AttributeAssignment object
*/
public static <T> AttributeAssignment createAttributeAssignment(String id, String category, T value) {
@@ -71,13 +72,13 @@ public class TestUtilsCommon {
}
return new StdAttributeAssignment(new IdentifierImpl(category),
- new IdentifierImpl(id), "", attributeValue);
+ new IdentifierImpl(id), "", attributeValue);
}
/**
* createXacmlObligation.
*
- * @param id String obligation id
+ * @param id String obligation id
* @param attributeAssignments Collection of AttributeAssignment objects
* @return Obligation object
*/
@@ -97,7 +98,7 @@ public class TestUtilsCommon {
for (Entry<String, String> entrySet : ids.entrySet()) {
policyIds.add(new StdIdReference(new IdentifierImpl(entrySet.getKey()),
- StdVersion.newInstance(entrySet.getValue())));
+ StdVersion.newInstance(entrySet.getValue())));
}
return policyIds;
@@ -106,15 +107,15 @@ public class TestUtilsCommon {
/**
* createXacmlResponse.
*
- * @param code StatusCode
- * @param decision Decision
+ * @param code StatusCode
+ * @param decision Decision
* @param obligations Collection of Obligation objects
- * @param policyIds Collection of IdReference objects
+ * @param policyIds Collection of IdReference objects
* @return Response object
*/
- public static Response createXacmlResponse(StatusCode code, String message, Decision decision,
- Collection<Obligation> obligations,
- Collection<IdReference> policyIds) {
+ public static Response createXacmlResponse(StatusCode code, String message, Decision decision,
+ Collection<Obligation> obligations,
+ Collection<IdReference> policyIds) {
StdStatus status = new StdStatus(code, message);
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java
index 251c9710..f5c60443 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,16 +24,16 @@
package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class ToscaDictionaryTest {
+class ToscaDictionaryTest {
@Test
- public void testConstructorIsProtected() throws Exception {
+ void testConstructorIsProtected() throws Exception {
//
// Ensure that this is static class
//
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java
index bee4ba3d..f09af12f 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,15 +21,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class ToscaPolicyConversionExceptionTest {
+class ToscaPolicyConversionExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(5, new ExceptionsTester().test(ToscaPolicyConversionException.class));
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java
index ef74beae..0542b5b4 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.att.research.xacml.api.XACML3;
import java.lang.reflect.Constructor;
@@ -42,15 +42,15 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.parameters.annotations.NotNull;
import org.onap.policy.common.utils.coder.CoderException;
-public class ToscaPolicyTranslatorUtilsTest {
+class ToscaPolicyTranslatorUtilsTest {
private static final ObjectFactory factory = new ObjectFactory();
@Test
- public void test() throws NoSuchMethodException, SecurityException {
+ void test() throws NoSuchMethodException, SecurityException {
final Constructor<ToscaPolicyTranslatorUtils> constructor
= ToscaPolicyTranslatorUtils.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
@@ -58,35 +58,35 @@ public class ToscaPolicyTranslatorUtilsTest {
}
@Test
- public void testTimeInRange() {
+ void testTimeInRange() {
ApplyType apply = ToscaPolicyTranslatorUtils.generateTimeInRange("00:00:00Z", "08:00:00Z", true);
assertThat(apply).isNotNull();
assertThat(apply.getExpression()).hasSize(3);
}
@Test
- public void testBuildAndAppend() {
+ void testBuildAndAppend() {
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, new MatchType())).isInstanceOf(AnyOfType.class);
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, new AllOfType())).isInstanceOf(AnyOfType.class);
- assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, new String())).isNull();
+ assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, "")).isNull();
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendTarget(new TargetType(),
- new AnyOfType()).getAnyOf()).hasSize(1);
+ new AnyOfType()).getAnyOf()).hasSize(1);
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendTarget(new TargetType(),
- new MatchType()).getAnyOf()).hasSize(1);
+ new MatchType()).getAnyOf()).hasSize(1);
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendTarget(new TargetType(),
- new String()).getAnyOf()).isEmpty();
+ "").getAnyOf()).isEmpty();
}
@Test
- public void testInteger() {
+ void testInteger() {
assertThat(ToscaPolicyTranslatorUtils.parseInteger("foo")).isNull();
assertThat(ToscaPolicyTranslatorUtils.parseInteger("1")).isEqualTo(1);
assertThat(ToscaPolicyTranslatorUtils.parseInteger("1.0")).isEqualTo(1);
}
@Test
- public void testAddingVariables() {
+ void testAddingVariables() {
ApplyType applyType = new ApplyType();
applyType.setFunctionId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue());
@@ -109,7 +109,7 @@ public class ToscaPolicyTranslatorUtilsTest {
variable.setVariableId("my-variable-id");
ConditionType newCondition = ToscaPolicyTranslatorUtils.addVariableToCondition(condition, variable,
- XACML3.ID_FUNCTION_AND);
+ XACML3.ID_FUNCTION_AND);
assertThat(newCondition.getExpression().getValue()).isInstanceOf(ApplyType.class);
Object obj = newCondition.getExpression().getValue();
@@ -119,23 +119,23 @@ public class ToscaPolicyTranslatorUtilsTest {
@SuppressWarnings("deprecation")
@Test
- public void testDecodeProperties() throws ToscaPolicyConversionException {
+ void testDecodeProperties() throws ToscaPolicyConversionException {
Data data = ToscaPolicyTranslatorUtils.decodeProperties(Map.of("value", 20), Data.class);
assertThat(data.getValue()).isEqualTo(20);
// null value - invalid
assertThatThrownBy(() -> ToscaPolicyTranslatorUtils.decodeProperties(Map.of(), Data.class))
- .isInstanceOf(ToscaPolicyConversionException.class).hasMessageContaining("item \"value\"");
+ .isInstanceOf(ToscaPolicyConversionException.class).hasMessageContaining("item \"value\"");
// value is not an integer - cannot even decode it
assertThatThrownBy(() -> ToscaPolicyTranslatorUtils.decodeProperties(Map.of("value", "abc"), Data.class))
- .isInstanceOf(ToscaPolicyConversionException.class).getCause()
- .isInstanceOf(CoderException.class);
+ .isInstanceOf(ToscaPolicyConversionException.class).getCause()
+ .isInstanceOf(CoderException.class);
// null properties - cannot even decode
assertThatThrownBy(() -> ToscaPolicyTranslatorUtils.decodeProperties(null, Data.class))
- .isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessage("Cannot decode Data from null properties");
+ .isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessage("Cannot decode Data from null properties");
}
@Getter
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java
index be27b313..25ba6493 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,15 +23,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class XacmlApplicationExceptionTest {
+class XacmlApplicationExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(5, new ExceptionsTester().test(XacmlApplicationException.class));
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
index 30bf232a..d2e23fe4 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,13 +26,13 @@ package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.util.XACMLPolicyWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
@@ -48,10 +48,9 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,9 +59,8 @@ import org.slf4j.LoggerFactory;
* that reference policies.
*
* @author pameladragosh
- *
*/
-public class XacmlPolicyUtilsTest {
+class XacmlPolicyUtilsTest {
private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPolicyUtilsTest.class);
static Properties properties;
@@ -77,7 +75,7 @@ public class XacmlPolicyUtilsTest {
static PolicyType policy4 = XacmlPolicyUtils.createEmptyPolicy("policy4", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
static PolicySetType policySet5 = XacmlPolicyUtils.createEmptyPolicySet(
- "policyset1", XACML3.ID_POLICY_FIRST_APPLICABLE);
+ "policyset1", XACML3.ID_POLICY_FIRST_APPLICABLE);
static Path path1;
static Path path2;
@@ -89,17 +87,15 @@ public class XacmlPolicyUtilsTest {
/**
* Temporary folder where we will store newly created policies.
*/
- @ClassRule
- public static TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Setup the JUnit tests by finishing creating the policies and
* writing them out to the temporary folder.
- *
- * @throws Exception thrown
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ public static void setUp() {
assertThatCode(() -> {
//
// Load our test property object
@@ -113,7 +109,7 @@ public class XacmlPolicyUtilsTest {
//
if (!"/".equals(File.separator)) {
List<String> fileProps = properties.keySet().stream().map(Object::toString)
- .filter(key -> key.endsWith(".file")).toList();
+ .filter(key -> key.endsWith(".file")).toList();
for (String fileProp : fileProps) {
properties.setProperty(fileProp, properties.getProperty(fileProp).replace("/", File.separator));
}
@@ -121,13 +117,14 @@ public class XacmlPolicyUtilsTest {
//
// Save root policy
//
- Path rootFile = XacmlPolicyUtils.constructUniquePolicyFilename(rootPolicy, policyFolder.getRoot().toPath());
+ Path rootFile = XacmlPolicyUtils.constructUniquePolicyFilename(rootPolicy,
+ policyFolder.toAbsolutePath());
LOGGER.info("Creating Root Policy {}", rootFile.toAbsolutePath());
rootPath = XacmlPolicyUtils.writePolicyFile(rootFile, rootPolicy);
//
// Create policies - Policies 1 and 2 will become references in the
// root policy. While Policies 3 and 4 will become references in the
- // soon to be created PolicySet 5 below.
+ // soon-to-be created PolicySet 5 below.
//
path1 = createPolicyContents(policy1, "resource1");
LOGGER.info(new String(Files.readAllBytes(path1)));
@@ -153,7 +150,7 @@ public class XacmlPolicyUtilsTest {
//
// Save that to disk
//
- File policySetFile = policyFolder.newFile("policySet5.xml");
+ File policySetFile = policyFolder.resolve("policySet5.xml").toFile();
LOGGER.info("Creating PolicySet {}", policySetFile.getAbsolutePath());
policySetPath = XACMLPolicyWriter.writePolicyFile(policySetFile.toPath(), policySet5);
@@ -163,21 +160,20 @@ public class XacmlPolicyUtilsTest {
/**
* Helper method that creates a very simple Policy and Rule and saves it to disk.
*
- * @param policy Policy to store contents in
+ * @param policy Policy to store contents in
* @param resource A simple resource id for the Target
* @return Path object of the policy
- * @throws IOException If unable to write to disk
*/
- private static Path createPolicyContents(PolicyType policy, String resource) throws IOException {
+ private static Path createPolicyContents(PolicyType policy, String resource) {
//
// Create The Match
//
MatchType matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_STRING_EQUAL,
- resource,
- XACML3.ID_DATATYPE_STRING,
- XACML3.ID_RESOURCE_RESOURCE_ID,
- XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
+ XACML3.ID_FUNCTION_STRING_EQUAL,
+ resource,
+ XACML3.ID_DATATYPE_STRING,
+ XACML3.ID_RESOURCE_RESOURCE_ID,
+ XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
//
// This is our outer AnyOf - which is an OR
//
@@ -200,26 +196,27 @@ public class XacmlPolicyUtilsTest {
//
// Save it to disk
//
- Path policyFile = XacmlPolicyUtils.constructUniquePolicyFilename(policy, policyFolder.getRoot().toPath());
+ Path policyFile = XacmlPolicyUtils.constructUniquePolicyFilename(policy,
+ policyFolder.toAbsolutePath());
LOGGER.info("Creating Policy {}", policyFile.toAbsolutePath());
return XacmlPolicyUtils.writePolicyFile(policyFile, policy);
}
@Test
- public void testUncommonConditions() throws IOException {
- Path fileTemp = policyFolder.newFile().toPath();
+ void testUncommonConditions() {
+ Path fileTemp = policyFolder.toFile().toPath();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->
XacmlPolicyUtils.writePolicyFile(fileTemp, "not a policy")
);
- Path rootPath = policyFolder.getRoot().toPath();
+ Path rootPathZ = policyFolder.toAbsolutePath();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->
- XacmlPolicyUtils.constructUniquePolicyFilename("not a policy", rootPath)
+ XacmlPolicyUtils.constructUniquePolicyFilename("not a policy", rootPathZ)
);
}
@Test
- public void testUpdatingPolicies() {
+ void testUpdatingPolicies() {
assertThatCode(() -> {
//
// Just update root and policies
@@ -248,7 +245,7 @@ public class XacmlPolicyUtilsTest {
}
@Test
- public void testRemovingReferencedProperties() {
+ void testRemovingReferencedProperties() {
//
// Dump what we are starting with
//
@@ -286,7 +283,7 @@ public class XacmlPolicyUtilsTest {
}
@Test
- public void testRemovingRootProperties() {
+ void testRemovingRootProperties() {
//
// Dump what we are starting with
//
@@ -309,11 +306,12 @@ public class XacmlPolicyUtilsTest {
}
@Test
- public void testCopyingProperties() throws Exception {
+ void testCopyingProperties() throws Exception {
//
// Copy to this folder
//
- File copyFolder = policyFolder.newFolder("copy");
+ File copyFolder = policyFolder.resolve("copy").toFile();
+ assertTrue(copyFolder.mkdirs());
assertThat(copyFolder).exists();
//
// Mock up a properties object
@@ -324,19 +322,19 @@ public class XacmlPolicyUtilsTest {
//
// Write the properties out to a file
//
- Path fileProperties = XacmlPolicyUtils.getPropertiesPath(policyFolder.getRoot().toPath());
+ Path fileProperties = XacmlPolicyUtils.getPropertiesPath(policyFolder.toAbsolutePath());
XacmlPolicyUtils.storeXacmlProperties(mockProperties, fileProperties);
//
// Now we can test the copy method
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile("copy/" + filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve("copy/" + filename).toFile();
File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
- fileProperties.toAbsolutePath().toString(), mockProperties, myCreator);
+ fileProperties.toAbsolutePath().toString(), mockProperties, myCreator);
assertThat(propertiesFile).canRead();
assertThat(Path.of(copyFolder.getAbsolutePath(),
- rootPath.getFileName().toString()).toFile()).canRead();
+ rootPath.getFileName().toString()).toFile()).canRead();
assertThat(Path.of(copyFolder.getAbsolutePath(),
- path1.getFileName().toString()).toFile()).canRead();
+ path1.getFileName().toString()).toFile()).canRead();
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java
index e157f174..dcf788d4 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,8 +25,8 @@ package org.onap.policy.pdp.xacml.application.common.matchable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.att.research.xacml.api.Identifier;
import com.att.research.xacml.api.XACML3;
@@ -42,8 +42,8 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -59,7 +59,7 @@ import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionExcepti
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class MatchablePolicyTypeTest implements MatchableCallback {
+class MatchablePolicyTypeTest implements MatchableCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(MatchablePolicyTypeTest.class);
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
private static final String TEST_POLICYTYPE_FILE = "src/test/resources/matchable/onap.policies.Test-1.0.0.yaml";
@@ -73,8 +73,8 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
*
* @throws CoderException object
*/
- @BeforeClass
- public static void setupLoadPolicy() throws CoderException {
+ @BeforeAll
+ static void setupLoadPolicy() throws CoderException {
//
// Load our test policy type
//
@@ -116,7 +116,7 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
}
@Test
- public void testAllCodeCoverage() {
+ void testAllCodeCoverage() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
new MatchablePolicyType(null, null));
@@ -162,7 +162,7 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
}
@Test
- public void testPrimitiveValidation() throws Exception {
+ void testPrimitiveValidation() throws Exception {
ToscaProperty property = new ToscaProperty();
MatchablePropertyTypeBoolean booleanValue = new MatchablePropertyTypeBoolean(property);
assertThat(booleanValue.validate(Boolean.TRUE)).isEqualTo(Boolean.TRUE);
@@ -194,12 +194,12 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
}
@Test
- public void testMatchables() throws ToscaPolicyConversionException {
+ void testMatchables() throws ToscaPolicyConversionException {
//
// Step 1: Create matchables from the PolicyType
//
MatchablePolicyType matchablePolicyType = new MatchablePolicyType(testTemplate.getPolicyTypes()
- .get(TEST_POLICYTYPE), this);
+ .get(TEST_POLICYTYPE), this);
assertThat(matchablePolicyType).isNotNull();
assertThat(matchablePolicyType.getPolicyId()).isNotNull();
assertThat(matchablePolicyType.getPolicyId().getName()).isEqualTo(TEST_POLICYTYPE);
@@ -257,7 +257,7 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
@SuppressWarnings("unchecked")
private void generateTargetType(TargetType target, MatchablePolicyType matchablePolicyType,
- Map<String, Object> properties) throws ToscaPolicyConversionException {
+ Map<String, Object> properties) throws ToscaPolicyConversionException {
for (Entry<String, Object> entrySet : properties.entrySet()) {
String propertyName = entrySet.getKey();
Object propertyValue = entrySet.getValue();
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
index c38ab716..9eb04241 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,8 @@ package org.onap.policy.pdp.xacml.application.common.operationshistory;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
import com.att.research.xacml.api.Attribute;
@@ -44,20 +45,19 @@ import java.util.LinkedList;
import java.util.Properties;
import java.util.Queue;
import java.util.UUID;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.guard.OperationsHistory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@RunWith(MockitoJUnitRunner.class)
-public class CountRecentOperationsPipTest {
+@ExtendWith(MockitoExtension.class)
+class CountRecentOperationsPipTest {
private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);
private static final String ACTOR = "my-actor";
@@ -95,8 +95,8 @@ public class CountRecentOperationsPipTest {
*
* @throws IOException if properties cannot be loaded
*/
- @BeforeClass
- public static void setUpBeforeClass() throws IOException {
+ @BeforeAll
+ static void setUpBeforeClass() throws IOException {
//
// Load our test properties to use
//
@@ -114,14 +114,17 @@ public class CountRecentOperationsPipTest {
//
//
//
- LOGGER.info("Configured own entity manager {}", em.toString());
+ LOGGER.info("Configured own entity manager {}", em);
}
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() {
+ @AfterAll
+ static void cleanup() {
+ if (emf != null) {
+ emf.close();
+ }
if (em != null) {
em.close();
}
@@ -132,9 +135,9 @@ public class CountRecentOperationsPipTest {
*
* @throws Exception if an error occurs
*/
- @Before
- public void setUp() throws Exception {
- when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
+ @BeforeEach
+ void setUp() throws Exception {
+ lenient().when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
pipEngine = new MyPip();
@@ -148,12 +151,12 @@ public class CountRecentOperationsPipTest {
}
@Test
- public void testAttributesRequired() {
+ void testAttributesRequired() {
assertEquals(3, pipEngine.attributesRequired().size());
}
@Test
- public void testConfigure_DbException() {
+ void testConfigure_DbException() {
properties.put("jakarta.persistence.jdbc.url", "invalid");
assertThatCode(() ->
pipEngine.configure("issuer", properties)
@@ -161,44 +164,44 @@ public class CountRecentOperationsPipTest {
}
@Test
- public void testGetAttributes_NullIssuer() throws PIPException {
+ void testGetAttributes_NullIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn(null);
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_WrongIssuer() throws PIPException {
+ void testGetAttributes_WrongIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_NullActor() throws PIPException {
+ void testGetAttributes_NullActor() throws PIPException {
attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_NullRecipe() throws PIPException {
+ void testGetAttributes_NullRecipe() throws PIPException {
attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_NullTarget() throws PIPException {
+ void testGetAttributes_NullTarget() throws PIPException {
attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testShutdown() {
+ void testShutdown() {
pipEngine.shutdown();
assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
.withMessageContaining("Engine is shutdown");
}
@Test
- public void testGetCountFromDb() throws Exception {
+ void testGetCountFromDb() throws Exception {
//
// Configure it using properties
//
@@ -231,7 +234,7 @@ public class CountRecentOperationsPipTest {
}
@Test
- public void testStringToChronosUnit() throws PIPException {
+ void testStringToChronosUnit() throws PIPException {
// not configured yet
OperationsHistory newEntry = createEntry();
assertEquals(-1, getCount(newEntry));
@@ -260,8 +263,8 @@ public class CountRecentOperationsPipTest {
private long getCount(OperationsHistory newEntry) throws PIPException {
responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
- attributes = new LinkedList<>(
- Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));
+ attributes = new LinkedList<>(Arrays.asList(newEntry.getActor(),
+ newEntry.getOperation(), newEntry.getTarget()));
PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java
index bd53789f..5bbbd2c1 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,8 @@ package org.onap.policy.pdp.xacml.application.common.operationshistory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -43,16 +43,16 @@ import java.time.Instant;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.guard.OperationsHistory;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class GetOperationOutcomePipTest {
+class GetOperationOutcomePipTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class);
private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
@@ -75,8 +75,8 @@ public class GetOperationOutcomePipTest {
*
* @throws Exception connectivity issues
*/
- @BeforeClass
- public static void setupDatabase() throws Exception {
+ @BeforeAll
+ static void setupDatabase() throws Exception {
LOGGER.info("Setting up PIP Testing");
//
// Load our test properties to use
@@ -95,14 +95,14 @@ public class GetOperationOutcomePipTest {
//
//
//
- LOGGER.info("Configured own entity manager", em.toString());
+ LOGGER.info("Configured own entity manager {}", em);
}
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() {
+ @AfterAll
+ static void cleanup() {
if (em != null) {
em.close();
}
@@ -113,8 +113,8 @@ public class GetOperationOutcomePipTest {
*
* @throws Exception if an error occurs
*/
- @Before
- public void setupEngine() throws Exception {
+ @BeforeEach
+ void setupEngine() throws Exception {
when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
//
// Create instance
@@ -136,12 +136,12 @@ public class GetOperationOutcomePipTest {
}
@Test
- public void testAttributesRequired() {
+ void testAttributesRequired() {
assertEquals(1, pipEngine.attributesRequired().size());
}
@Test
- public void testConfigure_DbException() throws Exception {
+ void testConfigure_DbException() {
properties.put("jakarta.persistence.jdbc.url", "invalid");
assertThatCode(() ->
pipEngine.configure("issuer", properties)
@@ -149,19 +149,19 @@ public class GetOperationOutcomePipTest {
}
@Test
- public void testGetAttributes_NullIssuer() throws PIPException {
+ void testGetAttributes_NullIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn(null);
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_WrongIssuer() throws PIPException {
+ void testGetAttributes_WrongIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes() throws Exception {
+ void testGetAttributes() throws Exception {
//
//
//
@@ -179,12 +179,12 @@ public class GetOperationOutcomePipTest {
}
@Test
- public void testGetOutcomeFromDb() throws Exception {
+ void testGetOutcomeFromDb() throws Exception {
//
// Use reflection to run getCountFromDB
//
Method method = GetOperationOutcomePip.class.getDeclaredMethod("doDatabaseQuery",
- String.class);
+ String.class);
method.setAccessible(true);
//
// Test pipEngine
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java
index 75af4482..a32b89c5 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,9 +25,9 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import com.att.research.xacml.api.Advice;
import com.att.research.xacml.api.AttributeAssignment;
@@ -39,13 +40,15 @@ import com.att.research.xacml.std.StdStatusCode;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
@@ -54,7 +57,7 @@ import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class StdBaseTranslatorTest {
+class StdBaseTranslatorTest {
String policyJson;
String policyBadJson;
@@ -70,57 +73,57 @@ public class StdBaseTranslatorTest {
/**
* beforeSetup - loads and creates objects used later by the tests.
- * @throws CoderException CoderException
*
+ * @throws CoderException CoderException
*/
- @Before
- public void beforeSetup() throws CoderException {
+ @BeforeEach
+ void beforeSetup() throws CoderException {
policyJson = ResourceUtils.getResourceAsString("test.policy.json");
policyBadJson = ResourceUtils.getResourceAsString("test.policy.bad.json");
assignmentPolicyId = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
- "policy.id"
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
+ "policy.id"
+ );
assignmentPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentBadPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyBadJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyBadJson
+ );
assignmentWeight = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
- 0
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
+ 0
+ );
assignmentPolicyType = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
- "onap.policies.Test"
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
+ "onap.policies.Test"
+ );
assignmentUnknown = TestUtilsCommon.createAttributeAssignment(
- "foo:bar",
- XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
- 10.2
- );
+ "foo:bar",
+ XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
+ 10.2
+ );
obligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType));
}
@Test
- public void testTranslatorNormalFlow() throws Exception {
+ void testTranslatorNormalFlow() throws Exception {
StdBaseTranslator translator = new MyStdBaseTranslator();
assertNotNull(translator);
assertThatThrownBy(() -> translator.convertPolicy(null)).isInstanceOf(ToscaPolicyConversionException.class);
@@ -141,33 +144,33 @@ public class StdBaseTranslatorTest {
assertThat(policySet.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(policySet.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).hasSize(4);
+ .getAttributeAssignmentExpression()).hasSize(4);
PolicyType policy = new PolicyType();
translator.addObligation(policy, null, policyJson, null, null);
assertThat(policy.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(policy.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).hasSize(1);
+ .getAttributeAssignmentExpression()).hasSize(1);
RuleType rule = new RuleType();
translator.addObligation(rule, "policy.id", null, null, "foo.bar");
assertThat(rule.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(rule.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).hasSize(2);
+ .getAttributeAssignmentExpression()).hasSize(2);
rule = new RuleType();
translator.addObligation(rule, null, null, null, null);
assertThat(rule.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(rule.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).isEmpty();
+ .getAttributeAssignmentExpression()).isEmpty();
//
// Should not throw an exception
//
- translator.addObligation(new String(), "policy.id", policyJson, null, "foo.bar");
+ translator.addObligation("", "policy.id", policyJson, null, "foo.bar");
//
// Test the response conversion
@@ -177,7 +180,7 @@ public class StdBaseTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null,
- Decision.PERMIT, Arrays.asList(obligation), policyIds);
+ Decision.PERMIT, Collections.singletonList(obligation), policyIds);
DecisionResponse decision = translator.convertResponse(xacmlResponse);
@@ -188,18 +191,18 @@ public class StdBaseTranslatorTest {
}
@Test
- public void testBadData() throws ToscaPolicyConversionException, ParseException {
+ void testBadData() throws ToscaPolicyConversionException, ParseException {
TestTranslator translator = new TestTranslator();
assertThatThrownBy(() -> translator.convertPolicy(
- new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("missing metadata");
+ new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessageContaining("missing metadata");
translator.metadata.put(StdBaseTranslator.POLICY_ID, "random.policy.id");
assertThatThrownBy(() -> translator.convertPolicy(
- new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("missing metadata");
+ new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessageContaining("missing metadata");
translator.metadata.put(StdBaseTranslator.POLICY_VERSION, "1.0.0");
@@ -211,7 +214,7 @@ public class StdBaseTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null,
- Decision.PERMIT, Arrays.asList(obligation), policyIds);
+ Decision.PERMIT, Collections.singletonList(obligation), policyIds);
DecisionResponse decision = translator.convertResponse(xacmlResponse);
@@ -221,18 +224,18 @@ public class StdBaseTranslatorTest {
assertThat(decision.getPolicies()).isEmpty();
Obligation badObligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentBadPolicy, assignmentUnknown));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentBadPolicy, assignmentUnknown));
xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_MISSING_ATTRIBUTE, null,
- Decision.PERMIT, Arrays.asList(badObligation), policyIds);
+ Decision.PERMIT, List.of(badObligation), policyIds);
decision = translator.convertResponse(xacmlResponse);
assertNotNull(decision);
xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
- "Bad obligation", Decision.DENY, Arrays.asList(badObligation), policyIds);
+ "Bad obligation", Decision.DENY, List.of(badObligation), policyIds);
decision = translator.convertResponse(xacmlResponse);
@@ -241,27 +244,31 @@ public class StdBaseTranslatorTest {
assertThat(decision.getMessage()).isEqualTo("Bad obligation");
}
- private class MyStdBaseTranslator extends StdBaseTranslator {
+ private static class MyStdBaseTranslator extends StdBaseTranslator {
@Override
protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
@Override
protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
}
- private class TestTranslator extends StdBaseTranslator {
- public Map<String, Object> metadata = new HashMap<>();
+ private static class TestTranslator extends StdBaseTranslator {
+ Map<String, Object> metadata = new HashMap<>();
@Override
protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
@Override
protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
@Override
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java
index be7e0cea..fcb6b91f 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,25 +21,25 @@
package org.onap.policy.pdp.xacml.application.common.std;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
-@RunWith(MockitoJUnitRunner.class)
-public class StdCombinedPolicyRequestTest {
+@ExtendWith(MockitoExtension.class)
+class StdCombinedPolicyRequestTest {
private static final String ACTION = "my-action";
private static final String ONAP_NAME = "my-name";
private static final String ONAP_INSTANCE = "my-instance";
@@ -56,8 +57,8 @@ public class StdCombinedPolicyRequestTest {
/**
* Initializes objects.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
resources = new TreeMap<>();
when(decreq.getResource()).thenReturn(resources);
@@ -68,7 +69,7 @@ public class StdCombinedPolicyRequestTest {
}
@Test
- public void testCreateInstance() {
+ void testCreateInstance() {
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY, 100);
resources.put(StdCombinedPolicyRequest.POLICY_TYPE_KEY, 101);
@@ -86,7 +87,7 @@ public class StdCombinedPolicyRequestTest {
}
@Test
- public void testCreateInstance_StringValues() {
+ void testCreateInstance_StringValues() {
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY, POLICY_ID);
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY + "-x", "unused value");
resources.put(StdCombinedPolicyRequest.POLICY_TYPE_KEY, POLICY_TYPE);
@@ -103,7 +104,7 @@ public class StdCombinedPolicyRequestTest {
}
@Test
- public void testCreateInstance_Collections() {
+ void testCreateInstance_Collections() {
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY, Collections.singleton(POLICY_ID));
resources.put(StdCombinedPolicyRequest.POLICY_TYPE_KEY, Collections.singleton(POLICY_TYPE));
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java
index 9f0e0ac9..d379feef 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +25,7 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.att.research.xacml.api.AttributeAssignment;
import com.att.research.xacml.api.Decision;
@@ -35,10 +36,11 @@ import com.att.research.xacml.std.StdStatusCode;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -51,7 +53,7 @@ import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class StdCombinedPolicyResultsTranslatorTest {
+class StdCombinedPolicyResultsTranslatorTest {
String policyJson;
String policyBadJson;
@@ -65,38 +67,38 @@ public class StdCombinedPolicyResultsTranslatorTest {
/**
* setup - preload policies.
*/
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
policyJson = ResourceUtils.getResourceAsString("test.policy.json");
policyBadJson = ResourceUtils.getResourceAsString("test.policy.bad.json");
assignmentPolicyId = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentBadPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyBadJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyBadJson
+ );
obligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentPolicyId, assignmentPolicy));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentPolicyId, assignmentPolicy));
}
@Test
- public void test() throws ParseException {
+ void test() throws ParseException {
StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
assertNotNull(translator);
@@ -109,7 +111,7 @@ public class StdCombinedPolicyResultsTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null,
- Decision.PERMIT, Arrays.asList(obligation), policyIds);
+ Decision.PERMIT, Collections.singletonList(obligation), policyIds);
DecisionResponse decision = translator.convertResponse(xacmlResponse);
@@ -120,16 +122,16 @@ public class StdCombinedPolicyResultsTranslatorTest {
}
@Test
- public void testConvert() throws ToscaPolicyConversionException, CoderException {
+ void testConvert() throws ToscaPolicyConversionException, CoderException {
StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
assertThatThrownBy(() -> translator.convertPolicy(null)).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("Cannot convert a NULL policy");
+ .hasMessageContaining("Cannot convert a NULL policy");
assertThatThrownBy(() -> translator.convertPolicy(
- new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("missing metadata");
+ new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessageContaining("missing metadata");
StandardCoder coder = new StandardCoder();
@@ -148,7 +150,7 @@ public class StdCombinedPolicyResultsTranslatorTest {
}
@Test
- public void testDecision() throws ToscaPolicyConversionException {
+ void testDecision() throws ToscaPolicyConversionException {
StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
DecisionRequest decision = new DecisionRequest();
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java
index 57ab227a..3dbc613a 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +21,8 @@
package org.onap.policy.pdp.xacml.application.common.std;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.att.research.xacml.api.Request;
@@ -32,17 +33,17 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
-@RunWith(MockitoJUnitRunner.class)
-public class StdMatchablePolicyRequestTest {
+@ExtendWith(MockitoExtension.class)
+class StdMatchablePolicyRequestTest {
private static final String ACTION = "my-action";
private static final String ONAP_NAME = "my-name";
private static final String ONAP_INSTANCE = "my-instance";
@@ -57,13 +58,11 @@ public class StdMatchablePolicyRequestTest {
private Map<String, Object> resources;
- private Request stdreq;
-
/**
* Initializes objects.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
resources = new TreeMap<>();
when(decreq.getResource()).thenReturn(resources);
@@ -74,12 +73,12 @@ public class StdMatchablePolicyRequestTest {
}
@Test
- public void testCreateInstance() throws XacmlApplicationException {
+ void testCreateInstance() throws XacmlApplicationException {
resources.put("resource1", RESOURCE1);
resources.put("resource2", RESOURCE2);
resources.put("resource3", Arrays.asList(RESOURCE3, RESOURCE4));
- stdreq = StdMatchablePolicyRequest.createInstance(decreq);
+ Request stdreq = StdMatchablePolicyRequest.createInstance(decreq);
assertNotNull(stdreq);
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java
new file mode 100644
index 00000000..121f8dec
--- /dev/null
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java
@@ -0,0 +1,124 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2024 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pdp.xacml.application.common.std;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.api.Obligation;
+import com.att.research.xacml.api.Request;
+import com.att.research.xacml.std.IdentifierImpl;
+import java.util.HashMap;
+import java.util.HashSet;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.onap.policy.models.decisions.concepts.DecisionRequest;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
+import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
+
+class StdMatchableTranslator2Test {
+
+ @Test
+ void convertRequest() throws ToscaPolicyConversionException {
+ var translator = new StdMatchableTranslator();
+ var returnRequest = Mockito.mock(Request.class);
+ var decisionRequest = Mockito.mock(DecisionRequest.class);
+
+ try (MockedStatic<StdMatchablePolicyRequest> utilities = Mockito.mockStatic(StdMatchablePolicyRequest.class)) {
+ utilities.when(() -> StdMatchablePolicyRequest.createInstance(decisionRequest))
+ .thenReturn(returnRequest);
+
+ assertEquals(returnRequest, translator.convertRequest(decisionRequest));
+ }
+ }
+
+ @Test
+ void convertRequest_Exception() {
+ var translator = new StdMatchableTranslator();
+ var decisionRequest = Mockito.mock(DecisionRequest.class);
+
+ try (MockedStatic<StdMatchablePolicyRequest> utilities = Mockito.mockStatic(StdMatchablePolicyRequest.class)) {
+ utilities.when(() -> StdMatchablePolicyRequest.createInstance(decisionRequest))
+ .thenThrow(new XacmlApplicationException("throwing an exception"));
+
+ assertThrows(ToscaPolicyConversionException.class, () -> translator.convertRequest(decisionRequest));
+ }
+ }
+
+ @Test
+ void scanClosestMatchObligation() {
+ var translator = new StdMatchableTranslator();
+ var obligation = Mockito.mock(Obligation.class);
+ when(obligation.getId()).thenReturn(new IdentifierImpl("id"));
+ when(obligation.getAttributeAssignments()).thenReturn(new HashSet<>());
+
+ assertDoesNotThrow(() -> translator.scanClosestMatchObligation(new HashMap<>(), obligation));
+ }
+
+ @Test
+ void convertPolicy() throws ToscaPolicyConversionException {
+ var translator = mock(StdMatchableTranslator.class);
+ var toscaPolicy = Mockito.mock(ToscaPolicy.class);
+ when(translator.convertPolicy(toscaPolicy)).thenCallRealMethod();
+ when(translator.findPolicyType(toscaPolicy.getTypeIdentifier())).thenReturn(null);
+
+ assertThrows(ToscaPolicyConversionException.class, () -> translator.convertPolicy(toscaPolicy));
+ }
+
+ @Test
+ void retrievePolicyType() {
+ var hashMap = new HashMap<String, ToscaPolicyType>();
+ var toscaPolicyType = new ToscaPolicyType();
+ hashMap.put("someId", toscaPolicyType);
+
+ var toscaTemplate = mock(ToscaServiceTemplate.class);
+ when(toscaTemplate.getPolicyTypes()).thenReturn(hashMap);
+
+ var translator = mock(StdMatchableTranslator.class);
+ when(translator.findPolicyType(any())).thenReturn(toscaTemplate);
+ when(translator.retrievePolicyType("someId")).thenCallRealMethod();
+
+ assertEquals(toscaPolicyType, translator.retrievePolicyType("someId"));
+ }
+
+ @Test
+ void retrievePolicyType_Exception() {
+ var translator = mock(StdMatchableTranslator.class);
+ when(translator.findPolicyType(any())).thenReturn(null);
+ when(translator.retrievePolicyType("someId")).thenCallRealMethod();
+
+ assertNull(translator.retrievePolicyType("someId"));
+ }
+
+ @Test
+ void retrieveDataType() {
+ assertNull(new StdMatchableTranslator().retrieveDataType("dataType"));
+ }
+} \ No newline at end of file
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
index 95880efe..54c3a1b8 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,9 @@
package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -54,11 +54,10 @@ import java.util.UUID;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
@@ -92,8 +91,8 @@ public class StdMatchableTranslatorTest {
private static ToscaServiceTemplate testTemplate;
private static HttpClient apiClient;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static java.nio.file.Path policyFolder;
/**
* Initializes {@link #clientParams} and starts a simple REST server to handle the
@@ -101,8 +100,8 @@ public class StdMatchableTranslatorTest {
*
* @throws IOException if an error occurs
*/
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
+ @BeforeAll
+ static void setUpBeforeClass() throws Exception {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
//
@@ -115,21 +114,7 @@ public class StdMatchableTranslatorTest {
when(clientParams.getHostname()).thenReturn("localhost");
when(clientParams.getPort()).thenReturn(port);
- Properties props = new Properties();
- props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
-
- final String svcpfx =
- PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
-
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
- Integer.toString(clientParams.getPort()));
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
- ApiRestController.class.getName());
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- GsonMessageBodyHandler.class.getName());
+ Properties props = getProperties();
HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
@@ -144,7 +129,7 @@ public class StdMatchableTranslatorTest {
//
ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
//
- // Make sure all the fields are setup properly
+ // Make sure all the fields are set up properly
//
JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
jtst.fromAuthorative(serviceTemplate);
@@ -159,13 +144,32 @@ public class StdMatchableTranslatorTest {
logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testTemplate);
}
- @AfterClass
+ private static Properties getProperties() {
+ Properties props = new Properties();
+ props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
+
+ final String svcpfx =
+ PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
+
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
+ Integer.toString(clientParams.getPort()));
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
+ ApiRestController.class.getName());
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
+ GsonMessageBodyHandler.class.getName());
+ return props;
+ }
+
+ @AfterAll
public static void tearDownAfterClass() {
HttpServletServerFactoryInstance.getServerFactory().destroy();
}
@Test
- public void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
+ void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
//
// Create our translator
//
@@ -174,19 +178,19 @@ public class StdMatchableTranslatorTest {
//
// Set it up
//
- translator.setPathForData(policyFolder.getRoot().toPath());
+ translator.setPathForData(policyFolder.getRoot().toAbsolutePath());
translator.setApiClient(apiClient);
//
// Load policies to test
//
String policyYaml = ResourceUtils.getResourceAsString(
- "src/test/resources/matchable/test.policies.input.tosca.yaml");
+ "src/test/resources/matchable/test.policies.input.tosca.yaml");
//
// Serialize it into a class
//
ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
//
- // Make sure all the fields are setup properly
+ // Make sure all the fields are set up properly
//
JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
jtst.fromAuthorative(serviceTemplate);
@@ -209,7 +213,7 @@ public class StdMatchableTranslatorTest {
//
List<AttributeAssignment> listAttributes = new ArrayList<>();
ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
- .getObligationExpression().get(0);
+ .getObligationExpression().get(0);
assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
//
// Copy into the list
@@ -217,23 +221,23 @@ public class StdMatchableTranslatorTest {
xacmlObligation.getAttributeAssignmentExpression().forEach(assignment -> {
Object value = ((AttributeValueType) assignment.getExpression().getValue()).getContent().get(0);
listAttributes.add(TestUtilsCommon.createAttributeAssignment(assignment.getAttributeId(),
- assignment.getCategory(), value));
+ assignment.getCategory(), value));
});
//
// Pretend we got multiple policies to match a fictional request
//
Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- listAttributes);
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ listAttributes);
Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- listAttributes);
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ listAttributes);
//
// Should ignore this obligation
//
Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
- "nobody:cares",
- listAttributes);
+ "nobody:cares",
+ listAttributes);
//
// Create a test XACML Response
//
@@ -242,8 +246,8 @@ public class StdMatchableTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
com.att.research.xacml.api.Response xacmlResponse = TestUtilsCommon.createXacmlResponse(
- StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
- Arrays.asList(obligation1, obligation2, obligation3), policyIds);
+ StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
+ Arrays.asList(obligation1, obligation2, obligation3), policyIds);
//
// Test the response
//
@@ -280,15 +284,15 @@ public class StdMatchableTranslatorTest {
* Retrieves the specified version of a particular policy type.
*
* @param policyTypeId ID of desired policy type
- * @param versionId version of desired policy type
- * @param requestId optional request ID
- *
+ * @param versionId version of desired policy type
+ * @param requestId optional request ID
* @return the Response object containing the results of the API operation
*/
@GET
@Path("/policytypes/{policyTypeId}/versions/{versionId}")
public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
- @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
+ @PathParam("versionId") String versionId,
+ @HeaderParam("X-ONAP-RequestID") UUID requestId) {
logger.info("request for policy type={} version={}", policyTypeId, versionId);
return Response.status(Response.Status.OK).entity(testTemplate).build();
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java
index 82347474..4bacaf3c 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,10 +23,11 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -46,15 +48,15 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Properties;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
-@RunWith(MockitoJUnitRunner.class)
-public class StdOnapPipTest {
+@ExtendWith(MockitoExtension.class)
+class StdOnapPipTest {
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final String MY_ID = "my-id";
private static final String ISSUER = "my-issuer";
@@ -81,25 +83,25 @@ public class StdOnapPipTest {
*
* @throws PIPException if an error occurs
*/
- @Before
+ @BeforeEach
public void setUp() throws PIPException {
resp = new StdMutablePIPResponse();
- when(request.getIssuer()).thenReturn(ISSUER);
- when(request.getAttributeId()).thenReturn(ATTRIBUTE_ID);
+ lenient().when(request.getIssuer()).thenReturn(ISSUER);
+ lenient().when(request.getAttributeId()).thenReturn(ATTRIBUTE_ID);
pip = new MyPip();
- when(finder.getMatchingAttributes(request, pip)).thenReturn(resp);
+ lenient().when(finder.getMatchingAttributes(request, pip)).thenReturn(resp);
}
@Test
- public void testAttributesProvided() {
+ void testAttributesProvided() {
assertTrue(pip.attributesProvided().isEmpty());
}
@Test
- public void testConfigureStringProperties() throws PIPException {
+ void testConfigureStringProperties() throws PIPException {
Properties props = new Properties();
pip.configure(MY_ID, props);
@@ -108,19 +110,19 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipFinderPipRequest_NullResponse() {
+ void testGetAttributePipFinderPipRequest_NullResponse() {
assertNull(pip.getAttribute(finder, request));
}
@Test
- public void testGetAttributePipFinderPipRequest() {
+ void testGetAttributePipFinderPipRequest() {
pip.addStringAttribute(resp, CATEGORY, CATEGORY, STRING_VALUE, request);
assertEquals(STRING_VALUE, pip.getAttribute(finder, request));
}
@Test
- public void testGetAttributePipRequestPipFinder_NoStatus() {
+ void testGetAttributePipRequestPipFinder_NoStatus() {
resp.setStatus(null);
pip.addStringAttribute(resp, CATEGORY, CATEGORY, STRING_VALUE, request);
@@ -128,7 +130,7 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipRequestPipFinder_StatusNotOk() {
+ void testGetAttributePipRequestPipFinder_StatusNotOk() {
Status status = mock(Status.class);
when(status.isOk()).thenReturn(false);
resp.setStatus(status);
@@ -139,7 +141,7 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipRequestPipFinder_StatusOk() {
+ void testGetAttributePipRequestPipFinder_StatusOk() {
Status status = mock(Status.class);
when(status.isOk()).thenReturn(true);
resp.setStatus(status);
@@ -150,12 +152,12 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipRequestPipFinder_NoAttributes() {
+ void testGetAttributePipRequestPipFinder_NoAttributes() {
assertNull(pip.getAttribute(request, finder));
}
@Test
- public void testGetAttributePipRequestPipFinder_Ex() throws PIPException {
+ void testGetAttributePipRequestPipFinder_Ex() throws PIPException {
when(finder.getMatchingAttributes(request, pip)).thenThrow(new PIPException(EXPECTED_EXCEPTION));
pip.addStringAttribute(resp, CATEGORY, CATEGORY, STRING_VALUE, request);
@@ -164,19 +166,19 @@ public class StdOnapPipTest {
}
@Test
- public void testFindFirstAttributeValue_NoAttributes() {
+ void testFindFirstAttributeValue_NoAttributes() {
assertNull(pip.findFirstAttributeValue(resp));
}
@Test
- public void testFindFirstAttributeValue_NullAttributeValue() {
+ void testFindFirstAttributeValue_NullAttributeValue() {
pip.addIntegerAttribute(resp, CATEGORY, ATTRIBUTE_ID, INT_VALUE, request);
assertNull(pip.findFirstAttributeValue(resp));
}
@Test
- public void testFindFirstAttributeValue_NullValues() {
+ void testFindFirstAttributeValue_NullValues() {
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, null, request);
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, STRING_VALUE, request);
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, null, request);
@@ -185,7 +187,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddIntegerAttribute() {
+ void testAddIntegerAttribute() {
pip.addIntegerAttribute(resp, CATEGORY, ATTRIBUTE_ID, INT_VALUE, request);
assertEquals(1, resp.getAttributes().size());
@@ -200,7 +202,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddIntegerAttribute_Ex() {
+ void testAddIntegerAttribute_Ex() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeInteger(int value) throws DataTypeException {
@@ -212,7 +214,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddIntegerAttribute_Null() {
+ void testAddIntegerAttribute_Null() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeInteger(int value) throws DataTypeException {
@@ -224,7 +226,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddLongAttribute() {
+ void testAddLongAttribute() {
pip.addLongAttribute(resp, CATEGORY, ATTRIBUTE_ID, LONG_VALUE, request);
assertEquals(1, resp.getAttributes().size());
@@ -239,7 +241,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddLongAttribute_Ex() {
+ void testAddLongAttribute_Ex() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeLong(long value) throws DataTypeException {
@@ -251,7 +253,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddLongAttribute_NullAttrValue() {
+ void testAddLongAttribute_NullAttrValue() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeLong(long value) throws DataTypeException {
@@ -263,7 +265,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddStringAttribute() {
+ void testAddStringAttribute() {
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, STRING_VALUE, request);
assertEquals(1, resp.getAttributes().size());
@@ -278,7 +280,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddStringAttribute_Ex() {
+ void testAddStringAttribute_Ex() {
pip = new MyPip() {
@Override
protected AttributeValue<String> makeString(String value) throws DataTypeException {
@@ -290,7 +292,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddStringAttribute_NullAttrValue() {
+ void testAddStringAttribute_NullAttrValue() {
pip = new MyPip() {
@Override
protected AttributeValue<String> makeString(String value) throws DataTypeException {
@@ -302,13 +304,13 @@ public class StdOnapPipTest {
}
@Test
- public void testShutdown() {
+ void testShutdown() {
assertThatCode(() -> pip.shutdown()).doesNotThrowAnyException();
assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pip.configure("foo", new Properties()))
.withMessageContaining("Engine is shutdown");
}
- private class MyPip extends StdOnapPip {
+ private static class MyPip extends StdOnapPip {
@Override
public Collection<PIPRequest> attributesRequired() {
@@ -316,7 +318,7 @@ public class StdOnapPipTest {
}
@Override
- public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
+ public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) {
return null;
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java
index ea1e04d1..54fda276 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,17 +23,17 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import com.att.research.xacml.api.Request;
import com.att.research.xacml.api.Response;
@@ -45,17 +46,18 @@ import com.google.common.io.Files;
import java.io.File;
import java.nio.file.Path;
import java.util.HashSet;
+import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
@@ -67,15 +69,15 @@ import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@RunWith(MockitoJUnitRunner.class)
-public class StdXacmlApplicationServiceProviderTest {
+@ExtendWith(MockitoExtension.class)
+class StdXacmlApplicationServiceProviderTest {
private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
private static final String TEMP_DIR_NAME = "src/test/resources/temp";
- private static File TEMP_DIR = new File(TEMP_DIR_NAME);
- private static Path TEMP_PATH = TEMP_DIR.toPath();
- private static File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
- private static File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
+ private static final File TEMP_DIR = new File(TEMP_DIR_NAME);
+ private static final Path TEMP_PATH = TEMP_DIR.toPath();
+ private static final File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
+ private static final File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final String POLICY_NAME = "my-name";
private static final String POLICY_VERSION = "1.2.3";
@@ -100,24 +102,23 @@ public class StdXacmlApplicationServiceProviderTest {
private Response resp;
private ToscaPolicy policy;
- private PolicyType internalPolicy;
private StdXacmlApplicationServiceProvider prov;
/**
* Creates the temp directory.
*/
- @BeforeClass
- public static void setUpBeforeClass() {
+ @BeforeAll
+ static void setUpBeforeClass() {
assertTrue(TEMP_DIR.mkdir());
}
/**
* Deletes the temp directory and its contents.
*/
- @AfterClass
- public static void tearDownAfterClass() {
- for (File file : TEMP_DIR.listFiles()) {
+ @AfterAll
+ static void tearDownAfterClass() {
+ for (File file : Objects.requireNonNull(TEMP_DIR.listFiles())) {
if (!file.delete()) {
logger.warn("cannot delete: {}", file);
}
@@ -133,22 +134,22 @@ public class StdXacmlApplicationServiceProviderTest {
*
* @throws Exception if an error occurs
*/
- @Before
- public void setUp() throws Exception {
+ @BeforeEach
+ void setUp() throws Exception {
policy = new ToscaPolicy();
policy.setType(POLICY_TYPE);
policy.setName(POLICY_NAME);
policy.setVersion(POLICY_VERSION);
- internalPolicy = new PolicyType();
+ PolicyType internalPolicy = new PolicyType();
internalPolicy.setPolicyId(POLICY_NAME);
internalPolicy.setVersion(POLICY_VERSION);
- when(engineFactory.newEngine(any())).thenReturn(engine);
+ lenient().when(engineFactory.newEngine(any())).thenReturn(engine);
- when(engine.decide(req)).thenReturn(resp);
+ lenient().when(engine.decide(req)).thenReturn(resp);
- when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
+ lenient().when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
prov = new MyProv();
@@ -156,17 +157,17 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testApplicationName() {
+ void testApplicationName() {
assertNotNull(prov.applicationName());
}
@Test
- public void testActionDecisionsSupported() {
+ void testActionDecisionsSupported() {
assertTrue(prov.actionDecisionsSupported().isEmpty());
}
@Test
- public void testInitialize_testGetXxx() throws XacmlApplicationException {
+ void testInitialize_testGetXxx() throws XacmlApplicationException {
prov.initialize(TEMP_PATH, apiClient);
assertEquals(TEMP_PATH, prov.getDataPath());
@@ -177,32 +178,32 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testInitialize_Ex() throws XacmlApplicationException {
+ void testInitialize_Ex() {
assertThatThrownBy(() -> prov.initialize(new File(TEMP_DIR_NAME + "-nonExistent").toPath(), apiClient))
- .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
+ .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
}
@Test
- public void testSupportedPolicyTypes() {
+ void testSupportedPolicyTypes() {
assertThat(prov.supportedPolicyTypes()).isEmpty();
}
@Test
- public void testCanSupportPolicyType() {
+ void testCanSupportPolicyType() {
assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
}
@Test
- public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
- when(trans.convertPolicy(policy)).thenReturn(null);
+ void testLoadPolicy_ConversionError() throws ToscaPolicyConversionException {
+ lenient().when(trans.convertPolicy(policy)).thenReturn(null);
assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
}
@Test
- public void testLoadPolicy_testUnloadPolicy() throws Exception {
+ void testLoadPolicy_testUnloadPolicy() throws Exception {
prov.initialize(TEMP_PATH, apiClient);
- PROP_FILE.delete();
+ tryDeletePropFile();
final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
@@ -230,7 +231,7 @@ public class StdXacmlApplicationServiceProviderTest {
/*
* Prepare for unload.
*/
- PROP_FILE.delete();
+ tryDeletePropFile();
assertTrue(prov.unloadPolicy(policy));
@@ -248,7 +249,7 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testUnloadPolicy_NotDeployed() throws Exception {
+ void testUnloadPolicy_NotDeployed() throws Exception {
prov.initialize(TEMP_PATH, apiClient);
assertFalse(prov.unloadPolicy(policy));
@@ -258,14 +259,14 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testMakeDecision() throws ToscaPolicyConversionException {
+ void testMakeDecision() throws ToscaPolicyConversionException {
prov.createEngine(null);
DecisionRequest decreq = mock(DecisionRequest.class);
- when(trans.convertRequest(decreq)).thenReturn(req);
+ lenient().when(trans.convertRequest(decreq)).thenReturn(req);
DecisionResponse decresp = mock(DecisionResponse.class);
- when(trans.convertResponse(resp)).thenReturn(decresp);
+ lenient().when(trans.convertResponse(resp)).thenReturn(decresp);
Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
assertSame(decresp, result.getKey());
@@ -276,41 +277,41 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testGetTranslator() {
+ void testGetTranslator() {
assertSame(trans, prov.getTranslator());
}
@Test
- public void testCreateEngine() throws FactoryException {
+ void testCreateEngine() throws FactoryException {
// success
prov.createEngine(null);
assertSame(engine, prov.getEngine());
// null - should be unchanged
- when(engineFactory.newEngine(any())).thenReturn(null);
+ lenient().when(engineFactory.newEngine(any())).thenReturn(null);
prov.createEngine(null);
assertSame(engine, prov.getEngine());
// exception - should be unchanged
- when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
+ lenient().when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
prov.createEngine(null);
assertSame(engine, prov.getEngine());
}
@Test
- public void testXacmlDecision() throws PDPException {
+ void testXacmlDecision() throws PDPException {
prov.createEngine(null);
// success
assertSame(resp, prov.xacmlDecision(req));
// exception
- when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
+ lenient().when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
assertNull(prov.xacmlDecision(req));
}
@Test
- public void testGetPdpEngineFactory() throws XacmlApplicationException {
+ void testGetPdpEngineFactory() throws XacmlApplicationException {
// use the real engine factory
engineFactory = null;
@@ -320,6 +321,12 @@ public class StdXacmlApplicationServiceProviderTest {
assertNotNull(prov.getEngine());
}
+ private void tryDeletePropFile() {
+ if (!PROP_FILE.delete()) {
+ logger.warn("{} not deleted", PROP_FILE);
+ }
+ }
+
private class MyProv extends StdXacmlApplicationServiceProvider {
@Override
diff --git a/applications/common/src/test/resources/META-INF/persistence.xml b/applications/common/src/test/resources/META-INF/persistence.xml
index 53597b91..1f11f3dd 100644
--- a/applications/common/src/test/resources/META-INF/persistence.xml
+++ b/applications/common/src/test/resources/META-INF/persistence.xml
@@ -4,7 +4,7 @@
ONAP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -20,17 +20,15 @@
============LICENSE_END=========================================================
-->
-<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
-
+<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd">
<persistence-unit name="PipEngineTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>org.onap.policy.guard.OperationsHistory</class>
-
<properties>
<property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="jakarta.persistence.schema-generation.create-source" value="metadata"/>
- <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.show_sql" value="false"/>
</properties>
</persistence-unit>
diff --git a/applications/guard/pom.xml b/applications/guard/pom.xml
index 658b28d6..1b3ba522 100644
--- a/applications/guard/pom.xml
+++ b/applications/guard/pom.xml
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>xacml-guard</artifactId>
diff --git a/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java b/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
index 184db863..4cea61c6 100644
--- a/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
+++ b/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -75,19 +75,10 @@ public class GuardTranslator implements ToscaPolicyTranslator {
//
// common guard property fields
//
- public static final String FIELD_ACTOR = "actor";
- public static final String FIELD_OPERATION = "operation";
public static final String FIELD_CONTROLLOOP = "id";
public static final String FIELD_TIMERANGE = "timeRange";
//
- // frequency property fields
- //
- public static final String FIELD_TIMEWINDOW = "timeWindow";
- public static final String FIELD_TIMEUNITS = "timeUnits";
- public static final String FIELD_LIMIT = "limit";
-
- //
// minmax property fields
//
public static final String FIELD_TARGET = "target";
@@ -99,17 +90,6 @@ public class GuardTranslator implements ToscaPolicyTranslator {
//
public static final String FIELD_BLACKLIST = "blacklist";
- //
- // filter property fields
- //
- public static final String FIELD_FILTER_WHITELIST = "whitelist";
- public static final String FIELD_FILTER_ALGORITHM = "algorithm";
- public static final String FIELD_FILTER_FILTERS = "filters";
- public static final String FIELD_FILTER_FIELD = "field";
- public static final String FIELD_FILTER_FUNCTION = "function";
- public static final String FIELD_FILTER_FILTER = "filter";
- public static final String FIELD_FILTER_BLACKLIST = "blacklist";
-
public static final String POLICYTYPE_FREQUENCY = "onap.policies.controlloop.guard.common.FrequencyLimiter";
public static final String POLICYTYPE_MINMAX = "onap.policies.controlloop.guard.common.MinMax";
public static final String POLICYTYPE_BLACKLIST = "onap.policies.controlloop.guard.common.Blacklist";
@@ -286,7 +266,7 @@ public class GuardTranslator implements ToscaPolicyTranslator {
}
/**
- * Generate the targetType for the policy. Optional to add MatchType for the target. eg. the
+ * Generate the targetType for the policy. Optional to add MatchType for the target. e.g. the
* blacklist policy type uses the target in a different manner.
*
* @param properties TOSCA properties object
@@ -327,7 +307,6 @@ public class GuardTranslator implements ToscaPolicyTranslator {
return target;
}
- @SuppressWarnings("unchecked")
protected AllOfType addMatch(AllOfType allOf, Object value, Identifier attributeId) {
if (value instanceof String) {
if (".*".equals(value.toString())) {
@@ -350,8 +329,8 @@ public class GuardTranslator implements ToscaPolicyTranslator {
}
return allOf;
}
- if (value instanceof Collection) {
- ((Collection<String>) value).forEach(val -> {
+ if (value instanceof Collection<?> collection) {
+ collection.forEach(val -> {
var match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
XACML3.ID_FUNCTION_STRING_EQUAL,
val,
@@ -365,27 +344,6 @@ public class GuardTranslator implements ToscaPolicyTranslator {
return allOf;
}
- protected void addTimeRangeMatch(AllOfType allOf, TimeRange timeRange) {
-
- var matchStart = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_TIME_GREATER_THAN_OR_EQUAL,
- timeRange.getStartTime(),
- XACML3.ID_DATATYPE_TIME,
- XACML3.ID_ENVIRONMENT_CURRENT_TIME,
- XACML3.ID_ATTRIBUTE_CATEGORY_ENVIRONMENT);
-
- allOf.getMatch().add(matchStart);
-
- var matchEnd = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_TIME_LESS_THAN_OR_EQUAL,
- timeRange.getEndTime(),
- XACML3.ID_DATATYPE_TIME,
- XACML3.ID_ENVIRONMENT_CURRENT_TIME,
- XACML3.ID_ATTRIBUTE_CATEGORY_ENVIRONMENT);
-
- allOf.getMatch().add(matchEnd);
- }
-
protected VariableReferenceType createTimeRangeVariable(Map<String, Object> properties, PolicyType newPolicyType)
throws ToscaPolicyConversionException {
//
@@ -456,7 +414,7 @@ public class GuardTranslator implements ToscaPolicyTranslator {
FrequencyDefinition frequencyDef = ToscaPolicyTranslatorUtils.decodeProperties(toscaPolicy.getProperties(),
FrequencyDefinition.class);
//
- // See if its possible to generate a count
+ // See if it's possible to generate a count
//
String timeWindow = null;
if (frequencyDef.getTimeWindow() != null) {
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java
index d0541e2a..c1c072db 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,30 +26,30 @@ package org.onap.policy.xacml.pdp.application.guard;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class CoordinationGuardTranslatorTest {
+class CoordinationGuardTranslatorTest {
@Test
- public void testUnsupportedMethods() {
+ void testUnsupportedMethods() {
CoordinationGuardTranslator translator = new CoordinationGuardTranslator();
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> translator.convertRequest(null))
- .withMessageContaining("this convertRequest shouldn't be used");
+ .isThrownBy(() -> translator.convertRequest(null))
+ .withMessageContaining("this convertRequest shouldn't be used");
assertThat(translator.convertResponse(null)).isNull();
}
@Test
- public void testLoadingDirectives() {
+ void testLoadingDirectives() {
assertThat(CoordinationGuardTranslator.loadCoordinationDirectiveFromFile(null)).isNull();
assertThat(CoordinationGuardTranslator.loadCoordinationDirectiveFromFile("nonexistent.yaml")).isNull();
CoordinationDirective directive = CoordinationGuardTranslator
- .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
+ .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
assertThat(directive).isNotNull();
assertThat(directive.getCoordinationFunction()).isEqualTo("whatisthisvaluesupposedtobe");
assertThat(directive.getControlLoop()).hasSize(2);
@@ -56,14 +57,14 @@ public class CoordinationGuardTranslatorTest {
}
@Test
- public void testGeneratingXacml() {
+ void testGeneratingXacml() {
CoordinationDirective directive = CoordinationGuardTranslator
- .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
+ .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> CoordinationGuardTranslator
- .generateXacmlFromCoordinationDirective(directive, "idontexist.yaml"))
- .withMessageContaining("Unable to find prototype ");
+ .isThrownBy(() -> CoordinationGuardTranslator
+ .generateXacmlFromCoordinationDirective(directive, "idontexist.yaml"))
+ .withMessageContaining("Unable to find prototype ");
}
}
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
index 31e576ff..a11f19d8 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,28 +28,26 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import com.att.research.xacml.api.Response;
import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
+import java.nio.file.Path;
import java.sql.Date;
import java.time.Instant;
import java.time.OffsetDateTime;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.UUID;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -66,47 +64,46 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class GuardPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class GuardPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
private static DecisionRequest requestVfCount;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static EntityManager em;
+ private static EntityManagerFactory emf;
private static final String DENY = "Deny";
private static final String PERMIT = "Permit";
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
LOGGER.info("Setting up class");
//
- // Setup our temporary folder
+ // Set up our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties", properties,
- myCreator);
+ myCreator);
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Find the guard service application and save for use in all the tests
//
StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -132,33 +129,35 @@ public class GuardPdpApplicationTest {
// Load Decision Requests
//
requestVfCount =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
+ DecisionRequest.class);
//
// Create EntityManager for manipulating DB
//
String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
- em = Persistence
- .createEntityManagerFactory(GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
- .createEntityManager();
+ emf = Persistence.createEntityManagerFactory(
+ GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties);
+ em = emf.createEntityManager();
}
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() throws Exception {
+ @AfterAll
+ static void cleanup() {
if (em != null) {
em.close();
}
+ if (emf != null) {
+ emf.close();
+ }
}
/**
* Clears the database before each test so there are no operations in it.
- *
*/
- @Before
- public void startClean() throws Exception {
+ @BeforeEach
+ void startClean() {
em.getTransaction().begin();
em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
em.getTransaction().commit();
@@ -169,9 +168,8 @@ public class GuardPdpApplicationTest {
*
* @param expected from the response
* @param response received
- *
**/
- public void checkDecision(String expected, DecisionResponse response) throws CoderException {
+ void checkDecision(String expected, DecisionResponse response) throws CoderException {
LOGGER.info("Looking for {} Decision", expected);
assertThat(response).isNotNull();
assertThat(response.getStatus()).isNotNull();
@@ -191,11 +189,10 @@ public class GuardPdpApplicationTest {
/**
* Request a decision and check that it matches expectation.
*
- * @param request to send to Xacml PDP
+ * @param request to send to Xacml PDP
* @param expected from the response
- *
**/
- public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
+ void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
//
// Ask for a decision
//
@@ -207,7 +204,7 @@ public class GuardPdpApplicationTest {
}
@Test
- public void test1Basics() throws CoderException, IOException {
+ void test1Basics() {
LOGGER.info("**************** Running test1Basics ****************");
//
// Make sure there's an application name
@@ -225,37 +222,36 @@ public class GuardPdpApplicationTest {
assertThat(service.supportedPolicyTypes()).isNotEmpty();
assertThat(service.supportedPolicyTypes()).hasSize(5);
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.0")))
- .isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.0")))
+ .isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.1")))
- .isFalse();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.1")))
+ .isFalse();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.1"))).isFalse();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.1"))).isFalse();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
+ "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
+ "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier("onap.foo", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Filter", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Filter", "1.0.0"))).isTrue();
}
@Test
- public void test2NoPolicies() throws CoderException {
+ void test2NoPolicies() {
LOGGER.info("**************** Running test2NoPolicies ****************");
assertThatCode(() -> requestAndCheckDecision(requestVfCount, PERMIT)).doesNotThrowAnyException();
}
@Test
- public void test3FrequencyLimiter()
- throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
+ void test3FrequencyLimiter() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running test3FrequencyLimiter ****************");
//
// Now load the vDNS frequency limiter Policy - make sure
@@ -263,7 +259,7 @@ public class GuardPdpApplicationTest {
// into the PDP.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("policies/vDNS.policy.guard.frequencylimiter.input.tosca.yaml", service);
+ TestUtils.loadPolicies("policies/vDNS.policy.guard.frequencylimiter.input.tosca.yaml", service);
assertThat(loadedPolicies).hasSize(1);
assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.frequency.scaleout");
//
@@ -282,7 +278,7 @@ public class GuardPdpApplicationTest {
@SuppressWarnings("unchecked")
@Test
- public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
+ void test4MinMax() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running test4MinMax ****************");
//
// Now load the vDNS min max Policy - make sure
@@ -290,7 +286,7 @@ public class GuardPdpApplicationTest {
// into the PDP.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("policies/vDNS.policy.guard.minmaxvnfs.input.tosca.yaml", service);
+ TestUtils.loadPolicies("policies/vDNS.policy.guard.minmaxvnfs.input.tosca.yaml", service);
assertThat(loadedPolicies).hasSize(1);
assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.minmax.scaleout");
//
@@ -327,13 +323,13 @@ public class GuardPdpApplicationTest {
@SuppressWarnings("unchecked")
@Test
- public void test5Blacklist() throws CoderException, XacmlApplicationException {
+ void test5Blacklist() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running test5Blacklist ****************");
//
// Load the blacklist policy in with the others.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("policies/vDNS.policy.guard.blacklist.input.tosca.yaml", service);
+ TestUtils.loadPolicies("policies/vDNS.policy.guard.blacklist.input.tosca.yaml", service);
assertThat(loadedPolicies).hasSize(1);
assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.blacklist.scaleout");
//
@@ -344,7 +340,7 @@ public class GuardPdpApplicationTest {
// vfcount=1 between min of 1 and max of 2: change the
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("target",
- "the-vfmodule-where-root-is-true");
+ "the-vfmodule-where-root-is-true");
//
// vfcount=0 below min of 1: should get a Deny because target IS blacklisted
//
@@ -353,7 +349,7 @@ public class GuardPdpApplicationTest {
// vfcount=1 between min of 1 and max of 2: change the
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("target",
- "another-vfmodule-where-root-is-true");
+ "another-vfmodule-where-root-is-true");
//
// vfcount=0 below min of 1: should get a Deny because target IS blacklisted
//
@@ -362,14 +358,14 @@ public class GuardPdpApplicationTest {
@SuppressWarnings("unchecked")
@Test
- public void test6Filters() throws Exception {
+ void test6Filters() throws Exception {
LOGGER.info("**************** Running test6Filters ****************");
//
// Re-Load Decision Request - so we can start from scratch
//
requestVfCount =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
+ DecisionRequest.class);
//
// Ensure we are a permit to start
//
@@ -378,7 +374,7 @@ public class GuardPdpApplicationTest {
// Load the filter policy in with the others.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("src/test/resources/test.policy.guard.filters.yaml", service);
+ TestUtils.loadPolicies("src/test/resources/test.policy.guard.filters.yaml", service);
assertThat(loadedPolicies).hasSize(2);
//
// Although the region is blacklisted, the id is not
@@ -388,7 +384,7 @@ public class GuardPdpApplicationTest {
// Put in a different vnf id
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
- "different-vnf-id-should-be-denied");
+ "different-vnf-id-should-be-denied");
//
// The region is blacklisted, and the id is not allowed
//
@@ -397,7 +393,7 @@ public class GuardPdpApplicationTest {
// Let's switch to a different region
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("cloud-region.cloud-region-id",
- "RegionTwo");
+ "RegionTwo");
//
// The region is whitelisted, and the id is also allowed
//
@@ -406,7 +402,7 @@ public class GuardPdpApplicationTest {
// Put in a blacklisted vnf id
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
- "f17face5-69cb-4c88-9e0b-7426db7edddd");
+ "f17face5-69cb-4c88-9e0b-7426db7edddd");
//
// Although region is whitelisted, the id is blacklisted
//
@@ -415,7 +411,7 @@ public class GuardPdpApplicationTest {
// Let's switch to a different region
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("cloud-region.cloud-region-id",
- "RegionThree");
+ "RegionThree");
//
// There is no filter for this region, but the id is still blacklisted
//
@@ -424,7 +420,7 @@ public class GuardPdpApplicationTest {
// Put in a different vnf id
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
- "different-vnf-id-should-be-permitted");
+ "different-vnf-id-should-be-permitted");
//
// There is no filter for this region, and the id is not blacklisted
//
@@ -432,19 +428,19 @@ public class GuardPdpApplicationTest {
}
@Test
- public void test7TimeInRange() throws Exception {
+ void test7TimeInRange() throws Exception {
LOGGER.info("**************** Running test7TimeInRange ****************");
//
// Re-Load Decision Request - so we can start from scratch
//
DecisionRequest requestInRange =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.timeinrange.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.timeinrange.json"),
+ DecisionRequest.class);
//
// Load the test policy in with the others.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("src/test/resources/test-time-in-range.yaml", service);
+ TestUtils.loadPolicies("src/test/resources/test-time-in-range.yaml", service);
assertThat(loadedPolicies).hasSize(1);
//
// Mock what the current date and time is. Set to 12 Noon
@@ -497,20 +493,20 @@ public class GuardPdpApplicationTest {
//
// Get the properties
//
- Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
- assertThat(properties).isNotNull();
+ Map<String, Object> localProps = (Map<String, Object>) request.getResource().get("guard");
+ assertThat(localProps).isNotNull();
//
// Add an entry
//
OperationsHistory newEntry = new OperationsHistory();
- newEntry.setActor(properties.get("actor").toString());
- newEntry.setOperation(properties.get("operation").toString());
- newEntry.setClosedLoopName(properties.get("clname").toString());
+ newEntry.setActor(localProps.get("actor").toString());
+ newEntry.setOperation(localProps.get("operation").toString());
+ newEntry.setClosedLoopName(localProps.get("clname").toString());
newEntry.setOutcome("SUCCESS");
newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
newEntry.setEndtime(Date.from(Instant.now()));
newEntry.setRequestId(UUID.randomUUID().toString());
- newEntry.setTarget(properties.get("target").toString());
+ newEntry.setTarget(localProps.get("target").toString());
LOGGER.info("Inserting {}", newEntry);
em.getTransaction().begin();
em.persist(newEntry);
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java
index 1c925ce2..4b21bf38 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,16 +28,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class GuardPolicyRequestTest {
+class GuardPolicyRequestTest {
@Test
- public void testAnomalies() throws ToscaPolicyConversionException {
+ void testAnomalies() throws ToscaPolicyConversionException {
DecisionRequest decisionRequest = new DecisionRequest();
assertThat(GuardPolicyRequest.createInstance(decisionRequest)).isNotNull();
@@ -95,12 +96,12 @@ public class GuardPolicyRequestTest {
}
@Test
- public void testFilterResources() throws Exception {
+ void testFilterResources() throws Exception {
StandardCoder gson = new StandardCoder();
DecisionRequest request = gson.decode(
- TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.filter.json"),
- DecisionRequest.class);
+ TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.filter.json"),
+ DecisionRequest.class);
GuardPolicyRequest guardRequest = GuardPolicyRequest.createInstance(request);
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
index ac36ec72..d80d85b1 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,7 +43,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -58,26 +58,26 @@ import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionExcepti
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class GuardTranslatorTest {
+class GuardTranslatorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GuardTranslatorTest.class);
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
- private GuardTranslator translator = new GuardTranslator();
+ private final GuardTranslator translator = new GuardTranslator();
@Test
- public void testRequest() throws Exception {
+ void testRequest() throws Exception {
DecisionRequest decisionRequest = gson.decode(
- TextFileUtils.getTextFileAsString(
- "src/test/resources/requests/guard.vfCount.json"),
- DecisionRequest.class);
+ TextFileUtils.getTextFileAsString(
+ "src/test/resources/requests/guard.vfCount.json"),
+ DecisionRequest.class);
Request xacmlRequest = translator.convertRequest(decisionRequest);
assertThat(xacmlRequest).isNotNull();
}
@Test
- public void testResponse() {
+ void testResponse() {
StdStatus status = new StdStatus(StdStatusCode.STATUS_CODE_OK);
StdMutableResult result = new StdMutableResult(Decision.PERMIT, status);
StdMutableResponse response = new StdMutableResponse(result);
@@ -101,7 +101,7 @@ public class GuardTranslatorTest {
@Test
- public void testBadPolicies() throws Exception {
+ void testBadPolicies() throws Exception {
String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/test-bad-policies.yaml");
//
// Serialize it into a class
@@ -127,7 +127,7 @@ public class GuardTranslatorTest {
name2message.put("blacklist-noblacklist", "item \"blacklist\"");
name2message.put("filter-noalgorithm", "item \"algorithm\"");
name2message.put("filter-badalgorithm",
- "Unexpected value for algorithm, should be whitelist-overrides or blacklist-overrides");
+ "Unexpected value for algorithm, should be whitelist-overrides or blacklist-overrides");
name2message.put("filter-nofilter", "item \"filters\"");
name2message.put("filter-nocollection", "Cannot decode FilterDefinition");
name2message.put("filter-noarray", "Cannot decode FilterDefinition");
@@ -142,7 +142,7 @@ public class GuardTranslatorTest {
//
for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
for (ToscaPolicy policy : policies.values()) {
- LOGGER.info("Testing policy " + policy.getName());
+ LOGGER.info("Testing policy {}", policy.getName());
String expectedMsg = name2message.get(policy.getName());
assertThat(expectedMsg).as(policy.getName()).isNotNull();
@@ -154,7 +154,7 @@ public class GuardTranslatorTest {
}
@Test
- public void testPolicyConversion() throws Exception {
+ void testPolicyConversion() throws Exception {
String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/test-policies.yaml");
//
// Serialize it into a class
@@ -198,13 +198,13 @@ public class GuardTranslatorTest {
// Validate each policy type
//
if (GuardTranslator.POLICYTYPE_FREQUENCY.equals(policy.getType())) {
- validateFrequency(policy, xacmlPolicy);
+ validateFrequency(xacmlPolicy);
} else if (GuardTranslator.POLICYTYPE_MINMAX.equals(policy.getType())) {
validateMinMax(policy, xacmlPolicy);
} else if (GuardTranslator.POLICYTYPE_BLACKLIST.equals(policy.getType())) {
validateBlacklist(policy, xacmlPolicy);
} else if (GuardTranslator.POLICYTYPE_FILTER.equals(policy.getType())) {
- validateFilter(policy, xacmlPolicy);
+ validateFilter(xacmlPolicy);
}
}
}
@@ -213,11 +213,11 @@ public class GuardTranslatorTest {
testPol.setProperties(new LinkedHashMap<>());
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> translator.convertPolicy(testPol));
+ .isThrownBy(() -> translator.convertPolicy(testPol));
testPol.setProperties(null);
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> translator.convertPolicy(testPol));
+ .isThrownBy(() -> translator.convertPolicy(testPol));
}
private void validateCommon(ToscaPolicy policy, PolicyType xacmlPolicy) {
@@ -225,7 +225,6 @@ public class GuardTranslatorTest {
boolean foundOperation = false;
boolean foundTarget = false;
boolean foundControlLoop = false;
- //boolean foundTimeRange = false;
assertThat(xacmlPolicy.getTarget()).isNotNull();
assertThat(xacmlPolicy.getTarget().getAnyOf()).isNotEmpty();
@@ -238,11 +237,11 @@ public class GuardTranslatorTest {
// These fields are required
//
if (ToscaDictionary.ID_RESOURCE_GUARD_ACTOR.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(match.getAttributeValue().getContent()).isNotNull();
foundActor = true;
} else if (ToscaDictionary.ID_RESOURCE_GUARD_RECIPE.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(match.getAttributeValue().getContent()).isNotNull();
foundOperation = true;
} else {
@@ -250,22 +249,16 @@ public class GuardTranslatorTest {
// These fields are optional
//
if (ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties()).containsKey("target");
foundTarget = true;
}
if (ToscaDictionary.ID_RESOURCE_GUARD_CLNAME.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_CONTROLLOOP);
foundControlLoop = true;
}
- /*
- if (XACML3.ID_ENVIRONMENT_CURRENT_TIME.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
- assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_TIMERANGE);
- foundTimeRange = true;
- }
- */
+
}
}
}
@@ -283,9 +276,9 @@ public class GuardTranslatorTest {
}
}
- private void validateFrequency(ToscaPolicy policy, PolicyType xacmlPolicy) {
+ private void validateFrequency(PolicyType xacmlPolicy) {
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
assertThat(((RuleType) rule).getCondition()).isNotNull();
@@ -297,7 +290,7 @@ public class GuardTranslatorTest {
boolean foundTarget = false;
boolean foundMinOrMax = false;
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
for (AnyOfType anyOf : ((RuleType) rule).getTarget().getAnyOf()) {
@@ -306,13 +299,13 @@ public class GuardTranslatorTest {
assertThat(allOf.getMatch()).isNotEmpty();
for (MatchType match : allOf.getMatch()) {
if (ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_TARGET);
foundTarget = true;
} else if (ToscaDictionary.ID_RESOURCE_GUARD_VFCOUNT.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties().keySet()).containsAnyOf(GuardTranslator.FIELD_MIN,
- GuardTranslator.FIELD_MAX);
+ GuardTranslator.FIELD_MAX);
foundMinOrMax = true;
}
}
@@ -325,7 +318,7 @@ public class GuardTranslatorTest {
private void validateBlacklist(ToscaPolicy policy, PolicyType xacmlPolicy) {
boolean foundBlacklist = false;
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
assertThat(((RuleType) rule).getTarget()).isNotNull();
@@ -337,7 +330,7 @@ public class GuardTranslatorTest {
assertThat(allOf.getMatch()).hasSize(1);
for (MatchType match : allOf.getMatch()) {
assertThat(match.getAttributeDesignator().getAttributeId())
- .isEqualTo(ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString());
+ .isEqualTo(ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString());
assertThat(match.getAttributeValue().getContent()).containsAnyOf("vnf1", "vnf2");
//
// This just checks that policy did have a blacklist in it.
@@ -351,10 +344,10 @@ public class GuardTranslatorTest {
assertThat(foundBlacklist).isTrue();
}
- private void validateFilter(ToscaPolicy policy, PolicyType xacmlPolicy) {
+ private void validateFilter(PolicyType xacmlPolicy) {
assertThat(xacmlPolicy.getRuleCombiningAlgId()).endsWith("-overrides");
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
assertThat(((RuleType) rule).getTarget()).isNotNull();
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java
index 4e7bb12f..5d19a905 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,25 +27,24 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.io.File;
-import java.io.IOException;
+import java.nio.file.Path;
import java.time.Instant;
import java.util.Date;
-import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.UUID;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -60,36 +59,37 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class SonCoordinationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class SonCoordinationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SonCoordinationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
private static DecisionRequest requestVpciNode1;
private static DecisionRequest requestVsonhNode1;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static EntityManager em;
+ private static EntityManagerFactory emf;
private static final String DENY = "Deny";
private static final String PERMIT = "Permit";
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
LOGGER.info("Setting up class");
//
- // Setup our temporary folder
+ // Set up our temporary folder
//
XacmlPolicyUtils.FileCreator myCreator =
- (String filename) -> policyFolder.newFile(filename);
+ (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
"src/test/resources/xacml.properties", properties, myCreator);
//
@@ -102,9 +102,7 @@ public class SonCoordinationTest {
//
StringBuilder strDump =
new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -138,18 +136,16 @@ public class SonCoordinationTest {
"src/test/resources/requests/coordination.cl.vSonh.node.1.json"),
DecisionRequest.class);
String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
- em = Persistence
- .createEntityManagerFactory(SonCoordinationTest.properties.getProperty(persistenceUnit),
- properties)
- .createEntityManager();
+ emf = Persistence.createEntityManagerFactory(
+ SonCoordinationTest.properties.getProperty(persistenceUnit), properties);
+ em = emf.createEntityManager();
}
/**
* Clears the database before each test.
- *
*/
- @Before
- public void startClean() throws Exception {
+ @BeforeEach
+ void startClean() {
em.getTransaction().begin();
em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
em.getTransaction().commit();
@@ -158,11 +154,14 @@ public class SonCoordinationTest {
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() throws Exception {
+ @AfterAll
+ static void cleanup() {
if (em != null) {
em.close();
}
+ if (emf != null) {
+ emf.close();
+ }
}
/**
@@ -170,9 +169,8 @@ public class SonCoordinationTest {
*
* @param expected from the response
* @param response received
- *
**/
- public void checkDecision(String expected, DecisionResponse response) throws CoderException {
+ void checkDecision(String expected, DecisionResponse response) throws CoderException {
LOGGER.info("Looking for {} Decision", expected);
assertThat(response).isNotNull();
assertThat(response.getStatus()).isNotNull();
@@ -186,11 +184,10 @@ public class SonCoordinationTest {
/**
* Request a decision and check that it matches expectation.
*
- * @param request to send to Xacml PDP
+ * @param request to send to Xacml PDP
* @param expected from the response
- *
**/
- public void requestAndCheckDecision(DecisionRequest request, String expected)
+ void requestAndCheckDecision(DecisionRequest request, String expected)
throws CoderException {
//
@@ -204,7 +201,7 @@ public class SonCoordinationTest {
}
@Test
- public void test1() throws CoderException, IOException, XacmlApplicationException {
+ void test1() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running vPci and vSonh Control Loops ****************");
//
// Now load the test coordination policy - make sure
@@ -228,7 +225,7 @@ public class SonCoordinationTest {
//
// Open vSonh on node1
//
- long vsonhId = insertOperationEvent(requestVsonhNode1, "Started");
+ long vsonhId = insertOperationEvent(requestVsonhNode1);
//
// Under current coordination policy vPci should get a deny
//
@@ -244,7 +241,7 @@ public class SonCoordinationTest {
//
// Open vPci on node1
//
- long vpciId = insertOperationEvent(requestVpciNode1, "Started");
+ long vpciId = insertOperationEvent(requestVpciNode1);
//
// Under current coordination policy vSonh should get a deny
//
@@ -260,23 +257,23 @@ public class SonCoordinationTest {
}
@SuppressWarnings("unchecked")
- private long insertOperationEvent(DecisionRequest request, String outcome) {
+ private long insertOperationEvent(DecisionRequest request) {
//
// Get the properties
//
- Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
+ Map<String, Object> localProps = (Map<String, Object>) request.getResource().get("guard");
//
// Add an entry
//
OperationsHistory newEntry = new OperationsHistory();
- newEntry.setActor(properties.get("actor").toString());
- newEntry.setOperation(properties.get("operation").toString());
- newEntry.setClosedLoopName(properties.get("clname").toString());
- newEntry.setOutcome(outcome);
+ newEntry.setActor(localProps.get("actor").toString());
+ newEntry.setOperation(localProps.get("operation").toString());
+ newEntry.setClosedLoopName(localProps.get("clname").toString());
+ newEntry.setOutcome("Started");
newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
newEntry.setEndtime(Date.from(Instant.now()));
newEntry.setRequestId(UUID.randomUUID().toString());
- newEntry.setTarget(properties.get("target").toString());
+ newEntry.setTarget(localProps.get("target").toString());
em.getTransaction().begin();
em.persist(newEntry);
em.getTransaction().commit();
@@ -284,7 +281,6 @@ public class SonCoordinationTest {
}
private void updateOperationEvent(long id, String outcome) {
-
OperationsHistory updateEntry = em.find(OperationsHistory.class, id);
updateEntry.setOutcome(outcome);
updateEntry.setEndtime(Date.from(Instant.now()));
diff --git a/applications/guard/src/test/resources/META-INF/persistence.xml b/applications/guard/src/test/resources/META-INF/persistence.xml
index 569d3da7..5327a314 100644
--- a/applications/guard/src/test/resources/META-INF/persistence.xml
+++ b/applications/guard/src/test/resources/META-INF/persistence.xml
@@ -4,7 +4,7 @@
ONAP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -20,15 +20,14 @@
============LICENSE_END=========================================================
-->
-<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
+<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd">
<persistence-unit name="OperationsHistoryPUTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>org.onap.policy.guard.OperationsHistory</class>
-
<properties>
<property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
- <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.format_sql" value="false"/>
</properties>
diff --git a/applications/match/pom.xml b/applications/match/pom.xml
index 6c8d793f..5c8d40e9 100644
--- a/applications/match/pom.xml
+++ b/applications/match/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>xacml-match</artifactId>
@@ -35,11 +35,6 @@
<dependencies>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
diff --git a/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java b/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java
index b022bca1..904cc252 100644
--- a/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java
+++ b/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,21 +27,19 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -56,52 +54,52 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class MatchPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class MatchPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MatchPdpApplicationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static DecisionRequest baseRequest;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ static void setUp() throws Exception {
//
// Load Single Decision Request
//
baseRequest = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.match.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.match.input.json"),
+ DecisionRequest.class);
//
// Setup our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ properties, myCreator);
//
// Copy the test policy types into data area
//
String policy = "onap.policies.match.Test";
String policyType = ResourceUtils.getResourceAsString("src/test/resources/" + policy + ".yaml");
LOGGER.info("Copying {}", policyType);
- Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
- policyType.getBytes());
+ Files.write(Paths.get(policyFolder.toFile().getAbsolutePath(), policy + "-1.0.0.yaml"),
+ policyType.getBytes());
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Iterate through Xacml application services and find
// the optimization service. Save it for use throughout
@@ -134,7 +132,7 @@ public class MatchPdpApplicationTest {
}
@Test
- public void test01Basics() {
+ void test01Basics() {
//
// Make sure there's an application name
//
@@ -149,13 +147,13 @@ public class MatchPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.match.Test", "1.0.0"))).isTrue();
+ "onap.policies.match.Test", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.foobar", "1.0.0"))).isFalse();
+ "onap.foobar", "1.0.0"))).isFalse();
}
@Test
- public void test02NoPolicies() throws CoderException {
+ void test02NoPolicies() throws CoderException {
//
// Ask for a decision when there are no policies loaded
//
@@ -168,7 +166,7 @@ public class MatchPdpApplicationTest {
}
@Test
- public void test03Match() throws CoderException, FileNotFoundException, IOException,
+ void test03Match() throws
XacmlApplicationException {
//
// Now load all the test match policies
@@ -208,7 +206,7 @@ public class MatchPdpApplicationTest {
//
// Validate it
//
- validateDecision(response, baseRequest, "value1");
+ validateDecision(response, "value1");
//
// Ask for bar
//
@@ -222,7 +220,7 @@ public class MatchPdpApplicationTest {
//
// Validate it
//
- validateDecision(response, baseRequest, "value2");
+ validateDecision(response, "value2");
//
// Ask for hello (should return nothing)
//
@@ -246,7 +244,7 @@ public class MatchPdpApplicationTest {
}
@SuppressWarnings("unchecked")
- private void validateDecision(DecisionResponse decision, DecisionRequest request, String value) {
+ private void validateDecision(DecisionResponse decision, String value) {
for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
assertThat(entrySet.getValue()).isInstanceOf(Map.class);
diff --git a/applications/monitoring/pom.xml b/applications/monitoring/pom.xml
index 91f44cae..beedf1b1 100644
--- a/applications/monitoring/pom.xml
+++ b/applications/monitoring/pom.xml
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>xacml-monitoring</artifactId>
diff --git a/applications/monitoring/src/test/java/cucumber/RunCucumberTest.java b/applications/monitoring/src/test/java/cucumber/RunCucumberTest.java
deleted file mode 100644
index f0b9d7f5..00000000
--- a/applications/monitoring/src/test/java/cucumber/RunCucumberTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package cucumber;
-
-import io.cucumber.junit.Cucumber;
-import io.cucumber.junit.CucumberOptions;
-import org.junit.runner.RunWith;
-
-@RunWith(Cucumber.class)
-@CucumberOptions()
-public class RunCucumberTest {
-} \ No newline at end of file
diff --git a/applications/monitoring/src/test/java/cucumber/Stepdefs.java b/applications/monitoring/src/test/java/cucumber/Stepdefs.java
deleted file mode 100644
index 0a1d333a..00000000
--- a/applications/monitoring/src/test/java/cucumber/Stepdefs.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package cucumber;
-
-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;
-import io.cucumber.java.en.Given;
-import io.cucumber.java.en.Then;
-import io.cucumber.java.en.When;
-import org.junit.ClassRule;
-import org.junit.rules.TemporaryFolder;
-
-public class Stepdefs {
-
- /*
-
- private static final Logger logger = LoggerFactory.getLogger(Stepdefs.class);
-
- public static OnapXacmlPdpEngine onapPdpEngine;
- public static Properties properties;
- public static Map<String, Object> tcaPolicy;
- public static Request request;
- public static File pathProperties;
- public static File pathRootPolicy;
-
- /**
- * Temporary folder where we will store newly created policies.
- */
- @ClassRule
- public TemporaryFolder policyFolder = new TemporaryFolder();
-
- /**
- * This is a simple annotation class to simulate
- * requests coming in.
- */
- @XACMLRequest(ReturnPolicyIdList = true)
- public class MyXacmlRequest {
-
- @XACMLSubject(includeInResults = true)
- String onapName = "DCAE";
-
- @XACMLResource(includeInResults = true)
- String resource = "onap.policies.Monitoring";
-
- @XACMLAction()
- String action = "configure";
- }
-
- /**
- * Initialization.
- */
- @Given("Initialization")
- public void initialization() {
- /*
- //
- // Everything initializes upon startup
- //
- assertThatCode(() -> {
- //
- // Assume XACML REST Controller loads PDP engine
- //
- onapPdpEngine = new OnapXacmlPdpEngine();
- //
- // Come up with defaults
- //
- File path = Paths.get("src/test/resources").toFile();
- /*
- // try (InputStream is = new FileInputStream("src/test/resources/xacml.properties")) {
- // properties = new Properties();
- // properties.load(is);
- // onapPdpEngine.initializeEngine(properties);
-// }
- onapPdpEngine.initialize(path.toPath());
- //
- // Store the properties in new path
- //
- // JUNIT IS CRASHING - THE TEMP FOLDER NOT CREATED -->
- //pathProperties = policyFolder.newFile("xacml.properties");
- //
- // Store the root policies
- //
- for (String rootPolicyId : XACMLProperties.getRootPolicyIDs(properties)) {
- logger.debug("Root policy id: " + rootPolicyId);
- }
-
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @When("Decision Requested")
- public void decision_Requested() {
- /*
- //
- // Simulate a request coming in from Xacml REST server
- //
- assertThatCode(() -> {
- request = RequestParser.parseRequest(new MyXacmlRequest());
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @Then("Decision Permit {int} Obligations")
- public void decision_Permit_Obligations(Integer int1) {
- /*
- Response response = onapPdpEngine.decision(request);
- for (Result result : response.getResults()) {
- logger.debug(result.getDecision().toString());
- assertEquals(Decision.PERMIT, result.getDecision());
- assertThat(result.getObligations().size()).isEqualTo(int1);
- }
- */
- }
-
- /**
- * Initialization.
- */
- @When("The application gets new Tosca Policy")
- public void the_application_gets_new_Tosca_Policy() {
- /*
- //
- // The Xacml PDP REST controller Would receive this from the PAP
- //
- // And then parse it looking for Policy Types
- //
- assertThatCode(() -> {
- try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.input.yaml")) {
- Yaml yaml = new Yaml();
- tcaPolicy = yaml.load(is);
- //
- // Do we test iterating and determining if supported?
- //
-
- }
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @Then("Load Policy")
- public void load_Policy() {
- /*
- assertThatCode(() -> {
- //
- // Load the policies
- //
- List<PolicyType> convertedPolicies = onapPdpEngine.convertPolicies(tcaPolicy);
- //
- // Store these in temporary folder
- //
- int id = 1;
- List<Path> newReferencedPolicies = new ArrayList<>();
- for (PolicyType convertedPolicy : convertedPolicies) {
- //
- // I don't think we should use the policy id as the filename - there could
- // possibly be duplicates. eg. Not guaranteed to be unique.
- //
- File file = policyFolder.newFile("policy." + id + convertedPolicy.getPolicyId() + ".xml");
- logger.info("Creating Policy {}", file.getAbsolutePath());
- Path path = XACMLPolicyWriter.writePolicyFile(file.toPath(), convertedPolicy);
- //
- // Add it to our list
- //
- newReferencedPolicies.add(path);
- }
- //
- // Now updated the properties
- //
- Path[] args = new Path[newReferencedPolicies.size()];
- newReferencedPolicies.toArray(args);
- XACMLProperties.setXacmlReferencedProperties(properties, args);
- //
- // Reload the PDP engine
- //
- onapPdpEngine.initializeEngine(properties);
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @Then("Save Configuration")
- public void save_Configuration() {
- /*
- assertThatCode(() -> {
- //
- // Save the configuration
- //
- onapPdpEngine.storeXacmlProperties(pathProperties.getAbsolutePath());
- }).doesNotThrowAnyException();
- */
- }
-}
diff --git a/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java b/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
index b4a5579e..9debb6b1 100644
--- a/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
+++ b/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,18 +27,18 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import java.io.File;
+import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -53,8 +53,8 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class MonitoringPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class MonitoringPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
private static final Properties properties = new Properties();
@@ -64,40 +64,40 @@ public class MonitoringPdpApplicationTest {
private static final StandardCoder gson = new StandardCoder();
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
//
// Load Single Decision Request
//
requestSinglePolicy = gson.decode(
- TextFileUtils
- .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
+ DecisionRequest.class);
// Load Single Decision Request
//
requestPolicyType = gson.decode(
- TextFileUtils
+ TextFileUtils
.getTextFileAsString("../../main/src/test/resources/decisions/decision.policytype.input.json"),
- DecisionRequest.class);
+ DecisionRequest.class);
//
- // Setup our temporary folder
+ // Set up our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = policyFolder::newFile;
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
properties, myCreator);
//
// Load XacmlApplicationServiceProvider service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Look for our class instance and save it
//
@@ -127,7 +127,7 @@ public class MonitoringPdpApplicationTest {
}
@Test
- public void test1Basics() {
+ void test1Basics() {
//
// Make sure there's an application name
//
@@ -137,17 +137,17 @@ public class MonitoringPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "2.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier(
+ new ToscaConceptIdentifier(
"onap.policies.monitoring.foobar", "1.0.1"))).isTrue();
assertThat(service.canSupportPolicyType(
new ToscaConceptIdentifier(
"onap.policies.monitoring.foobar", "2.0.1"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
+ new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
//
// Ensure it supports decisions
//
@@ -155,7 +155,7 @@ public class MonitoringPdpApplicationTest {
}
@Test
- public void test2NoPolicies() {
+ void test2NoPolicies() {
//
// Ask for a decision
//
@@ -189,28 +189,28 @@ public class MonitoringPdpApplicationTest {
}
@Test
- public void tes3AddvDnsPolicy() throws CoderException, XacmlApplicationException {
+ void tes3AddvDnsPolicy() throws CoderException, XacmlApplicationException {
testAddPolicy("src/test/resources/vDNS.policy.input.yaml",
"onap.policies.monitoring.cdap.tca.hi.lo.app",
"onap.scaleout.tca");
}
@Test
- public void tes4AddvFirewall1Policy() throws CoderException, XacmlApplicationException {
+ void tes4AddvFirewall1Policy() throws CoderException, XacmlApplicationException {
testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.yaml",
"onap.policies.monitoring.tcagen2",
"onap.vfirewall.tca");
}
@Test
- public void tes5AddvFirewall2Policy() throws CoderException, XacmlApplicationException {
+ void tes5AddvFirewall2Policy() throws CoderException, XacmlApplicationException {
testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.v2.yaml",
"onap.policies.monitoring.tcagen2",
"onap.vfirewall.tca");
}
@SuppressWarnings("unchecked")
- public void testAddPolicy(String policyResource, String policyType, String policyId)
+ void testAddPolicy(String policyResource, String policyType, String policyId)
throws CoderException, XacmlApplicationException {
//
// Now load the vDNS Policy - make sure
diff --git a/applications/naming/pom.xml b/applications/naming/pom.xml
index ac18c330..61fdd2dc 100644
--- a/applications/naming/pom.xml
+++ b/applications/naming/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>xacml-naming</artifactId>
@@ -35,11 +35,6 @@
<dependencies>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
diff --git a/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java b/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java
index aa8fde41..deeee2f5 100644
--- a/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java
+++ b/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,25 +27,22 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.Arrays;
import java.util.Collection;
-import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
import org.assertj.core.api.Condition;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -60,61 +57,53 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class NamingPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class NamingPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(NamingPdpApplicationTest.class);
- private static Properties properties = new Properties();
- private static File propertiesFile;
+ private static final Properties properties = new Properties();
private static XacmlApplicationServiceProvider service;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static DecisionRequest baseRequest;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ static void setUp() throws Exception {
//
// Load Single Decision Request
//
baseRequest = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.naming.input.json"),
- DecisionRequest.class);
- //
- // Setup our temporary folder
- //
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
- propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.naming.input.json"),
+ DecisionRequest.class);
+
//
// Copy the test policy types into data area
//
String policy = "onap.policies.Naming";
String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
LOGGER.info("Copying {}", policyType);
- Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
- policyType.getBytes());
+ Files.write(Paths.get(policyFolder.toFile().getAbsolutePath(), policy + "-1.0.0.yaml"),
+ policyType.getBytes());
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Iterate through Xacml application services and find
// the optimization service. Save it for use throughout
// all the Junit tests.
//
StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -136,11 +125,15 @@ public class NamingPdpApplicationTest {
// Tell it to initialize based on the properties file
// we just built for it.
//
+
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
+ File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
+ properties, myCreator);
service.initialize(propertiesFile.toPath().getParent(), null);
}
@Test
- public void test01Basics() {
+ void test01Basics() {
//
// Make sure there's an application name
//
@@ -155,13 +148,13 @@ public class NamingPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.Naming", "1.0.0"))).isTrue();
+ "onap.policies.Naming", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.foobar", "1.0.0"))).isFalse();
+ "onap.foobar", "1.0.0"))).isFalse();
}
@Test
- public void test02NoPolicies() throws CoderException {
+ void test02NoPolicies() throws CoderException {
//
// Ask for a decision when there are no policies loaded
//
@@ -180,7 +173,7 @@ public class NamingPdpApplicationTest {
}
@Test
- public void test03Naming() throws CoderException, FileNotFoundException, IOException,
+ void test03Naming() throws
XacmlApplicationException {
//
// Now load all the optimization policies
@@ -198,7 +191,7 @@ public class NamingPdpApplicationTest {
//
// Ask for VNF
//
- baseRequest.getResource().put("policy-type", Arrays.asList("onap.policies.Naming"));
+ baseRequest.getResource().put("policy-type", List.of("onap.policies.Naming"));
//
// Ask for a decision for VNF default policies
//
@@ -238,13 +231,13 @@ public class NamingPdpApplicationTest {
Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
validateMatchable((Collection<String>) request.getResource().get("nfRole"),
- (Collection<String>) policyProperties.get("nfRole"));
+ (Collection<String>) policyProperties.get("nfRole"));
validateMatchable((Collection<String>) request.getResource().get("naming-type"),
- (Collection<String>) policyProperties.get("naming-type"));
+ (Collection<String>) policyProperties.get("naming-type"));
validateMatchable((Collection<String>) request.getResource().get("property-name"),
- (Collection<String>) policyProperties.get("property-name"));
+ (Collection<String>) policyProperties.get("property-name"));
}
}
@@ -258,8 +251,8 @@ public class NamingPdpApplicationTest {
return;
}
Condition<String> condition = new Condition<>(
- requestList::contains,
- "Request list is contained");
+ requestList::contains,
+ "Request list is contained");
assertThat(policyProperties).haveAtLeast(1, condition);
}
diff --git a/applications/native/pom.xml b/applications/native/pom.xml
index 3522dc27..fa586d64 100644
--- a/applications/native/pom.xml
+++ b/applications/native/pom.xml
@@ -4,7 +4,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>xacml-native</artifactId>
diff --git a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java
index 6a706760..47e92c09 100644
--- a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java
+++ b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,13 +32,13 @@ import com.att.research.xacml.api.Response;
import com.att.research.xacml.std.dom.DOMRequest;
import com.att.research.xacml.std.dom.DOMResponse;
import java.io.File;
+import java.nio.file.Path;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -53,38 +53,38 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NativePdpApplicationTest {
+class NativePdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class);
private static final String PERMIT = "Permit";
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static NativePdpApplication service;
private static Request request;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
LOGGER.info("Setting up class");
//
// Setup our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ properties, myCreator);
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Find the native application and save for use in all the tests
//
@@ -115,12 +115,12 @@ public class NativePdpApplicationTest {
// Load XACML Request
//
request = DOMRequest.load(
- TextFileUtils.getTextFileAsString(
- "src/test/resources/requests/native.policy.request.xml"));
+ TextFileUtils.getTextFileAsString(
+ "src/test/resources/requests/native.policy.request.xml"));
}
@Test
- public void testUncommon() {
+ void testUncommon() {
NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
translator.convertRequest(null)
@@ -132,12 +132,12 @@ public class NativePdpApplicationTest {
assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
"onap.policies.native.Xacml", "1.0.0"))).isTrue();
assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
+ "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
assertThat(application.actionDecisionsSupported()).contains("native");
}
@Test
- public void testBadPolicies() throws Exception {
+ void testBadPolicies() throws Exception {
NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml");
//
@@ -173,7 +173,7 @@ public class NativePdpApplicationTest {
}
@Test
- public void testNativePolicy() throws Exception {
+ void testNativePolicy() throws Exception {
LOGGER.info("*********** Running native policy test *************");
//
@@ -184,18 +184,16 @@ public class NativePdpApplicationTest {
//
// Send the request and verify decision result
//
- requestAndCheckDecision(request, PERMIT);
+ requestAndCheckDecision(request);
}
/**
* Request a decision and check that it matches expectation.
*
* @param request to send to XACML PDP
- * @param expected from the response
* @throws Exception on errors requesting a decision and checking the returned decision
- *
**/
- private void requestAndCheckDecision(Request request, String expected) throws Exception {
+ private void requestAndCheckDecision(Request request) throws Exception {
//
// Ask for a decision
//
@@ -203,23 +201,21 @@ public class NativePdpApplicationTest {
//
// Check decision
//
- checkDecision(expected, decision);
+ checkDecision(decision);
}
/**
* Check that decision matches expectation.
*
- * @param expected from the response
* @param response received
* @throws Exception on errors checking the decision
- *
**/
- private void checkDecision(String expected, Response response) throws Exception {
- LOGGER.info("Looking for {} Decision", expected);
+ private void checkDecision(Response response) throws Exception {
+ LOGGER.info("Looking for {} Decision", NativePdpApplicationTest.PERMIT);
assertThat(response).isNotNull();
Decision decision = response.getResults().iterator().next().getDecision();
assertThat(decision).isNotNull();
- assertThat(decision).hasToString(expected);
+ assertThat(decision).hasToString(NativePdpApplicationTest.PERMIT);
LOGGER.info("Xacml response we received {}", DOMResponse.toString(response));
}
}
diff --git a/applications/optimization/pom.xml b/applications/optimization/pom.xml
index 9134766d..cfb7d931 100644
--- a/applications/optimization/pom.xml
+++ b/applications/optimization/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>applications</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<artifactId>xacml-optimization</artifactId>
@@ -35,11 +35,6 @@
<dependencies>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
diff --git a/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java b/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java
index 6d86bdb4..55be0e1b 100644
--- a/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java
+++ b/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +34,8 @@ import com.att.research.xacml.std.StdMutableRequest;
import com.att.research.xacml.std.StdMutableRequestAttributes;
import com.att.research.xacml.std.annotations.XACMLSubject;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -75,12 +76,12 @@ public class OptimizationSubscriberRequest extends StdMatchablePolicyRequest {
// Should always be a collection, but in case someone changes
// the class without checking this repo.
//
- if (entrySet.getValue() instanceof Collection) {
- addSubject(contextAttributes, (Collection) entrySet.getValue(),
- ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
+ if (entrySet.getValue() instanceof Collection collection) {
+ addSubject(contextAttributes, collection,
+ ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
} else {
- addSubject(contextAttributes, Arrays.asList(entrySet.getValue().toString()),
- ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
+ addSubject(contextAttributes, Collections.singletonList(entrySet.getValue().toString()),
+ ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
}
} catch (DataTypeException e) {
throw new XacmlApplicationException("Failed to add resource ", e);
@@ -91,19 +92,20 @@ public class OptimizationSubscriberRequest extends StdMatchablePolicyRequest {
}
protected static StdMutableRequestAttributes addSubject(StdMutableRequestAttributes attributes,
- Collection<Object> values, Identifier id) throws DataTypeException {
+ Collection<Object> values, Identifier id)
+ throws DataTypeException {
var factory = getDataTypeFactory();
if (factory == null) {
return null;
}
for (Object value : values) {
- var mutableAttribute = new StdMutableAttribute();
+ var mutableAttribute = new StdMutableAttribute();
mutableAttribute.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT);
mutableAttribute.setAttributeId(id);
mutableAttribute.setIncludeInResults(true);
- DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
+ DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
AttributeValue<?> attributeValue = dataTypeExtended.createAttributeValue(value);
Collection<AttributeValue<?>> attributeValues = new ArrayList<>();
attributeValues.add(attributeValue);
diff --git a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
index f9fe8728..a93895c1 100644
--- a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
+++ b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,9 +30,9 @@ import com.att.research.xacml.api.Response;
import com.google.common.collect.Lists;
import java.io.File;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -40,12 +40,11 @@ import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
import org.assertj.core.api.Condition;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
@@ -64,16 +63,16 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class OptimizationPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class OptimizationPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static DecisionRequest baseRequest;
- private static String[] listPolicyTypeFiles = {
+ private static final String[] listPolicyTypeFiles = {
"onap.policies.Optimization",
"onap.policies.optimization.Resource",
"onap.policies.optimization.Service",
@@ -87,53 +86,51 @@ public class OptimizationPdpApplicationTest {
"onap.policies.optimization.resource.Vim_fit",
"onap.policies.optimization.resource.VnfPolicy"};
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ static void setUp() throws Exception {
//
// Load Single Decision Request
//
baseRequest = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.optimization.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.optimization.input.json"),
+ DecisionRequest.class);
//
// Setup our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ properties, myCreator);
//
// Copy the test policy types into data area
//
for (String policy : listPolicyTypeFiles) {
String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
LOGGER.info("Copying {}", policyType);
- Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
- policyType.getBytes());
+ Files.write(Paths.get(policyFolder.toFile().getAbsolutePath(), policy + "-1.0.0.yaml"),
+ policyType.getBytes());
}
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Iterate through Xacml application services and find
// the optimization service. Save it for use throughout
// all the Junit tests.
//
StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -162,7 +159,7 @@ public class OptimizationPdpApplicationTest {
* Simply test some of the simple methods for the application.
*/
@Test
- public void test01Basics() {
+ void test01Basics() {
//
// Make sure there's an application name
//
@@ -177,13 +174,13 @@ public class OptimizationPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.optimization.resource.AffinityPolicy", "1.0.0"))).isTrue();
+ "onap.policies.optimization.resource.AffinityPolicy", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.optimization.service.SubscriberPolicy", "1.0.0"))).isTrue();
+ "onap.policies.optimization.service.SubscriberPolicy", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.optimization.service.CustomUseCase", "1.0.0"))).isTrue();
+ "onap.policies.optimization.service.CustomUseCase", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.foobar", "1.0.0"))).isFalse();
+ "onap.foobar", "1.0.0"))).isFalse();
}
/**
@@ -192,7 +189,7 @@ public class OptimizationPdpApplicationTest {
* @throws CoderException CoderException
*/
@Test
- public void test02NoPolicies() throws CoderException {
+ void test02NoPolicies() throws CoderException {
//
// Ask for a decision when there are no policies loaded
//
@@ -217,12 +214,12 @@ public class OptimizationPdpApplicationTest {
* @throws XacmlApplicationException could not load policies
*/
@Test
- public void test03OptimizationDefault() throws XacmlApplicationException {
+ void test03OptimizationDefault() throws XacmlApplicationException {
//
// Now load all the optimization policies
//
List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies("src/test/resources/test-optimization-policies.yaml",
- service);
+ service);
assertThat(loadedPolicies).isNotNull().hasSize(14);
validateDecisionCount(2);
@@ -233,7 +230,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test04OptimizationDefaultHpa() {
+ void test04OptimizationDefaultHpa() {
//
// Add in policy type
//
@@ -248,7 +245,7 @@ public class OptimizationPdpApplicationTest {
assertThat(response.getPolicies()).hasSize(1);
response.getPolicies().forEach((key, value) -> {
assertThat(((Map<String, Object>) value)).containsEntry("type",
- "onap.policies.optimization.resource.HpaPolicy");
+ "onap.policies.optimization.resource.HpaPolicy");
});
//
// Validate it
@@ -261,7 +258,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test05OptimizationDefaultGeography() throws CoderException {
+ void test05OptimizationDefaultGeography() {
//
// Remove all the policy-type resources from the request
//
@@ -279,7 +276,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test06OptimizationDefaultGeographyAndService() {
+ void test06OptimizationDefaultGeographyAndService() {
//
// Add vCPE to the service list
//
@@ -293,7 +290,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test07OptimizationDefaultGeographyAndServiceAndResource() {
+ void test07OptimizationDefaultGeographyAndServiceAndResource() {
//
// Add vG to the resource list
//
@@ -307,7 +304,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test08OptimizationGeographyAndServiceAndResourceAndScopeIsGoldSubscriber() {
+ void test08OptimizationGeographyAndServiceAndResourceAndScopeIsGoldSubscriber() {
//
// Add gold as a scope
//
@@ -321,7 +318,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test09OptimizationGeographyAndServiceAndResourceAndScopeGoldOrPlatinumSubscriber() {
+ void test09OptimizationGeographyAndServiceAndResourceAndScopeGoldOrPlatinumSubscriber() {
//
// Add platinum to the scope list: this is now gold OR platinum
//
@@ -336,7 +333,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test10OptimizationGeographyAndServiceAndResourceAndScopeNotGoldStillPlatinum() {
+ void test10OptimizationGeographyAndServiceAndResourceAndScopeNotGoldStillPlatinum() {
//
// Add gold as a scope
//
@@ -351,7 +348,7 @@ public class OptimizationPdpApplicationTest {
* Filter by Affinity policy.
*/
@Test
- public void test11OptimizationPolicyTypeDefault() {
+ void test11OptimizationPolicyTypeDefault() {
//
// Add in policy type
//
@@ -366,7 +363,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test12OptimizationPolicyTypeDefault() {
+ void test12OptimizationPolicyTypeDefault() {
//
// Add in another policy type
//
@@ -377,7 +374,7 @@ public class OptimizationPdpApplicationTest {
}
@Test
- public void test999BadSubscriberPolicies() throws Exception {
+ void test999BadSubscriberPolicies() throws Exception {
final StandardYamlCoder yamlCoder = new StandardYamlCoder();
//
// Decode it
@@ -460,16 +457,16 @@ public class OptimizationPdpApplicationTest {
Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
validateMatchable((Collection<String>) request.getResource().get("scope"),
- (Collection<String>) policyProperties.get("scope"));
+ (Collection<String>) policyProperties.get("scope"));
validateMatchable((Collection<String>) request.getResource().get("services"),
- (Collection<String>) policyProperties.get("services"));
+ (Collection<String>) policyProperties.get("services"));
validateMatchable((Collection<String>) request.getResource().get("resources"),
- (Collection<String>) policyProperties.get("resources"));
+ (Collection<String>) policyProperties.get("resources"));
validateMatchable((Collection<String>) request.getResource().get("geography"),
- (Collection<String>) policyProperties.get("geography"));
+ (Collection<String>) policyProperties.get("geography"));
}
}
@@ -483,8 +480,8 @@ public class OptimizationPdpApplicationTest {
return;
}
Condition<String> condition = new Condition<>(
- requestList::contains,
- "Request list is contained");
+ requestList::contains,
+ "Request list is contained");
assertThat(policyProperties).haveAtLeast(1, condition);
}
diff --git a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java
index 3fd9e44b..c400e987 100644
--- a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java
+++ b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,13 +30,13 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
-public class OptimizationSubscriberRequestTest {
+class OptimizationSubscriberRequestTest {
private static StandardCoder gson = new StandardCoder();
private DecisionRequest request;
@@ -44,19 +45,19 @@ public class OptimizationSubscriberRequestTest {
*
* @throws Exception Exception if unable to load
*/
- @Before
- public void setupLoadDecision() throws Exception {
+ @BeforeEach
+ void setupLoadDecision() throws Exception {
request = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.optimization.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.optimization.input.json"),
+ DecisionRequest.class);
assertThat(request).isNotNull();
}
@Test
- public void testDecisionRequest() throws Exception {
+ void testDecisionRequest() throws Exception {
//
// Add context
//
diff --git a/applications/pom.xml b/applications/pom.xml
index d57ab1a1..8f686a11 100644
--- a/applications/pom.xml
+++ b/applications/pom.xml
@@ -27,7 +27,7 @@
<parent>
<groupId>org.onap.policy.xacml-pdp</groupId>
<artifactId>policy-xacml-pdp</artifactId>
- <version>4.0.0-SNAPSHOT</version>
+ <version>4.0.1-SNAPSHOT</version>
</parent>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>