2  * ============LICENSE_START=======================================================
 
   3  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
 
   4  * ================================================================================
 
   5  * Licensed under the Apache License, Version 2.0 (the "License");
 
   6  * you may not use this file except in compliance with the License.
 
   7  * You may obtain a copy of the License at
 
   9  *      http://www.apache.org/licenses/LICENSE-2.0
 
  11  * Unless required by applicable law or agreed to in writing, software
 
  12  * distributed under the License is distributed on an "AS IS" BASIS,
 
  13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  14  * See the License for the specific language governing permissions and
 
  15  * limitations under the License.
 
  17  * SPDX-License-Identifier: Apache-2.0
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.policy.pdp.xacml.application.common.std;
 
  23 import static org.assertj.core.api.Assertions.assertThat;
 
  24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
  25 import static org.junit.Assert.assertEquals;
 
  26 import static org.junit.Assert.assertFalse;
 
  27 import static org.junit.Assert.assertNotNull;
 
  28 import static org.junit.Assert.assertNull;
 
  29 import static org.junit.Assert.assertSame;
 
  30 import static org.junit.Assert.assertTrue;
 
  31 import static org.mockito.ArgumentMatchers.any;
 
  32 import static org.mockito.Mockito.mock;
 
  33 import static org.mockito.Mockito.times;
 
  34 import static org.mockito.Mockito.verify;
 
  35 import static org.mockito.Mockito.when;
 
  37 import com.att.research.xacml.api.Request;
 
  38 import com.att.research.xacml.api.Response;
 
  39 import com.att.research.xacml.api.pdp.PDPEngine;
 
  40 import com.att.research.xacml.api.pdp.PDPEngineFactory;
 
  41 import com.att.research.xacml.api.pdp.PDPException;
 
  42 import com.att.research.xacml.util.FactoryException;
 
  43 import com.att.research.xacml.util.XACMLProperties;
 
  44 import com.google.common.io.Files;
 
  46 import java.nio.file.Path;
 
  47 import java.util.HashSet;
 
  48 import java.util.Properties;
 
  50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 
  51 import org.apache.commons.lang3.tuple.Pair;
 
  52 import org.junit.AfterClass;
 
  53 import org.junit.Before;
 
  54 import org.junit.BeforeClass;
 
  55 import org.junit.Test;
 
  56 import org.junit.runner.RunWith;
 
  57 import org.mockito.Mock;
 
  58 import org.mockito.junit.MockitoJUnitRunner;
 
  59 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
 
  60 import org.onap.policy.models.decisions.concepts.DecisionRequest;
 
  61 import org.onap.policy.models.decisions.concepts.DecisionResponse;
 
  62 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
 
  63 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
 
  64 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
 
  65 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
 
  66 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
 
  67 import org.slf4j.Logger;
 
  68 import org.slf4j.LoggerFactory;
 
  70 @RunWith(MockitoJUnitRunner.class)
 
  71 public class StdXacmlApplicationServiceProviderTest {
 
  72     private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
 
  74     private static final String TEMP_DIR_NAME = "src/test/resources/temp";
 
  75     private static File TEMP_DIR = new File(TEMP_DIR_NAME);
 
  76     private static Path TEMP_PATH = TEMP_DIR.toPath();
 
  77     private static File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
 
  78     private static File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
 
  79     private static final String EXPECTED_EXCEPTION = "expected exception";
 
  80     private static final String POLICY_NAME = "my-name";
 
  81     private static final String POLICY_VERSION = "1.2.3";
 
  82     private static final String POLICY_TYPE = "my-type";
 
  83     private static final RestServerParameters apiRestParameters = new RestServerParameters();
 
  86     private ToscaPolicyTranslator trans;
 
  89     private PDPEngineFactory engineFactory;
 
  92     private PDPEngine engine;
 
  98     private Response resp;
 
 100     private ToscaPolicy policy;
 
 101     private PolicyType internalPolicy;
 
 103     private StdXacmlApplicationServiceProvider prov;
 
 106      * Creates the temp directory.
 
 109     public static void setUpBeforeClass() {
 
 110         assertTrue(TEMP_DIR.mkdir());
 
 114      * Deletes the temp directory and its contents.
 
 117     public static void tearDownAfterClass() {
 
 118         for (File file : TEMP_DIR.listFiles()) {
 
 119             if (!file.delete()) {
 
 120                 logger.warn("cannot delete: {}", file);
 
 124         if (!TEMP_DIR.delete()) {
 
 125             logger.warn("cannot delete: {}", TEMP_DIR);
 
 130      * Initializes objects, including the provider.
 
 132      * @throws Exception if an error occurs
 
 135     public void setUp() throws Exception {
 
 136         policy = new ToscaPolicy();
 
 137         policy.setType(POLICY_TYPE);
 
 138         policy.setName(POLICY_NAME);
 
 139         policy.setVersion(POLICY_VERSION);
 
 141         internalPolicy = new PolicyType();
 
 142         internalPolicy.setPolicyId(POLICY_NAME);
 
 143         internalPolicy.setVersion(POLICY_VERSION);
 
 145         when(engineFactory.newEngine(any())).thenReturn(engine);
 
 147         when(engine.decide(req)).thenReturn(resp);
 
 149         when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
 
 153         Files.copy(SOURCE_PROP_FILE, PROP_FILE);
 
 157     public void testApplicationName() {
 
 158         assertNotNull(prov.applicationName());
 
 162     public void testActionDecisionsSupported() {
 
 163         assertTrue(prov.actionDecisionsSupported().isEmpty());
 
 167     public void testInitialize_testGetXxx() throws XacmlApplicationException {
 
 168         prov.initialize(TEMP_PATH, apiRestParameters);
 
 170         assertEquals(TEMP_PATH, prov.getDataPath());
 
 171         assertNotNull(prov.getEngine());
 
 173         Properties props = prov.getProperties();
 
 174         assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
 
 178     public void testInitialize_Ex() throws XacmlApplicationException {
 
 179         assertThatThrownBy(() -> prov.initialize(new File(TEMP_DIR_NAME + "-nonExistent").toPath(), apiRestParameters))
 
 180                         .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
 
 184     public void testSupportedPolicyTypes() {
 
 185         assertThat(prov.supportedPolicyTypes()).isEmpty();
 
 189     public void testCanSupportPolicyType() {
 
 190         assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
 
 194     public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
 
 195         when(trans.convertPolicy(policy)).thenReturn(null);
 
 197         assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
 
 201     public void testLoadPolicy_testUnloadPolicy() throws Exception {
 
 202         prov.initialize(TEMP_PATH, apiRestParameters);
 
 205         final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
 
 208         prov.loadPolicy(policy);
 
 210         // policy file should have been created
 
 211         File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
 
 212         assertTrue(policyFile.exists());
 
 214         // new property file should have been created
 
 215         assertTrue(PROP_FILE.exists());
 
 217         // should have re-created the engine
 
 218         verify(engineFactory, times(2)).newEngine(any());
 
 220         final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
 
 221         assertEquals(set.size() + 1, set2.size());
 
 223         Set<String> set3 = new HashSet<>(set2);
 
 225         assertEquals("[root1]", set3.toString());
 
 229          * Prepare for unload.
 
 233         assertTrue(prov.unloadPolicy(policy));
 
 235         // policy file should have been removed
 
 236         assertFalse(policyFile.exists());
 
 238         // new property file should have been created
 
 239         assertTrue(PROP_FILE.exists());
 
 241         // should have re-created the engine
 
 242         verify(engineFactory, times(3)).newEngine(any());
 
 244         set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
 
 245         assertEquals(set.toString(), set3.toString());
 
 249     public void testUnloadPolicy_NotDeployed() throws Exception {
 
 250         prov.initialize(TEMP_PATH, apiRestParameters);
 
 252         assertFalse(prov.unloadPolicy(policy));
 
 254         // no additional calls
 
 255         verify(engineFactory, times(1)).newEngine(any());
 
 259     public void testMakeDecision() throws ToscaPolicyConversionException {
 
 260         prov.createEngine(null);
 
 262         DecisionRequest decreq = mock(DecisionRequest.class);
 
 263         when(trans.convertRequest(decreq)).thenReturn(req);
 
 265         DecisionResponse decresp = mock(DecisionResponse.class);
 
 266         when(trans.convertResponse(resp)).thenReturn(decresp);
 
 268         Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
 
 269         assertSame(decresp, result.getKey());
 
 270         assertSame(resp, result.getValue());
 
 272         verify(trans).convertRequest(decreq);
 
 273         verify(trans).convertResponse(resp);
 
 277     public void testGetTranslator() {
 
 278         assertSame(trans, prov.getTranslator());
 
 282     public void testCreateEngine() throws FactoryException {
 
 284         prov.createEngine(null);
 
 285         assertSame(engine, prov.getEngine());
 
 287         // null - should be unchanged
 
 288         when(engineFactory.newEngine(any())).thenReturn(null);
 
 289         prov.createEngine(null);
 
 290         assertSame(engine, prov.getEngine());
 
 292         // exception - should be unchanged
 
 293         when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
 
 294         prov.createEngine(null);
 
 295         assertSame(engine, prov.getEngine());
 
 299     public void testXacmlDecision() throws PDPException {
 
 300         prov.createEngine(null);
 
 303         assertSame(resp, prov.xacmlDecision(req));
 
 306         when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
 
 307         assertNull(prov.xacmlDecision(req));
 
 311     public void testGetPdpEngineFactory() throws XacmlApplicationException {
 
 312         // use the real engine factory
 
 313         engineFactory = null;
 
 316         prov.initialize(TEMP_PATH, apiRestParameters);
 
 318         assertNotNull(prov.getEngine());
 
 321     private class MyProv extends StdXacmlApplicationServiceProvider {
 
 324         protected ToscaPolicyTranslator getTranslator(String type) {
 
 329         protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
 
 330             return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());