Fix Db connection issues in TOSCA control loop 60/125460/2
authorFrancescoFioraEst <francesco.fiora@est.tech>
Wed, 27 Oct 2021 09:18:32 +0000 (10:18 +0100)
committerFrancescoFioraEst <francesco.fiora@est.tech>
Wed, 3 Nov 2021 12:58:18 +0000 (12:58 +0000)
Issue-ID: POLICY-3153
Change-Id: I28a7962027a9cb383238a6d3765a46a905f8e58b
Signed-off-by: FrancescoFioraEst <francesco.fiora@est.tech>
models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java [new file with mode: 0644]
models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProviderFactory.java
models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractModelsProvider.java
models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java [new file with mode: 0644]
models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java
models-provider/src/main/java/org/onap/policy/models/provider/impl/DbPolicyModelsProviderImpl.java [new file with mode: 0644]
models-provider/src/main/java/org/onap/policy/models/provider/impl/ModelsProvider.java [new file with mode: 0644]

diff --git a/models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java b/models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java
new file mode 100644 (file)
index 0000000..72d5683
--- /dev/null
@@ -0,0 +1,520 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  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.
+ * 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.models.dao.impl;
+
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import javax.persistence.TypedQuery;
+import lombok.RequiredArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.models.base.PfConcept;
+import org.onap.policy.models.base.PfConceptKey;
+import org.onap.policy.models.base.PfGeneratedIdKey;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.base.PfReferenceKey;
+import org.onap.policy.models.base.PfReferenceTimestampKey;
+import org.onap.policy.models.base.PfTimestampKey;
+import org.onap.policy.models.base.PfUtils;
+import org.onap.policy.models.dao.DaoParameters;
+import org.onap.policy.models.dao.PfDao;
+import org.onap.policy.models.dao.PfFilter;
+import org.onap.policy.models.dao.PfFilterFactory;
+import org.onap.policy.models.dao.PfFilterParametersIntfc;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The Class ProxyDao is an JPA implementation of the {@link ProxyDao} class for Policy Framework concepts
+ * ({@link PfConcept}). It uses the default JPA implementation in the javax {@link Persistence} class.
+ */
+@RequiredArgsConstructor
+public class ProxyDao implements PfDao {
+    private static final Logger LOGGER = LoggerFactory.getLogger(ProxyDao.class);
+
+    // @formatter:off
+    private static final String NAME           = "name";
+    private static final String VERSION        = "version";
+    private static final String TIMESTAMP      = "timeStamp";
+    private static final String GENERATEDID    = "Id";
+    private static final String PARENT_NAME    = "parentname";
+    private static final String PARENT_VERSION = "parentversion";
+    private static final String LOCAL_NAME     = "localname";
+
+    private static final String TABLE_TOKEN = "__TABLE__";
+
+    private static final String DELETE_FROM_TABLE = "DELETE FROM __TABLE__ c";
+
+    private static final String SELECT_FROM_TABLE = "SELECT c FROM __TABLE__ c";
+
+    private static final String WHERE      = " WHERE ";
+    private static final String AND        = " AND ";
+    private static final String ORDER_BY        = " ORDER BY c.";
+
+    private static final String NAME_FILTER            = "c.key.name = :name";
+    private static final String VERSION_FILTER         = "c.key.version = :version";
+    private static final String TIMESTAMP_FILTER       = "c.key.timeStamp = :timeStamp";
+    private static final String TIMESTAMP_FILTER_NOKEY = "c.timeStamp = :timeStamp";
+    private static final String GENERATED_ID_FILTER    = "c.key.generatedId = :Id";
+    private static final String PARENT_NAME_FILTER     = "c.key.parentKeyName = :parentname";
+    private static final String PARENT_VERSION_FILTER  = "c.key.parentKeyVersion = :parentversion";
+    private static final String LOCAL_NAME_FILTER      = "c.key.localName = :localname";
+
+    private static final String CLONE_ERR_MSG = "Could not clone object of class \"{}\"";
+
+    private static final String DELETE_BY_CONCEPT_KEY =
+            DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER;
+
+    private static final String DELETE_BY_TIMESTAMP_KEY =
+            DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER  + AND + TIMESTAMP_FILTER;
+
+    private static final String DELETE_BY_GENERATED_ID_KEY =
+            DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER  + AND + GENERATED_ID_FILTER;
+
+    private static final String DELETE_BY_REFERENCE_KEY =
+            DELETE_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER;
+
+    private static final String SELECT_ALL_FOR_PARENT =
+            SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER;
+
+    private static final String SELECT_ALL_VERSIONS_FOR_PARENT =
+            SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER;
+
+    private static final String SELECT_ALL_VERSIONS = SELECT_FROM_TABLE + WHERE + NAME_FILTER;
+
+    private static final String SELECT_BY_CONCEPT_KEY =
+            SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER;
+
+    private static final String SELECT_BY_TIMESTAMP_NOKEY =
+            SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER_NOKEY;
+
+    private static final String SELECT_BY_REFERENCE_KEY =
+            SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER;
+    // @formatter:on
+
+    // Entity manager for JPA
+    private final EntityManager mg;
+
+    @Override
+    public void init(final DaoParameters daoParameters) throws PfModelException {
+        // Entity manager for JPA should be created at Service level
+    }
+
+    @Override
+    public final void close() {
+        // Entity manager for JPA should be close at Service level
+    }
+
+    @Override
+    public <T extends PfConcept> void create(final T obj) {
+        if (obj == null) {
+            return;
+        }
+        mg.merge(obj);
+        mg.flush();
+    }
+
+    @Override
+    public <T extends PfConcept> void delete(final T obj) {
+        if (obj == null) {
+            return;
+        }
+        mg.remove(mg.contains(obj) ? obj : mg.merge(obj));
+    }
+
+    @Override
+    public <T extends PfConcept> void delete(final Class<T> someClass, final PfConceptKey key) {
+        if (key == null) {
+            return;
+        }
+        // @formatter:off
+        mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass)
+            .setParameter(NAME,    key.getName())
+            .setParameter(VERSION, key.getVersion())
+            .executeUpdate();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> void delete(final Class<T> someClass, final PfReferenceKey key) {
+        if (key == null) {
+            return;
+        }
+        // @formatter:off
+        mg.createQuery(setQueryTable(DELETE_BY_REFERENCE_KEY, someClass), someClass)
+            .setParameter(PARENT_NAME,    key.getParentKeyName())
+            .setParameter(PARENT_VERSION, key.getParentKeyVersion())
+            .setParameter(LOCAL_NAME,     key.getLocalName())
+            .executeUpdate();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> void delete(final Class<T> someClass, final PfTimestampKey key) {
+        if (key == null) {
+            return;
+        }
+
+        // @formatter:off
+        mg.createQuery(setQueryTable(DELETE_BY_TIMESTAMP_KEY, someClass), someClass)
+                .setParameter(NAME,    key.getName())
+                .setParameter(VERSION, key.getVersion())
+                .setParameter(TIMESTAMP, key.getTimeStamp())
+                .executeUpdate();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> void delete(final Class<T> someClass, final PfGeneratedIdKey key) {
+        if (key == null) {
+            return;
+        }
+
+        // @formatter:off
+        mg.createQuery(setQueryTable(DELETE_BY_GENERATED_ID_KEY, someClass), someClass)
+                .setParameter(NAME,    key.getName())
+                .setParameter(VERSION, key.getVersion())
+                .setParameter(GENERATEDID, key.getGeneratedId())
+                .executeUpdate();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> void createCollection(final Collection<T> objs) {
+        if (objs == null || objs.isEmpty()) {
+            return;
+        }
+
+        for (final T t : objs) {
+            mg.merge(t);
+        }
+    }
+
+    @Override
+    public <T extends PfConcept> void deleteCollection(final Collection<T> objs) {
+        if (objs == null || objs.isEmpty()) {
+            return;
+        }
+
+        for (final T t : objs) {
+            mg.remove(mg.contains(t) ? t : mg.merge(t));
+        }
+    }
+
+    @Override
+    public <T extends PfConcept> int deleteByConceptKey(final Class<T> someClass, final Collection<PfConceptKey> keys) {
+        if (keys == null || keys.isEmpty()) {
+            return 0;
+        }
+        var deletedCount = 0;
+
+        for (final PfConceptKey key : keys) {
+            // @formatter:off
+            deletedCount += mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass)
+                .setParameter(NAME,    key.getName())
+                .setParameter(VERSION, key.getVersion())
+                .executeUpdate();
+            // @formatter:on
+        }
+
+        return deletedCount;
+    }
+
+    @Override
+    public <T extends PfConcept> int deleteByReferenceKey(final Class<T> someClass,
+            final Collection<PfReferenceKey> keys) {
+        if (keys == null || keys.isEmpty()) {
+            return 0;
+        }
+        var deletedCount = 0;
+
+        for (final PfReferenceKey key : keys) {
+            // @formatter:off
+            deletedCount += mg.createQuery(setQueryTable(DELETE_BY_REFERENCE_KEY, someClass), someClass)
+                .setParameter(PARENT_NAME,    key.getParentKeyName())
+                .setParameter(PARENT_VERSION, key.getParentKeyVersion())
+                .setParameter(LOCAL_NAME,     key.getLocalName())
+                .executeUpdate();
+            // @formatter:on
+        }
+        return deletedCount;
+    }
+
+    @Override
+    public <T extends PfConcept> void deleteAll(final Class<T> someClass) {
+        mg.createQuery(setQueryTable(DELETE_FROM_TABLE, someClass), someClass).executeUpdate();
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, final String name,
+            final String version) {
+        if (name == null) {
+            return getAll(someClass);
+        }
+
+        if (version == null) {
+            return getAllVersions(someClass, name);
+        }
+
+        var foundConcept = get(someClass, new PfConceptKey(name, version));
+
+        return (foundConcept == null ? Collections.emptyList() : Collections.singletonList(foundConcept));
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getFiltered(final Class<T> someClass, PfFilterParametersIntfc filterParams) {
+
+        PfFilter filter = new PfFilterFactory().createFilter(someClass);
+        var filterQueryString =
+                SELECT_FROM_TABLE + filter.genWhereClause(filterParams) + filter.genOrderClause(filterParams);
+
+        TypedQuery<T> query = mg.createQuery(setQueryTable(filterQueryString, someClass), someClass);
+        filter.setParams(query, filterParams);
+
+        LOGGER.debug("filterQueryString is  \"{}\"", filterQueryString);
+        return query.getResultList();
+    }
+
+    @Override
+    public <T extends PfConcept> T get(final Class<T> someClass, final PfConceptKey key) {
+        return genericGet(someClass, key);
+    }
+
+    @Override
+    public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceKey key) {
+        return genericGet(someClass, key);
+    }
+
+    @Override
+    public <T extends PfConcept> T get(final Class<T> someClass, final PfGeneratedIdKey key) {
+        return genericGet(someClass, key);
+    }
+
+    @Override
+    public <T extends PfConcept> T get(final Class<T> someClass, final PfTimestampKey key) {
+        return genericGet(someClass, key);
+    }
+
+    @Override
+    public <T extends PfConcept> T get(final Class<T> someClass, final PfReferenceTimestampKey key) {
+        return genericGet(someClass, key);
+    }
+
+    private <T extends PfConcept> T genericGet(final Class<T> someClass, final Object key) {
+        if (someClass == null) {
+            return null;
+        }
+
+        final var t = mg.find(someClass, key);
+        return checkAndReturn(someClass, t);
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getAll(final Class<T> someClass) {
+        if (someClass == null) {
+            return Collections.emptyList();
+        }
+
+        return mg.createQuery(setQueryTable(SELECT_FROM_TABLE, someClass), someClass).getResultList();
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getAll(final Class<T> someClass, final PfConceptKey parentKey) {
+        if (someClass == null) {
+            return Collections.emptyList();
+        }
+
+        // @formatter:off
+        return mg.createQuery(setQueryTable(SELECT_ALL_FOR_PARENT, someClass), someClass)
+                .setParameter(PARENT_NAME,    parentKey.getName())
+                .setParameter(PARENT_VERSION, parentKey.getVersion())
+                .getResultList();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getAll(Class<T> someClass, String orderBy, Integer numRecords) {
+
+        if (someClass == null) {
+            return Collections.emptyList();
+        }
+
+        String query = setQueryTable(SELECT_FROM_TABLE, someClass);
+
+        if (StringUtils.isNotBlank(orderBy)) {
+            query = query.concat(ORDER_BY).concat(orderBy);
+        }
+
+        return mg.createQuery(query, someClass).setMaxResults(numRecords).getResultList();
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getAllVersionsByParent(final Class<T> someClass, final String parentKeyName) {
+        if (someClass == null || parentKeyName == null) {
+            return Collections.emptyList();
+        }
+
+        // @formatter:off
+        return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS_FOR_PARENT, someClass), someClass)
+                .setParameter(PARENT_NAME, parentKeyName)
+                .getResultList();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getAllVersions(final Class<T> someClass, final String conceptName) {
+        if (someClass == null || conceptName == null) {
+            return Collections.emptyList();
+        }
+
+        // @formatter:off
+        return mg.createQuery(setQueryTable(SELECT_ALL_VERSIONS, someClass), someClass)
+                .setParameter(NAME, conceptName)
+                .getResultList();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getByTimestamp(final Class<T> someClass, final PfGeneratedIdKey key,
+            final Instant timeStamp) {
+        if (someClass == null || key == null || timeStamp == null) {
+            return Collections.emptyList();
+        }
+
+        // @formatter:off
+        return mg.createQuery(setQueryTable(SELECT_BY_TIMESTAMP_NOKEY, someClass), someClass)
+                .setParameter(NAME,    key.getName())
+                .setParameter(VERSION, key.getVersion())
+                .setParameter(TIMESTAMP, Timestamp.from(timeStamp))
+                .getResultList();
+        // @formatter:on
+    }
+
+    @Override
+    public <T extends PfConcept> T getConcept(final Class<T> someClass, final PfConceptKey key) {
+        if (someClass == null || key == null) {
+            return null;
+        }
+
+        // @formatter:off
+        var ret = mg.createQuery(setQueryTable(SELECT_BY_CONCEPT_KEY, someClass), someClass)
+                .setParameter(NAME,    key.getName())
+                .setParameter(VERSION, key.getVersion())
+                .getResultList();
+        // @formatter:on
+
+        return getSingleResult(someClass, key.getId(), ret);
+    }
+
+    @Override
+    public <T extends PfConcept> T getConcept(final Class<T> someClass, final PfReferenceKey key) {
+        if (someClass == null || key == null) {
+            return null;
+        }
+
+        // @formatter:off
+        var ret = mg.createQuery(setQueryTable(SELECT_BY_REFERENCE_KEY, someClass), someClass)
+                .setParameter(PARENT_NAME,    key.getParentKeyName())
+                .setParameter(PARENT_VERSION, key.getParentKeyVersion())
+                .setParameter(LOCAL_NAME,     key.getLocalName())
+                .getResultList();
+        // @formatter:on
+
+        return getSingleResult(someClass, key.getId(), ret);
+    }
+
+    @Override
+    public <T extends PfConcept> T update(final T obj) {
+        var ret = mg.merge(obj);
+        mg.flush();
+        return ret;
+    }
+
+    @Override
+    public <T extends PfConcept> long size(final Class<T> someClass) {
+        if (someClass == null) {
+            return 0;
+        }
+
+        long size = 0;
+        /*
+         * The invoking code only passes well-known classes into this method, thus
+         * disabling the sonar about SQL injection.
+         */
+        size = mg.createQuery("SELECT COUNT(c) FROM " + someClass.getSimpleName() + " c", Long.class) // NOSONAR
+                .getSingleResult();
+        return size;
+    }
+
+    /**
+     * Add the table to a query string.
+     *
+     * @param queryString the query string
+     * @param tableClass the class name of the table
+     * @return the updated query string
+     */
+    private <T extends PfConcept> String setQueryTable(final String queryString, final Class<T> tableClass) {
+        return queryString.replace(TABLE_TOKEN, tableClass.getSimpleName());
+    }
+
+    /**
+     * Check that a query returned one and only one entry and return that entry.
+     *
+     * @param someClass the class being searched for
+     * @param searchFilter the search filter
+     * @param resultList the result list returned by the query
+     * @return the single unique result
+     */
+    private <T extends PfConcept> T getSingleResult(final Class<T> someClass, final String searchFilter,
+            List<T> resultList) {
+        if (resultList == null || resultList.isEmpty()) {
+            return null;
+        }
+        if (resultList.size() > 1) {
+            throw new IllegalArgumentException("More than one result was returned query on " + someClass
+                    + " with filter " + searchFilter + ": " + resultList);
+        }
+        return resultList.get(0);
+    }
+
+    /**
+     * check the result get from database and return the object.
+     *
+     * @param <T> the type of the object to get, a subclass of {@link PfConcept}
+     * @param someClass the class of the object to get, a subclass of {@link PfConcept}
+     * @param objToCheck the object that was retrieved from the database
+     * @return the checked object or null
+     */
+    private <T extends PfConcept> T checkAndReturn(final Class<T> someClass, final T objToCheck) {
+        if (objToCheck != null) {
+            try {
+                return PfUtils.makeCopy(objToCheck);
+            } catch (final Exception e) {
+                LOGGER.warn(CLONE_ERR_MSG, someClass.getName(), e);
+            }
+        }
+        return null;
+    }
+}
index 858b614..7cd36a5 100644 (file)
@@ -24,8 +24,7 @@ package org.onap.policy.models.provider;
 import javax.ws.rs.core.Response;
 import lombok.NonNull;
 import org.onap.policy.models.base.PfModelException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.onap.policy.models.dao.impl.ProxyDao;
 
 /**
  * A factory for creating PolicyModelsProvider objects using the default Policy Framework implementation.
@@ -33,7 +32,43 @@ import org.slf4j.LoggerFactory;
  * @author Liam Fallon (liam.fallon@est.tech)
  */
 public class PolicyModelsProviderFactory {
-    private static final Logger LOGGER = LoggerFactory.getLogger(PolicyModelsProviderFactory.class);
+
+    /**
+     * Create PolicyModelsProvider.
+     *
+     * @param pfDao the ProxyDao
+     * @param parameters the PolicyModelsProviderParameters
+     * @return the PolicyModelsProvider
+     * @throws PfModelException on errors creating an implementation of the PolicyModelProvider
+     */
+    public PolicyModelsProvider createPolicyModelsProvider(@NonNull final ProxyDao pfDao,
+            @NonNull final PolicyModelsProviderParameters parameters) throws PfModelException {
+        // Get the class for the PolicyModelsProvider
+        Class<?> implementationClass = null;
+        try {
+            // Check if the implementation class is on the classpath
+            implementationClass = Class.forName(parameters.getImplementation());
+        } catch (final Exception exc) {
+            String errorMessage = "could not find implementation of the \"PolicyModelsProvider\" interface \""
+                    + parameters.getImplementation() + "\"";
+            throw new PfModelException(Response.Status.NOT_FOUND, errorMessage, exc);
+        }
+
+        // It is, now check if it is a PolicyModelsProvider
+        if (!PolicyModelsProvider.class.isAssignableFrom(implementationClass)) {
+            String errorMessage = "the class \"" + implementationClass.getName()
+                    + "\" is not an implementation of the \"PolicyModelsProvider\" interface";
+            throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+
+        try {
+            return (PolicyModelsProvider) implementationClass.getConstructor(ProxyDao.class).newInstance(pfDao);
+        } catch (Exception exc) {
+            String errorMessage =
+                    "could not create an instance of PolicyModelsProvider \"" + parameters.getImplementation() + "\"";
+            throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc);
+        }
+    }
 
     /**
      * Creates a new PolicyModelsProvider object from its implementation.
@@ -51,7 +86,6 @@ public class PolicyModelsProviderFactory {
         } catch (final Exception exc) {
             String errorMessage = "could not find implementation of the \"PolicyModelsProvider\" interface \""
                     + parameters.getImplementation() + "\"";
-            LOGGER.warn(errorMessage);
             throw new PfModelException(Response.Status.NOT_FOUND, errorMessage, exc);
         }
 
@@ -59,7 +93,6 @@ public class PolicyModelsProviderFactory {
         if (!PolicyModelsProvider.class.isAssignableFrom(implementationClass)) {
             String errorMessage = "the class \"" + implementationClass.getName()
                     + "\" is not an implementation of the \"PolicyModelsProvider\" interface";
-            LOGGER.warn(errorMessage);
             throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage);
         }
 
@@ -73,7 +106,6 @@ public class PolicyModelsProviderFactory {
         } catch (Exception exc) {
             String errorMessage =
                     "could not create an instance of PolicyModelsProvider \"" + parameters.getImplementation() + "\"";
-            LOGGER.warn(errorMessage);
             throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc);
         }
     }
index dc0a1f6..7f6c4e5 100644 (file)
 package org.onap.policy.models.provider.impl;
 
 import java.io.Closeable;
-import java.util.Properties;
 import javax.ws.rs.core.Response;
 import lombok.Getter;
 import lombok.NonNull;
-import org.eclipse.persistence.config.PersistenceUnitProperties;
 import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.dao.DaoParameters;
 import org.onap.policy.models.dao.PfDao;
-import org.onap.policy.models.dao.PfDaoFactory;
-import org.onap.policy.models.dao.impl.DefaultPfDao;
 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -73,33 +68,7 @@ public abstract class AbstractModelsProvider implements Closeable {
             throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
         }
 
-        // Parameters for the DAO
-        final var daoParameters = new DaoParameters();
-        daoParameters.setPluginClass(DefaultPfDao.class.getName());
-        daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
-
-        // @formatter:off
-        var jdbcProperties = new Properties();
-        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
-        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
-        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
-        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, parameters.getDatabasePassword());
-        jdbcProperties.setProperty(PersistenceUnitProperties.TARGET_DATABASE,
-                        (parameters.getDatabaseType() == null ? "MySQL" : parameters.getDatabaseType()));
-        // @formatter:on
-
-        daoParameters.setJdbcProperties(jdbcProperties);
-
-        try {
-            pfDao = new PfDaoFactory().createPfDao(daoParameters);
-            pfDao.init(daoParameters);
-        } catch (Exception exc) {
-            String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
-                    + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
-
-            this.close();
-            throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
-        }
+        pfDao = ModelsProvider.init(parameters);
     }
 
     @Override
diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java
new file mode 100644 (file)
index 0000000..fa76583
--- /dev/null
@@ -0,0 +1,352 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  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.
+ * 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.models.provider.impl;
+
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import javax.ws.rs.core.Response;
+import lombok.NonNull;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.dao.PfDao;
+import org.onap.policy.models.pap.concepts.PolicyAudit;
+import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider;
+import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter;
+import org.onap.policy.models.pdp.concepts.Pdp;
+import org.onap.policy.models.pdp.concepts.PdpGroup;
+import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
+import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
+import org.onap.policy.models.pdp.concepts.PdpStatistics;
+import org.onap.policy.models.pdp.concepts.PdpSubGroup;
+import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters;
+import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
+import org.onap.policy.models.pdp.persistence.provider.PdpStatisticsProvider;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter;
+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.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
+import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider;
+
+public abstract class AbstractPolicyModelsProvider implements PolicyModelsProvider {
+
+    protected abstract PfDao getPfDao();
+
+    @Override
+    public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getServiceTemplateList(getPfDao(), name, version);
+    }
+
+
+    @Override
+    public List<ToscaServiceTemplate> getFilteredServiceTemplateList(
+            @NonNull ToscaEntityFilter<ToscaServiceTemplate> filter) throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getFilteredServiceTemplateList(getPfDao(), filter);
+    }
+
+    @Override
+    public ToscaServiceTemplate createServiceTemplate(@NonNull final ToscaServiceTemplate serviceTemplate)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().createServiceTemplate(getPfDao(), serviceTemplate);
+    }
+
+    @Override
+    public ToscaServiceTemplate updateServiceTemplate(@NonNull final ToscaServiceTemplate serviceTemplate)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().updateServiceTemplate(getPfDao(), serviceTemplate);
+    }
+
+    @Override
+    public ToscaServiceTemplate deleteServiceTemplate(@NonNull final String name, @NonNull final String version)
+            throws PfModelException {
+        assertInitialized();
+
+        return new AuthorativeToscaProvider().deleteServiceTemplate(getPfDao(), name, version);
+    }
+
+    @Override
+    public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getPolicyTypes(getPfDao(), name, version);
+    }
+
+    @Override
+    public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getPolicyTypeList(getPfDao(), name, version);
+    }
+
+    @Override
+    public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaEntityFilter<ToscaPolicyType> filter)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getFilteredPolicyTypes(getPfDao(), filter);
+    }
+
+    @Override
+    public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaEntityFilter<ToscaPolicyType> filter)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getFilteredPolicyTypeList(getPfDao(), filter);
+    }
+
+    @Override
+    public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().createPolicyTypes(getPfDao(), serviceTemplate);
+    }
+
+    @Override
+    public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().updatePolicyTypes(getPfDao(), serviceTemplate);
+    }
+
+    @Override
+    public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
+            throws PfModelException {
+        assertInitialized();
+
+        var policyTypeIdentifier = new ToscaConceptIdentifier(name, version);
+        assertPolicyTypeNotSupportedInPdpGroup(policyTypeIdentifier);
+
+        return new AuthorativeToscaProvider().deletePolicyType(getPfDao(), name, version);
+    }
+
+    @Override
+    public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getPolicies(getPfDao(), name, version);
+    }
+
+    @Override
+    public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getPolicyList(getPfDao(), name, version);
+    }
+
+    @Override
+    public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaTypedEntityFilter<ToscaPolicy> filter)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getFilteredPolicies(getPfDao(), filter);
+    }
+
+    @Override
+    public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaTypedEntityFilter<ToscaPolicy> filter)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().getFilteredPolicyList(getPfDao(), filter);
+    }
+
+    @Override
+    public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().createPolicies(getPfDao(), serviceTemplate);
+    }
+
+    @Override
+    public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
+            throws PfModelException {
+        assertInitialized();
+        return new AuthorativeToscaProvider().updatePolicies(getPfDao(), serviceTemplate);
+    }
+
+    @Override
+    public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
+            throws PfModelException {
+        assertInitialized();
+
+        var policyIdentifier = new ToscaConceptIdentifier(name, version);
+        assertPolicyNotDeployedInPdpGroup(policyIdentifier);
+
+        return new AuthorativeToscaProvider().deletePolicy(getPfDao(), name, version);
+    }
+
+    @Override
+    public List<PdpGroup> getPdpGroups(final String name) throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().getPdpGroups(getPfDao(), name);
+    }
+
+    @Override
+    public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().getFilteredPdpGroups(getPfDao(), filter);
+    }
+
+    @Override
+    public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().createPdpGroups(getPfDao(), pdpGroups);
+    }
+
+    @Override
+    public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().updatePdpGroups(getPfDao(), pdpGroups);
+    }
+
+    @Override
+    public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup)
+            throws PfModelException {
+        assertInitialized();
+        new PdpProvider().updatePdpSubGroup(getPfDao(), pdpGroupName, pdpSubGroup);
+    }
+
+    @Override
+    public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp)
+            throws PfModelException {
+        new PdpProvider().updatePdp(getPfDao(), pdpGroupName, pdpSubGroup, pdp);
+    }
+
+    @Override
+    public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().deletePdpGroup(getPfDao(), name);
+    }
+
+    @Override
+    public List<PdpStatistics> getFilteredPdpStatistics(PdpFilterParameters filterParams) throws PfModelException {
+        assertInitialized();
+        return new PdpStatisticsProvider().getFilteredPdpStatistics(getPfDao(), filterParams);
+    }
+
+    @Override
+    public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
+            throws PfModelException {
+        assertInitialized();
+        return new PdpStatisticsProvider().createPdpStatistics(getPfDao(), pdpStatisticsList);
+    }
+
+    @Override
+    public List<PdpStatistics> updatePdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
+            throws PfModelException {
+        assertInitialized();
+        return new PdpStatisticsProvider().updatePdpStatistics(getPfDao(), pdpStatisticsList);
+    }
+
+    @Override
+    public List<PdpStatistics> deletePdpStatistics(@NonNull final String name, final Instant timestamp)
+            throws PfModelException {
+        assertInitialized();
+        return new PdpStatisticsProvider().deletePdpStatistics(getPfDao(), name, timestamp);
+    }
+
+    @Override
+    public List<PdpPolicyStatus> getAllPolicyStatus() throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().getAllPolicyStatus(getPfDao());
+    }
+
+    @Override
+    public List<PdpPolicyStatus> getAllPolicyStatus(@NonNull ToscaConceptIdentifierOptVersion policy)
+            throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().getAllPolicyStatus(getPfDao(), policy);
+    }
+
+    @Override
+    public List<PdpPolicyStatus> getGroupPolicyStatus(@NonNull String groupName) throws PfModelException {
+        assertInitialized();
+        return new PdpProvider().getGroupPolicyStatus(getPfDao(), groupName);
+    }
+
+    @Override
+    public void cudPolicyStatus(Collection<PdpPolicyStatus> createObjs, Collection<PdpPolicyStatus> updateObjs,
+            Collection<PdpPolicyStatus> deleteObjs) {
+        assertInitialized();
+        new PdpProvider().cudPolicyStatus(getPfDao(), createObjs, updateObjs, deleteObjs);
+    }
+
+    @Override
+    public void createAuditRecords(List<PolicyAudit> auditRecords) {
+        assertInitialized();
+        new PolicyAuditProvider().createAuditRecords(getPfDao(), auditRecords);
+    }
+
+    @Override
+    public List<PolicyAudit> getAuditRecords(AuditFilter auditFilter) {
+        assertInitialized();
+        return new PolicyAuditProvider().getAuditRecords(getPfDao(), auditFilter);
+    }
+
+    /**
+     * Check if the model provider is initialized.
+     */
+    private void assertInitialized() {
+        if (getPfDao() == null) {
+            var errorMessage = "policy models provider is not initilaized";
+            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        }
+    }
+
+    /**
+     * Assert that the policy type is not supported in any PDP group.
+     *
+     * @param policyTypeIdentifier the policy type identifier
+     * @throws PfModelException if the policy type is supported in a PDP group
+     */
+    private void assertPolicyTypeNotSupportedInPdpGroup(ToscaConceptIdentifier policyTypeIdentifier)
+            throws PfModelException {
+        for (PdpGroup pdpGroup : getPdpGroups(null)) {
+            for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
+                if (pdpSubGroup.getSupportedPolicyTypes().contains(policyTypeIdentifier)) {
+                    throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
+                            "policy type is in use, it is referenced in PDP group " + pdpGroup.getName() + " subgroup "
+                                    + pdpSubGroup.getPdpType());
+                }
+            }
+        }
+    }
+
+    /**
+     * Assert that the policy is not deployed in a PDP group.
+     *
+     * @param policyIdentifier the identifier of the policy
+     * @throws PfModelException thrown if the policy is deployed in a PDP group
+     */
+    private void assertPolicyNotDeployedInPdpGroup(final ToscaConceptIdentifier policyIdentifier)
+            throws PfModelException {
+        for (PdpGroup pdpGroup : getPdpGroups(null)) {
+            for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
+                if (pdpSubGroup.getPolicies().contains(policyIdentifier)) {
+                    throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
+                            "policy is in use, it is deployed in PDP group " + pdpGroup.getName() + " subgroup "
+                                    + pdpSubGroup.getPdpType());
+                }
+            }
+        }
+    }
+
+}
index 05722d7..af03fdb 100644 (file)
 
 package org.onap.policy.models.provider.impl;
 
-import java.time.Instant;
-import java.util.Collection;
-import java.util.List;
 import javax.ws.rs.core.Response;
+import lombok.Getter;
 import lombok.NonNull;
 import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.base.PfModelRuntimeException;
-import org.onap.policy.models.pap.concepts.PolicyAudit;
-import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider;
-import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter;
-import org.onap.policy.models.pdp.concepts.Pdp;
-import org.onap.policy.models.pdp.concepts.PdpGroup;
-import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
-import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
-import org.onap.policy.models.pdp.concepts.PdpStatistics;
-import org.onap.policy.models.pdp.concepts.PdpSubGroup;
-import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters;
-import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
-import org.onap.policy.models.pdp.persistence.provider.PdpStatisticsProvider;
-import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.dao.PfDao;
 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter;
-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.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
-import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * This class provides an implementation of the Policy Models Provider for the ONAP Policy Framework that works towards
@@ -58,308 +37,50 @@ import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvide
  *
  * @author Liam Fallon (liam.fallon@est.tech)
  */
-public class DatabasePolicyModelsProviderImpl extends AbstractModelsProvider implements PolicyModelsProvider {
+public class DatabasePolicyModelsProviderImpl extends AbstractPolicyModelsProvider {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderImpl.class);
+
+    private final PolicyModelsProviderParameters parameters;
+
+    // Database connection and the DAO for reading and writing Policy Framework concepts
+    @Getter
+    private PfDao pfDao;
+
     /**
      * Constructor that takes the parameters.
      *
      * @param parameters the parameters for the provider
      */
     public DatabasePolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {
-        super(parameters);
-    }
-
-    @Override
-    public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getServiceTemplateList(getPfDao(), name, version);
-    }
-
-
-    @Override
-    public List<ToscaServiceTemplate> getFilteredServiceTemplateList(
-            @NonNull ToscaEntityFilter<ToscaServiceTemplate> filter) throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getFilteredServiceTemplateList(getPfDao(), filter);
-    }
-
-    @Override
-    public ToscaServiceTemplate createServiceTemplate(@NonNull final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().createServiceTemplate(getPfDao(), serviceTemplate);
-    }
-
-    @Override
-    public ToscaServiceTemplate updateServiceTemplate(@NonNull final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().updateServiceTemplate(getPfDao(), serviceTemplate);
-    }
-
-    @Override
-    public ToscaServiceTemplate deleteServiceTemplate(@NonNull final String name, @NonNull final String version)
-            throws PfModelException {
-        assertInitialized();
-
-        return new AuthorativeToscaProvider().deleteServiceTemplate(getPfDao(), name, version);
-    }
-
-    @Override
-    public ToscaServiceTemplate getPolicyTypes(final String name, final String version) throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getPolicyTypes(getPfDao(), name, version);
-    }
-
-    @Override
-    public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getPolicyTypeList(getPfDao(), name, version);
-    }
-
-    @Override
-    public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaEntityFilter<ToscaPolicyType> filter)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getFilteredPolicyTypes(getPfDao(), filter);
-    }
-
-    @Override
-    public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaEntityFilter<ToscaPolicyType> filter)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getFilteredPolicyTypeList(getPfDao(), filter);
-    }
-
-    @Override
-    public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().createPolicyTypes(getPfDao(), serviceTemplate);
-    }
-
-    @Override
-    public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().updatePolicyTypes(getPfDao(), serviceTemplate);
-    }
-
-    @Override
-    public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version)
-            throws PfModelException {
-        assertInitialized();
-
-        var policyTypeIdentifier = new ToscaConceptIdentifier(name, version);
-        assertPolicyTypeNotSupportedInPdpGroup(policyTypeIdentifier);
-
-        return new AuthorativeToscaProvider().deletePolicyType(getPfDao(), name, version);
-    }
-
-    @Override
-    public ToscaServiceTemplate getPolicies(final String name, final String version) throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getPolicies(getPfDao(), name, version);
-    }
-
-    @Override
-    public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getPolicyList(getPfDao(), name, version);
-    }
-
-    @Override
-    public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaTypedEntityFilter<ToscaPolicy> filter)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getFilteredPolicies(getPfDao(), filter);
-    }
-
-    @Override
-    public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaTypedEntityFilter<ToscaPolicy> filter)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().getFilteredPolicyList(getPfDao(), filter);
-    }
-
-    @Override
-    public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().createPolicies(getPfDao(), serviceTemplate);
-    }
-
-    @Override
-    public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate)
-            throws PfModelException {
-        assertInitialized();
-        return new AuthorativeToscaProvider().updatePolicies(getPfDao(), serviceTemplate);
+        this.parameters = parameters;
     }
 
     @Override
-    public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version)
-            throws PfModelException {
-        assertInitialized();
+    public synchronized void init() throws PfModelException {
+        LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
+                parameters.getPersistenceUnit());
 
-        var policyIdentifier = new ToscaConceptIdentifier(name, version);
-        assertPolicyNotDeployedInPdpGroup(policyIdentifier);
-
-        return new AuthorativeToscaProvider().deletePolicy(getPfDao(), name, version);
-    }
-
-    @Override
-    public List<PdpGroup> getPdpGroups(final String name) throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().getPdpGroups(getPfDao(), name);
-    }
-
-    @Override
-    public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().getFilteredPdpGroups(getPfDao(), filter);
-    }
-
-    @Override
-    public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().createPdpGroups(getPfDao(), pdpGroups);
-    }
-
-    @Override
-    public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().updatePdpGroups(getPfDao(), pdpGroups);
-    }
-
-    @Override
-    public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup)
-            throws PfModelException {
-        assertInitialized();
-        new PdpProvider().updatePdpSubGroup(getPfDao(), pdpGroupName, pdpSubGroup);
-    }
-
-    @Override
-    public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp)
-            throws PfModelException {
-        new PdpProvider().updatePdp(getPfDao(), pdpGroupName, pdpSubGroup, pdp);
-    }
-
-    @Override
-    public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().deletePdpGroup(getPfDao(), name);
-    }
-
-    @Override
-    public List<PdpStatistics> getFilteredPdpStatistics(PdpFilterParameters filterParams) throws PfModelException {
-        assertInitialized();
-        return new PdpStatisticsProvider().getFilteredPdpStatistics(getPfDao(), filterParams);
-    }
-
-    @Override
-    public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
-            throws PfModelException {
-        assertInitialized();
-        return new PdpStatisticsProvider().createPdpStatistics(getPfDao(), pdpStatisticsList);
-    }
-
-    @Override
-    public List<PdpStatistics> updatePdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList)
-            throws PfModelException {
-        assertInitialized();
-        return new PdpStatisticsProvider().updatePdpStatistics(getPfDao(), pdpStatisticsList);
-    }
-
-    @Override
-    public List<PdpStatistics> deletePdpStatistics(@NonNull final String name, final Instant timestamp)
-            throws PfModelException {
-        assertInitialized();
-        return new PdpStatisticsProvider().deletePdpStatistics(getPfDao(), name, timestamp);
-    }
-
-    @Override
-    public List<PdpPolicyStatus> getAllPolicyStatus() throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().getAllPolicyStatus(getPfDao());
-    }
-
-    @Override
-    public List<PdpPolicyStatus> getAllPolicyStatus(@NonNull ToscaConceptIdentifierOptVersion policy)
-            throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().getAllPolicyStatus(getPfDao(), policy);
-    }
-
-    @Override
-    public List<PdpPolicyStatus> getGroupPolicyStatus(@NonNull String groupName) throws PfModelException {
-        assertInitialized();
-        return new PdpProvider().getGroupPolicyStatus(getPfDao(), groupName);
-    }
-
-    @Override
-    public void cudPolicyStatus(Collection<PdpPolicyStatus> createObjs, Collection<PdpPolicyStatus> updateObjs,
-            Collection<PdpPolicyStatus> deleteObjs) {
-        assertInitialized();
-        new PdpProvider().cudPolicyStatus(getPfDao(), createObjs, updateObjs, deleteObjs);
-    }
+        if (pfDao != null) {
+            var errorMessage = "provider is already initialized";
+            throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage);
+        }
 
-    @Override
-    public void createAuditRecords(List<PolicyAudit> auditRecords) {
-        assertInitialized();
-        new PolicyAuditProvider().createAuditRecords(getPfDao(), auditRecords);
+        pfDao = ModelsProvider.init(parameters);
     }
 
     @Override
-    public List<PolicyAudit> getAuditRecords(AuditFilter auditFilter) {
-        assertInitialized();
-        return new PolicyAuditProvider().getAuditRecords(getPfDao(), auditFilter);
-    }
+    public synchronized void close() throws PfModelException {
+        LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
+                parameters.getPersistenceUnit());
 
-    /**
-     * Check if the model provider is initialized.
-     */
-    private void assertInitialized() {
-        if (getPfDao() == null) {
-            var errorMessage = "policy models provider is not initilaized";
-            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage);
+        if (pfDao != null) {
+            pfDao.close();
+            pfDao = null;
         }
-    }
 
-    /**
-     * Assert that the policy type is not supported in any PDP group.
-     *
-     * @param policyTypeIdentifier the policy type identifier
-     * @throws PfModelException if the policy type is supported in a PDP group
-     */
-    private void assertPolicyTypeNotSupportedInPdpGroup(ToscaConceptIdentifier policyTypeIdentifier)
-            throws PfModelException {
-        for (PdpGroup pdpGroup : getPdpGroups(null)) {
-            for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
-                if (pdpSubGroup.getSupportedPolicyTypes().contains(policyTypeIdentifier)) {
-                    throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
-                            "policy type is in use, it is referenced in PDP group " + pdpGroup.getName() + " subgroup "
-                                    + pdpSubGroup.getPdpType());
-                }
-            }
-        }
+        LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(),
+                parameters.getPersistenceUnit());
     }
 
-    /**
-     * Assert that the policy is not deployed in a PDP group.
-     *
-     * @param policyIdentifier the identifier of the policy
-     * @throws PfModelException thrown if the policy is deployed in a PDP group
-     */
-    private void assertPolicyNotDeployedInPdpGroup(final ToscaConceptIdentifier policyIdentifier)
-            throws PfModelException {
-        for (PdpGroup pdpGroup : getPdpGroups(null)) {
-            for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {
-                if (pdpSubGroup.getPolicies().contains(policyIdentifier)) {
-                    throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE,
-                            "policy is in use, it is deployed in PDP group " + pdpGroup.getName() + " subgroup "
-                                    + pdpSubGroup.getPdpType());
-                }
-            }
-        }
-    }
 }
diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DbPolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DbPolicyModelsProviderImpl.java
new file mode 100644 (file)
index 0000000..1c34c30
--- /dev/null
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  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.
+ * 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.models.provider.impl;
+
+import lombok.Getter;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.dao.impl.ProxyDao;
+
+public class DbPolicyModelsProviderImpl extends AbstractPolicyModelsProvider {
+
+    // Database connection and the DAO for reading and writing Policy Framework concepts
+    @Getter
+    private final ProxyDao pfDao;
+
+    /**
+     * Constructor.
+     *
+     * @param pfDao the ProxyDao
+     */
+    public DbPolicyModelsProviderImpl(ProxyDao pfDao) {
+        this.pfDao = pfDao;
+    }
+
+    @Override
+    public void init() throws PfModelException {
+        // Not needs
+    }
+
+    @Override
+    public void close() throws PfModelException {
+        // Not needs
+    }
+}
diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/ModelsProvider.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/ModelsProvider.java
new file mode 100644 (file)
index 0000000..36c762e
--- /dev/null
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  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.
+ * 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.models.provider.impl;
+
+import java.util.Properties;
+import javax.ws.rs.core.Response;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.eclipse.persistence.config.PersistenceUnitProperties;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.dao.DaoParameters;
+import org.onap.policy.models.dao.PfDao;
+import org.onap.policy.models.dao.PfDaoFactory;
+import org.onap.policy.models.dao.impl.DefaultPfDao;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class ModelsProvider {
+
+    /**
+     * Initialise the provider.
+     *
+     * @throws PfModelException in initialisation errors
+     */
+    public static PfDao init(PolicyModelsProviderParameters parameters) throws PfModelException {
+        // Parameters for the DAO
+        final var daoParameters = new DaoParameters();
+        daoParameters.setPluginClass(DefaultPfDao.class.getName());
+        daoParameters.setPersistenceUnit(parameters.getPersistenceUnit());
+
+        // @formatter:off
+        var jdbcProperties = new Properties();
+        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER,   parameters.getDatabaseDriver());
+        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL,      parameters.getDatabaseUrl());
+        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER,     parameters.getDatabaseUser());
+        jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, parameters.getDatabasePassword());
+        jdbcProperties.setProperty(PersistenceUnitProperties.TARGET_DATABASE,
+                        (parameters.getDatabaseType() == null ? "MySQL" : parameters.getDatabaseType()));
+        // @formatter:on
+
+        daoParameters.setJdbcProperties(jdbcProperties);
+
+        PfDao pfDao = null;
+        try {
+            pfDao = new PfDaoFactory().createPfDao(daoParameters);
+            pfDao.init(daoParameters);
+        } catch (Exception exc) {
+            String errorMessage = "could not create Data Access Object (DAO) using url \"" + parameters.getDatabaseUrl()
+                    + "\" and persistence unit \"" + parameters.getPersistenceUnit() + "\"";
+            if (pfDao != null) {
+                pfDao.close();
+            }
+
+            throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc);
+        }
+        return pfDao;
+    }
+
+}