From af22e3dbddd5b372e815970ff43cc73e29135218 Mon Sep 17 00:00:00 2001 From: Ryan Goulding Date: Thu, 17 Aug 2017 16:15:39 -0400 Subject: Fix service registration for SDNC Addresses the inherit race conditions associated with the BundleActivator abstraction. From lessons learned in OpenDaylight project, dependency injection and service injection via Aries Blueprint is faster, more deterministic, and has better error messaging than using BundleActivator(s). This change addresses several aspects: 1) DBLIBResourceActivator is changed to DBLIBResourceProvider. This was done in order to imply that this is no longer an Activator or subclass of an Activator. The class is a POJO. 2) DBLIBResourceProvider is split from a single monolithic method into several more manageable and better documented methods. 3) Documentation surrounding the resolution of the DB properties is added so that a developer can more easily identify the strategy (priority) used for resolving properties. 4) dblib-blueprint.xml is added. This is used to register the configuration bean (DBLIBResourceProvider), and pass it as an argument to the actual Service (DBLIBResourceManager). 5) Tests are added to test the functionality and resolution of the properties file loading. Issue-Id: SDNC-54 Change-Id: Ie9d5fb423ae7a67e9aec026c78321537399cc308 Signed-off-by: Ryan Goulding --- dblib/provider/pom.xml | 13 +- .../sli/core/dblib/DBLIBResourceActivator.java | 130 ---------------- .../sli/core/dblib/DBLIBResourceProvider.java | 164 +++++++++++++++++++++ .../ccsdk/sli/core/dblib/DBResourceManager.java | 83 ++++++----- .../DblibDefaultFileResolver.java | 63 ++++++++ .../DblibEnvVarFileResolver.java | 68 +++++++++ .../DblibJREFileResolver.java | 73 +++++++++ .../DblibKarafRootFileResolver.java | 64 ++++++++ .../DblibPropertiesFileResolver.java | 45 ++++++ .../org/opendaylight/blueprint/dblib-blueprint.xml | 13 ++ .../DblibDefaultFileResolverTest.java | 24 +++ .../DblibEnvVarFileResolverTest.java | 23 +++ .../DblibJREFileResolverTest.java | 17 +++ .../DblibKarafRootFileResolverTest.java | 14 ++ .../ccsdk/sli/core/sli/SvcLogicDblibStore.java | 2 +- 15 files changed, 621 insertions(+), 175 deletions(-) delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceActivator.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolver.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolver.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolver.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolver.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibPropertiesFileResolver.java create mode 100644 dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml create mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java create mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java create mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java create mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index 1f9a5d47..11e0ff74 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -52,6 +52,17 @@ tomcat-jdbc ${tomcat-jdbc.version} + + com.google.guava + guava + + + + + org.mockito + mockito-core + test + @@ -64,9 +75,7 @@ org.onap.ccsdk.sli.core.dblib - org.onap.ccsdk.sli.core.dblib.DBLIBResourceActivator org.onap.ccsdk.sli.core.dblib;version=${project.version} - * true diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceActivator.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceActivator.java deleted file mode 100644 index 8ae9a266..00000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceActivator.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * onap - * ================================================================================ - * Copyright (C) 2016 - 2017 ONAP - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.sli.core.dblib; - -import java.io.File; -import java.net.URL; -import java.util.Properties; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DBLIBResourceActivator implements BundleActivator { - - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final String DBLIB_PROP_PATH = "/dblib.properties"; - - private ServiceRegistration registration = null; - - private static final Logger LOG = LoggerFactory.getLogger(DBLIBResourceActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception { - LOG.info("entering DBLIBResourceActivator.start"); - - DbLibService jdbcDataSource = null; - // Read properties - Properties props = new Properties(); - - File file = null; - URL propURL = null; - String propDir = System.getenv(SDNC_CONFIG_DIR); - if ((propDir == null) || (propDir.length() == 0)) { - propDir = "/opt/sdnc/data/properties"; - } - file = new File(propDir + DBLIB_PROP_PATH); - if(file.exists()) { - propURL = file.toURI().toURL(); - LOG.info("Using property file (1): " + file.toString()); - } else { - propURL = ctx.getBundle().getResource("dblib.properties"); - URL tmp = null; - if (propURL == null) { - file = new File(DBLIB_PROP_PATH); - tmp = this.getClass().getResource(DBLIB_PROP_PATH); -// if(!file.exists()) { - if(tmp == null) { - throw new DblibConfigurationException("Missing configuration properties resource(3) : " + DBLIB_PROP_PATH); - } else { - propURL = tmp; //file.toURI().toURL(); - LOG.info("Using property file (4): " + file.toString()); - } - } else { - LOG.info("Using property file (2): " + propURL.toString()); - } - } - - - try { - props.load(propURL.openStream()); - } catch (Exception e) { - throw new DblibConfigurationException("Could not load properties at URL " + propURL.toString(), e); - - } - - - - try { - jdbcDataSource = DBResourceManager.create(props); - } catch (Exception exc) { - throw new DblibConfigurationException("Could not get initialize database", exc); - } - - String regName = jdbcDataSource.getClass().getName(); - - LOG.info("Registering DBResourceManager service "+regName); - registration = ctx.registerService(new String[] { regName, DbLibService.class.getName(), "javax.sql.DataSource" }, jdbcDataSource, null); - } - - @Override - public void stop(BundleContext ctx) throws Exception { - LOG.info("entering DBLIBResourceActivator.stop"); - if (registration != null) - { - try { - ServiceReference sref = ctx.getServiceReference(DbLibService.class.getName()); - - if (sref == null) { - LOG.warn("Could not find service reference for DBLIB service (" + DbLibService.class.getName() + ")"); - } else { - DBResourceManager dblibSvc = (DBResourceManager) ctx.getService(sref); - if (dblibSvc == null) { - LOG.warn("Could not find service reference for DBLIB service (" + DbLibService.class.getName() + ")"); - } else { - dblibSvc.cleanUp(); - } - } - } catch(Throwable exc) { - LOG.warn("Cleanup", exc); - } - - registration.unregister(); - registration = null; - LOG.debug("Deregistering DBResourceManager service"); - } - } - -} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java new file mode 100644 index 00000000..201cc401 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.dblib; + +import com.google.common.annotations.VisibleForTesting; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Optional; +import java.util.Properties; +import java.util.Vector; + +import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibDefaultFileResolver; +import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibEnvVarFileResolver; +import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibJREFileResolver; +import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibKarafRootFileResolver; +import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibPropertiesFileResolver; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Responsible for determining the properties file to use and instantiating the DBResourceManager + * Service. The priority for properties file resolution is as follows: + * + *
    + *
  1. A directory identified by the system environment variable SDNC_CONFIG_DIR
  2. + *
  3. The default directory DEFAULT_DBLIB_PROP_DIR
  4. + *
  5. A directory identified by the JRE argument dblib.properties
  6. + *
  7. A dblib.properties file located in the karaf root directory
  8. + *
+ */ +public class DBLIBResourceProvider { + + private static final Logger LOG = LoggerFactory.getLogger(DBLIBResourceProvider.class); + + /** + * The name of the properties file for database configuration + */ + private static final String DBLIB_PROP_FILE_NAME = "dblib.properties"; + + /** + * A prioritized list of strategies for resolving dblib properties files. + */ + private Vector dblibPropertiesFileResolvers = new Vector(); + + /** + * The configuration properties for the db connection. + */ + private Properties properties; + + /** + * Set up the prioritized list of strategies for resolving dblib properties files. + */ + public DBLIBResourceProvider() { + dblibPropertiesFileResolvers.add(new DblibEnvVarFileResolver( + "Using property file (1) from environment variable" + )); + dblibPropertiesFileResolvers.add(new DblibDefaultFileResolver( + "Using property file (1) from default directory" + )); + dblibPropertiesFileResolvers.add(new DblibJREFileResolver( + "Using property file (2) from JRE argument" + )); + dblibPropertiesFileResolvers.add(new DblibKarafRootFileResolver( + "Using property file (4) from karaf root", this)); + + // determines properties file as according to the priority described in the class header comment + final File propertiesFile = determinePropertiesFile(this); + if (propertiesFile != null) { + try { + final FileInputStream fileInputStream = new FileInputStream(propertiesFile); + properties = new Properties(); + properties.load(fileInputStream); + } catch (final IOException e) { + LOG.error("Failed to load properties for file: {}", propertiesFile.toString(), + new DblibConfigurationException("Failed to load properties for file: " + + propertiesFile.toString(), e)); + } + } + } + + /** + * Extract db config properties. + * + * @return the db config properties + */ + public Properties getProperties() { + return properties; + } + + /** + * Reports the method chosen for properties resolution to the Logger. + * + * @param message Some user friendly message + * @param fileOptional The file location of the chosen properties file + * @return the file location of the chosen properties file + */ + private static File reportSuccess(final String message, final Optional fileOptional) { + final File file = fileOptional.get(); + LOG.info("{} {}", message, file.getPath()); + return file; + } + + /** + * Reports fatal errors. This is the case in which no properties file could be found. + * + * @param message An appropriate fatal error message + * @param dblibConfigurationException An exception describing what went wrong during resolution + */ + private static void reportFailure(final String message, + final DblibConfigurationException dblibConfigurationException) { + + LOG.error("{}", message, dblibConfigurationException); + } + + /** + * Determines the dblib properties file to use based on the following priority: + *
    + *
  1. A directory identified by the system environment variable SDNC_CONFIG_DIR
  2. + *
  3. The default directory DEFAULT_DBLIB_PROP_DIR
  4. + *
  5. A directory identified by the JRE argument dblib.properties
  6. + *
  7. A dblib.properties file located in the karaf root directory
  8. + *
+ */ + @VisibleForTesting + File determinePropertiesFile(final DBLIBResourceProvider dblibResourceProvider) { + + for (final DblibPropertiesFileResolver dblibPropertiesFileResolver : dblibPropertiesFileResolvers) { + final Optional fileOptional = dblibPropertiesFileResolver.resolveFile(DBLIB_PROP_FILE_NAME); + if (fileOptional.isPresent()) { + return reportSuccess(dblibPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional); + } + } + + reportFailure("Missing configuration properties resource(3)", + new DblibConfigurationException("Missing configuration properties resource(3): " + + DBLIB_PROP_FILE_NAME)); + return null; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java index 78b970bf..46c003a5 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java @@ -105,67 +105,72 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb protected final long expectedCompletionTime; protected final long unprocessedFailoverThreshold; - public DBResourceManager(Properties props){ - this.configProps = props; + public DBResourceManager(final DBLIBResourceProvider configuration) { + this(configuration.getProperties()); + } + + public DBResourceManager(final Properties properties) { + this.configProps = properties; // get retry interval value - retryInterval = getLongFromProperties(props, "org.onap.dblib.connection.retry", 10000L); + retryInterval = getLongFromProperties(properties, "org.onap.dblib.connection.retry", 10000L); // get recovery mode flag - recoveryMode = getBooleanFromProperties(props, "org.onap.dblib.connection.recovery", true); + recoveryMode = getBooleanFromProperties(properties, "org.onap.dblib.connection.recovery", true); if(!recoveryMode) { recoveryMode = false; LOGGER.info("Recovery Mode disabled"); } // get time out value for thread cleanup - terminationTimeOut = getLongFromProperties(props, "org.onap.dblib.termination.timeout", 300000L); + terminationTimeOut = getLongFromProperties(properties, "org.onap.dblib.termination.timeout", 300000L); // get properties for monitoring - monitorDbResponse = getBooleanFromProperties(props, "org.onap.dblib.connection.monitor", false); - monitoringInterval = getLongFromProperties(props, "org.onap.dblib.connection.monitor.interval", 1000L); - monitoringInitialDelay = getLongFromProperties(props, "org.onap.dblib.connection.monitor.startdelay", 5000L); - expectedCompletionTime = getLongFromProperties(props, "org.onap.dblib.connection.monitor.expectedcompletiontime", 5000L); - unprocessedFailoverThreshold = getLongFromProperties(props, "org.onap.dblib.connection.monitor.unprocessedfailoverthreshold", 3L); + monitorDbResponse = getBooleanFromProperties(properties, "org.onap.dblib.connection.monitor", false); + monitoringInterval = getLongFromProperties(properties, "org.onap.dblib.connection.monitor.interval", 1000L); + monitoringInitialDelay = getLongFromProperties(properties, "org.onap.dblib.connection.monitor.startdelay", 5000L); + expectedCompletionTime = getLongFromProperties(properties, "org.onap.dblib.connection.monitor.expectedcompletiontime", 5000L); + unprocessedFailoverThreshold = getLongFromProperties(properties, "org.onap.dblib.connection.monitor.unprocessedfailoverthreshold", 3L); // initialize performance monitor - PollingWorker.createInistance(props); + PollingWorker.createInistance(properties); // initialize recovery thread worker = new RecoveryMgr(); worker.setName("DBResourcemanagerWatchThread"); worker.setDaemon(true); worker.start(); + + try { + this.config(properties); + } catch (final Exception e) { + // TODO: config throws Exception which is poor practice. Eliminate this in a separate patch. + LOGGER.error("Fatal Exception encountered while configuring DBResourceManager", e); + } } - private void config(Properties ctx) throws Exception { + private void config(Properties configProps) throws Exception { - DbConfigPool dbConfig = DBConfigFactory.createConfig(this.configProps); + final DbConfigPool dbConfig = DBConfigFactory.createConfig(configProps); + final AbstractResourceManagerFactory factory = + AbstractDBResourceManagerFactory.getFactory(dbConfig.getType()); + LOGGER.info("Default DB config is : {}", dbConfig.getType()); + LOGGER.info("Using factory : {}", factory.getClass().getName()); - try { - AbstractResourceManagerFactory factory = AbstractDBResourceManagerFactory.getFactory(dbConfig.getType()); - if(LOGGER.isInfoEnabled()){ - LOGGER.info("Default DB config is : " + dbConfig.getType()); - LOGGER.info("Using factory : " + factory.getClass().getName()); - } - CachedDataSource[] cachedDS = factory.initDBResourceManager(dbConfig, this); - if(cachedDS == null || cachedDS.length == 0) { - LOGGER.error("Initialization of CachedDataSources failed. No instance was created."); - throw new Exception("Failed to initialize DB Library. No data source was created."); - } + final CachedDataSource[] cachedDS = factory.initDBResourceManager(dbConfig, this); + if (cachedDS == null || cachedDS.length == 0) { + LOGGER.error("Initialization of CachedDataSources failed. No instance was created."); + throw new Exception("Failed to initialize DB Library. No data source was created."); + } - for(int i=0; i/opt/sdnc/data/properties + */ +public class DblibDefaultFileResolver implements DblibPropertiesFileResolver { + + /** + * Default path to look for the configuration directory + */ + private static final Path DEFAULT_DBLIB_PROP_DIR = Paths.get("opt", "sdnc", "data", "properties"); + + private final String successMessage; + + public DblibDefaultFileResolver(final String successMessage) { + this.successMessage = successMessage; + } + + /** + * Parse a properties file location based on the default properties location + * + * @return an Optional File containing the location if it exists, or an empty Optional + */ + @Override + public Optional resolveFile(final String dblibFileName) { + final File fileFromDefaultDblibDir = DEFAULT_DBLIB_PROP_DIR.resolve(dblibFileName).toFile(); + if (fileFromDefaultDblibDir.exists()) { + Optional.of(fileFromDefaultDblibDir); + } + return Optional.empty(); + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolver.java new file mode 100644 index 00000000..17c42ec8 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolver.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import com.google.common.base.Strings; +import java.io.File; +import java.nio.file.Paths; +import java.util.Optional; + +/** + * Resolves dblib properties files relative to the directory identified by the SDNC_CONFIG_DIR + * environment variable. + */ +public class DblibEnvVarFileResolver implements DblibPropertiesFileResolver { + + /** + * Key for environment variable representing the configuration directory + */ + private static final String SDNC_CONFIG_DIR_PROP_KEY = "SDNC_CONFIG_DIR"; + + private final String successMessage; + + public DblibEnvVarFileResolver(final String successMessage) { + this.successMessage = successMessage; + } + + /** + * Parse a properties file location based on System environment variable + * + * @return an Optional File containing the location if it exists, or an empty Optional + */ + @Override + public Optional resolveFile(final String dblibFileName) { + // attempt to resolve the property directory from the corresponding environment variable + final String propDirectoryFromEnvVariable = System.getenv(SDNC_CONFIG_DIR_PROP_KEY); + final File fileFromEnvVariable; + if (!Strings.isNullOrEmpty(propDirectoryFromEnvVariable)) { + fileFromEnvVariable = Paths.get(propDirectoryFromEnvVariable).resolve(dblibFileName).toFile(); + if(fileFromEnvVariable.exists()) { + return Optional.of(fileFromEnvVariable); + } + } + return Optional.empty(); + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolver.java new file mode 100644 index 00000000..673ccbf0 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolver.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import java.io.File; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Optional; +import org.onap.ccsdk.sli.core.dblib.DBLIBResourceProvider; +import org.osgi.framework.FrameworkUtil; + +/** + * Resolves dblib properties files relative to the directory identified by the JRE property + * dblib.properties. + */ +public class DblibJREFileResolver implements DblibPropertiesFileResolver { + + /** + * Key for JRE argument representing the configuration directory + */ + private static final String DBLIB_JRE_PROPERTY_KEY = "dblib.properties"; + + private final String successMessage; + + public DblibJREFileResolver(final String successMessage) { + this.successMessage = successMessage; + } + + /** + * Parse a properties file location based on JRE argument + * + * @return an Optional File containing the location if it exists, or an empty Optional + */ + @Override + public Optional resolveFile(final String dblibFileName) { + final URL jreArgumentUrl = FrameworkUtil.getBundle(DBLIBResourceProvider.class) + .getResource(DBLIB_JRE_PROPERTY_KEY); + try { + if (jreArgumentUrl == null) { + return Optional.empty(); + } + final Path dblibPath = Paths.get(jreArgumentUrl.toURI()); + return Optional.of(dblibPath.resolve(dblibFileName).toFile()); + } catch(final URISyntaxException e) { + return Optional.empty(); + } + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolver.java new file mode 100644 index 00000000..d2b164e3 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolver.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import java.io.File; +import java.net.URL; +import java.util.Optional; +import org.onap.ccsdk.sli.core.dblib.DBLIBResourceProvider; + +/** + * Resolves dblib properties files relative to the karaf root directory. + */ +public class DblibKarafRootFileResolver implements DblibPropertiesFileResolver { + + final DBLIBResourceProvider dblibResourceProvider; + + private final String successMessage; + + public DblibKarafRootFileResolver(final String successMessage, final DBLIBResourceProvider dblibResourceProvider) { + this.successMessage = successMessage; + this.dblibResourceProvider = dblibResourceProvider; + } + + /** + * Parse a properties file location relative to the karaf root + * + * @return an Optional File containing the location if it exists, or an empty Optional + */ + @Override + public Optional resolveFile(final String dblibFileName) { + final URL fromKarafRoot = dblibResourceProvider.getClass().getResource(dblibFileName); + if (fromKarafRoot != null) { + final File propertiesFile = new File(fromKarafRoot.getFile()); + if (propertiesFile.exists()) { + return Optional.of(propertiesFile); + } + return Optional.empty(); + } + return Optional.empty(); + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibPropertiesFileResolver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibPropertiesFileResolver.java new file mode 100644 index 00000000..97ab08ac --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibPropertiesFileResolver.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import java.io.File; +import java.util.Optional; + +/** + * Strategy for resolving dblib properties. + */ +public interface DblibPropertiesFileResolver { + + /** + * Resolve dblib properties file. + * + * @param dblibFileName the name of the file to look for at the specific location. + * @return An optional File or empty. + */ + Optional resolveFile(final String dblibFileName); + + /** + * A success message, used only for logging now. + * + * @return a success message, used only for logging now. + */ + String getSuccessfulResolutionMessage(); +} diff --git a/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml b/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml new file mode 100644 index 00000000..ee3e0f03 --- /dev/null +++ b/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java new file mode 100644 index 00000000..41011e55 --- /dev/null +++ b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java @@ -0,0 +1,24 @@ +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; + +public class DblibDefaultFileResolverTest { + + @Test + public void resolveFile() throws Exception { + final DblibPropertiesFileResolver resolver = new DblibDefaultFileResolver("success"); + final Optional file = resolver.resolveFile("doesnotexist.cfg"); + assertFalse(file.isPresent()); + } + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final DblibPropertiesFileResolver resolver = new DblibDefaultFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java new file mode 100644 index 00000000..77589893 --- /dev/null +++ b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java @@ -0,0 +1,23 @@ +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; + +public class DblibEnvVarFileResolverTest { + @Test + public void resolveFile() throws Exception { + final DblibPropertiesFileResolver resolver = new DblibEnvVarFileResolver("success"); + final Optional file = resolver.resolveFile("doesnotexist.cfg"); + assertFalse(file.isPresent()); + } + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final DblibPropertiesFileResolver resolver = new DblibEnvVarFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java new file mode 100644 index 00000000..117492d0 --- /dev/null +++ b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java @@ -0,0 +1,17 @@ +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; + +public class DblibJREFileResolverTest { + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final DblibPropertiesFileResolver resolver = new DblibJREFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java new file mode 100644 index 00000000..0a032e8b --- /dev/null +++ b/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java @@ -0,0 +1,14 @@ +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class DblibKarafRootFileResolverTest { + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final DblibPropertiesFileResolver resolver = new DblibKarafRootFileResolver("success", null); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicDblibStore.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicDblibStore.java index 2aed6511..de3682d8 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicDblibStore.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicDblibStore.java @@ -498,7 +498,7 @@ public class SvcLogicDblibStore implements SvcLogicStore { } try { - dblibSvc = DBResourceManager.create(dblibProps); + dblibSvc = new DBResourceManager(dblibProps); JavaSingleton.setInstance(dblibSvc); } catch (Exception e) { LOG.warn("Caught exception trying to create DBResourceManager", e); -- cgit 1.2.3-korg