Changed identifiers to concept identifiers
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdXacmlApplicationServiceProvider.java
index 1711985..fcfbf53 100644 (file)
@@ -2,7 +2,8 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 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,23 +29,23 @@ import com.att.research.xacml.api.pdp.PDPEngine;
 import com.att.research.xacml.api.pdp.PDPEngineFactory;
 import com.att.research.xacml.api.pdp.PDPException;
 import com.att.research.xacml.util.FactoryException;
-import com.att.research.xacml.util.XACMLPolicyWriter;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import lombok.Getter;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import org.apache.commons.lang3.tuple.Pair;
 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
 import org.onap.policy.models.decisions.concepts.DecisionRequest;
 import org.onap.policy.models.decisions.concepts.DecisionResponse;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
@@ -56,6 +57,11 @@ import org.slf4j.LoggerFactory;
 public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(StdXacmlApplicationServiceProvider.class);
+
+    protected String applicationName = "Please Override";
+    protected List<String> actions = Collections.emptyList();
+    protected List<ToscaConceptIdentifier> supportedPolicyTypes = new ArrayList<>();
+
     private Path pathForData = null;
     @Getter
     private RestServerParameters policyApiParameters;
@@ -63,18 +69,18 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
     private PDPEngine pdpEngine = null;
     private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
 
-    public StdXacmlApplicationServiceProvider() {
+    protected StdXacmlApplicationServiceProvider() {
         super();
     }
 
     @Override
     public String applicationName() {
-        return "Please Override";
+        return applicationName;
     }
 
     @Override
     public List<String> actionDecisionsSupported() {
-        return Collections.emptyList();
+        return actions;
     }
 
     @Override
@@ -105,23 +111,22 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
     }
 
     @Override
-    public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
-        throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
+    public List<ToscaConceptIdentifier> supportedPolicyTypes() {
+        return supportedPolicyTypes;
     }
 
     @Override
-    public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
+    public boolean canSupportPolicyType(ToscaConceptIdentifier policyTypeId) {
         throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
     }
 
     @Override
-    public synchronized boolean loadPolicy(ToscaPolicy toscaPolicy) {
+    public synchronized void loadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
         try {
             //
             // Convert the policies first
             //
-            PolicyType xacmlPolicy = this.getTranslator(toscaPolicy.getType())
-                .convertPolicy(toscaPolicy);
+            Object xacmlPolicy = this.getTranslator(toscaPolicy.getType()).convertPolicy(toscaPolicy);
             if (xacmlPolicy == null) {
                 throw new ToscaPolicyConversionException("Failed to convert policy");
             }
@@ -137,9 +142,12 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
             // Write the policy to disk
             // Maybe check for an error
             //
-            XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
+            if (XacmlPolicyUtils.writePolicyFile(refPath, xacmlPolicy) == null) {
+                throw new ToscaPolicyConversionException("Unable to writePolicyFile");
+            }
             if (LOGGER.isInfoEnabled()) {
-                LOGGER.info("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
+                LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
+                    new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
             }
             //
             // Add root policy to properties object
@@ -163,10 +171,8 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
             //
             this.mapLoadedPolicies.put(toscaPolicy, refPath);
         } catch (IOException | ToscaPolicyConversionException e) {
-            LOGGER.error("Failed to loadPolicies {}", e);
-            return false;
+            throw new XacmlApplicationException("loadPolicy failed", e);
         }
-        return true;
     }
 
     @Override
@@ -195,7 +201,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
             Files.delete(refPolicy);
         } catch (IOException e) {
             LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
-                    refPolicy.toAbsolutePath().toString(), e);
+                    refPolicy.toAbsolutePath(), e);
         }
         //
         // Write the properties to disk
@@ -228,11 +234,21 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
     }
 
     @Override
-    public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request) {
+    public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
+            Map<String, String[]> requestQueryParams) {
         //
         // Convert to a XacmlRequest
         //
-        Request xacmlRequest = this.getTranslator().convertRequest(request);
+        Request xacmlRequest;
+        try {
+            xacmlRequest = this.getTranslator().convertRequest(request);
+        } catch (ToscaPolicyConversionException e) {
+            LOGGER.error("Failed to convert request", e);
+            DecisionResponse response = new DecisionResponse();
+            response.setStatus("error");
+            response.setMessage(e.getLocalizedMessage());
+            return Pair.of(response, null);
+        }
         //
         // Now get a decision
         //
@@ -274,11 +290,30 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
             PDPEngineFactory factory = getPdpEngineFactory();
             PDPEngine engine = factory.newEngine(properties);
             if (engine != null) {
+                //
+                // If there is a previous engine have it shutdown.
+                //
+                this.destroyEngine();
+                //
+                // Save it off
+                //
                 this.pdpEngine = engine;
             }
         } catch (FactoryException e) {
-            LOGGER.error("Failed to create XACML PDP Engine {}", e);
+            LOGGER.error("Failed to create XACML PDP Engine", e);
+        }
+    }
+
+    protected synchronized void destroyEngine() {
+        if (this.pdpEngine == null) {
+            return;
+        }
+        try {
+            this.pdpEngine.shutdown();
+        } catch (Exception e) {
+            LOGGER.warn("Exception thrown when destroying XACML PDP engine.", e);
         }
+        this.pdpEngine = null;
     }
 
     /**
@@ -299,7 +334,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
         try {
             response = this.pdpEngine.decide(request);
         } catch (PDPException e) {
-            LOGGER.error("Xacml PDP Engine failed {}", e);
+            LOGGER.error("Xacml PDP Engine decide failed", e);
         } finally {
             //
             // Track the end of timing