From 2a93b9ddf308b6bdd135be182c1b3fa779891840 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Tue, 18 Jul 2017 19:40:01 -0400 Subject: Populate seed code Add seed code for sli/core repository Issue: CCSDK-6 Change-Id: Iaeb54c6135a94a6ffec0c7fd96505d72d18aeb00 Signed-off-by: Dan Timoney --- .../sdnc/sli/resource/dblib/CachedDataSource.java | 616 +++++++++++++++ .../resource/dblib/CachedDataSourceFactory.java | 45 ++ .../sdnc/sli/resource/dblib/DBConfigException.java | 47 ++ .../sli/resource/dblib/DBLIBResourceActivator.java | 130 ++++ .../sdnc/sli/resource/dblib/DBLibConnection.java | 390 ++++++++++ .../sdnc/sli/resource/dblib/DBLibException.java | 39 + .../sdnc/sli/resource/dblib/DBResourceManager.java | 862 +++++++++++++++++++++ .../sli/resource/dblib/DBResourceObserver.java | 27 + .../sdnc/sli/resource/dblib/DataAccessor.java | 33 + .../sli/resource/dblib/DataSourceComparator.java | 33 + .../sdnc/sli/resource/dblib/DbLibService.java | 46 ++ .../dblib/DblibConfigurationException.java | 45 ++ .../dblib/NoAvailableConnectionsException.java | 36 + .../dblib/TerminatingCachedDataSource.java | 82 ++ .../resource/dblib/config/BaseDBConfiguration.java | 104 +++ .../sli/resource/dblib/config/DbConfigPool.java | 56 ++ .../resource/dblib/config/JDBCConfiguration.java | 31 + .../factory/AbstractDBResourceManagerFactory.java | 39 + .../factory/AbstractResourceManagerFactory.java | 104 +++ .../resource/dblib/factory/DBConfigFactory.java | 100 +++ .../dblib/factory/FactoryNotDefinedException.java | 37 + .../dblib/jdbc/JdbcDBCachedDataSource.java | 249 ++++++ .../dblib/jdbc/JdbcDbResourceManagerFactory.java | 186 +++++ .../resource/dblib/jdbc/MySQLCachedDataSource.java | 217 ++++++ .../sdnc/sli/resource/dblib/pm/PollingWorker.java | 217 ++++++ .../sli/resource/dblib/pm/SQLExecutionMonitor.java | 237 ++++++ .../dblib/pm/SQLExecutionMonitorObserver.java | 37 + dblib/provider/src/main/resources/dblib.properties | 13 + 28 files changed, 4058 insertions(+) create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/MySQLCachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java create mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java create mode 100755 dblib/provider/src/main/resources/dblib.properties (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java new file mode 100644 index 000000000..58a0aeb11 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java @@ -0,0 +1,616 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.io.Closeable; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Observer; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetProvider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitor; +import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitorObserver; +import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitor.TestObject; +import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; + + +/** + * @version $Revision: 1.13 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ + +public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver +{ + private static Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); + + protected static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; + + protected long CONN_REQ_TIMEOUT = 30L; + protected long DATA_REQ_TIMEOUT = 100L; + + private final SQLExecutionMonitor monitor; + protected DataSource ds = null; + protected String connectionName = null; + protected boolean initialized = false; + + private long interval = 1000; + private long initialDelay = 5000; + private long expectedCompletionTime = 50L; + private boolean canTakeOffLine = true; + private long unprocessedFailoverThreshold = 3L; + + private long nextErrorReportTime = 0L; + + private String globalHostName = null; + + + public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException + { + configure(jdbcElem); + monitor = new SQLExecutionMonitor(this); + } + + protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + /* (non-Javadoc) + * @see javax.sql.DataSource#getConnection() + */ + public Connection getConnection() throws SQLException + { + return ds.getConnection(); + } + + public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable + { + TestObject testObject = null; + testObject = monitor.registerRequest(); + + Connection connection = null; + try { + connection = this.getConnection(); + if(connection == null ) { + throw new SQLException("Connection invalid"); + } + if(LOGGER.isDebugEnabled()) + LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); + return executePreparedStatement(connection, statement, arguments, true); + } finally { + try { + if(connection != null && !connection.isClosed()) { + connection.close(); + } + } catch(Throwable exc) { + // the exception not monitored + } finally { + connection = null; + } + + monitor.deregisterReguest(testObject); + } + } + + public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable + { + TestObject testObject = null; + testObject = monitor.registerRequest(); + + Connection connection = null; + try { + connection = this.getConnection(); + if(connection == null ) { + throw new SQLException("Connection invalid"); + } + if(LOGGER.isDebugEnabled()) + LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); + return executeUpdatePreparedStatement(connection, statement, arguments, true); + } finally { + try { + if(connection != null && !connection.isClosed()) { + connection.close(); + } + } catch(Throwable exc) { + // the exception not monitored + } finally { + connection = null; + } + + monitor.deregisterReguest(testObject); + } + } + + CachedRowSet executePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable + { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL Statement: "+ statement); + if(arguments != null && !arguments.isEmpty()) { + LOGGER.debug("Argunments: "+ Arrays.toString(arguments.toArray())); + } + } + + ResultSet rs = null; + try { + data = RowSetProvider.newFactory().createCachedRowSet(); + PreparedStatement ps = conn.prepareStatement(statement); + if(arguments != null) + { + for(int i = 0, max = arguments.size(); i < max; i++){ + ps.setObject(i+1, arguments.get(i)); + } + } + rs = ps.executeQuery(); + data.populate(rs); + // Point the rowset Cursor to the start + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); } + } catch(SQLException exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + try { conn.rollback(); } catch(Throwable thr){} + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; + } catch(Throwable exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; // new SQLException(exc); + } finally { + + try { + if(rs != null){ + rs.close(); + rs = null; + } + } catch(Exception exc){ + + } + try { + if(conn != null && close){ + conn.close(); + conn = null; + } + } catch(Exception exc){ + + } + } + + return data; + } + + boolean executeUpdatePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + + int rs = -1; + try { + data = RowSetProvider.newFactory().createCachedRowSet(); + PreparedStatement ps = conn.prepareStatement(statement); + if(arguments != null) + { + for(int i = 0, max = arguments.size(); i < max; i++){ + if(arguments.get(i) instanceof Blob) { + ps.setBlob(i+1, (Blob)arguments.get(i)); + } else if(arguments.get(i) instanceof Timestamp) { + ps.setTimestamp(i+1, (Timestamp)arguments.get(i)); + } else if(arguments.get(i) instanceof Integer) { + ps.setInt(i+1, (Integer)arguments.get(i)); + } else if(arguments.get(i) instanceof Long) { + ps.setLong(i+1, (Long)arguments.get(i)); + } else if(arguments.get(i) instanceof Date) { + ps.setDate(i+1, (Date)arguments.get(i)); + } else { + ps.setObject(i+1, arguments.get(i)); + } + } + } + rs = ps.executeUpdate(); + // Point the rowset Cursor to the start + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); + } + } catch(SQLException exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + try { conn.rollback(); } catch(Throwable thr){} + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; + } catch(Throwable exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; // new SQLException(exc); + } finally { + try { + if(conn != null && close){ + conn.close(); + conn = null; + } + } catch(Exception exc){ + + } + } + + return true; + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) + */ + public Connection getConnection(String username, String password) + throws SQLException + { + return ds.getConnection(username, password); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getLogWriter() + */ + public PrintWriter getLogWriter() throws SQLException + { + return ds.getLogWriter(); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getLoginTimeout() + */ + public int getLoginTimeout() throws SQLException + { + return ds.getLoginTimeout(); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) + */ + public void setLogWriter(PrintWriter out) throws SQLException + { + ds.setLogWriter(out); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#setLoginTimeout(int) + */ + public void setLoginTimeout(int seconds) throws SQLException + { + ds.setLoginTimeout(seconds); + } + + + public final String getDbConnectionName(){ + return connectionName; + } + + protected final void setDbConnectionName(String name) { + this.connectionName = name; + } + + public void cleanUp(){ + if(ds != null && ds instanceof Closeable) { + try { + ((Closeable)ds).close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage()); + } + } + ds = null; + monitor.deleteObservers(); + monitor.cleanup(); + } + + public boolean isInitialized() { + return initialized; + } + + protected boolean testConnection(){ + return testConnection(false); + } + + protected boolean testConnection(boolean error_level){ + Connection conn = null; + ResultSet rs = null; + Statement stmt = null; + try + { + Boolean readOnly = null; + String hostname = null; + conn = this.getConnection(); + stmt = conn.createStatement(); + rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); //("SELECT 1 FROM DUAL"); //"select BANNER from SYS.V_$VERSION" + while(rs.next()) + { + readOnly = rs.getBoolean(1); + hostname = rs.getString(2); + + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL DataSource <"+getDbConnectionName() + "> connected to " + hostname + ", read-only is " + readOnly + ", tested successfully "); + } + } + + } catch (Throwable exc) { + if(error_level) { + LOGGER.error("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } else { + LOGGER.info("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } + return false; + } finally { + if(rs != null) { + try { + rs.close(); + rs = null; + } catch (SQLException e) { + } + } + if(stmt != null) { + try { + stmt.close(); + stmt = null; + } catch (SQLException e) { + } + } + if(conn !=null){ + try { + conn.close(); + conn = null; + } catch (SQLException e) { + } + } + } + return true; + } + + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public T unwrap(Class iface) throws SQLException { + return null; + } + + @SuppressWarnings("deprecation") + public void setConnectionCachingEnabled(boolean state) + { +// if(ds != null && ds instanceof OracleDataSource) +// try { +// ((OracleDataSource)ds).setConnectionCachingEnabled(true); +// } catch (SQLException exc) { +// LOGGER.warn("", exc); +// } + } + + public void addObserver(Observer observer) { + monitor.addObserver(observer); + } + + public void deleteObserver(Observer observer) { + monitor.deleteObserver(observer); + } + + public long getInterval() { + return interval; + } + + public long getInitialDelay() { + return initialDelay; + } + + public void setInterval(long value) { + interval = value; + } + + public void setInitialDelay(long value) { + initialDelay = value; + } + + public long getExpectedCompletionTime() { + return expectedCompletionTime; + } + + public void setExpectedCompletionTime(long value) { + expectedCompletionTime = value; + } + + public long getUnprocessedFailoverThreshold() { + return unprocessedFailoverThreshold; + } + + public void setUnprocessedFailoverThreshold(long value) { + this.unprocessedFailoverThreshold = value; + } + + public boolean canTakeOffLine() { + return canTakeOffLine; + } + + public void blockImmediateOffLine() { + canTakeOffLine = false; + final Thread offLineTimer = new Thread() + { + public void run(){ + try { + Thread.sleep(30000L); + }catch(Throwable exc){ + + }finally{ + canTakeOffLine = true; + } + } + }; + offLineTimer.setDaemon(true); + offLineTimer.start(); + } + + /** + * @return the monitor + */ + final SQLExecutionMonitor getMonitor() { + return monitor; + } + + protected boolean isSlave() throws PoolExhaustedException, MySQLNonTransientConnectionException { + CachedRowSet rs = null; + boolean isSlave = true; + String hostname = "UNDETERMINED"; + try { + boolean localSlave = true; + rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList()); + while(rs.next()) { + localSlave = rs.getBoolean(1); + hostname = rs.getString(2); + } + isSlave = localSlave; + } catch(PoolExhaustedException | MySQLNonTransientConnectionException peexc){ + throw peexc; + } catch (SQLException e) { + LOGGER.error("", e); + isSlave = true; + } catch (Throwable e) { + LOGGER.error("", e); + isSlave = true; + } + if(isSlave){ + LOGGER.debug("SQL SLAVE : "+connectionName + " on server " + hostname); + } else { + LOGGER.debug("SQL MASTER : "+connectionName + " on server " + hostname); + } + return isSlave; + } + + public boolean isFabric() { + return false; + } + + protected boolean lockTable(Connection conn, String tableName) { + boolean retValue = false; + Statement lock = null; + try { + if(tableName != null) { + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); + if("SVC_LOGIC".equals(tableName)) { + Exception e = new Exception(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + LOGGER.debug(sw.toString()); + } + } + lock = conn.createStatement(); + lock.execute("LOCK TABLES " + tableName + " WRITE"); + retValue = true; + } + } catch(Exception exc){ + LOGGER.error("", exc); + retValue = false; + } finally { + try { + lock.close(); + } catch(Exception exc) { + + } + } + return retValue; + } + + protected boolean unlockTable(Connection conn) { + boolean retValue = false; + Statement lock = null; + try { + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); + } + lock = conn.createStatement(); + retValue = lock.execute("UNLOCK TABLES"); + } catch(Exception exc){ + LOGGER.error("", exc); + retValue = false; + } finally { + try { + lock.close(); + } catch(Exception exc) { + + } + } + return retValue; + } + + public void getPoolInfo(boolean allocation) { + + } + + public long getNextErrorReportTime() { + return nextErrorReportTime; + } + + public void setNextErrorReportTime(long nextTime) { + this.nextErrorReportTime = nextTime; + } + + public void setGlobalHostName(String hostname) { + this.globalHostName = hostname; + } + + public String getGlobalHostName() { + return globalHostName; + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java new file mode 100644 index 000000000..3e51ed942 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + + +import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.jdbc.JdbcDBCachedDataSource; +import org.openecomp.sdnc.sli.resource.dblib.jdbc.MySQLCachedDataSource; + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class CachedDataSourceFactory { + + public static CachedDataSource createDataSource(BaseDBConfiguration config) { + if(config instanceof JDBCConfiguration) + return JdbcDBCachedDataSource.createInstance(config); + + return (CachedDataSource)null; + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java new file mode 100644 index 000000000..b324e6a2c --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class DBConfigException extends RuntimeException +{ + /** + * + */ + private static final long serialVersionUID = 4752405152537680257L; + + public DBConfigException(Exception e) + { + super(e.toString()); + } + + public DBConfigException(String msg) + { + super(msg); + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java new file mode 100644 index 000000000..150a9a82f --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.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/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java new file mode 100644 index 000000000..5c1f51040 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java @@ -0,0 +1,390 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.ArrayList; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; + +import javax.sql.rowset.CachedRowSet; + +import org.apache.tomcat.jdbc.pool.PooledConnection; +import org.apache.tomcat.jdbc.pool.ProxyConnection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DBLibConnection implements Connection { + + private static Logger LOGGER = LoggerFactory.getLogger(DBLibConnection.class); + + private final Connection connection; + private final CachedDataSource dataSource; + private boolean locked = false; + private String tableName = null; + + public DBLibConnection(Connection con, CachedDataSource dataSource){ + this.connection = con; + this.dataSource = dataSource; + locked = false; + dataSource.getPoolInfo(true); + } + + public boolean lockTable(String tablename) { + this.tableName = tablename; + return locked = dataSource.lockTable(connection, tableName); + } + + public void resetInactivityTimer() { + Class iface = PooledConnection.class; + try { + PooledConnection pc = connection.unwrap(iface); + pc.setTimestamp(System.currentTimeMillis()); + } catch (SQLException e) { + LOGGER.warn("Failed resetting timeout timer", e); + } + } + + public boolean unlock() { + dataSource.unlockTable(connection); + return locked = false; + } + + public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable + { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + resetInactivityTimer(); + return dataSource.executeUpdatePreparedStatement(connection, statement, newList, false); + } + + public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable + { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + resetInactivityTimer(); + return dataSource.executePreparedStatement(connection, statement, newList, false); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return connection.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return connection.isWrapperFor(iface); + } + + @Override + public Statement createStatement() throws SQLException { + return connection.createStatement(); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + return connection.prepareStatement(sql); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + return connection.prepareCall(sql); + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return connection.nativeSQL(sql); + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + connection.setAutoCommit(autoCommit); + } + + @Override + public boolean getAutoCommit() throws SQLException { + return connection.getAutoCommit(); + } + + @Override + public void commit() throws SQLException { + connection.commit(); + } + + @Override + public void rollback() throws SQLException { + connection.rollback(); + } + + @Override + public void close() throws SQLException { + if(this.locked) { + try { + this.unlock(); + } catch(Throwable th) { + LOGGER.error("Failed unlocking",th); + } + } + if(connection != null && !connection.isClosed()) { + connection.close(); + } + dataSource.getPoolInfo(false); + } + + @Override + public boolean isClosed() throws SQLException { + return connection.isClosed(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return connection.getMetaData(); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + connection.setReadOnly(readOnly); + } + + @Override + public boolean isReadOnly() throws SQLException { + return connection.isReadOnly(); + } + + @Override + public void setCatalog(String catalog) throws SQLException { + connection.setCatalog(catalog); + } + + @Override + public String getCatalog() throws SQLException { + return connection.getCatalog(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + connection.setTransactionIsolation(level); + } + + @Override + public int getTransactionIsolation() throws SQLException { + return connection.getTransactionIsolation(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return connection.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + connection.clearWarnings(); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return connection.createStatement(resultSetType, resultSetConcurrency); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return connection.prepareCall(sql, resultSetType, resultSetConcurrency); + } + + @Override + public Map> getTypeMap() throws SQLException { + return connection.getTypeMap(); + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + connection.setTypeMap(map); + } + + @Override + public void setHoldability(int holdability) throws SQLException { + connection.setHoldability(holdability); + } + + @Override + public int getHoldability() throws SQLException { + return connection.getHoldability(); + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return connection.setSavepoint(); + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return connection.setSavepoint(name); + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + connection.rollback(savepoint); + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + connection.releaseSavepoint(savepoint); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return connection.prepareStatement(sql, autoGeneratedKeys); + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return connection.prepareStatement(sql, columnIndexes); + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return connection.prepareStatement(sql, columnNames); + } + + @Override + public Clob createClob() throws SQLException { + return connection.createClob(); + } + + @Override + public Blob createBlob() throws SQLException { + return connection.createBlob(); + } + + @Override + public NClob createNClob() throws SQLException { + return connection.createNClob(); + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return connection.createSQLXML(); + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return connection.isValid(timeout); + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + connection.setClientInfo(name, value); + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + connection.setClientInfo(properties); + } + + @Override + public String getClientInfo(String name) throws SQLException { + return connection.getClientInfo(name); + } + + @Override + public Properties getClientInfo() throws SQLException { + return connection.getClientInfo(); + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return connection.createArrayOf(typeName, elements); + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return connection.createStruct(typeName, attributes); + } + + @Override + public void setSchema(String schema) throws SQLException { + connection.setSchema(schema); + } + + @Override + public String getSchema() throws SQLException { + return connection.getSchema(); + } + + @Override + public void abort(Executor executor) throws SQLException { + connection.abort(executor); + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + connection.setNetworkTimeout(executor, milliseconds); + } + + @Override + public int getNetworkTimeout() throws SQLException { + return connection.getNetworkTimeout(); + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java new file mode 100644 index 000000000..cc80741dc --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.sql.SQLException; + +/** + * An exception time for handling DBLIB specific error handling. + */ +public class DBLibException extends SQLException { + + /** + * + */ + private static final long serialVersionUID = -5345059355083984696L; + + public DBLibException(String message){ + super(message); + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java new file mode 100644 index 000000000..5cf2953b7 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java @@ -0,0 +1,862 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLDataException; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLSyntaxErrorException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Observable; +import java.util.PriorityQueue; +import java.util.Properties; +import java.util.Queue; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; + +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; +import org.openecomp.sdnc.sli.resource.dblib.factory.AbstractDBResourceManagerFactory; +import org.openecomp.sdnc.sli.resource.dblib.factory.AbstractResourceManagerFactory; +import org.openecomp.sdnc.sli.resource.dblib.factory.DBConfigFactory; +import org.openecomp.sdnc.sli.resource.dblib.pm.PollingWorker; +import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitor; +import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * @version $Revision: 1.15 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class DBResourceManager implements DataSource, DataAccessor, DBResourceObserver, DbLibService { + private static Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); + + transient boolean terminating = false; + transient protected long retryInterval = 10000L; + transient boolean recoveryMode = true; + + protected final AtomicBoolean dsSelector = new AtomicBoolean(); + +// Queue dsQueue = new ConcurrentLinkedQueue(); + Queue dsQueue = new PriorityQueue(4, new Comparator(){ + + @Override + public int compare(CachedDataSource left, CachedDataSource right) { + try { + if(!left.isSlave()) + return -1; + if(!right.isSlave()) + return 1; + + } catch (Throwable e) { + LOGGER.warn("", e); + } + return 0; + } + + }); + protected final Set broken = Collections.synchronizedSet(new HashSet()); + protected final Object monitor = new Object(); + protected final Properties configProps; + protected final Thread worker; + + protected final long terminationTimeOut; + protected final boolean monitorDbResponse; + protected final long monitoringInterval; + protected final long monitoringInitialDelay; + protected final long expectedCompletionTime; + protected final long unprocessedFailoverThreshold; + + public DBResourceManager(Properties props){ + this.configProps = props; + + // get retry interval value + retryInterval = getLongFromProperties(props, "org.openecomp.dblib.connection.retry", 10000L); + + // get recovery mode flag + recoveryMode = getBooleanFromProperties(props, "org.openecomp.dblib.connection.recovery", true); + if(!recoveryMode) + { + recoveryMode = false; + LOGGER.info("Recovery Mode disabled"); + } + // get time out value for thread cleanup + terminationTimeOut = getLongFromProperties(props, "org.openecomp.dblib.termination.timeout", 300000L); + // get properties for monitoring + monitorDbResponse = getBooleanFromProperties(props, "org.openecomp.dblib.connection.monitor", false); + monitoringInterval = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.interval", 1000L); + monitoringInitialDelay = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.startdelay", 5000L); + expectedCompletionTime = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.expectedcompletiontime", 5000L); + unprocessedFailoverThreshold = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.unprocessedfailoverthreshold", 3L); + + // initialize performance monitor + PollingWorker.createInistance(props); + + // initialize recovery thread + worker = new RecoveryMgr(); + worker.setName("DBResourcemanagerWatchThread"); + worker.setDaemon(true); + worker.start(); + } + + private void config(Properties ctx) throws Exception { + + DbConfigPool dbConfig = DBConfigFactory.createConfig(this.configProps); + + 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."); + } + + for(int i=0; i 1){ + handleGetConnectionException(dataSource, new Exception(data.toString())); + } + } + } + } + } + + public void testForceRecovery() + { + CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + handleGetConnectionException(active, new Exception("test")); + } + + class RecoveryMgr extends Thread { + + public void run() { + while(!terminating) + { + try { + Thread.sleep(retryInterval); + } catch (InterruptedException e1) { } + CachedDataSource brokenSource = null; + try { + if (!broken.isEmpty()) { + CachedDataSource[] sourceArray = broken.toArray(new CachedDataSource[0]); + for (int i = 0; i < sourceArray.length; i++) + { + brokenSource = sourceArray[i]; + if (brokenSource instanceof TerminatingCachedDataSource) + break; + if (resetConnectionPool(brokenSource)) { + broken.remove(brokenSource); + brokenSource.blockImmediateOffLine(); + dsQueue.add(brokenSource); + LOGGER.info("DataSource <" + + brokenSource.getDbConnectionName() + + "> recovered."); + } + brokenSource = null; + } + } + } catch (Exception exc) { + LOGGER.warn(exc.getMessage()); + if(brokenSource != null){ + try { + if(!broken.contains(brokenSource)) + broken.add(brokenSource); + brokenSource = null; + } catch (Exception e1) { } + } + } + } + LOGGER.info("DBResourceManager.RecoveryMgr <"+this.toString() +"> terminated." ); + } + + private boolean resetConnectionPool(CachedDataSource dataSource){ + try { + return dataSource.testConnection(); + } catch (Exception exc) { + LOGGER.info("DataSource <" + dataSource.getDbConnectionName() + "> resetCache failed with error: "+ exc.getMessage()); + return false; + } + } + } + + /* (non-Javadoc) + * @see org.openecomp.sdnc.sli.resource.dblib.DbLibService#getData(java.lang.String, java.util.ArrayList, java.lang.String) + */ + @Override + public CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) throws SQLException { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + if(recoveryMode) + return requestDataWithRecovery(statement, newList, preferredDS); + else + return requestDataNoRecovery(statement, newList, preferredDS); + } + + private CachedRowSet requestDataWithRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { + Throwable lastException = null; + CachedDataSource active = null; + + // test if there are any connection pools available + LinkedList sources = new LinkedList(this.dsQueue); + if(sources.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); + } + if(preferredDS != null && !sources.peek().getDbConnectionName().equals(preferredDS)) { + Collections.reverse(sources); + } + + + // loop through available data sources to retrieve data. + while(!sources.isEmpty()) + { + active = sources.peek(); + + long time = System.currentTimeMillis(); + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + master = null; + } + } + sources.remove(active); + return active.getData(statement, arguments); + } catch(SQLDataException exc){ + throw exc; + } catch(SQLSyntaxErrorException exc){ + throw exc; + } catch(SQLIntegrityConstraintViolationException exc){ + throw exc; + } catch(Throwable exc){ + lastException = exc; + String message = exc.getMessage(); + if(message == null) { + if(exc.getCause() != null) { + message = exc.getCause().getMessage(); + } + if(message == null) + message = exc.getClass().getName(); + } + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + handleGetConnectionException(active, exc); + } finally { + if(LOGGER.isDebugEnabled()){ + time = (System.currentTimeMillis() - time); + LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + if(lastException instanceof SQLException){ + throw (SQLException)lastException; + } + // repackage the exception + // you are here because either you run out of available data sources + // or the last exception was not of SQLException type. + // repackage the exception + if(lastException == null) { + throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); + } else { + SQLException exception = new DBLibException(lastException.getMessage()); + exception.setStackTrace(lastException.getStackTrace()); + if(lastException.getCause() instanceof SQLException) { + throw (SQLException)lastException.getCause(); + } + throw exception; + } + } + + private CachedRowSet requestDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { + if(dsQueue.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + } + CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + long time = System.currentTimeMillis(); + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) + active = master; + } + return active.getData(statement, arguments); +// } catch(SQLDataException exc){ +// throw exc; + } catch(Throwable exc){ + String message = exc.getMessage(); + if(message == null) + message = exc.getClass().getName(); + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + if(exc instanceof SQLException) + throw (SQLException)exc; + else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } finally { + if(LOGGER.isDebugEnabled()){ + time = (System.currentTimeMillis() - time); + LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + + + /* (non-Javadoc) + * @see org.openecomp.sdnc.sli.resource.dblib.DbLibService#writeData(java.lang.String, java.util.ArrayList, java.lang.String) + */ + @Override + public boolean writeData(String statement, ArrayList arguments, String preferredDS) throws SQLException + { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + + return writeDataNoRecovery(statement, newList, preferredDS); + } + + CachedDataSource findMaster() throws PoolExhaustedException, MySQLNonTransientConnectionException { + CachedDataSource master = null; + CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); + for(int i=0; i arguments, String preferredDS) throws SQLException { + if(dsQueue.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + } + + boolean initialRequest = true; + boolean retryAllowed = true; + CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + long time = System.currentTimeMillis(); + while(initialRequest) { + initialRequest = false; + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + } + } + + return active.writeData(statement, arguments); + } catch(Throwable exc){ + String message = exc.getMessage(); + if(message == null) + message = exc.getClass().getName(); + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + if(exc instanceof SQLException) { + SQLException sqlExc = SQLException.class.cast(exc); + // handle read-only exception + if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { + LOGGER.warn("retrying due to: " + sqlExc.getMessage()); + dsQueue.remove(active); + dsQueue.add(active); + if(retryAllowed){ + retryAllowed = false; + initialRequest = true; + continue; + } + } + throw (SQLException)exc; + } else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } finally { + if(LOGGER.isDebugEnabled()){ + time = (System.currentTimeMillis() - time); + LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + return true; + } + + private void setDataSource(CachedDataSource dataSource) { + if(dataSource.testConnection(true)){ + this.dsQueue.add(dataSource); + } else { + this.broken.add(dataSource); + } + } + + public Connection getConnection() throws SQLException { + Throwable lastException = null; + CachedDataSource active = null; + + if(dsQueue.isEmpty()){ + throw new DBLibException("No active DB connection pools are available in GetConnection call."); + } + + try { + active = dsQueue.peek(); + CachedDataSource tmpActive = findMaster(); + if(tmpActive != null) { + active = tmpActive; + } + return new DBLibConnection(active.getConnection(), active); + } catch(javax.sql.rowset.spi.SyncFactoryException exc){ + LOGGER.debug("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); + LOGGER.warn("CLASSPATH issue. Allowing retry", exc); + lastException = exc; + } catch(PoolExhaustedException exc) { + throw new NoAvailableConnectionsException(exc); + } catch(MySQLNonTransientConnectionException exc){ + throw new NoAvailableConnectionsException(exc); + } catch(Exception exc){ + lastException = exc; + if(recoveryMode){ + handleGetConnectionException(active, exc); + } else { + if(exc instanceof MySQLNonTransientConnectionException) { + throw new NoAvailableConnectionsException(exc); + } if(exc instanceof SQLException) { + throw (SQLException)exc; + } else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } + } catch (Throwable trwb) { + DBLibException excptn = new DBLibException(trwb.getMessage()); + excptn.setStackTrace(trwb.getStackTrace()); + throw excptn; + } finally { + if(LOGGER.isDebugEnabled()){ + displayState(); + } + } + + if(lastException instanceof SQLException){ + throw (SQLException)lastException; + } + // repackage the exception + if(lastException == null) { + throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); + } else { + SQLException exception = new DBLibException(lastException.getMessage()); + exception.setStackTrace(lastException.getStackTrace()); + if(lastException.getCause() instanceof SQLException) { +// exception.setNextException((SQLException)lastException.getCause()); + throw (SQLException)lastException.getCause(); + } + throw exception; + } + } + + public Connection getConnection(String username, String password) + throws SQLException { + CachedDataSource active = null; + + if(dsQueue.isEmpty()){ + throw new DBLibException("No active DB connection pools are available in GetConnection call."); + } + + + try { + active = dsQueue.peek(); + CachedDataSource tmpActive = findMaster(); + if(tmpActive != null) { + active = tmpActive; + } + return active.getConnection(username, password); + } catch(Throwable exc){ + if(recoveryMode){ + handleGetConnectionException(active, exc); + } else { + if(exc instanceof SQLException) + throw (SQLException)exc; + else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } + + } + + throw new DBLibException("No connections available in DBResourceManager in GetConnection call."); + } + + private void handleGetConnectionException(CachedDataSource source, Throwable exc) { + try { + if(!source.canTakeOffLine()) + { + LOGGER.error("Could not switch due to blocking"); + return; + } + + boolean removed = dsQueue.remove(source); + if(!broken.contains(source)) + { + if(broken.add(source)) + { + LOGGER.warn("DB Recovery: DataSource <" + source.getDbConnectionName() + "> put in the recovery mode. Reason : " + exc.getMessage()); + } else { + LOGGER.warn("Error putting DataSource <" +source.getDbConnectionName()+ "> in recovery mode."); + } + } else { + LOGGER.info("DB Recovery: DataSource <" + source.getDbConnectionName() + "> already in recovery queue"); + } + if(removed) + { + if(!dsQueue.isEmpty()) + { + LOGGER.warn("DB DataSource <" + dsQueue.peek().getDbConnectionName() + "> became active"); + } + } + } catch (Exception e) { + LOGGER.error("", e); + } + } + + public void cleanUp() { + for(Iterator it=dsQueue.iterator();it.hasNext();){ + CachedDataSource cds = (CachedDataSource)it.next(); + it.remove(); + cds.cleanUp(); + } + + try { + this.terminating = true; + if(broken != null) + { + try { + broken.add( new TerminatingCachedDataSource(null)); + } catch(Exception exc){ + LOGGER.error("Waiting for Worker to stop", exc); + } + } + worker.join(terminationTimeOut); + LOGGER.info("DBResourceManager.RecoveryMgr <"+worker.toString() +"> termination was successful: " + worker.getState()); + } catch(Exception exc){ + LOGGER.error("Waiting for Worker thread to terminate ", exc); + } + } + + public static DBResourceManager create(Properties props) throws Exception { + DBResourceManager dbmanager = new DBResourceManager(props); + dbmanager.config(props); + return dbmanager; + } + + public PrintWriter getLogWriter() throws SQLException { + return ((CachedDataSource)this.dsQueue.peek()).getLogWriter(); + } + + public int getLoginTimeout() throws SQLException { + return ((CachedDataSource)this.dsQueue.peek()).getLoginTimeout(); + } + + public void setLogWriter(PrintWriter out) throws SQLException { + ((CachedDataSource)this.dsQueue.peek()).setLogWriter(out); + } + + public void setLoginTimeout(int seconds) throws SQLException { + ((CachedDataSource)this.dsQueue.peek()).setLoginTimeout(seconds); + } + + public void displayState(){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); + CachedDataSource current = (CachedDataSource)dsQueue.peek(); + if(current != null) { + LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); + } + } + } + + /* (non-Javadoc) + * @see org.openecomp.sdnc.sli.resource.dblib.DbLibService#isActive() + */ + @Override + public boolean isActive() { + return this.dsQueue.size()>0; + } + + public String getActiveStatus(){ + return "Connected: " + dsQueue.size()+"\tIn-recovery: "+broken.size(); + } + + public String getDBStatus(boolean htmlFormat) { + StringBuilder buffer = new StringBuilder(); + + ArrayList list = new ArrayList(); + list.addAll(dsQueue); + list.addAll(broken); + if (htmlFormat) + { + buffer.append("") + .append("Name:").append(""); + for (int i = 0; i < list.size(); i++) { + buffer.append(""); + buffer.append(((CachedDataSource) list.get(i)).getDbConnectionName()).append(""); + } + buffer.append(""); + + buffer.append("State:"); + for (int i = 0; i < list.size(); i++) { + if (broken.contains(list.get(i))) { + buffer.append("in recovery"); + } + if (dsQueue.contains(list.get(i))) { + if (dsQueue.peek() == list.get(i)) + buffer.append("active"); + else + buffer.append("standby"); + } + } + buffer.append(""); + + } else { + for (int i = 0; i < list.size(); i++) { + buffer.append("Name: ").append(((CachedDataSource) list.get(i)).getDbConnectionName()); + buffer.append("\tState: "); + if (broken.contains(list.get(i))) { + buffer.append("in recovery"); + } else + if (dsQueue.contains(list.get(i))) { + if (dsQueue.peek() == list.get(i)) + buffer.append("active"); + else + buffer.append("standby"); + } + + buffer.append("\n"); + + } + } + return buffer.toString(); + } + + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public T unwrap(Class iface) throws SQLException { + return null; + } + + /** + * @return the monitorDbResponse + */ + public final boolean isMonitorDbResponse() { + return recoveryMode && monitorDbResponse; + } + + public void test(){ + CachedDataSource obj = dsQueue.peek(); + Exception ption = new Exception(); + try { + for(int i=0; i<5; i++) + { + handleGetConnectionException(obj, ption); + } + } catch(Throwable exc){ + LOGGER.warn("", exc); + } + } + + public String getPreferredDSName(){ + if(isActive()){ + return getPreferredDataSourceName(dsSelector); + } + return ""; + } + + public String getPreferredDataSourceName(AtomicBoolean flipper) { + + LinkedList snapshot = new LinkedList(dsQueue); + if(snapshot.size() > 1){ + CachedDataSource first = snapshot.getFirst(); + CachedDataSource last = snapshot.getLast(); + + int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); + if(delta < 0) { + flipper.set(false); + } else if(delta > 0) { + flipper.set(true); + } else { + // check the last value and return !last + flipper.getAndSet(!flipper.get()); + } + + if (flipper.get()) + Collections.reverse(snapshot); + } + return snapshot.peek().getDbConnectionName(); + } + + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + return null; + } + + public String getMasterName() { + if(isActive()){ + return getMasterDataSourceName(dsSelector); + } + return ""; + } + + + private String getMasterDataSourceName(AtomicBoolean flipper) { + + LinkedList snapshot = new LinkedList(dsQueue); + if(snapshot.size() > 1){ + CachedDataSource first = snapshot.getFirst(); + CachedDataSource last = snapshot.getLast(); + + int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); + if(delta < 0) { + flipper.set(false); + } else if(delta > 0) { + flipper.set(true); + } else { + // check the last value and return !last + flipper.getAndSet(!flipper.get()); + } + + if (flipper.get()) + Collections.reverse(snapshot); + } + return snapshot.peek().getDbConnectionName(); + } + + class RemindTask extends TimerTask { + public void run() { + CachedDataSource ds = dsQueue.peek(); + if(ds != null) + ds.getPoolInfo(false); + } + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java new file mode 100644 index 000000000..e06779f35 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.util.Observer; + +public interface DBResourceObserver extends Observer { + public boolean isMonitorDbResponse(); +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java new file mode 100644 index 000000000..cd054a51d --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.sql.SQLException; +import java.util.ArrayList; + +import javax.sql.rowset.CachedRowSet; + +public interface DataAccessor { + + public abstract CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) + throws SQLException; + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java new file mode 100644 index 000000000..37d625136 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.util.Comparator; + +public interface DataSourceComparator extends Comparator { + + public abstract CachedDataSource getLastUsed(); + + public abstract void setLastUsed(CachedDataSource lastUsed); + + public abstract int compare(CachedDataSource ds1, CachedDataSource ds2); + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java new file mode 100644 index 000000000..25edd1f07 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.sql.SQLException; +import java.util.ArrayList; + +import javax.sql.rowset.CachedRowSet; + +public interface DbLibService { + + /* (non-Javadoc) + * @see DataAccessor#getData(java.lang.String, java.util.ArrayList) + */ + public abstract CachedRowSet getData(String statement, + ArrayList arguments, String preferredDS) + throws SQLException; + + /* (non-Javadoc) + * @see DataAccessor#writeData(java.lang.String, java.util.ArrayList) + */ + public abstract boolean writeData(String statement, + ArrayList arguments, String preferredDS) + throws SQLException; + + public abstract boolean isActive(); + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java new file mode 100644 index 000000000..17700a5ee --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + + +public class DblibConfigurationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public DblibConfigurationException() + { + super(); + } + + public DblibConfigurationException(String msg) + { + super(msg); + } + + public DblibConfigurationException(String msg, Throwable t) + { + super(msg, t); + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java new file mode 100644 index 000000000..16895b4d5 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.sql.SQLException; + +public class NoAvailableConnectionsException extends SQLException { + + /** + * + */ + private static final long serialVersionUID = -6259205931674413018L; + + public NoAvailableConnectionsException(Exception exc) { + super(exc); + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java new file mode 100644 index 000000000..234bbed0c --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib; + +import java.sql.SQLFeatureNotSupportedException; +import java.util.logging.Logger; + +import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitorObserver; + + +public class TerminatingCachedDataSource extends CachedDataSource implements SQLExecutionMonitorObserver { + + public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { + super(jdbcElem); + } + + protected void configure(BaseDBConfiguration jdbcElem) throws DBConfigException { + // no action + } + + public long getInterval() { + return 1000; + } + + public long getInitialDelay() { + return 1000; + } + + public long getExpectedCompletionTime() { + return 50; + } + + public void setExpectedCompletionTime(long value) { + + } + + public void setInterval(long value) { + + } + + public void setInitialDelay(long value) { + + } + + public long getUnprocessedFailoverThreshold() { + return 3; + } + + public void setUnprocessedFailoverThreshold(long value) { + + } + + public int compareTo(CachedDataSource ods) + { + return 0; + } + + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java new file mode 100644 index 000000000..976b1cf2d --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.config; + +import java.util.Properties; + +public abstract class BaseDBConfiguration { + public static final String DATABASE_TYPE = "org.openecomp.sdnc.sli.dbtype"; + public static final String DATABASE_URL = "org.openecomp.sdnc.sli.jdbc.url"; + public static final String DATABASE_NAME = "org.openecomp.sdnc.sli.jdbc.database"; + public static final String CONNECTION_NAME = "org.openecomp.sdnc.sli.jdbc.connection.name"; + public static final String DATABASE_USER = "org.openecomp.sdnc.sli.jdbc.user"; + public static final String DATABASE_PSSWD = "org.openecomp.sdnc.sli.jdbc.password"; + public static final String CONNECTION_TIMEOUT="org.openecomp.sdnc.sli.jdbc.connection.timeout"; + public static final String REQUEST_TIMEOUT = "org.openecomp.sdnc.sli.jdbc.request.timeout"; + public static final String MIN_LIMIT = "org.openecomp.sdnc.sli.jdbc.limit.min"; + public static final String MAX_LIMIT = "org.openecomp.sdnc.sli.jdbc.limit.max"; + public static final String INIT_LIMIT = "org.openecomp.sdnc.sli.jdbc.limit.init"; + public static final String DATABASE_HOSTS = "org.openecomp.sdnc.sli.jdbc.hosts"; + + + protected final Properties props; + + public BaseDBConfiguration(Properties properties) { + this.props = properties; + } + + public int getConnTimeout() { + try { + String value = props.getProperty(CONNECTION_TIMEOUT); + return Integer.parseInt(value); + } catch(Exception exc) { + return -1; + } + } + + public int getRequestTimeout() { + try { + String value = props.getProperty(REQUEST_TIMEOUT); + if(value == null) + return -1; + return Integer.parseInt(value); + } catch(Exception exc) { + return -1; + } + } + + public String getDbConnectionName() { + return props.getProperty(CONNECTION_NAME); + } + + public String getDatabaseName() { + return props.getProperty(DATABASE_NAME); + } + + public String getDbUserId() { + return props.getProperty(DATABASE_USER); + } + + public String getDbPasswd() { + return props.getProperty(DATABASE_PSSWD); + } + + public int getDbMinLimit() { + String value = props.getProperty(MIN_LIMIT); + return Integer.parseInt(value); + } + + public int getDbMaxLimit() { + String value = props.getProperty(MAX_LIMIT); + return Integer.parseInt(value); + } + + public int getDbInitialLimit() { + String value = props.getProperty(INIT_LIMIT); + return Integer.parseInt(value); + } + + public String getDbUrl() { + return props.getProperty(DATABASE_URL); + } + + public String getServerGroup() { + return null; + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java new file mode 100644 index 000000000..117f9321d --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.config; + +import java.util.ArrayList; +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DbConfigPool { + private static Logger LOGGER = LoggerFactory.getLogger(DbConfigPool.class); + + private final String type; + + private ArrayList configurations = new ArrayList(); + + public DbConfigPool(Properties properties) { + LOGGER.debug("Initializing DbConfigType"); + type = properties.getProperty(BaseDBConfiguration.DATABASE_TYPE, "JDBC").toUpperCase(); + } + + public int getTimeout() { + // TODO Auto-generated method stub + return 0; + } + + public String getType() { + return type; + } + + public JDBCConfiguration[] getJDBCbSourceArray() { + return configurations.toArray(new JDBCConfiguration[configurations.size()]); + } + + public void addConfiguration(BaseDBConfiguration config) { + configurations.add(config); + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java new file mode 100644 index 000000000..cb6ea3e5c --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.config; + +import java.util.Properties; + +public class JDBCConfiguration extends BaseDBConfiguration { + + public JDBCConfiguration(Properties xmlElem) { + super(xmlElem); + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java new file mode 100644 index 000000000..f4291a7dd --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.factory; + +import org.openecomp.sdnc.sli.resource.dblib.jdbc.JdbcDbResourceManagerFactory; + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class AbstractDBResourceManagerFactory { + + public static AbstractResourceManagerFactory getFactory(String type) throws FactoryNotDefinedException { + + // JDBC + return JdbcDbResourceManagerFactory.createIntstance(); + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java new file mode 100644 index 000000000..0f58a3f03 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.factory; + + +import java.sql.SQLException; +import java.util.Set; +import java.util.concurrent.Callable; + +import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource; +import org.openecomp.sdnc.sli.resource.dblib.CachedDataSourceFactory; +import org.openecomp.sdnc.sli.resource.dblib.DBConfigException; +import org.openecomp.sdnc.sli.resource.dblib.DBResourceManager; +import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; +import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @version $Revision: 1.6 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public abstract class AbstractResourceManagerFactory { + private static Logger LOGGER = LoggerFactory.getLogger(AbstractResourceManagerFactory.class); + + public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager) throws Exception; + public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager dbResourceManager, String sourceName) throws SQLException ; + + + public static AbstractResourceManagerFactory createIntstance() throws FactoryNotDefinedException { + throw new FactoryNotDefinedException("Factory method 'createIntstance' needs to be overriden in DBResourceManagerFactory"); + } + + public class DBInitTask implements Callable + { + private BaseDBConfiguration config = null; + private Set activeTasks; + + public DBInitTask(JDBCConfiguration jdbcconfig, Set tasks) { + this.config = jdbcconfig; + this.activeTasks = tasks; + } + + public CachedDataSource call() throws Exception { + CachedDataSource ds = null; + try { + ds = CachedDataSourceFactory.createDataSource(config); + return ds; + } finally { + synchronized(activeTasks) { + activeTasks.remove(this); + if (activeTasks.isEmpty()) { + final Runnable closure = new Runnable() { + + public void run() { + try { + Thread.sleep(300); + } catch (Exception e) { + } + synchronized(activeTasks) { + activeTasks.notifyAll(); + } + } + }; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Completed CachedDataSource.Call and notifyAll from " + ds.getDbConnectionName()); + } + Thread worker = new Thread(closure); + worker.setDaemon(true); + worker.start(); + } else { + if (LOGGER.isDebugEnabled()) { + if (ds != null) { + LOGGER.debug("Completed CachedDataSource.Call from " + ds.getDbConnectionName()); + } + } + } + } + } + } + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java new file mode 100644 index 000000000..8aadcae6b --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.factory; + + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Properties; + +import org.slf4j.LoggerFactory; + +import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; +import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki 01/17/08 Initial version + */ +public class DBConfigFactory { + + public static DbConfigPool createConfig(Properties resource) { + return getConfigparams(resource); + } + + static DbConfigPool getConfigparams(Properties properties){ + DbConfigPool xmlConfig = new DbConfigPool(properties); + ArrayList propertySets = new ArrayList(); + + if("JDBC".equalsIgnoreCase(xmlConfig.getType())) { + String hosts = properties.getProperty(BaseDBConfiguration.DATABASE_HOSTS); + if(hosts == null || hosts.isEmpty()) { + propertySets.add(properties); + } else { + String[] newhost = hosts.split(","); + for(int i=0; i< newhost.length; i++) { + Properties localset = new Properties(); + localset.putAll(properties); + String url = localset.getProperty(BaseDBConfiguration.DATABASE_URL); + if(url.contains("DBHOST")) + url = url.replace("DBHOST", newhost[i]); + if(url.contains("dbhost")) + url = url.replace("dbhost", newhost[i]); + localset.setProperty(BaseDBConfiguration.DATABASE_URL, url); + localset.setProperty(BaseDBConfiguration.CONNECTION_NAME, newhost[i]); + propertySets.add(localset); + } + } + } else { + propertySets.add(properties); + } + try { + Iterator it = propertySets.iterator(); + while(it.hasNext()) { + BaseDBConfiguration config = parse(it.next()); + xmlConfig.addConfiguration(config); + } + + } catch (Exception e) { + LoggerFactory.getLogger(DBConfigFactory.class).warn("",e); + } + + return xmlConfig; + } + + public static BaseDBConfiguration parse(Properties props) throws Exception { + + String type = props.getProperty(BaseDBConfiguration.DATABASE_TYPE); + + BaseDBConfiguration config = null; + + if("JDBC".equalsIgnoreCase(type)) { + config = new JDBCConfiguration(props); + } + + return config; + + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java new file mode 100644 index 000000000..e38cd3519 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.factory; + + +/** + * @version 1.3 + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki 01/16/08 Initial version + */ +public class FactoryNotDefinedException extends Exception { + + public FactoryNotDefinedException(String message) { + super(message); + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java new file mode 100644 index 000000000..90c76f637 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.jdbc; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLFeatureNotSupportedException; + +import org.apache.tomcat.jdbc.pool.DataSource; +import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource; +import org.openecomp.sdnc.sli.resource.dblib.DBConfigException; +import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; +import com.mysql.jdbc.Driver; + + +/** + * @version $Revision: 1.7 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ + +public class JdbcDBCachedDataSource extends CachedDataSource +{ + private String dbUserId; + private String dbPasswd; + private String dbUrl; + + private int minLimit; + private int maxLimit; + private int initialLimit; + + private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; + + private static Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class); + + /** + * @param jdbcElem + */ + public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem) + { + super(jdbcElem); + } + + @Override + protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException + { + BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem; + if(jdbcConfig.getConnTimeout() > 0){ + this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); + } + if(jdbcConfig.getRequestTimeout() > 0){ + this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); + } + + // set connection pool name + String dbConnectionName = jdbcConfig.getDbConnectionName(); + super.setDbConnectionName(dbConnectionName); + // Configure the JDBC connection + dbUserId = jdbcConfig.getDbUserId(); + if (dbUserId == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + dbPasswd = jdbcConfig.getDbPasswd(); + if (dbPasswd == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + /* + dbDriver = jdbcConfig.getDbDriver(); + if (dbDriver == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new ScpTblUpdateError(errorMsg); + } + */ + + minLimit = jdbcConfig.getDbMinLimit(); +// if (minLimit == null) +// { +// String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); +// } + maxLimit = jdbcConfig.getDbMaxLimit(); +// if (maxLimit == null) +// { +// String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); +// } + initialLimit = jdbcConfig.getDbInitialLimit(); +// if (initialLimit == null) +// { +// String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); +// } + + dbUrl = jdbcConfig.getDbUrl(); + if(dbUrl == null){ + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + try { + Driver dr = new com.mysql.jdbc.Driver(); + Class clazz = Class.forName("com.mysql.jdbc.Driver") ; + + PoolProperties p = new PoolProperties(); + p.setDriverClassName("com.mysql.jdbc.Driver"); + p.setUrl(dbUrl); + p.setUsername(dbUserId); + p.setPassword(dbPasswd); + p.setJmxEnabled(true); + p.setTestWhileIdle(false); + p.setTestOnBorrow(true); + p.setValidationQuery("SELECT 1"); + p.setTestOnReturn(false); + p.setValidationInterval(30000); + p.setTimeBetweenEvictionRunsMillis(30000); + p.setInitialSize(initialLimit); + p.setMaxActive(maxLimit); + p.setMaxIdle(maxLimit); + p.setMaxWait(10000); + p.setRemoveAbandonedTimeout(60); + p.setMinEvictableIdleTimeMillis(30000); + p.setMinIdle(minLimit); + p.setLogAbandoned(true); + p.setRemoveAbandoned(true); + p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); + + DataSource dataSource = new DataSource(p); + + synchronized(this) + { + this.ds = dataSource; + Connection con = null; + PreparedStatement st = null; + ResultSet rs = null; + + try { + con = dataSource.getConnection(); + st = con.prepareStatement("Select 1 FROM DUAL"); + rs = st.executeQuery(); + } catch(Exception exc) { + LOGGER.error(exc.getMessage()); + } finally { + if(rs != null) rs.close(); + if(st != null) st.close(); + if(con != null) con.close(); + } + + initialized = true; + LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); + } + +// } catch (SQLException exc) { +// initialized = false; +// StringBuffer sb = new StringBuffer(); +// sb.append("Failed to initialize MySQLDataSource<"); +// sb.append(dbConnectionName).append(">. Reason: "); +// sb.append(exc.getMessage()); +// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +//// throw new DBConfigException(e.getMessage()); + } catch (Exception exc) { + initialized = false; + StringBuffer sb = new StringBuffer(); + sb.append("Failed to initialize MySQLCachedDataSource <"); + sb.append(dbConnectionName).append(">. Reason: "); + sb.append(exc.getMessage()); + LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +// throw new DBConfigException(e.getMessage()); + } + } + + public final String getDbUrl() + { + return dbUrl; + } + + public final String getDbUserId() + { + return dbUserId; + } + + public final String getDbPasswd() + { + return dbPasswd; + } + + public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { + return new JdbcDBCachedDataSource(config); + } + + public String toString(){ + return getDbConnectionName(); + } + + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } + + public void cleanUp(){ + DataSource dataSource = (DataSource)ds; + dataSource.getPool().purge(); + int active = dataSource.getActive(); + int size = dataSource.getSize(); + dataSource.close(true); + super.cleanUp(); + } + +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java new file mode 100644 index 000000000..84399dfd9 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.jdbc; + + +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; + +import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource; +import org.openecomp.sdnc.sli.resource.dblib.CachedDataSourceFactory; +import org.openecomp.sdnc.sli.resource.dblib.DBResourceManager; +import org.openecomp.sdnc.sli.resource.dblib.DataSourceComparator; +import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; +import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; +import org.openecomp.sdnc.sli.resource.dblib.factory.AbstractResourceManagerFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @version $Revision: 1.6 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class JdbcDbResourceManagerFactory extends AbstractResourceManagerFactory { + private static Logger LOGGER = LoggerFactory.getLogger(JdbcDbResourceManagerFactory.class ); + private JdbcDbResourceManagerFactory(){ + + } + + class MyFutureTask extends FutureTask + { + + public MyFutureTask(Callable result) { + super(result); + } + + } + + public CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager, String sourceName) throws SQLException + { + // here create the data sources objects + JDBCConfiguration[] list = dbConfig.getJDBCbSourceArray(); + CachedDataSource[] cachedDS = new CachedDataSource[1]; + + for(int i=0, max=list.length; i tasks = new HashSet(); + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating " + list.length + " datasources."); + } + + for(int i=0, max=list.length; i 0){ + this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); + } + if(jdbcConfig.getRequestTimeout() > 0){ + this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); + } + + // set connection pool name + String dbConnectionName = jdbcConfig.getDbConnectionName(); + super.setDbConnectionName(dbConnectionName); + // Configure the JDBC connection + dbUserId = jdbcConfig.getDbUserId(); + if (dbUserId == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + dbPasswd = jdbcConfig.getDbPasswd(); + if (dbPasswd == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + /* + dbDriver = jdbcConfig.getDbDriver(); + if (dbDriver == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new ScpTblUpdateError(errorMsg); + } + */ + + minLimit = Integer.toString(jdbcConfig.getDbMinLimit()); + if (minLimit == null) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + maxLimit = Integer.toString(jdbcConfig.getDbMaxLimit()); + if (maxLimit == null) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + initialLimit = Integer.toString(jdbcConfig.getDbInitialLimit()); + if (initialLimit == null) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + dbUrl = jdbcConfig.getDbUrl(); + if(dbUrl == null){ + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + try { + + MysqlDataSource dataSource = new MysqlDataSource(); + dataSource.setUser(dbUserId); + dataSource.setPassword(dbPasswd); + dataSource.setURL(dbUrl); +// dataSource.setInitialSize(5); +// dataSource.setMaxTotal(60); +// dataSource.setMaxActive(100); +// dataSource.setMaxWait(10000); +// dataSource.setMaxIdle(10); + + Properties connAttr = new Properties(); + + connAttr.setProperty("MinLimit", minLimit); + connAttr.setProperty("MaxLimit", maxLimit); + connAttr.setProperty("InitialLimit", initialLimit); + connAttr.setProperty("TRANSACTION_ISOLATION","SERIALIZABLE"); + connAttr.setProperty("CONNECTION_TAG", dbConnectionName.toUpperCase()+"_CONNECTION"); + connAttr.setProperty("InactivityTimeout", "900"); + connAttr.setProperty("AbandonedConnectionTimeout", "600"); + connAttr.setProperty("PropertyCheckInterval", "60"); + connAttr.setProperty("ValidateConnection", "true"); + + + synchronized(this) + { + this.ds = dataSource; + + initialized = true; + LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); + } + +// } catch (SQLException exc) { +// initialized = false; +// StringBuffer sb = new StringBuffer(); +// sb.append("Failed to initialize MySQLDataSource<"); +// sb.append(dbConnectionName).append(">. Reason: "); +// sb.append(exc.getMessage()); +// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +//// throw new DBConfigException(e.getMessage()); + } catch (Exception exc) { + initialized = false; + StringBuffer sb = new StringBuffer(); + sb.append("Failed to initialize MySQLCachedDataSource <"); + sb.append(dbConnectionName).append(">. Reason: "); + sb.append(exc.getMessage()); + LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +// throw new DBConfigException(e.getMessage()); + } + } + + public final String getDbUrl() + { + return dbUrl; + } + + public final String getDbUserId() + { + return dbUserId; + } + + public final String getDbPasswd() + { + return dbPasswd; + } + + public static MySQLCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { + return new MySQLCachedDataSource(config); + } + + public String toString(){ + return getDbConnectionName(); + } + + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java new file mode 100644 index 000000000..de87fa7e8 --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.pm; + +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.TreeSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.atomic.AtomicLong; + +public class PollingWorker implements Runnable { + + private Logger LOGGER = LoggerFactory.getLogger(PollingWorker.class); + + private static PollingWorker self = null; + + private LinkedBlockingQueue tasks = new LinkedBlockingQueue(100); + private long interval = 1000L; + private Thread worker = null; + private AtomicLong[] counters = null; + private int[] bucketUnit = null; + private static boolean enabled = false; + private Timer timer = null; + + public static void post(long starttime){ + PollingWorker temp = self; + if(temp != null && enabled) { + temp.register(new TestSample(starttime)); + } + } + + public static void createInistance(Properties props){ + self = new PollingWorker(props); + } + + private PollingWorker(Properties ctxprops){ + if(ctxprops==null || ctxprops.getProperty("org.openecomp.sdnc.dblib.pm") == null){ + enabled = false; + } else { + if("true".equalsIgnoreCase((String)ctxprops.getProperty("org.openecomp.sdnc.dblib.pm"))){ + enabled = true; + } else { + enabled = false; + } + } + + interval = Long.parseLong(( ctxprops == null || ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.interval") == null) ? "60" : (String)ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.interval")); + // '0' bucket is to count exceptions + String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.sampling")==null) ? "0,2,5,10,20,50,100" : (String)ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.sampling")).split(","); + + if(enabled){ + bucketUnit = new int[sampling.length]; + for(int i=0, max = bucketUnit.length; i x.starttime) + return -1; + if(endtime > x.endtime) + return -1; + return 0; + } + return 1; + } + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java new file mode 100644 index 000000000..c58c9db7d --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java @@ -0,0 +1,237 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.pm; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; +import java.util.Observable; +import java.util.Observer; +import java.util.SortedSet; +import java.util.Timer; +import java.util.TimerTask; +import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicLong; + +import org.openecomp.sdnc.sli.resource.dblib.DBResourceObserver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SQLExecutionMonitor extends Observable +{ + private static Logger LOGGER = LoggerFactory.getLogger(SQLExecutionMonitor.class); + + final static long MILISECOND = 1000000L; + final static long SECOND = 1000L*MILISECOND; + + private final Timer timer; + // collection + private final SortedSet innerSet; + private SQLExecutionMonitorObserver parent = null; + private final AtomicLong completionCounter; + private boolean activeState = false; + private final long interval; + private final long initialDelay; + private final long EXPECTED_TIME_TO_COMPLETE; + private final long UNPROCESSED_FAILOVER_THRESHOLD; + + private final class MonitoringTask extends TimerTask + { + + public void run() + { + try { + TestObject testObj = new TestObject(); + testObj.setStartTime(testObj.getStartTime() - EXPECTED_TIME_TO_COMPLETE); + + // take a snapshot of the current task list + TestObject[] array = innerSet.toArray(new TestObject[0]); + SortedSet copyCurrent = new TreeSet(Arrays.asList(array)); + // get the list of the tasks that are older than the specified + // interval. + SortedSet unprocessed = copyCurrent.headSet(testObj); + + long succesfulCount = completionCounter.get(); + int unprocessedCount = unprocessed.size(); + + if (!unprocessed.isEmpty() && unprocessedCount > UNPROCESSED_FAILOVER_THRESHOLD && succesfulCount == 0) + { + // switch the Connection Pool to passive + setChanged(); + notifyObservers("Open JDBC requests=" + unprocessedCount+" in "+SQLExecutionMonitor.this.parent.getDbConnectionName()); + } + } catch (Exception exc) { + LOGGER.error("", exc); + } finally { + completionCounter.set(0L); + } + } + } + + public static class TestObject implements Comparable, Serializable + { + + private static final long serialVersionUID = 1L; + private long starttime; + private long randId; + + public TestObject() + { + starttime = System.nanoTime(); + } + + public long getStartTime() + { + return starttime; + } + + public void setStartTime(long newTime) + { + starttime = newTime; + } + + public int compareTo(TestObject o) + { + if( this == o) + return 0; + if(this.starttime > o.getStartTime()) + return 1; + if(this.starttime < o.getStartTime()) + return -1; + + if(this.hashCode() > o.hashCode()) + return 1; + if(this.hashCode() < o.hashCode()) + return -1; + + return 0; + } + + public String toString() + { + return Long.toString(starttime)+"#"+ this.hashCode(); + } + + public boolean equals(Object obj) + { + if (this == obj) + return true; + + return (obj instanceof TestObject + && starttime == ((TestObject) obj).getStartTime() + && hashCode() == ((TestObject) obj).hashCode()); + } + } + + public SQLExecutionMonitor(SQLExecutionMonitorObserver parent) + { + this.parent = parent; + completionCounter = new AtomicLong(0L); + interval = parent.getInterval(); + initialDelay = parent.getInitialDelay(); + this.UNPROCESSED_FAILOVER_THRESHOLD = parent.getUnprocessedFailoverThreshold(); + this.EXPECTED_TIME_TO_COMPLETE = parent.getExpectedCompletionTime()*MILISECOND; + + innerSet = Collections.synchronizedSortedSet(new TreeSet()); + timer = new Timer(); + } + + public void cleanup() + { + timer.cancel(); + } + + // registerRequest + public TestObject registerRequest() + { + if(activeState) + { + TestObject test = new TestObject(); + if(innerSet.add(test)) + return test; + } + return null; + } + + // deregisterSuccessfulReguest + public boolean deregisterReguest(TestObject test) + { + if(test == null) + return false; + // remove from the collection + if(innerSet.remove(test) && activeState) + { + completionCounter.incrementAndGet(); + return true; + } + return false; + } + + public void terminate() { + timer.cancel(); + } + + /** + * @return the parent + */ + public final Object getParent() { + return parent; + } + + public void addObserver(Observer observer) + { + if(observer instanceof DBResourceObserver) + { + DBResourceObserver dbObserver = (DBResourceObserver)observer; + if(dbObserver.isMonitorDbResponse()) + { + if(countObservers() == 0) + { + TimerTask remindTask = new MonitoringTask(); + timer.schedule(remindTask, initialDelay, interval); + activeState = true; + } + } + } + super.addObserver(observer); + } + + public void deleteObserver(Observer observer) + { + super.deleteObserver(observer); + if(observer instanceof DBResourceObserver) + { + DBResourceObserver dbObserver = (DBResourceObserver)observer; + if(dbObserver.isMonitorDbResponse()) + { + if(countObservers() == 0) + { + timer.cancel(); + activeState = false; + } + } + } + } + + public final int getPorcessedConnectionsCount() { + return innerSet.size(); + } +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java new file mode 100644 index 000000000..1f329750b --- /dev/null +++ b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openecomp + * ================================================================================ + * Copyright (C) 2016 - 2017 AT&T + * ================================================================================ + * 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.openecomp.sdnc.sli.resource.dblib.pm; + +public interface SQLExecutionMonitorObserver { + public String getDbConnectionName(); + + public long getInterval(); + public void setInterval(long value); + + public long getInitialDelay(); + public void setInitialDelay(long value); + + public long getExpectedCompletionTime(); + public void setExpectedCompletionTime(long value); + + public long getUnprocessedFailoverThreshold(); + public void setUnprocessedFailoverThreshold(long value); +} diff --git a/dblib/provider/src/main/resources/dblib.properties b/dblib/provider/src/main/resources/dblib.properties new file mode 100755 index 000000000..ac295c78d --- /dev/null +++ b/dblib/provider/src/main/resources/dblib.properties @@ -0,0 +1,13 @@ +org.openecomp.sdnc.sli.dbtype=jdbc +org.openecomp.sdnc.sli.jdbc.hosts=sdnctldb01,sdnctldb02 +org.openecomp.sdnc.sli.jdbc.url=jdbc:mysql://DBHOST:3306/sdnctl +org.openecomp.sdnc.sli.jdbc.database=sdnctl +org.openecomp.sdnc.sli.jdbc.user={user for sdnctl} +org.openecomp.sdnc.sli.jdbc.password={password for sdnctl} +org.openecomp.sdnc.sli.jdbc.connection.name=sdnctldb01 + +org.openecomp.sdnc.sli.jdbc.connection.timeout=50 +org.openecomp.sdnc.sli.jdbc.request.timeout=100 +org.openecomp.sdnc.sli.jdbc.limit.init=10 +org.openecomp.sdnc.sli.jdbc.limit.min=10 +org.openecomp.sdnc.sli.jdbc.limit.max=20 -- cgit 1.2.3-korg From 32f16144e17d2df0831f14d9e65a83756a6ef844 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Thu, 27 Jul 2017 16:32:20 -0400 Subject: Refactor dblib Changed openecomp references in dblib, filters and sli to onap. Note: these must be committed together to get a clean compile. Issue: CCSDK-11 Change-Id: Ibe0f64fb20f3ae9cdda2f7ea969ca722bbde0d15 Signed-off-by: Dan Timoney --- dblib/pom.xml | 4 +- dblib/provider/pom.xml | 9 +- .../ccsdk/sli/core/dblib/CachedDataSource.java | 617 ++++++++++ .../sli/core/dblib/CachedDataSourceFactory.java | 45 + .../ccsdk/sli/core/dblib/DBConfigException.java | 47 + .../sli/core/dblib/DBLIBResourceActivator.java | 130 +++ .../onap/ccsdk/sli/core/dblib/DBLibConnection.java | 390 +++++++ .../onap/ccsdk/sli/core/dblib/DBLibException.java | 39 + .../ccsdk/sli/core/dblib/DBResourceManager.java | 863 ++++++++++++++ .../ccsdk/sli/core/dblib/DBResourceObserver.java | 27 + .../onap/ccsdk/sli/core/dblib/DataAccessor.java | 33 + .../ccsdk/sli/core/dblib/DataSourceComparator.java | 33 + .../onap/ccsdk/sli/core/dblib/DbLibService.java | 46 + .../core/dblib/DblibConfigurationException.java | 45 + .../dblib/NoAvailableConnectionsException.java | 36 + .../core/dblib/TerminatingCachedDataSource.java | 82 ++ .../sli/core/dblib/config/BaseDBConfiguration.java | 104 ++ .../ccsdk/sli/core/dblib/config/DbConfigPool.java | 56 + .../sli/core/dblib/config/JDBCConfiguration.java | 31 + .../factory/AbstractDBResourceManagerFactory.java | 39 + .../factory/AbstractResourceManagerFactory.java | 104 ++ .../sli/core/dblib/factory/DBConfigFactory.java | 99 ++ .../dblib/factory/FactoryNotDefinedException.java | 37 + .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 249 ++++ .../dblib/jdbc/JdbcDbResourceManagerFactory.java | 186 +++ .../sli/core/dblib/jdbc/MySQLCachedDataSource.java | 217 ++++ .../ccsdk/sli/core/dblib/pm/PollingWorker.java | 217 ++++ .../sli/core/dblib/pm/SQLExecutionMonitor.java | 237 ++++ .../core/dblib/pm/SQLExecutionMonitorObserver.java | 37 + .../sdnc/sli/resource/dblib/CachedDataSource.java | 616 ---------- .../resource/dblib/CachedDataSourceFactory.java | 45 - .../sdnc/sli/resource/dblib/DBConfigException.java | 47 - .../sli/resource/dblib/DBLIBResourceActivator.java | 130 --- .../sdnc/sli/resource/dblib/DBLibConnection.java | 390 ------- .../sdnc/sli/resource/dblib/DBLibException.java | 39 - .../sdnc/sli/resource/dblib/DBResourceManager.java | 862 -------------- .../sli/resource/dblib/DBResourceObserver.java | 27 - .../sdnc/sli/resource/dblib/DataAccessor.java | 33 - .../sli/resource/dblib/DataSourceComparator.java | 33 - .../sdnc/sli/resource/dblib/DbLibService.java | 46 - .../dblib/DblibConfigurationException.java | 45 - .../dblib/NoAvailableConnectionsException.java | 36 - .../dblib/TerminatingCachedDataSource.java | 82 -- .../resource/dblib/config/BaseDBConfiguration.java | 104 -- .../sli/resource/dblib/config/DbConfigPool.java | 56 - .../resource/dblib/config/JDBCConfiguration.java | 31 - .../factory/AbstractDBResourceManagerFactory.java | 39 - .../factory/AbstractResourceManagerFactory.java | 104 -- .../resource/dblib/factory/DBConfigFactory.java | 100 -- .../dblib/factory/FactoryNotDefinedException.java | 37 - .../dblib/jdbc/JdbcDBCachedDataSource.java | 249 ---- .../dblib/jdbc/JdbcDbResourceManagerFactory.java | 186 --- .../resource/dblib/jdbc/MySQLCachedDataSource.java | 217 ---- .../sdnc/sli/resource/dblib/pm/PollingWorker.java | 217 ---- .../sli/resource/dblib/pm/SQLExecutionMonitor.java | 237 ---- .../dblib/pm/SQLExecutionMonitorObserver.java | 37 - dblib/provider/src/main/resources/dblib.properties | 24 +- filters/features/src/main/resources/features.xml | 5 +- .../src/assembly/assemble_installer_zip.xml | 5 +- .../src/assembly/assemble_mvnrepo_zip.xml | 5 +- .../src/main/resources/scripts/install-feature.sh | 5 +- filters/provider/pom.xml | 13 +- .../org/onap/ccsdk/sli/core/filters/Activator.java | 62 + .../org/onap/ccsdk/sli/core/filters/LogFilter.java | 221 ++++ .../filters/RequestResponseDbLoggingFilter.java | 297 +++++ .../core/filters/RequestResponseLoggingFilter.java | 288 +++++ .../java/org/openecomp/sdnc/filters/Activator.java | 63 -- .../java/org/openecomp/sdnc/filters/LogFilter.java | 222 ---- .../filters/RequestResponseDbLoggingFilter.java | 297 ----- .../sdnc/filters/RequestResponseLoggingFilter.java | 289 ----- pom.xml | 5 +- sli/common/pom.xml | 6 +- .../org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 | 67 ++ .../antlr4/org/openecomp/sdnc/sli/ExprGrammar.g4 | 66 -- .../ccsdk/sli/core/sli/BreakNodeException.java | 45 + .../ccsdk/sli/core/sli/ConfigurationException.java | 44 + .../sli/core/sli/DuplicateValueException.java | 44 + .../org/onap/ccsdk/sli/core/sli/MessageWriter.java | 301 +++++ .../org/onap/ccsdk/sli/core/sli/MetricLogger.java | 300 +++++ .../onap/ccsdk/sli/core/sli/SvcLogicAdaptor.java | 41 + .../org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java | 173 +++ .../sli/core/sli/SvcLogicBinaryExpression.java | 148 +++ .../onap/ccsdk/sli/core/sli/SvcLogicContext.java | 247 ++++ .../ccsdk/sli/core/sli/SvcLogicDblibStore.java | 532 +++++++++ .../onap/ccsdk/sli/core/sli/SvcLogicException.java | 45 + .../ccsdk/sli/core/sli/SvcLogicExprListener.java | 315 ++++++ .../core/sli/SvcLogicExprParserErrorListener.java | 43 + .../ccsdk/sli/core/sli/SvcLogicExpression.java | 50 + .../sli/core/sli/SvcLogicExpressionFactory.java | 98 ++ .../ccsdk/sli/core/sli/SvcLogicFunctionCall.java | 79 ++ .../org/onap/ccsdk/sli/core/sli/SvcLogicGraph.java | 183 +++ .../ccsdk/sli/core/sli/SvcLogicJavaPlugin.java | 33 + .../onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java | 894 +++++++++++++++ .../org/onap/ccsdk/sli/core/sli/SvcLogicNode.java | 455 ++++++++ .../onap/ccsdk/sli/core/sli/SvcLogicParser.java | 597 ++++++++++ .../sli/core/sli/SvcLogicParserException.java | 42 + .../onap/ccsdk/sli/core/sli/SvcLogicRecorder.java | 29 + .../onap/ccsdk/sli/core/sli/SvcLogicResource.java | 52 + .../org/onap/ccsdk/sli/core/sli/SvcLogicStore.java | 36 + .../ccsdk/sli/core/sli/SvcLogicStoreFactory.java | 95 ++ .../ccsdk/sli/core/sli/SvcLogicVariableTerm.java | 76 ++ .../org/openecomp/sdnc/sli/BreakNodeException.java | 46 - .../openecomp/sdnc/sli/ConfigurationException.java | 45 - .../sdnc/sli/DuplicateValueException.java | 45 - .../java/org/openecomp/sdnc/sli/MessageWriter.java | 302 ----- .../java/org/openecomp/sdnc/sli/MetricLogger.java | 301 ----- .../org/openecomp/sdnc/sli/SvcLogicAdaptor.java | 42 - .../java/org/openecomp/sdnc/sli/SvcLogicAtom.java | 174 --- .../sdnc/sli/SvcLogicBinaryExpression.java | 149 --- .../org/openecomp/sdnc/sli/SvcLogicContext.java | 248 ---- .../org/openecomp/sdnc/sli/SvcLogicDblibStore.java | 533 --------- .../org/openecomp/sdnc/sli/SvcLogicException.java | 46 - .../openecomp/sdnc/sli/SvcLogicExprListener.java | 316 ------ .../sdnc/sli/SvcLogicExprParserErrorListener.java | 44 - .../org/openecomp/sdnc/sli/SvcLogicExpression.java | 51 - .../sdnc/sli/SvcLogicExpressionFactory.java | 99 -- .../openecomp/sdnc/sli/SvcLogicFunctionCall.java | 80 -- .../java/org/openecomp/sdnc/sli/SvcLogicGraph.java | 184 --- .../org/openecomp/sdnc/sli/SvcLogicJavaPlugin.java | 34 - .../org/openecomp/sdnc/sli/SvcLogicJdbcStore.java | 895 --------------- .../java/org/openecomp/sdnc/sli/SvcLogicNode.java | 456 -------- .../org/openecomp/sdnc/sli/SvcLogicParser.java | 598 ---------- .../sdnc/sli/SvcLogicParserException.java | 43 - .../org/openecomp/sdnc/sli/SvcLogicRecorder.java | 30 - .../org/openecomp/sdnc/sli/SvcLogicResource.java | 53 - .../java/org/openecomp/sdnc/sli/SvcLogicStore.java | 37 - .../openecomp/sdnc/sli/SvcLogicStoreFactory.java | 96 -- .../openecomp/sdnc/sli/SvcLogicVariableTerm.java | 77 -- sli/common/src/main/resources/crAseNetwork.sql | 5 +- .../ccsdk/sli/core/sli/SvcLogicContextTest.java | 68 ++ .../sli/core/sli/SvcLogicExpressionParserTest.java | 68 ++ .../ccsdk/sli/core/sli/SvcLogicParserTest.java | 162 +++ .../openecomp/sdnc/sli/SvcLogicContextTest.java | 69 -- .../sdnc/sli/SvcLogicExpressionParserTest.java | 69 -- .../org/openecomp/sdnc/sli/SvcLogicParserTest.java | 163 --- .../test/resources/EvcActivateSvcLogic_v100.xml | 5 +- .../src/test/resources/EvcPortSvcLogic_v100.xml | 5 +- .../test/resources/ReleasePortSvcLogic_v101.xml | 5 +- .../src/test/resources/bad_neutron_logic_v11.xml | 5 +- sli/common/src/test/resources/mergetest.xml | 5 +- .../src/test/resources/neutron_logic_v10.xml | 5 +- sli/common/src/test/resources/nonsense.xml | 5 +- .../src/test/resources/simplelogger.properties | 5 +- sli/common/src/test/resources/svclogic.properties | 5 +- sli/common/src/test/resources/svclogic.sh | 5 +- sli/features/src/main/resources/features.xml | 5 +- .../src/assembly/assemble_installer_zip.xml | 5 +- .../src/assembly/assemble_mvnrepo_zip.xml | 5 +- .../src/main/resources/scripts/install-feature.sh | 5 +- sli/pom.xml | 2 +- sli/provider/pom.xml | 6 +- .../sli/core/sli/provider/BlockNodeExecutor.java | 74 ++ .../sli/core/sli/provider/BreakNodeExecutor.java | 41 + .../sli/core/sli/provider/CallNodeExecutor.java | 164 +++ .../core/sli/provider/ConfigureNodeExecutor.java | 247 ++++ .../sli/core/sli/provider/DeleteNodeExecutor.java | 100 ++ .../sli/core/sli/provider/ExecuteNodeExecutor.java | 160 +++ .../sli/core/sli/provider/ExistsNodeExecutor.java | 104 ++ .../sli/core/sli/provider/ForNodeExecutor.java | 108 ++ .../core/sli/provider/GetResourceNodeExecutor.java | 133 +++ .../core/sli/provider/IsAvailableNodeExecutor.java | 102 ++ .../ccsdk/sli/core/sli/provider/MdsalHelper.java | 1185 +++++++++++++++++++ .../sli/core/sli/provider/NotifyNodeExecutor.java | 101 ++ .../sli/core/sli/provider/RecordNodeExecutor.java | 118 ++ .../sli/core/sli/provider/ReleaseNodeExecutor.java | 99 ++ .../sli/core/sli/provider/ReserveNodeExecutor.java | 113 ++ .../sli/core/sli/provider/ReturnNodeExecutor.java | 77 ++ .../sli/core/sli/provider/SaveNodeExecutor.java | 141 +++ .../sli/core/sli/provider/SetNodeExecutor.java | 188 ++++ .../sli/core/sli/provider/SvcLogicActivator.java | 224 ++++ .../core/sli/provider/SvcLogicAdaptorFactory.java | 85 ++ .../sli/provider/SvcLogicExpressionResolver.java | 604 ++++++++++ .../core/sli/provider/SvcLogicNodeExecutor.java | 109 ++ .../sli/core/sli/provider/SvcLogicService.java | 75 ++ .../sli/core/sli/provider/SvcLogicServiceImpl.java | 272 +++++ .../sli/core/sli/provider/SwitchNodeExecutor.java | 62 + .../sli/core/sli/provider/UpdateNodeExecutor.java | 135 +++ .../sli/core/sli/provider/WhileNodeExecutor.java | 74 ++ .../sdnc/sli/provider/BlockNodeExecutor.java | 75 -- .../sdnc/sli/provider/BreakNodeExecutor.java | 42 - .../sdnc/sli/provider/CallNodeExecutor.java | 165 --- .../sdnc/sli/provider/ConfigureNodeExecutor.java | 248 ---- .../sdnc/sli/provider/DeleteNodeExecutor.java | 101 -- .../sdnc/sli/provider/ExecuteNodeExecutor.java | 161 --- .../sdnc/sli/provider/ExistsNodeExecutor.java | 105 -- .../sdnc/sli/provider/ForNodeExecutor.java | 109 -- .../sdnc/sli/provider/GetResourceNodeExecutor.java | 134 --- .../sdnc/sli/provider/IsAvailableNodeExecutor.java | 103 -- .../openecomp/sdnc/sli/provider/MdsalHelper.java | 1186 -------------------- .../sdnc/sli/provider/NotifyNodeExecutor.java | 102 -- .../sdnc/sli/provider/RecordNodeExecutor.java | 119 -- .../sdnc/sli/provider/ReleaseNodeExecutor.java | 100 -- .../sdnc/sli/provider/ReserveNodeExecutor.java | 114 -- .../sdnc/sli/provider/ReturnNodeExecutor.java | 78 -- .../sdnc/sli/provider/SaveNodeExecutor.java | 142 --- .../sdnc/sli/provider/SetNodeExecutor.java | 189 ---- .../sdnc/sli/provider/SvcLogicActivator.java | 225 ---- .../sdnc/sli/provider/SvcLogicAdaptorFactory.java | 86 -- .../sli/provider/SvcLogicExpressionResolver.java | 605 ---------- .../sdnc/sli/provider/SvcLogicNodeExecutor.java | 110 -- .../sdnc/sli/provider/SvcLogicService.java | 76 -- .../sdnc/sli/provider/SvcLogicServiceImpl.java | 273 ----- .../sdnc/sli/provider/SwitchNodeExecutor.java | 63 -- .../sdnc/sli/provider/UpdateNodeExecutor.java | 136 --- .../sdnc/sli/provider/WhileNodeExecutor.java | 75 -- .../ccsdk/sli/core/sli/provider/BadPlugin.java | 55 + .../core/sli/provider/ExecuteNodeExecutorTest.java | 58 + .../sli/core/sli/provider/LunchSelectorPlugin.java | 77 ++ .../sli/core/sli/provider/MdsalHelperTest.java | 42 + .../core/sli/provider/MdsalHelperTesterUtil.java | 36 + .../ccsdk/sli/core/sli/provider/PluginTest.java | 107 ++ .../provider/SvcLogicExpressionResolverTest.java | 122 ++ .../sli/provider/SvcLogicGraphExecutorTest.java | 211 ++++ .../sli/core/sli/provider/VoidDummyPlugin.java | 37 + .../org/openecomp/sdnc/sli/provider/BadPlugin.java | 56 - .../sdnc/sli/provider/ExecuteNodeExecutorTest.java | 57 - .../sdnc/sli/provider/LunchSelectorPlugin.java | 78 -- .../sdnc/sli/provider/MdsalHelperTest.java | 43 - .../sdnc/sli/provider/MdsalHelperTesterUtil.java | 37 - .../openecomp/sdnc/sli/provider/PluginTest.java | 106 -- .../provider/SvcLogicExpressionResolverTest.java | 123 -- .../sli/provider/SvcLogicGraphExecutorTest.java | 212 ---- .../sdnc/sli/provider/VoidDummyPlugin.java | 38 - .../src/test/resources/l3sdn_logic_v10.xml | 5 +- .../src/test/resources/simplelogger.properties | 5 +- .../src/test/resources/svclogic.properties | 5 +- sli/recording/pom.xml | 4 +- .../ccsdk/sli/core/sli/recording/FileRecorder.java | 116 ++ .../sli/core/sli/recording/RecordingActivator.java | 74 ++ .../sli/core/sli/recording/Slf4jRecorder.java | 129 +++ .../openecomp/sdnc/sli/recording/FileRecorder.java | 117 -- .../sdnc/sli/recording/RecordingActivator.java | 75 -- .../sdnc/sli/recording/Slf4jRecorder.java | 130 --- .../src/main/resources/svclogic.properties | 5 +- .../features/src/main/resources/features.xml | 5 +- .../src/assembly/assemble_installer_zip.xml | 5 +- .../src/assembly/assemble_mvnrepo_zip.xml | 5 +- .../src/main/resources/scripts/install-feature.sh | 5 +- .../openecomp/sdnc/sli/SliPluginUtils/DME2.java | 11 +- .../sdnc/sli/SliPluginUtils/SliPluginUtils.java | 13 +- .../SliPluginUtils/SliPluginUtilsActivator.java | 5 +- .../sdnc/sli/SliPluginUtils/SliStringUtils.java | 11 +- .../sli/SliPluginUtils/SvcLogicContextList.java | 9 +- .../sli/SliPluginUtils/SvcLogicContextObject.java | 7 +- .../SliPluginUtils/commondatastructures/YesNo.java | 5 +- .../commondatastructures/package-info.java | 5 +- .../sli/SliPluginUtils/CheckParametersTest.java | 9 +- .../sdnc/sli/SliPluginUtils/Dme2Test.java | 5 +- .../SliPluginUtils_StaticFunctionsTest.java | 9 +- .../SliPluginUtils/SliPluginUtils_ctxSortList.java | 9 +- .../SliPluginUtils_ctxSortListTest.java | 9 +- .../sli/SliPluginUtils/SliStringUtilsTest.java | 9 +- .../SliPluginUtils/SvcLogicContextListTest.java | 7 +- sliapi/features/src/main/resources/features.xml | 5 +- .../src/assembly/assemble_installer_zip.xml | 5 +- .../src/assembly/assemble_mvnrepo_zip.xml | 5 +- .../src/main/resources/scripts/install-feature.sh | 5 +- .../impl/rev140523/SliapiProviderModule.java | 5 +- .../rev140523/SliapiProviderModuleFactory.java | 5 +- .../org/openecomp/sdnc/sliapi/SliapiHelper.java | 7 +- .../org/openecomp/sdnc/sliapi/sliapiProvider.java | 7 +- .../src/main/resources/initial/sliapi-provider.xml | 5 +- src/site/apt/nodes.apt | 5 +- src/site/site.xml | 5 +- 264 files changed, 16399 insertions(+), 16527 deletions(-) create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBConfigException.java create 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/DBLibConnection.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibException.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationException.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsException.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/JDBCConfiguration.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java create mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/MySQLCachedDataSource.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java delete mode 100644 dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java create mode 100644 filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/Activator.java create mode 100644 filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/LogFilter.java create mode 100644 filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java create mode 100644 filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java delete mode 100644 filters/provider/src/main/java/org/openecomp/sdnc/filters/Activator.java delete mode 100644 filters/provider/src/main/java/org/openecomp/sdnc/filters/LogFilter.java delete mode 100644 filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseDbLoggingFilter.java delete mode 100644 filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseLoggingFilter.java create mode 100755 sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 delete mode 100755 sli/common/src/main/antlr4/org/openecomp/sdnc/sli/ExprGrammar.g4 create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/BreakNodeException.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ConfigurationException.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/DuplicateValueException.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MetricLogger.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAdaptor.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicBinaryExpression.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicContext.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicDblibStore.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicException.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprListener.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprParserErrorListener.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicFunctionCall.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicGraph.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserException.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicRecorder.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStore.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStoreFactory.java create mode 100644 sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicVariableTerm.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/BreakNodeException.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/ConfigurationException.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/DuplicateValueException.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/MessageWriter.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/MetricLogger.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAdaptor.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAtom.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicBinaryExpression.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicContext.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicDblibStore.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicException.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprListener.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprParserErrorListener.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpression.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpressionFactory.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicFunctionCall.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicGraph.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJavaPlugin.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJdbcStore.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicNode.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParser.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParserException.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicRecorder.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicResource.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStore.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStoreFactory.java delete mode 100644 sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicVariableTerm.java create mode 100644 sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java create mode 100644 sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java create mode 100644 sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserTest.java delete mode 100644 sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicContextTest.java delete mode 100644 sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicExpressionParserTest.java delete mode 100644 sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicParserTest.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BlockNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BreakNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ConfigureNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/DeleteNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExistsNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/GetResourceNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/IsAvailableNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/NotifyNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/RecordNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReleaseNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReserveNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReturnNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SaveNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SetNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicAdaptorFactory.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolver.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SwitchNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/UpdateNodeExecutor.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/WhileNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BlockNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BreakNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/CallNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ConfigureNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/DeleteNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExistsNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ForNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/GetResourceNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/IsAvailableNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/MdsalHelper.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/NotifyNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/RecordNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReleaseNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReserveNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReturnNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SaveNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SetNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicActivator.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicAdaptorFactory.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolver.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicService.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicServiceImpl.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SwitchNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/UpdateNodeExecutor.java delete mode 100644 sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/WhileNodeExecutor.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/BadPlugin.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/LunchSelectorPlugin.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTesterUtil.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/PluginTest.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolverTest.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicGraphExecutorTest.java create mode 100644 sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/VoidDummyPlugin.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/BadPlugin.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutorTest.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/LunchSelectorPlugin.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTest.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTesterUtil.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/PluginTest.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolverTest.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicGraphExecutorTest.java delete mode 100644 sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/VoidDummyPlugin.java create mode 100644 sli/recording/src/main/java/org/onap/ccsdk/sli/core/sli/recording/FileRecorder.java create mode 100644 sli/recording/src/main/java/org/onap/ccsdk/sli/core/sli/recording/RecordingActivator.java create mode 100644 sli/recording/src/main/java/org/onap/ccsdk/sli/core/sli/recording/Slf4jRecorder.java delete mode 100644 sli/recording/src/main/java/org/openecomp/sdnc/sli/recording/FileRecorder.java delete mode 100644 sli/recording/src/main/java/org/openecomp/sdnc/sli/recording/RecordingActivator.java delete mode 100644 sli/recording/src/main/java/org/openecomp/sdnc/sli/recording/Slf4jRecorder.java (limited to 'dblib/provider/src') diff --git a/dblib/pom.xml b/dblib/pom.xml index 722b2d7c6..775ff0591 100755 --- a/dblib/pom.xml +++ b/dblib/pom.xml @@ -34,9 +34,9 @@ 2016 - AT&T + ONAP - openecomp + onap diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index 078c75499..41d383ef0 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -63,12 +63,9 @@ true - org.openecomp.sdnc.sli.resource.dblib - org.openecomp.sdnc.sli.resource.dblib.DBLIBResourceActivator - org.openecomp.sdnc.sli.resource.dblib;version=${project.version} - + 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/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java new file mode 100644 index 000000000..9dc262d07 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -0,0 +1,617 @@ +/*- + * ============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.Closeable; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Observer; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetProvider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor.TestObject; + +import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; + + +/** + * @version $Revision: 1.13 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ + +public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver +{ + private static Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); + + protected static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; + + protected long CONN_REQ_TIMEOUT = 30L; + protected long DATA_REQ_TIMEOUT = 100L; + + private final SQLExecutionMonitor monitor; + protected DataSource ds = null; + protected String connectionName = null; + protected boolean initialized = false; + + private long interval = 1000; + private long initialDelay = 5000; + private long expectedCompletionTime = 50L; + private boolean canTakeOffLine = true; + private long unprocessedFailoverThreshold = 3L; + + private long nextErrorReportTime = 0L; + + private String globalHostName = null; + + + public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException + { + configure(jdbcElem); + monitor = new SQLExecutionMonitor(this); + } + + protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + /* (non-Javadoc) + * @see javax.sql.DataSource#getConnection() + */ + public Connection getConnection() throws SQLException + { + return ds.getConnection(); + } + + public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable + { + TestObject testObject = null; + testObject = monitor.registerRequest(); + + Connection connection = null; + try { + connection = this.getConnection(); + if(connection == null ) { + throw new SQLException("Connection invalid"); + } + if(LOGGER.isDebugEnabled()) + LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); + return executePreparedStatement(connection, statement, arguments, true); + } finally { + try { + if(connection != null && !connection.isClosed()) { + connection.close(); + } + } catch(Throwable exc) { + // the exception not monitored + } finally { + connection = null; + } + + monitor.deregisterReguest(testObject); + } + } + + public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable + { + TestObject testObject = null; + testObject = monitor.registerRequest(); + + Connection connection = null; + try { + connection = this.getConnection(); + if(connection == null ) { + throw new SQLException("Connection invalid"); + } + if(LOGGER.isDebugEnabled()) + LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); + return executeUpdatePreparedStatement(connection, statement, arguments, true); + } finally { + try { + if(connection != null && !connection.isClosed()) { + connection.close(); + } + } catch(Throwable exc) { + // the exception not monitored + } finally { + connection = null; + } + + monitor.deregisterReguest(testObject); + } + } + + CachedRowSet executePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable + { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL Statement: "+ statement); + if(arguments != null && !arguments.isEmpty()) { + LOGGER.debug("Argunments: "+ Arrays.toString(arguments.toArray())); + } + } + + ResultSet rs = null; + try { + data = RowSetProvider.newFactory().createCachedRowSet(); + PreparedStatement ps = conn.prepareStatement(statement); + if(arguments != null) + { + for(int i = 0, max = arguments.size(); i < max; i++){ + ps.setObject(i+1, arguments.get(i)); + } + } + rs = ps.executeQuery(); + data.populate(rs); + // Point the rowset Cursor to the start + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); } + } catch(SQLException exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + try { conn.rollback(); } catch(Throwable thr){} + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; + } catch(Throwable exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; // new SQLException(exc); + } finally { + + try { + if(rs != null){ + rs.close(); + rs = null; + } + } catch(Exception exc){ + + } + try { + if(conn != null && close){ + conn.close(); + conn = null; + } + } catch(Exception exc){ + + } + } + + return data; + } + + boolean executeUpdatePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + + int rs = -1; + try { + data = RowSetProvider.newFactory().createCachedRowSet(); + PreparedStatement ps = conn.prepareStatement(statement); + if(arguments != null) + { + for(int i = 0, max = arguments.size(); i < max; i++){ + if(arguments.get(i) instanceof Blob) { + ps.setBlob(i+1, (Blob)arguments.get(i)); + } else if(arguments.get(i) instanceof Timestamp) { + ps.setTimestamp(i+1, (Timestamp)arguments.get(i)); + } else if(arguments.get(i) instanceof Integer) { + ps.setInt(i+1, (Integer)arguments.get(i)); + } else if(arguments.get(i) instanceof Long) { + ps.setLong(i+1, (Long)arguments.get(i)); + } else if(arguments.get(i) instanceof Date) { + ps.setDate(i+1, (Date)arguments.get(i)); + } else { + ps.setObject(i+1, arguments.get(i)); + } + } + } + rs = ps.executeUpdate(); + // Point the rowset Cursor to the start + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); + } + } catch(SQLException exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + try { conn.rollback(); } catch(Throwable thr){} + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; + } catch(Throwable exc){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); + } + if(arguments != null && !arguments.isEmpty()) { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); + } else { + LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); + } + throw exc; // new SQLException(exc); + } finally { + try { + if(conn != null && close){ + conn.close(); + conn = null; + } + } catch(Exception exc){ + + } + } + + return true; + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) + */ + public Connection getConnection(String username, String password) + throws SQLException + { + return ds.getConnection(username, password); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getLogWriter() + */ + public PrintWriter getLogWriter() throws SQLException + { + return ds.getLogWriter(); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getLoginTimeout() + */ + public int getLoginTimeout() throws SQLException + { + return ds.getLoginTimeout(); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) + */ + public void setLogWriter(PrintWriter out) throws SQLException + { + ds.setLogWriter(out); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#setLoginTimeout(int) + */ + public void setLoginTimeout(int seconds) throws SQLException + { + ds.setLoginTimeout(seconds); + } + + + public final String getDbConnectionName(){ + return connectionName; + } + + protected final void setDbConnectionName(String name) { + this.connectionName = name; + } + + public void cleanUp(){ + if(ds != null && ds instanceof Closeable) { + try { + ((Closeable)ds).close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage()); + } + } + ds = null; + monitor.deleteObservers(); + monitor.cleanup(); + } + + public boolean isInitialized() { + return initialized; + } + + protected boolean testConnection(){ + return testConnection(false); + } + + protected boolean testConnection(boolean error_level){ + Connection conn = null; + ResultSet rs = null; + Statement stmt = null; + try + { + Boolean readOnly = null; + String hostname = null; + conn = this.getConnection(); + stmt = conn.createStatement(); + rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); //("SELECT 1 FROM DUAL"); //"select BANNER from SYS.V_$VERSION" + while(rs.next()) + { + readOnly = rs.getBoolean(1); + hostname = rs.getString(2); + + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("SQL DataSource <"+getDbConnectionName() + "> connected to " + hostname + ", read-only is " + readOnly + ", tested successfully "); + } + } + + } catch (Throwable exc) { + if(error_level) { + LOGGER.error("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } else { + LOGGER.info("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } + return false; + } finally { + if(rs != null) { + try { + rs.close(); + rs = null; + } catch (SQLException e) { + } + } + if(stmt != null) { + try { + stmt.close(); + stmt = null; + } catch (SQLException e) { + } + } + if(conn !=null){ + try { + conn.close(); + conn = null; + } catch (SQLException e) { + } + } + } + return true; + } + + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public T unwrap(Class iface) throws SQLException { + return null; + } + + @SuppressWarnings("deprecation") + public void setConnectionCachingEnabled(boolean state) + { +// if(ds != null && ds instanceof OracleDataSource) +// try { +// ((OracleDataSource)ds).setConnectionCachingEnabled(true); +// } catch (SQLException exc) { +// LOGGER.warn("", exc); +// } + } + + public void addObserver(Observer observer) { + monitor.addObserver(observer); + } + + public void deleteObserver(Observer observer) { + monitor.deleteObserver(observer); + } + + public long getInterval() { + return interval; + } + + public long getInitialDelay() { + return initialDelay; + } + + public void setInterval(long value) { + interval = value; + } + + public void setInitialDelay(long value) { + initialDelay = value; + } + + public long getExpectedCompletionTime() { + return expectedCompletionTime; + } + + public void setExpectedCompletionTime(long value) { + expectedCompletionTime = value; + } + + public long getUnprocessedFailoverThreshold() { + return unprocessedFailoverThreshold; + } + + public void setUnprocessedFailoverThreshold(long value) { + this.unprocessedFailoverThreshold = value; + } + + public boolean canTakeOffLine() { + return canTakeOffLine; + } + + public void blockImmediateOffLine() { + canTakeOffLine = false; + final Thread offLineTimer = new Thread() + { + public void run(){ + try { + Thread.sleep(30000L); + }catch(Throwable exc){ + + }finally{ + canTakeOffLine = true; + } + } + }; + offLineTimer.setDaemon(true); + offLineTimer.start(); + } + + /** + * @return the monitor + */ + final SQLExecutionMonitor getMonitor() { + return monitor; + } + + protected boolean isSlave() throws PoolExhaustedException, MySQLNonTransientConnectionException { + CachedRowSet rs = null; + boolean isSlave = true; + String hostname = "UNDETERMINED"; + try { + boolean localSlave = true; + rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList()); + while(rs.next()) { + localSlave = rs.getBoolean(1); + hostname = rs.getString(2); + } + isSlave = localSlave; + } catch(PoolExhaustedException | MySQLNonTransientConnectionException peexc){ + throw peexc; + } catch (SQLException e) { + LOGGER.error("", e); + isSlave = true; + } catch (Throwable e) { + LOGGER.error("", e); + isSlave = true; + } + if(isSlave){ + LOGGER.debug("SQL SLAVE : "+connectionName + " on server " + hostname); + } else { + LOGGER.debug("SQL MASTER : "+connectionName + " on server " + hostname); + } + return isSlave; + } + + public boolean isFabric() { + return false; + } + + protected boolean lockTable(Connection conn, String tableName) { + boolean retValue = false; + Statement lock = null; + try { + if(tableName != null) { + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); + if("SVC_LOGIC".equals(tableName)) { + Exception e = new Exception(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + LOGGER.debug(sw.toString()); + } + } + lock = conn.createStatement(); + lock.execute("LOCK TABLES " + tableName + " WRITE"); + retValue = true; + } + } catch(Exception exc){ + LOGGER.error("", exc); + retValue = false; + } finally { + try { + lock.close(); + } catch(Exception exc) { + + } + } + return retValue; + } + + protected boolean unlockTable(Connection conn) { + boolean retValue = false; + Statement lock = null; + try { + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); + } + lock = conn.createStatement(); + retValue = lock.execute("UNLOCK TABLES"); + } catch(Exception exc){ + LOGGER.error("", exc); + retValue = false; + } finally { + try { + lock.close(); + } catch(Exception exc) { + + } + } + return retValue; + } + + public void getPoolInfo(boolean allocation) { + + } + + public long getNextErrorReportTime() { + return nextErrorReportTime; + } + + public void setNextErrorReportTime(long nextTime) { + this.nextErrorReportTime = nextTime; + } + + public void setGlobalHostName(String hostname) { + this.globalHostName = hostname; + } + + public String getGlobalHostName() { + return globalHostName; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java new file mode 100644 index 000000000..07e3dfab1 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.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; + + +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.onap.ccsdk.sli.core.dblib.jdbc.JdbcDBCachedDataSource; +import org.onap.ccsdk.sli.core.dblib.jdbc.MySQLCachedDataSource; + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class CachedDataSourceFactory { + + public static CachedDataSource createDataSource(BaseDBConfiguration config) { + if(config instanceof JDBCConfiguration) + return JdbcDBCachedDataSource.createInstance(config); + + return (CachedDataSource)null; + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBConfigException.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBConfigException.java new file mode 100644 index 000000000..e41e29b5d --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBConfigException.java @@ -0,0 +1,47 @@ +/*- + * ============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; + + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class DBConfigException extends RuntimeException +{ + /** + * + */ + private static final long serialVersionUID = 4752405152537680257L; + + public DBConfigException(Exception e) + { + super(e.toString()); + } + + public DBConfigException(String msg) + { + super(msg); + } +} 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 new file mode 100644 index 000000000..8ae9a2665 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceActivator.java @@ -0,0 +1,130 @@ +/*- + * ============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/DBLibConnection.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java new file mode 100644 index 000000000..8181b1300 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java @@ -0,0 +1,390 @@ +/*- + * ============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.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.ArrayList; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; + +import javax.sql.rowset.CachedRowSet; + +import org.apache.tomcat.jdbc.pool.PooledConnection; +import org.apache.tomcat.jdbc.pool.ProxyConnection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DBLibConnection implements Connection { + + private static Logger LOGGER = LoggerFactory.getLogger(DBLibConnection.class); + + private final Connection connection; + private final CachedDataSource dataSource; + private boolean locked = false; + private String tableName = null; + + public DBLibConnection(Connection con, CachedDataSource dataSource){ + this.connection = con; + this.dataSource = dataSource; + locked = false; + dataSource.getPoolInfo(true); + } + + public boolean lockTable(String tablename) { + this.tableName = tablename; + return locked = dataSource.lockTable(connection, tableName); + } + + public void resetInactivityTimer() { + Class iface = PooledConnection.class; + try { + PooledConnection pc = connection.unwrap(iface); + pc.setTimestamp(System.currentTimeMillis()); + } catch (SQLException e) { + LOGGER.warn("Failed resetting timeout timer", e); + } + } + + public boolean unlock() { + dataSource.unlockTable(connection); + return locked = false; + } + + public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable + { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + resetInactivityTimer(); + return dataSource.executeUpdatePreparedStatement(connection, statement, newList, false); + } + + public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable + { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + resetInactivityTimer(); + return dataSource.executePreparedStatement(connection, statement, newList, false); + } + + @Override + public T unwrap(Class iface) throws SQLException { + return connection.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return connection.isWrapperFor(iface); + } + + @Override + public Statement createStatement() throws SQLException { + return connection.createStatement(); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + return connection.prepareStatement(sql); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + return connection.prepareCall(sql); + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return connection.nativeSQL(sql); + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + connection.setAutoCommit(autoCommit); + } + + @Override + public boolean getAutoCommit() throws SQLException { + return connection.getAutoCommit(); + } + + @Override + public void commit() throws SQLException { + connection.commit(); + } + + @Override + public void rollback() throws SQLException { + connection.rollback(); + } + + @Override + public void close() throws SQLException { + if(this.locked) { + try { + this.unlock(); + } catch(Throwable th) { + LOGGER.error("Failed unlocking",th); + } + } + if(connection != null && !connection.isClosed()) { + connection.close(); + } + dataSource.getPoolInfo(false); + } + + @Override + public boolean isClosed() throws SQLException { + return connection.isClosed(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return connection.getMetaData(); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + connection.setReadOnly(readOnly); + } + + @Override + public boolean isReadOnly() throws SQLException { + return connection.isReadOnly(); + } + + @Override + public void setCatalog(String catalog) throws SQLException { + connection.setCatalog(catalog); + } + + @Override + public String getCatalog() throws SQLException { + return connection.getCatalog(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + connection.setTransactionIsolation(level); + } + + @Override + public int getTransactionIsolation() throws SQLException { + return connection.getTransactionIsolation(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return connection.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + connection.clearWarnings(); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return connection.createStatement(resultSetType, resultSetConcurrency); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return connection.prepareCall(sql, resultSetType, resultSetConcurrency); + } + + @Override + public Map> getTypeMap() throws SQLException { + return connection.getTypeMap(); + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + connection.setTypeMap(map); + } + + @Override + public void setHoldability(int holdability) throws SQLException { + connection.setHoldability(holdability); + } + + @Override + public int getHoldability() throws SQLException { + return connection.getHoldability(); + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return connection.setSavepoint(); + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return connection.setSavepoint(name); + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + connection.rollback(savepoint); + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + connection.releaseSavepoint(savepoint); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return connection.prepareStatement(sql, autoGeneratedKeys); + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return connection.prepareStatement(sql, columnIndexes); + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return connection.prepareStatement(sql, columnNames); + } + + @Override + public Clob createClob() throws SQLException { + return connection.createClob(); + } + + @Override + public Blob createBlob() throws SQLException { + return connection.createBlob(); + } + + @Override + public NClob createNClob() throws SQLException { + return connection.createNClob(); + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return connection.createSQLXML(); + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return connection.isValid(timeout); + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + connection.setClientInfo(name, value); + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + connection.setClientInfo(properties); + } + + @Override + public String getClientInfo(String name) throws SQLException { + return connection.getClientInfo(name); + } + + @Override + public Properties getClientInfo() throws SQLException { + return connection.getClientInfo(); + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return connection.createArrayOf(typeName, elements); + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return connection.createStruct(typeName, attributes); + } + + @Override + public void setSchema(String schema) throws SQLException { + connection.setSchema(schema); + } + + @Override + public String getSchema() throws SQLException { + return connection.getSchema(); + } + + @Override + public void abort(Executor executor) throws SQLException { + connection.abort(executor); + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + connection.setNetworkTimeout(executor, milliseconds); + } + + @Override + public int getNetworkTimeout() throws SQLException { + return connection.getNetworkTimeout(); + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibException.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibException.java new file mode 100644 index 000000000..de241f478 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibException.java @@ -0,0 +1,39 @@ +/*- + * ============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.sql.SQLException; + +/** + * An exception time for handling DBLIB specific error handling. + */ +public class DBLibException extends SQLException { + + /** + * + */ + private static final long serialVersionUID = -5345059355083984696L; + + public DBLibException(String message){ + super(message); + } + +} 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 new file mode 100644 index 000000000..78b970bf5 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java @@ -0,0 +1,863 @@ +/*- + * ============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.PrintWriter; +import java.sql.Connection; +import java.sql.SQLDataException; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLSyntaxErrorException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Observable; +import java.util.PriorityQueue; +import java.util.Properties; +import java.util.Queue; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; + +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; +import org.onap.ccsdk.sli.core.dblib.factory.AbstractDBResourceManagerFactory; +import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; +import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; +import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; + +import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * @version $Revision: 1.15 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class DBResourceManager implements DataSource, DataAccessor, DBResourceObserver, DbLibService { + private static Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); + + transient boolean terminating = false; + transient protected long retryInterval = 10000L; + transient boolean recoveryMode = true; + + protected final AtomicBoolean dsSelector = new AtomicBoolean(); + +// Queue dsQueue = new ConcurrentLinkedQueue(); + Queue dsQueue = new PriorityQueue(4, new Comparator(){ + + @Override + public int compare(CachedDataSource left, CachedDataSource right) { + try { + if(!left.isSlave()) + return -1; + if(!right.isSlave()) + return 1; + + } catch (Throwable e) { + LOGGER.warn("", e); + } + return 0; + } + + }); + protected final Set broken = Collections.synchronizedSet(new HashSet()); + protected final Object monitor = new Object(); + protected final Properties configProps; + protected final Thread worker; + + protected final long terminationTimeOut; + protected final boolean monitorDbResponse; + protected final long monitoringInterval; + protected final long monitoringInitialDelay; + protected final long expectedCompletionTime; + protected final long unprocessedFailoverThreshold; + + public DBResourceManager(Properties props){ + this.configProps = props; + + // get retry interval value + retryInterval = getLongFromProperties(props, "org.onap.dblib.connection.retry", 10000L); + + // get recovery mode flag + recoveryMode = getBooleanFromProperties(props, "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); + // 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); + + // initialize performance monitor + PollingWorker.createInistance(props); + + // initialize recovery thread + worker = new RecoveryMgr(); + worker.setName("DBResourcemanagerWatchThread"); + worker.setDaemon(true); + worker.start(); + } + + private void config(Properties ctx) throws Exception { + + DbConfigPool dbConfig = DBConfigFactory.createConfig(this.configProps); + + 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."); + } + + for(int i=0; i 1){ + handleGetConnectionException(dataSource, new Exception(data.toString())); + } + } + } + } + } + + public void testForceRecovery() + { + CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + handleGetConnectionException(active, new Exception("test")); + } + + class RecoveryMgr extends Thread { + + public void run() { + while(!terminating) + { + try { + Thread.sleep(retryInterval); + } catch (InterruptedException e1) { } + CachedDataSource brokenSource = null; + try { + if (!broken.isEmpty()) { + CachedDataSource[] sourceArray = broken.toArray(new CachedDataSource[0]); + for (int i = 0; i < sourceArray.length; i++) + { + brokenSource = sourceArray[i]; + if (brokenSource instanceof TerminatingCachedDataSource) + break; + if (resetConnectionPool(brokenSource)) { + broken.remove(brokenSource); + brokenSource.blockImmediateOffLine(); + dsQueue.add(brokenSource); + LOGGER.info("DataSource <" + + brokenSource.getDbConnectionName() + + "> recovered."); + } + brokenSource = null; + } + } + } catch (Exception exc) { + LOGGER.warn(exc.getMessage()); + if(brokenSource != null){ + try { + if(!broken.contains(brokenSource)) + broken.add(brokenSource); + brokenSource = null; + } catch (Exception e1) { } + } + } + } + LOGGER.info("DBResourceManager.RecoveryMgr <"+this.toString() +"> terminated." ); + } + + private boolean resetConnectionPool(CachedDataSource dataSource){ + try { + return dataSource.testConnection(); + } catch (Exception exc) { + LOGGER.info("DataSource <" + dataSource.getDbConnectionName() + "> resetCache failed with error: "+ exc.getMessage()); + return false; + } + } + } + + /* (non-Javadoc) + * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#getData(java.lang.String, java.util.ArrayList, java.lang.String) + */ + @Override + public CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) throws SQLException { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + if(recoveryMode) + return requestDataWithRecovery(statement, newList, preferredDS); + else + return requestDataNoRecovery(statement, newList, preferredDS); + } + + private CachedRowSet requestDataWithRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { + Throwable lastException = null; + CachedDataSource active = null; + + // test if there are any connection pools available + LinkedList sources = new LinkedList(this.dsQueue); + if(sources.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); + } + if(preferredDS != null && !sources.peek().getDbConnectionName().equals(preferredDS)) { + Collections.reverse(sources); + } + + + // loop through available data sources to retrieve data. + while(!sources.isEmpty()) + { + active = sources.peek(); + + long time = System.currentTimeMillis(); + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + master = null; + } + } + sources.remove(active); + return active.getData(statement, arguments); + } catch(SQLDataException exc){ + throw exc; + } catch(SQLSyntaxErrorException exc){ + throw exc; + } catch(SQLIntegrityConstraintViolationException exc){ + throw exc; + } catch(Throwable exc){ + lastException = exc; + String message = exc.getMessage(); + if(message == null) { + if(exc.getCause() != null) { + message = exc.getCause().getMessage(); + } + if(message == null) + message = exc.getClass().getName(); + } + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + handleGetConnectionException(active, exc); + } finally { + if(LOGGER.isDebugEnabled()){ + time = (System.currentTimeMillis() - time); + LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + if(lastException instanceof SQLException){ + throw (SQLException)lastException; + } + // repackage the exception + // you are here because either you run out of available data sources + // or the last exception was not of SQLException type. + // repackage the exception + if(lastException == null) { + throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); + } else { + SQLException exception = new DBLibException(lastException.getMessage()); + exception.setStackTrace(lastException.getStackTrace()); + if(lastException.getCause() instanceof SQLException) { + throw (SQLException)lastException.getCause(); + } + throw exception; + } + } + + private CachedRowSet requestDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { + if(dsQueue.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + } + CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + long time = System.currentTimeMillis(); + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) + active = master; + } + return active.getData(statement, arguments); +// } catch(SQLDataException exc){ +// throw exc; + } catch(Throwable exc){ + String message = exc.getMessage(); + if(message == null) + message = exc.getClass().getName(); + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + if(exc instanceof SQLException) + throw (SQLException)exc; + else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } finally { + if(LOGGER.isDebugEnabled()){ + time = (System.currentTimeMillis() - time); + LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + + + /* (non-Javadoc) + * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#writeData(java.lang.String, java.util.ArrayList, java.lang.String) + */ + @Override + public boolean writeData(String statement, ArrayList arguments, String preferredDS) throws SQLException + { + ArrayList newList=new ArrayList(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + + return writeDataNoRecovery(statement, newList, preferredDS); + } + + CachedDataSource findMaster() throws PoolExhaustedException, MySQLNonTransientConnectionException { + CachedDataSource master = null; + CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); + for(int i=0; i arguments, String preferredDS) throws SQLException { + if(dsQueue.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + } + + boolean initialRequest = true; + boolean retryAllowed = true; + CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + long time = System.currentTimeMillis(); + while(initialRequest) { + initialRequest = false; + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + } + } + + return active.writeData(statement, arguments); + } catch(Throwable exc){ + String message = exc.getMessage(); + if(message == null) + message = exc.getClass().getName(); + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + if(exc instanceof SQLException) { + SQLException sqlExc = SQLException.class.cast(exc); + // handle read-only exception + if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { + LOGGER.warn("retrying due to: " + sqlExc.getMessage()); + dsQueue.remove(active); + dsQueue.add(active); + if(retryAllowed){ + retryAllowed = false; + initialRequest = true; + continue; + } + } + throw (SQLException)exc; + } else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } finally { + if(LOGGER.isDebugEnabled()){ + time = (System.currentTimeMillis() - time); + LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + return true; + } + + private void setDataSource(CachedDataSource dataSource) { + if(dataSource.testConnection(true)){ + this.dsQueue.add(dataSource); + } else { + this.broken.add(dataSource); + } + } + + public Connection getConnection() throws SQLException { + Throwable lastException = null; + CachedDataSource active = null; + + if(dsQueue.isEmpty()){ + throw new DBLibException("No active DB connection pools are available in GetConnection call."); + } + + try { + active = dsQueue.peek(); + CachedDataSource tmpActive = findMaster(); + if(tmpActive != null) { + active = tmpActive; + } + return new DBLibConnection(active.getConnection(), active); + } catch(javax.sql.rowset.spi.SyncFactoryException exc){ + LOGGER.debug("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); + LOGGER.warn("CLASSPATH issue. Allowing retry", exc); + lastException = exc; + } catch(PoolExhaustedException exc) { + throw new NoAvailableConnectionsException(exc); + } catch(MySQLNonTransientConnectionException exc){ + throw new NoAvailableConnectionsException(exc); + } catch(Exception exc){ + lastException = exc; + if(recoveryMode){ + handleGetConnectionException(active, exc); + } else { + if(exc instanceof MySQLNonTransientConnectionException) { + throw new NoAvailableConnectionsException(exc); + } if(exc instanceof SQLException) { + throw (SQLException)exc; + } else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } + } catch (Throwable trwb) { + DBLibException excptn = new DBLibException(trwb.getMessage()); + excptn.setStackTrace(trwb.getStackTrace()); + throw excptn; + } finally { + if(LOGGER.isDebugEnabled()){ + displayState(); + } + } + + if(lastException instanceof SQLException){ + throw (SQLException)lastException; + } + // repackage the exception + if(lastException == null) { + throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); + } else { + SQLException exception = new DBLibException(lastException.getMessage()); + exception.setStackTrace(lastException.getStackTrace()); + if(lastException.getCause() instanceof SQLException) { +// exception.setNextException((SQLException)lastException.getCause()); + throw (SQLException)lastException.getCause(); + } + throw exception; + } + } + + public Connection getConnection(String username, String password) + throws SQLException { + CachedDataSource active = null; + + if(dsQueue.isEmpty()){ + throw new DBLibException("No active DB connection pools are available in GetConnection call."); + } + + + try { + active = dsQueue.peek(); + CachedDataSource tmpActive = findMaster(); + if(tmpActive != null) { + active = tmpActive; + } + return active.getConnection(username, password); + } catch(Throwable exc){ + if(recoveryMode){ + handleGetConnectionException(active, exc); + } else { + if(exc instanceof SQLException) + throw (SQLException)exc; + else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } + + } + + throw new DBLibException("No connections available in DBResourceManager in GetConnection call."); + } + + private void handleGetConnectionException(CachedDataSource source, Throwable exc) { + try { + if(!source.canTakeOffLine()) + { + LOGGER.error("Could not switch due to blocking"); + return; + } + + boolean removed = dsQueue.remove(source); + if(!broken.contains(source)) + { + if(broken.add(source)) + { + LOGGER.warn("DB Recovery: DataSource <" + source.getDbConnectionName() + "> put in the recovery mode. Reason : " + exc.getMessage()); + } else { + LOGGER.warn("Error putting DataSource <" +source.getDbConnectionName()+ "> in recovery mode."); + } + } else { + LOGGER.info("DB Recovery: DataSource <" + source.getDbConnectionName() + "> already in recovery queue"); + } + if(removed) + { + if(!dsQueue.isEmpty()) + { + LOGGER.warn("DB DataSource <" + dsQueue.peek().getDbConnectionName() + "> became active"); + } + } + } catch (Exception e) { + LOGGER.error("", e); + } + } + + public void cleanUp() { + for(Iterator it=dsQueue.iterator();it.hasNext();){ + CachedDataSource cds = (CachedDataSource)it.next(); + it.remove(); + cds.cleanUp(); + } + + try { + this.terminating = true; + if(broken != null) + { + try { + broken.add( new TerminatingCachedDataSource(null)); + } catch(Exception exc){ + LOGGER.error("Waiting for Worker to stop", exc); + } + } + worker.join(terminationTimeOut); + LOGGER.info("DBResourceManager.RecoveryMgr <"+worker.toString() +"> termination was successful: " + worker.getState()); + } catch(Exception exc){ + LOGGER.error("Waiting for Worker thread to terminate ", exc); + } + } + + public static DBResourceManager create(Properties props) throws Exception { + DBResourceManager dbmanager = new DBResourceManager(props); + dbmanager.config(props); + return dbmanager; + } + + public PrintWriter getLogWriter() throws SQLException { + return ((CachedDataSource)this.dsQueue.peek()).getLogWriter(); + } + + public int getLoginTimeout() throws SQLException { + return ((CachedDataSource)this.dsQueue.peek()).getLoginTimeout(); + } + + public void setLogWriter(PrintWriter out) throws SQLException { + ((CachedDataSource)this.dsQueue.peek()).setLogWriter(out); + } + + public void setLoginTimeout(int seconds) throws SQLException { + ((CachedDataSource)this.dsQueue.peek()).setLoginTimeout(seconds); + } + + public void displayState(){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); + CachedDataSource current = (CachedDataSource)dsQueue.peek(); + if(current != null) { + LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); + } + } + } + + /* (non-Javadoc) + * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#isActive() + */ + @Override + public boolean isActive() { + return this.dsQueue.size()>0; + } + + public String getActiveStatus(){ + return "Connected: " + dsQueue.size()+"\tIn-recovery: "+broken.size(); + } + + public String getDBStatus(boolean htmlFormat) { + StringBuilder buffer = new StringBuilder(); + + ArrayList list = new ArrayList(); + list.addAll(dsQueue); + list.addAll(broken); + if (htmlFormat) + { + buffer.append("") + .append("Name:").append(""); + for (int i = 0; i < list.size(); i++) { + buffer.append(""); + buffer.append(((CachedDataSource) list.get(i)).getDbConnectionName()).append(""); + } + buffer.append(""); + + buffer.append("State:"); + for (int i = 0; i < list.size(); i++) { + if (broken.contains(list.get(i))) { + buffer.append("in recovery"); + } + if (dsQueue.contains(list.get(i))) { + if (dsQueue.peek() == list.get(i)) + buffer.append("active"); + else + buffer.append("standby"); + } + } + buffer.append(""); + + } else { + for (int i = 0; i < list.size(); i++) { + buffer.append("Name: ").append(((CachedDataSource) list.get(i)).getDbConnectionName()); + buffer.append("\tState: "); + if (broken.contains(list.get(i))) { + buffer.append("in recovery"); + } else + if (dsQueue.contains(list.get(i))) { + if (dsQueue.peek() == list.get(i)) + buffer.append("active"); + else + buffer.append("standby"); + } + + buffer.append("\n"); + + } + } + return buffer.toString(); + } + + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public T unwrap(Class iface) throws SQLException { + return null; + } + + /** + * @return the monitorDbResponse + */ + public final boolean isMonitorDbResponse() { + return recoveryMode && monitorDbResponse; + } + + public void test(){ + CachedDataSource obj = dsQueue.peek(); + Exception ption = new Exception(); + try { + for(int i=0; i<5; i++) + { + handleGetConnectionException(obj, ption); + } + } catch(Throwable exc){ + LOGGER.warn("", exc); + } + } + + public String getPreferredDSName(){ + if(isActive()){ + return getPreferredDataSourceName(dsSelector); + } + return ""; + } + + public String getPreferredDataSourceName(AtomicBoolean flipper) { + + LinkedList snapshot = new LinkedList(dsQueue); + if(snapshot.size() > 1){ + CachedDataSource first = snapshot.getFirst(); + CachedDataSource last = snapshot.getLast(); + + int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); + if(delta < 0) { + flipper.set(false); + } else if(delta > 0) { + flipper.set(true); + } else { + // check the last value and return !last + flipper.getAndSet(!flipper.get()); + } + + if (flipper.get()) + Collections.reverse(snapshot); + } + return snapshot.peek().getDbConnectionName(); + } + + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + return null; + } + + public String getMasterName() { + if(isActive()){ + return getMasterDataSourceName(dsSelector); + } + return ""; + } + + + private String getMasterDataSourceName(AtomicBoolean flipper) { + + LinkedList snapshot = new LinkedList(dsQueue); + if(snapshot.size() > 1){ + CachedDataSource first = snapshot.getFirst(); + CachedDataSource last = snapshot.getLast(); + + int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); + if(delta < 0) { + flipper.set(false); + } else if(delta > 0) { + flipper.set(true); + } else { + // check the last value and return !last + flipper.getAndSet(!flipper.get()); + } + + if (flipper.get()) + Collections.reverse(snapshot); + } + return snapshot.peek().getDbConnectionName(); + } + + class RemindTask extends TimerTask { + public void run() { + CachedDataSource ds = dsQueue.peek(); + if(ds != null) + ds.getPoolInfo(false); + } + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java new file mode 100644 index 000000000..2e1a6e953 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java @@ -0,0 +1,27 @@ +/*- + * ============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.util.Observer; + +public interface DBResourceObserver extends Observer { + public boolean isMonitorDbResponse(); +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java new file mode 100644 index 000000000..7921fa5c5 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java @@ -0,0 +1,33 @@ +/*- + * ============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.sql.SQLException; +import java.util.ArrayList; + +import javax.sql.rowset.CachedRowSet; + +public interface DataAccessor { + + public abstract CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) + throws SQLException; + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java new file mode 100644 index 000000000..bc14fb8b9 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java @@ -0,0 +1,33 @@ +/*- + * ============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.util.Comparator; + +public interface DataSourceComparator extends Comparator { + + public abstract CachedDataSource getLastUsed(); + + public abstract void setLastUsed(CachedDataSource lastUsed); + + public abstract int compare(CachedDataSource ds1, CachedDataSource ds2); + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java new file mode 100644 index 000000000..de9846679 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java @@ -0,0 +1,46 @@ +/*- + * ============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.sql.SQLException; +import java.util.ArrayList; + +import javax.sql.rowset.CachedRowSet; + +public interface DbLibService { + + /* (non-Javadoc) + * @see DataAccessor#getData(java.lang.String, java.util.ArrayList) + */ + public abstract CachedRowSet getData(String statement, + ArrayList arguments, String preferredDS) + throws SQLException; + + /* (non-Javadoc) + * @see DataAccessor#writeData(java.lang.String, java.util.ArrayList) + */ + public abstract boolean writeData(String statement, + ArrayList arguments, String preferredDS) + throws SQLException; + + public abstract boolean isActive(); + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationException.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationException.java new file mode 100644 index 000000000..be493aa1f --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationException.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; + + +public class DblibConfigurationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public DblibConfigurationException() + { + super(); + } + + public DblibConfigurationException(String msg) + { + super(msg); + } + + public DblibConfigurationException(String msg, Throwable t) + { + super(msg, t); + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsException.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsException.java new file mode 100644 index 000000000..a39e5c5b4 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsException.java @@ -0,0 +1,36 @@ +/*- + * ============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.sql.SQLException; + +public class NoAvailableConnectionsException extends SQLException { + + /** + * + */ + private static final long serialVersionUID = -6259205931674413018L; + + public NoAvailableConnectionsException(Exception exc) { + super(exc); + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java new file mode 100644 index 000000000..127e6d376 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java @@ -0,0 +1,82 @@ +/*- + * ============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.sql.SQLFeatureNotSupportedException; +import java.util.logging.Logger; + +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; + + +public class TerminatingCachedDataSource extends CachedDataSource implements SQLExecutionMonitorObserver { + + public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { + super(jdbcElem); + } + + protected void configure(BaseDBConfiguration jdbcElem) throws DBConfigException { + // no action + } + + public long getInterval() { + return 1000; + } + + public long getInitialDelay() { + return 1000; + } + + public long getExpectedCompletionTime() { + return 50; + } + + public void setExpectedCompletionTime(long value) { + + } + + public void setInterval(long value) { + + } + + public void setInitialDelay(long value) { + + } + + public long getUnprocessedFailoverThreshold() { + return 3; + } + + public void setUnprocessedFailoverThreshold(long value) { + + } + + public int compareTo(CachedDataSource ods) + { + return 0; + } + + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java new file mode 100644 index 000000000..4b738d426 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java @@ -0,0 +1,104 @@ +/*- + * ============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.config; + +import java.util.Properties; + +public abstract class BaseDBConfiguration { + public static final String DATABASE_TYPE = "org.onap.ccsdk.sli.dbtype"; + public static final String DATABASE_URL = "org.onap.ccsdk.sli.jdbc.url"; + public static final String DATABASE_NAME = "org.onap.ccsdk.sli.jdbc.database"; + public static final String CONNECTION_NAME = "org.onap.ccsdk.sli.jdbc.connection.name"; + public static final String DATABASE_USER = "org.onap.ccsdk.sli.jdbc.user"; + public static final String DATABASE_PSSWD = "org.onap.ccsdk.sli.jdbc.password"; + public static final String CONNECTION_TIMEOUT="org.onap.ccsdk.sli.jdbc.connection.timeout"; + public static final String REQUEST_TIMEOUT = "org.onap.ccsdk.sli.jdbc.request.timeout"; + public static final String MIN_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.min"; + public static final String MAX_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.max"; + public static final String INIT_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.init"; + public static final String DATABASE_HOSTS = "org.onap.ccsdk.sli.jdbc.hosts"; + + + protected final Properties props; + + public BaseDBConfiguration(Properties properties) { + this.props = properties; + } + + public int getConnTimeout() { + try { + String value = props.getProperty(CONNECTION_TIMEOUT); + return Integer.parseInt(value); + } catch(Exception exc) { + return -1; + } + } + + public int getRequestTimeout() { + try { + String value = props.getProperty(REQUEST_TIMEOUT); + if(value == null) + return -1; + return Integer.parseInt(value); + } catch(Exception exc) { + return -1; + } + } + + public String getDbConnectionName() { + return props.getProperty(CONNECTION_NAME); + } + + public String getDatabaseName() { + return props.getProperty(DATABASE_NAME); + } + + public String getDbUserId() { + return props.getProperty(DATABASE_USER); + } + + public String getDbPasswd() { + return props.getProperty(DATABASE_PSSWD); + } + + public int getDbMinLimit() { + String value = props.getProperty(MIN_LIMIT); + return Integer.parseInt(value); + } + + public int getDbMaxLimit() { + String value = props.getProperty(MAX_LIMIT); + return Integer.parseInt(value); + } + + public int getDbInitialLimit() { + String value = props.getProperty(INIT_LIMIT); + return Integer.parseInt(value); + } + + public String getDbUrl() { + return props.getProperty(DATABASE_URL); + } + + public String getServerGroup() { + return null; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java new file mode 100644 index 000000000..21fdab245 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java @@ -0,0 +1,56 @@ +/*- + * ============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.config; + +import java.util.ArrayList; +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DbConfigPool { + private static Logger LOGGER = LoggerFactory.getLogger(DbConfigPool.class); + + private final String type; + + private ArrayList configurations = new ArrayList(); + + public DbConfigPool(Properties properties) { + LOGGER.debug("Initializing DbConfigType"); + type = properties.getProperty(BaseDBConfiguration.DATABASE_TYPE, "JDBC").toUpperCase(); + } + + public int getTimeout() { + // TODO Auto-generated method stub + return 0; + } + + public String getType() { + return type; + } + + public JDBCConfiguration[] getJDBCbSourceArray() { + return configurations.toArray(new JDBCConfiguration[configurations.size()]); + } + + public void addConfiguration(BaseDBConfiguration config) { + configurations.add(config); + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/JDBCConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/JDBCConfiguration.java new file mode 100644 index 000000000..fea103569 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/JDBCConfiguration.java @@ -0,0 +1,31 @@ +/*- + * ============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.config; + +import java.util.Properties; + +public class JDBCConfiguration extends BaseDBConfiguration { + + public JDBCConfiguration(Properties xmlElem) { + super(xmlElem); + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java new file mode 100644 index 000000000..e88734d2e --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java @@ -0,0 +1,39 @@ +/*- + * ============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.factory; + +import org.onap.ccsdk.sli.core.dblib.jdbc.JdbcDbResourceManagerFactory; + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class AbstractDBResourceManagerFactory { + + public static AbstractResourceManagerFactory getFactory(String type) throws FactoryNotDefinedException { + + // JDBC + return JdbcDbResourceManagerFactory.createIntstance(); + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java new file mode 100644 index 000000000..6fc7e7a04 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java @@ -0,0 +1,104 @@ +/*- + * ============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.factory; + + +import java.sql.SQLException; +import java.util.Set; +import java.util.concurrent.Callable; + +import org.onap.ccsdk.sli.core.dblib.CachedDataSource; +import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; +import org.onap.ccsdk.sli.core.dblib.DBConfigException; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @version $Revision: 1.6 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public abstract class AbstractResourceManagerFactory { + private static Logger LOGGER = LoggerFactory.getLogger(AbstractResourceManagerFactory.class); + + public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager) throws Exception; + public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager dbResourceManager, String sourceName) throws SQLException ; + + + public static AbstractResourceManagerFactory createIntstance() throws FactoryNotDefinedException { + throw new FactoryNotDefinedException("Factory method 'createIntstance' needs to be overriden in DBResourceManagerFactory"); + } + + public class DBInitTask implements Callable + { + private BaseDBConfiguration config = null; + private Set activeTasks; + + public DBInitTask(JDBCConfiguration jdbcconfig, Set tasks) { + this.config = jdbcconfig; + this.activeTasks = tasks; + } + + public CachedDataSource call() throws Exception { + CachedDataSource ds = null; + try { + ds = CachedDataSourceFactory.createDataSource(config); + return ds; + } finally { + synchronized(activeTasks) { + activeTasks.remove(this); + if (activeTasks.isEmpty()) { + final Runnable closure = new Runnable() { + + public void run() { + try { + Thread.sleep(300); + } catch (Exception e) { + } + synchronized(activeTasks) { + activeTasks.notifyAll(); + } + } + }; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Completed CachedDataSource.Call and notifyAll from " + ds.getDbConnectionName()); + } + Thread worker = new Thread(closure); + worker.setDaemon(true); + worker.start(); + } else { + if (LOGGER.isDebugEnabled()) { + if (ds != null) { + LOGGER.debug("Completed CachedDataSource.Call from " + ds.getDbConnectionName()); + } + } + } + } + } + } + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java new file mode 100644 index 000000000..3caa7767e --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java @@ -0,0 +1,99 @@ +/*- + * ============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.factory; + + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.slf4j.LoggerFactory; + +/** + * @version $Revision: 1.1 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki 01/17/08 Initial version + */ +public class DBConfigFactory { + + public static DbConfigPool createConfig(Properties resource) { + return getConfigparams(resource); + } + + static DbConfigPool getConfigparams(Properties properties){ + DbConfigPool xmlConfig = new DbConfigPool(properties); + ArrayList propertySets = new ArrayList(); + + if("JDBC".equalsIgnoreCase(xmlConfig.getType())) { + String hosts = properties.getProperty(BaseDBConfiguration.DATABASE_HOSTS); + if(hosts == null || hosts.isEmpty()) { + propertySets.add(properties); + } else { + String[] newhost = hosts.split(","); + for(int i=0; i< newhost.length; i++) { + Properties localset = new Properties(); + localset.putAll(properties); + String url = localset.getProperty(BaseDBConfiguration.DATABASE_URL); + if(url.contains("DBHOST")) + url = url.replace("DBHOST", newhost[i]); + if(url.contains("dbhost")) + url = url.replace("dbhost", newhost[i]); + localset.setProperty(BaseDBConfiguration.DATABASE_URL, url); + localset.setProperty(BaseDBConfiguration.CONNECTION_NAME, newhost[i]); + propertySets.add(localset); + } + } + } else { + propertySets.add(properties); + } + try { + Iterator it = propertySets.iterator(); + while(it.hasNext()) { + BaseDBConfiguration config = parse(it.next()); + xmlConfig.addConfiguration(config); + } + + } catch (Exception e) { + LoggerFactory.getLogger(DBConfigFactory.class).warn("",e); + } + + return xmlConfig; + } + + public static BaseDBConfiguration parse(Properties props) throws Exception { + + String type = props.getProperty(BaseDBConfiguration.DATABASE_TYPE); + + BaseDBConfiguration config = null; + + if("JDBC".equalsIgnoreCase(type)) { + config = new JDBCConfiguration(props); + } + + return config; + + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java new file mode 100644 index 000000000..b6383a53b --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java @@ -0,0 +1,37 @@ +/*- + * ============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.factory; + + +/** + * @version 1.3 + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki 01/16/08 Initial version + */ +public class FactoryNotDefinedException extends Exception { + + public FactoryNotDefinedException(String message) { + super(message); + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java new file mode 100644 index 000000000..c024d0021 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -0,0 +1,249 @@ +/*- + * ============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.jdbc; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLFeatureNotSupportedException; + +import org.apache.tomcat.jdbc.pool.DataSource; +import org.apache.tomcat.jdbc.pool.PoolProperties; +import org.onap.ccsdk.sli.core.dblib.CachedDataSource; +import org.onap.ccsdk.sli.core.dblib.DBConfigException; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.mysql.jdbc.Driver; + + +/** + * @version $Revision: 1.7 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ + +public class JdbcDBCachedDataSource extends CachedDataSource +{ + private String dbUserId; + private String dbPasswd; + private String dbUrl; + + private int minLimit; + private int maxLimit; + private int initialLimit; + + private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; + + private static Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class); + + /** + * @param jdbcElem + */ + public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem) + { + super(jdbcElem); + } + + @Override + protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException + { + BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem; + if(jdbcConfig.getConnTimeout() > 0){ + this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); + } + if(jdbcConfig.getRequestTimeout() > 0){ + this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); + } + + // set connection pool name + String dbConnectionName = jdbcConfig.getDbConnectionName(); + super.setDbConnectionName(dbConnectionName); + // Configure the JDBC connection + dbUserId = jdbcConfig.getDbUserId(); + if (dbUserId == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + dbPasswd = jdbcConfig.getDbPasswd(); + if (dbPasswd == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + /* + dbDriver = jdbcConfig.getDbDriver(); + if (dbDriver == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new ScpTblUpdateError(errorMsg); + } + */ + + minLimit = jdbcConfig.getDbMinLimit(); +// if (minLimit == null) +// { +// String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); +// } + maxLimit = jdbcConfig.getDbMaxLimit(); +// if (maxLimit == null) +// { +// String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); +// } + initialLimit = jdbcConfig.getDbInitialLimit(); +// if (initialLimit == null) +// { +// String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); +// } + + dbUrl = jdbcConfig.getDbUrl(); + if(dbUrl == null){ + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + try { + Driver dr = new com.mysql.jdbc.Driver(); + Class clazz = Class.forName("com.mysql.jdbc.Driver") ; + + PoolProperties p = new PoolProperties(); + p.setDriverClassName("com.mysql.jdbc.Driver"); + p.setUrl(dbUrl); + p.setUsername(dbUserId); + p.setPassword(dbPasswd); + p.setJmxEnabled(true); + p.setTestWhileIdle(false); + p.setTestOnBorrow(true); + p.setValidationQuery("SELECT 1"); + p.setTestOnReturn(false); + p.setValidationInterval(30000); + p.setTimeBetweenEvictionRunsMillis(30000); + p.setInitialSize(initialLimit); + p.setMaxActive(maxLimit); + p.setMaxIdle(maxLimit); + p.setMaxWait(10000); + p.setRemoveAbandonedTimeout(60); + p.setMinEvictableIdleTimeMillis(30000); + p.setMinIdle(minLimit); + p.setLogAbandoned(true); + p.setRemoveAbandoned(true); + p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); + + DataSource dataSource = new DataSource(p); + + synchronized(this) + { + this.ds = dataSource; + Connection con = null; + PreparedStatement st = null; + ResultSet rs = null; + + try { + con = dataSource.getConnection(); + st = con.prepareStatement("Select 1 FROM DUAL"); + rs = st.executeQuery(); + } catch(Exception exc) { + LOGGER.error(exc.getMessage()); + } finally { + if(rs != null) rs.close(); + if(st != null) st.close(); + if(con != null) con.close(); + } + + initialized = true; + LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); + } + +// } catch (SQLException exc) { +// initialized = false; +// StringBuffer sb = new StringBuffer(); +// sb.append("Failed to initialize MySQLDataSource<"); +// sb.append(dbConnectionName).append(">. Reason: "); +// sb.append(exc.getMessage()); +// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +//// throw new DBConfigException(e.getMessage()); + } catch (Exception exc) { + initialized = false; + StringBuffer sb = new StringBuffer(); + sb.append("Failed to initialize MySQLCachedDataSource <"); + sb.append(dbConnectionName).append(">. Reason: "); + sb.append(exc.getMessage()); + LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +// throw new DBConfigException(e.getMessage()); + } + } + + public final String getDbUrl() + { + return dbUrl; + } + + public final String getDbUserId() + { + return dbUserId; + } + + public final String getDbPasswd() + { + return dbPasswd; + } + + public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { + return new JdbcDBCachedDataSource(config); + } + + public String toString(){ + return getDbConnectionName(); + } + + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } + + public void cleanUp(){ + DataSource dataSource = (DataSource)ds; + dataSource.getPool().purge(); + int active = dataSource.getActive(); + int size = dataSource.getSize(); + dataSource.close(true); + super.cleanUp(); + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java new file mode 100644 index 000000000..978de0eb3 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java @@ -0,0 +1,186 @@ +/*- + * ============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.jdbc; + + +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; + +import org.onap.ccsdk.sli.core.dblib.CachedDataSource; +import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.DataSourceComparator; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @version $Revision: 1.6 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ +public class JdbcDbResourceManagerFactory extends AbstractResourceManagerFactory { + private static Logger LOGGER = LoggerFactory.getLogger(JdbcDbResourceManagerFactory.class ); + private JdbcDbResourceManagerFactory(){ + + } + + class MyFutureTask extends FutureTask + { + + public MyFutureTask(Callable result) { + super(result); + } + + } + + public CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager, String sourceName) throws SQLException + { + // here create the data sources objects + JDBCConfiguration[] list = dbConfig.getJDBCbSourceArray(); + CachedDataSource[] cachedDS = new CachedDataSource[1]; + + for(int i=0, max=list.length; i tasks = new HashSet(); + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating " + list.length + " datasources."); + } + + for(int i=0, max=list.length; i 0){ + this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); + } + if(jdbcConfig.getRequestTimeout() > 0){ + this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); + } + + // set connection pool name + String dbConnectionName = jdbcConfig.getDbConnectionName(); + super.setDbConnectionName(dbConnectionName); + // Configure the JDBC connection + dbUserId = jdbcConfig.getDbUserId(); + if (dbUserId == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + dbPasswd = jdbcConfig.getDbPasswd(); + if (dbPasswd == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + /* + dbDriver = jdbcConfig.getDbDriver(); + if (dbDriver == null) + { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new ScpTblUpdateError(errorMsg); + } + */ + + minLimit = Integer.toString(jdbcConfig.getDbMinLimit()); + if (minLimit == null) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + maxLimit = Integer.toString(jdbcConfig.getDbMaxLimit()); + if (maxLimit == null) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + initialLimit = Integer.toString(jdbcConfig.getDbInitialLimit()); + if (initialLimit == null) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + dbUrl = jdbcConfig.getDbUrl(); + if(dbUrl == null){ + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); + } + + try { + + MysqlDataSource dataSource = new MysqlDataSource(); + dataSource.setUser(dbUserId); + dataSource.setPassword(dbPasswd); + dataSource.setURL(dbUrl); +// dataSource.setInitialSize(5); +// dataSource.setMaxTotal(60); +// dataSource.setMaxActive(100); +// dataSource.setMaxWait(10000); +// dataSource.setMaxIdle(10); + + Properties connAttr = new Properties(); + + connAttr.setProperty("MinLimit", minLimit); + connAttr.setProperty("MaxLimit", maxLimit); + connAttr.setProperty("InitialLimit", initialLimit); + connAttr.setProperty("TRANSACTION_ISOLATION","SERIALIZABLE"); + connAttr.setProperty("CONNECTION_TAG", dbConnectionName.toUpperCase()+"_CONNECTION"); + connAttr.setProperty("InactivityTimeout", "900"); + connAttr.setProperty("AbandonedConnectionTimeout", "600"); + connAttr.setProperty("PropertyCheckInterval", "60"); + connAttr.setProperty("ValidateConnection", "true"); + + + synchronized(this) + { + this.ds = dataSource; + + initialized = true; + LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); + } + +// } catch (SQLException exc) { +// initialized = false; +// StringBuffer sb = new StringBuffer(); +// sb.append("Failed to initialize MySQLDataSource<"); +// sb.append(dbConnectionName).append(">. Reason: "); +// sb.append(exc.getMessage()); +// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +//// throw new DBConfigException(e.getMessage()); + } catch (Exception exc) { + initialized = false; + StringBuffer sb = new StringBuffer(); + sb.append("Failed to initialize MySQLCachedDataSource <"); + sb.append(dbConnectionName).append(">. Reason: "); + sb.append(exc.getMessage()); + LOGGER.error("AS_CONF_ERROR: " + sb.toString()); +// throw new DBConfigException(e.getMessage()); + } + } + + public final String getDbUrl() + { + return dbUrl; + } + + public final String getDbUserId() + { + return dbUserId; + } + + public final String getDbPasswd() + { + return dbPasswd; + } + + public static MySQLCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { + return new MySQLCachedDataSource(config); + } + + public String toString(){ + return getDbConnectionName(); + } + + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java new file mode 100644 index 000000000..b670a832d --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java @@ -0,0 +1,217 @@ +/*- + * ============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.pm; + +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.TreeSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.atomic.AtomicLong; + +public class PollingWorker implements Runnable { + + private Logger LOGGER = LoggerFactory.getLogger(PollingWorker.class); + + private static PollingWorker self = null; + + private LinkedBlockingQueue tasks = new LinkedBlockingQueue(100); + private long interval = 1000L; + private Thread worker = null; + private AtomicLong[] counters = null; + private int[] bucketUnit = null; + private static boolean enabled = false; + private Timer timer = null; + + public static void post(long starttime){ + PollingWorker temp = self; + if(temp != null && enabled) { + temp.register(new TestSample(starttime)); + } + } + + public static void createInistance(Properties props){ + self = new PollingWorker(props); + } + + private PollingWorker(Properties ctxprops){ + if(ctxprops==null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm") == null){ + enabled = false; + } else { + if("true".equalsIgnoreCase((String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm"))){ + enabled = true; + } else { + enabled = false; + } + } + + interval = Long.parseLong(( ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval") == null) ? "60" : (String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval")); + // '0' bucket is to count exceptions + String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")==null) ? "0,2,5,10,20,50,100" : (String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")).split(","); + + if(enabled){ + bucketUnit = new int[sampling.length]; + for(int i=0, max = bucketUnit.length; i x.starttime) + return -1; + if(endtime > x.endtime) + return -1; + return 0; + } + return 1; + } + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java new file mode 100644 index 000000000..bcd4360e4 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java @@ -0,0 +1,237 @@ +/*- + * ============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.pm; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; +import java.util.Observable; +import java.util.Observer; +import java.util.SortedSet; +import java.util.Timer; +import java.util.TimerTask; +import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicLong; + +import org.onap.ccsdk.sli.core.dblib.DBResourceObserver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SQLExecutionMonitor extends Observable +{ + private static Logger LOGGER = LoggerFactory.getLogger(SQLExecutionMonitor.class); + + final static long MILISECOND = 1000000L; + final static long SECOND = 1000L*MILISECOND; + + private final Timer timer; + // collection + private final SortedSet innerSet; + private SQLExecutionMonitorObserver parent = null; + private final AtomicLong completionCounter; + private boolean activeState = false; + private final long interval; + private final long initialDelay; + private final long EXPECTED_TIME_TO_COMPLETE; + private final long UNPROCESSED_FAILOVER_THRESHOLD; + + private final class MonitoringTask extends TimerTask + { + + public void run() + { + try { + TestObject testObj = new TestObject(); + testObj.setStartTime(testObj.getStartTime() - EXPECTED_TIME_TO_COMPLETE); + + // take a snapshot of the current task list + TestObject[] array = innerSet.toArray(new TestObject[0]); + SortedSet copyCurrent = new TreeSet(Arrays.asList(array)); + // get the list of the tasks that are older than the specified + // interval. + SortedSet unprocessed = copyCurrent.headSet(testObj); + + long succesfulCount = completionCounter.get(); + int unprocessedCount = unprocessed.size(); + + if (!unprocessed.isEmpty() && unprocessedCount > UNPROCESSED_FAILOVER_THRESHOLD && succesfulCount == 0) + { + // switch the Connection Pool to passive + setChanged(); + notifyObservers("Open JDBC requests=" + unprocessedCount+" in "+SQLExecutionMonitor.this.parent.getDbConnectionName()); + } + } catch (Exception exc) { + LOGGER.error("", exc); + } finally { + completionCounter.set(0L); + } + } + } + + public static class TestObject implements Comparable, Serializable + { + + private static final long serialVersionUID = 1L; + private long starttime; + private long randId; + + public TestObject() + { + starttime = System.nanoTime(); + } + + public long getStartTime() + { + return starttime; + } + + public void setStartTime(long newTime) + { + starttime = newTime; + } + + public int compareTo(TestObject o) + { + if( this == o) + return 0; + if(this.starttime > o.getStartTime()) + return 1; + if(this.starttime < o.getStartTime()) + return -1; + + if(this.hashCode() > o.hashCode()) + return 1; + if(this.hashCode() < o.hashCode()) + return -1; + + return 0; + } + + public String toString() + { + return Long.toString(starttime)+"#"+ this.hashCode(); + } + + public boolean equals(Object obj) + { + if (this == obj) + return true; + + return (obj instanceof TestObject + && starttime == ((TestObject) obj).getStartTime() + && hashCode() == ((TestObject) obj).hashCode()); + } + } + + public SQLExecutionMonitor(SQLExecutionMonitorObserver parent) + { + this.parent = parent; + completionCounter = new AtomicLong(0L); + interval = parent.getInterval(); + initialDelay = parent.getInitialDelay(); + this.UNPROCESSED_FAILOVER_THRESHOLD = parent.getUnprocessedFailoverThreshold(); + this.EXPECTED_TIME_TO_COMPLETE = parent.getExpectedCompletionTime()*MILISECOND; + + innerSet = Collections.synchronizedSortedSet(new TreeSet()); + timer = new Timer(); + } + + public void cleanup() + { + timer.cancel(); + } + + // registerRequest + public TestObject registerRequest() + { + if(activeState) + { + TestObject test = new TestObject(); + if(innerSet.add(test)) + return test; + } + return null; + } + + // deregisterSuccessfulReguest + public boolean deregisterReguest(TestObject test) + { + if(test == null) + return false; + // remove from the collection + if(innerSet.remove(test) && activeState) + { + completionCounter.incrementAndGet(); + return true; + } + return false; + } + + public void terminate() { + timer.cancel(); + } + + /** + * @return the parent + */ + public final Object getParent() { + return parent; + } + + public void addObserver(Observer observer) + { + if(observer instanceof DBResourceObserver) + { + DBResourceObserver dbObserver = (DBResourceObserver)observer; + if(dbObserver.isMonitorDbResponse()) + { + if(countObservers() == 0) + { + TimerTask remindTask = new MonitoringTask(); + timer.schedule(remindTask, initialDelay, interval); + activeState = true; + } + } + } + super.addObserver(observer); + } + + public void deleteObserver(Observer observer) + { + super.deleteObserver(observer); + if(observer instanceof DBResourceObserver) + { + DBResourceObserver dbObserver = (DBResourceObserver)observer; + if(dbObserver.isMonitorDbResponse()) + { + if(countObservers() == 0) + { + timer.cancel(); + activeState = false; + } + } + } + } + + public final int getPorcessedConnectionsCount() { + return innerSet.size(); + } +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java new file mode 100644 index 000000000..c17696a80 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java @@ -0,0 +1,37 @@ +/*- + * ============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.pm; + +public interface SQLExecutionMonitorObserver { + public String getDbConnectionName(); + + public long getInterval(); + public void setInterval(long value); + + public long getInitialDelay(); + public void setInitialDelay(long value); + + public long getExpectedCompletionTime(); + public void setExpectedCompletionTime(long value); + + public long getUnprocessedFailoverThreshold(); + public void setUnprocessedFailoverThreshold(long value); +} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java deleted file mode 100644 index 58a0aeb11..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSource.java +++ /dev/null @@ -1,616 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.io.Closeable; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.Date; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Observer; - -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; -import javax.sql.rowset.RowSetProvider; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitor; -import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitorObserver; -import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitor.TestObject; -import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; - - -/** - * @version $Revision: 1.13 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ - -public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver -{ - private static Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); - - protected static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; - - protected long CONN_REQ_TIMEOUT = 30L; - protected long DATA_REQ_TIMEOUT = 100L; - - private final SQLExecutionMonitor monitor; - protected DataSource ds = null; - protected String connectionName = null; - protected boolean initialized = false; - - private long interval = 1000; - private long initialDelay = 5000; - private long expectedCompletionTime = 50L; - private boolean canTakeOffLine = true; - private long unprocessedFailoverThreshold = 3L; - - private long nextErrorReportTime = 0L; - - private String globalHostName = null; - - - public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException - { - configure(jdbcElem); - monitor = new SQLExecutionMonitor(this); - } - - protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; - /* (non-Javadoc) - * @see javax.sql.DataSource#getConnection() - */ - public Connection getConnection() throws SQLException - { - return ds.getConnection(); - } - - public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable - { - TestObject testObject = null; - testObject = monitor.registerRequest(); - - Connection connection = null; - try { - connection = this.getConnection(); - if(connection == null ) { - throw new SQLException("Connection invalid"); - } - if(LOGGER.isDebugEnabled()) - LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); - return executePreparedStatement(connection, statement, arguments, true); - } finally { - try { - if(connection != null && !connection.isClosed()) { - connection.close(); - } - } catch(Throwable exc) { - // the exception not monitored - } finally { - connection = null; - } - - monitor.deregisterReguest(testObject); - } - } - - public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable - { - TestObject testObject = null; - testObject = monitor.registerRequest(); - - Connection connection = null; - try { - connection = this.getConnection(); - if(connection == null ) { - throw new SQLException("Connection invalid"); - } - if(LOGGER.isDebugEnabled()) - LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); - return executeUpdatePreparedStatement(connection, statement, arguments, true); - } finally { - try { - if(connection != null && !connection.isClosed()) { - connection.close(); - } - } catch(Throwable exc) { - // the exception not monitored - } finally { - connection = null; - } - - monitor.deregisterReguest(testObject); - } - } - - CachedRowSet executePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable - { - long time = System.currentTimeMillis(); - - CachedRowSet data = null; - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL Statement: "+ statement); - if(arguments != null && !arguments.isEmpty()) { - LOGGER.debug("Argunments: "+ Arrays.toString(arguments.toArray())); - } - } - - ResultSet rs = null; - try { - data = RowSetProvider.newFactory().createCachedRowSet(); - PreparedStatement ps = conn.prepareStatement(statement); - if(arguments != null) - { - for(int i = 0, max = arguments.size(); i < max; i++){ - ps.setObject(i+1, arguments.get(i)); - } - } - rs = ps.executeQuery(); - data.populate(rs); - // Point the rowset Cursor to the start - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); } - } catch(SQLException exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - try { conn.rollback(); } catch(Throwable thr){} - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; - } catch(Throwable exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; // new SQLException(exc); - } finally { - - try { - if(rs != null){ - rs.close(); - rs = null; - } - } catch(Exception exc){ - - } - try { - if(conn != null && close){ - conn.close(); - conn = null; - } - } catch(Exception exc){ - - } - } - - return data; - } - - boolean executeUpdatePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable { - long time = System.currentTimeMillis(); - - CachedRowSet data = null; - - int rs = -1; - try { - data = RowSetProvider.newFactory().createCachedRowSet(); - PreparedStatement ps = conn.prepareStatement(statement); - if(arguments != null) - { - for(int i = 0, max = arguments.size(); i < max; i++){ - if(arguments.get(i) instanceof Blob) { - ps.setBlob(i+1, (Blob)arguments.get(i)); - } else if(arguments.get(i) instanceof Timestamp) { - ps.setTimestamp(i+1, (Timestamp)arguments.get(i)); - } else if(arguments.get(i) instanceof Integer) { - ps.setInt(i+1, (Integer)arguments.get(i)); - } else if(arguments.get(i) instanceof Long) { - ps.setLong(i+1, (Long)arguments.get(i)); - } else if(arguments.get(i) instanceof Date) { - ps.setDate(i+1, (Date)arguments.get(i)); - } else { - ps.setObject(i+1, arguments.get(i)); - } - } - } - rs = ps.executeUpdate(); - // Point the rowset Cursor to the start - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); - } - } catch(SQLException exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - try { conn.rollback(); } catch(Throwable thr){} - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; - } catch(Throwable exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; // new SQLException(exc); - } finally { - try { - if(conn != null && close){ - conn.close(); - conn = null; - } - } catch(Exception exc){ - - } - } - - return true; - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ - public Connection getConnection(String username, String password) - throws SQLException - { - return ds.getConnection(username, password); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getLogWriter() - */ - public PrintWriter getLogWriter() throws SQLException - { - return ds.getLogWriter(); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getLoginTimeout() - */ - public int getLoginTimeout() throws SQLException - { - return ds.getLoginTimeout(); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) - */ - public void setLogWriter(PrintWriter out) throws SQLException - { - ds.setLogWriter(out); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#setLoginTimeout(int) - */ - public void setLoginTimeout(int seconds) throws SQLException - { - ds.setLoginTimeout(seconds); - } - - - public final String getDbConnectionName(){ - return connectionName; - } - - protected final void setDbConnectionName(String name) { - this.connectionName = name; - } - - public void cleanUp(){ - if(ds != null && ds instanceof Closeable) { - try { - ((Closeable)ds).close(); - } catch (IOException e) { - LOGGER.warn(e.getMessage()); - } - } - ds = null; - monitor.deleteObservers(); - monitor.cleanup(); - } - - public boolean isInitialized() { - return initialized; - } - - protected boolean testConnection(){ - return testConnection(false); - } - - protected boolean testConnection(boolean error_level){ - Connection conn = null; - ResultSet rs = null; - Statement stmt = null; - try - { - Boolean readOnly = null; - String hostname = null; - conn = this.getConnection(); - stmt = conn.createStatement(); - rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); //("SELECT 1 FROM DUAL"); //"select BANNER from SYS.V_$VERSION" - while(rs.next()) - { - readOnly = rs.getBoolean(1); - hostname = rs.getString(2); - - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL DataSource <"+getDbConnectionName() + "> connected to " + hostname + ", read-only is " + readOnly + ", tested successfully "); - } - } - - } catch (Throwable exc) { - if(error_level) { - LOGGER.error("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } else { - LOGGER.info("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } - return false; - } finally { - if(rs != null) { - try { - rs.close(); - rs = null; - } catch (SQLException e) { - } - } - if(stmt != null) { - try { - stmt.close(); - stmt = null; - } catch (SQLException e) { - } - } - if(conn !=null){ - try { - conn.close(); - conn = null; - } catch (SQLException e) { - } - } - } - return true; - } - - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - public T unwrap(Class iface) throws SQLException { - return null; - } - - @SuppressWarnings("deprecation") - public void setConnectionCachingEnabled(boolean state) - { -// if(ds != null && ds instanceof OracleDataSource) -// try { -// ((OracleDataSource)ds).setConnectionCachingEnabled(true); -// } catch (SQLException exc) { -// LOGGER.warn("", exc); -// } - } - - public void addObserver(Observer observer) { - monitor.addObserver(observer); - } - - public void deleteObserver(Observer observer) { - monitor.deleteObserver(observer); - } - - public long getInterval() { - return interval; - } - - public long getInitialDelay() { - return initialDelay; - } - - public void setInterval(long value) { - interval = value; - } - - public void setInitialDelay(long value) { - initialDelay = value; - } - - public long getExpectedCompletionTime() { - return expectedCompletionTime; - } - - public void setExpectedCompletionTime(long value) { - expectedCompletionTime = value; - } - - public long getUnprocessedFailoverThreshold() { - return unprocessedFailoverThreshold; - } - - public void setUnprocessedFailoverThreshold(long value) { - this.unprocessedFailoverThreshold = value; - } - - public boolean canTakeOffLine() { - return canTakeOffLine; - } - - public void blockImmediateOffLine() { - canTakeOffLine = false; - final Thread offLineTimer = new Thread() - { - public void run(){ - try { - Thread.sleep(30000L); - }catch(Throwable exc){ - - }finally{ - canTakeOffLine = true; - } - } - }; - offLineTimer.setDaemon(true); - offLineTimer.start(); - } - - /** - * @return the monitor - */ - final SQLExecutionMonitor getMonitor() { - return monitor; - } - - protected boolean isSlave() throws PoolExhaustedException, MySQLNonTransientConnectionException { - CachedRowSet rs = null; - boolean isSlave = true; - String hostname = "UNDETERMINED"; - try { - boolean localSlave = true; - rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList()); - while(rs.next()) { - localSlave = rs.getBoolean(1); - hostname = rs.getString(2); - } - isSlave = localSlave; - } catch(PoolExhaustedException | MySQLNonTransientConnectionException peexc){ - throw peexc; - } catch (SQLException e) { - LOGGER.error("", e); - isSlave = true; - } catch (Throwable e) { - LOGGER.error("", e); - isSlave = true; - } - if(isSlave){ - LOGGER.debug("SQL SLAVE : "+connectionName + " on server " + hostname); - } else { - LOGGER.debug("SQL MASTER : "+connectionName + " on server " + hostname); - } - return isSlave; - } - - public boolean isFabric() { - return false; - } - - protected boolean lockTable(Connection conn, String tableName) { - boolean retValue = false; - Statement lock = null; - try { - if(tableName != null) { - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); - if("SVC_LOGIC".equals(tableName)) { - Exception e = new Exception(); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - LOGGER.debug(sw.toString()); - } - } - lock = conn.createStatement(); - lock.execute("LOCK TABLES " + tableName + " WRITE"); - retValue = true; - } - } catch(Exception exc){ - LOGGER.error("", exc); - retValue = false; - } finally { - try { - lock.close(); - } catch(Exception exc) { - - } - } - return retValue; - } - - protected boolean unlockTable(Connection conn) { - boolean retValue = false; - Statement lock = null; - try { - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); - } - lock = conn.createStatement(); - retValue = lock.execute("UNLOCK TABLES"); - } catch(Exception exc){ - LOGGER.error("", exc); - retValue = false; - } finally { - try { - lock.close(); - } catch(Exception exc) { - - } - } - return retValue; - } - - public void getPoolInfo(boolean allocation) { - - } - - public long getNextErrorReportTime() { - return nextErrorReportTime; - } - - public void setNextErrorReportTime(long nextTime) { - this.nextErrorReportTime = nextTime; - } - - public void setGlobalHostName(String hostname) { - this.globalHostName = hostname; - } - - public String getGlobalHostName() { - return globalHostName; - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java deleted file mode 100644 index 3e51ed942..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/CachedDataSourceFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - - -import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.jdbc.JdbcDBCachedDataSource; -import org.openecomp.sdnc.sli.resource.dblib.jdbc.MySQLCachedDataSource; - -/** - * @version $Revision: 1.1 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class CachedDataSourceFactory { - - public static CachedDataSource createDataSource(BaseDBConfiguration config) { - if(config instanceof JDBCConfiguration) - return JdbcDBCachedDataSource.createInstance(config); - - return (CachedDataSource)null; - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java deleted file mode 100644 index b324e6a2c..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBConfigException.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - - -/** - * @version $Revision: 1.1 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class DBConfigException extends RuntimeException -{ - /** - * - */ - private static final long serialVersionUID = 4752405152537680257L; - - public DBConfigException(Exception e) - { - super(e.toString()); - } - - public DBConfigException(String msg) - { - super(msg); - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java deleted file mode 100644 index 150a9a82f..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLIBResourceActivator.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.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/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java deleted file mode 100644 index 5c1f51040..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibConnection.java +++ /dev/null @@ -1,390 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Struct; -import java.util.ArrayList; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; - -import javax.sql.rowset.CachedRowSet; - -import org.apache.tomcat.jdbc.pool.PooledConnection; -import org.apache.tomcat.jdbc.pool.ProxyConnection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DBLibConnection implements Connection { - - private static Logger LOGGER = LoggerFactory.getLogger(DBLibConnection.class); - - private final Connection connection; - private final CachedDataSource dataSource; - private boolean locked = false; - private String tableName = null; - - public DBLibConnection(Connection con, CachedDataSource dataSource){ - this.connection = con; - this.dataSource = dataSource; - locked = false; - dataSource.getPoolInfo(true); - } - - public boolean lockTable(String tablename) { - this.tableName = tablename; - return locked = dataSource.lockTable(connection, tableName); - } - - public void resetInactivityTimer() { - Class iface = PooledConnection.class; - try { - PooledConnection pc = connection.unwrap(iface); - pc.setTimestamp(System.currentTimeMillis()); - } catch (SQLException e) { - LOGGER.warn("Failed resetting timeout timer", e); - } - } - - public boolean unlock() { - dataSource.unlockTable(connection); - return locked = false; - } - - public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable - { - ArrayList newList=new ArrayList(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - resetInactivityTimer(); - return dataSource.executeUpdatePreparedStatement(connection, statement, newList, false); - } - - public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable - { - ArrayList newList=new ArrayList(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - resetInactivityTimer(); - return dataSource.executePreparedStatement(connection, statement, newList, false); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return connection.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return connection.isWrapperFor(iface); - } - - @Override - public Statement createStatement() throws SQLException { - return connection.createStatement(); - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { - return connection.prepareStatement(sql); - } - - @Override - public CallableStatement prepareCall(String sql) throws SQLException { - return connection.prepareCall(sql); - } - - @Override - public String nativeSQL(String sql) throws SQLException { - return connection.nativeSQL(sql); - } - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - connection.setAutoCommit(autoCommit); - } - - @Override - public boolean getAutoCommit() throws SQLException { - return connection.getAutoCommit(); - } - - @Override - public void commit() throws SQLException { - connection.commit(); - } - - @Override - public void rollback() throws SQLException { - connection.rollback(); - } - - @Override - public void close() throws SQLException { - if(this.locked) { - try { - this.unlock(); - } catch(Throwable th) { - LOGGER.error("Failed unlocking",th); - } - } - if(connection != null && !connection.isClosed()) { - connection.close(); - } - dataSource.getPoolInfo(false); - } - - @Override - public boolean isClosed() throws SQLException { - return connection.isClosed(); - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - return connection.getMetaData(); - } - - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - connection.setReadOnly(readOnly); - } - - @Override - public boolean isReadOnly() throws SQLException { - return connection.isReadOnly(); - } - - @Override - public void setCatalog(String catalog) throws SQLException { - connection.setCatalog(catalog); - } - - @Override - public String getCatalog() throws SQLException { - return connection.getCatalog(); - } - - @Override - public void setTransactionIsolation(int level) throws SQLException { - connection.setTransactionIsolation(level); - } - - @Override - public int getTransactionIsolation() throws SQLException { - return connection.getTransactionIsolation(); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return connection.getWarnings(); - } - - @Override - public void clearWarnings() throws SQLException { - connection.clearWarnings(); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return connection.createStatement(resultSetType, resultSetConcurrency); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) - throws SQLException { - return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return connection.prepareCall(sql, resultSetType, resultSetConcurrency); - } - - @Override - public Map> getTypeMap() throws SQLException { - return connection.getTypeMap(); - } - - @Override - public void setTypeMap(Map> map) throws SQLException { - connection.setTypeMap(map); - } - - @Override - public void setHoldability(int holdability) throws SQLException { - connection.setHoldability(holdability); - } - - @Override - public int getHoldability() throws SQLException { - return connection.getHoldability(); - } - - @Override - public Savepoint setSavepoint() throws SQLException { - return connection.setSavepoint(); - } - - @Override - public Savepoint setSavepoint(String name) throws SQLException { - return connection.setSavepoint(name); - } - - @Override - public void rollback(Savepoint savepoint) throws SQLException { - connection.rollback(savepoint); - } - - @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - connection.releaseSavepoint(savepoint); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException { - return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return connection.prepareStatement(sql, autoGeneratedKeys); - } - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return connection.prepareStatement(sql, columnIndexes); - } - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return connection.prepareStatement(sql, columnNames); - } - - @Override - public Clob createClob() throws SQLException { - return connection.createClob(); - } - - @Override - public Blob createBlob() throws SQLException { - return connection.createBlob(); - } - - @Override - public NClob createNClob() throws SQLException { - return connection.createNClob(); - } - - @Override - public SQLXML createSQLXML() throws SQLException { - return connection.createSQLXML(); - } - - @Override - public boolean isValid(int timeout) throws SQLException { - return connection.isValid(timeout); - } - - @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { - connection.setClientInfo(name, value); - } - - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - connection.setClientInfo(properties); - } - - @Override - public String getClientInfo(String name) throws SQLException { - return connection.getClientInfo(name); - } - - @Override - public Properties getClientInfo() throws SQLException { - return connection.getClientInfo(); - } - - @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return connection.createArrayOf(typeName, elements); - } - - @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return connection.createStruct(typeName, attributes); - } - - @Override - public void setSchema(String schema) throws SQLException { - connection.setSchema(schema); - } - - @Override - public String getSchema() throws SQLException { - return connection.getSchema(); - } - - @Override - public void abort(Executor executor) throws SQLException { - connection.abort(executor); - } - - @Override - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - connection.setNetworkTimeout(executor, milliseconds); - } - - @Override - public int getNetworkTimeout() throws SQLException { - return connection.getNetworkTimeout(); - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java deleted file mode 100644 index cc80741dc..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBLibException.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.sql.SQLException; - -/** - * An exception time for handling DBLIB specific error handling. - */ -public class DBLibException extends SQLException { - - /** - * - */ - private static final long serialVersionUID = -5345059355083984696L; - - public DBLibException(String message){ - super(message); - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java deleted file mode 100644 index 5cf2953b7..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceManager.java +++ /dev/null @@ -1,862 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.io.PrintWriter; -import java.sql.Connection; -import java.sql.SQLDataException; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLIntegrityConstraintViolationException; -import java.sql.SQLSyntaxErrorException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Observable; -import java.util.PriorityQueue; -import java.util.Properties; -import java.util.Queue; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; - -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; -import org.openecomp.sdnc.sli.resource.dblib.factory.AbstractDBResourceManagerFactory; -import org.openecomp.sdnc.sli.resource.dblib.factory.AbstractResourceManagerFactory; -import org.openecomp.sdnc.sli.resource.dblib.factory.DBConfigFactory; -import org.openecomp.sdnc.sli.resource.dblib.pm.PollingWorker; -import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitor; -import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * @version $Revision: 1.15 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class DBResourceManager implements DataSource, DataAccessor, DBResourceObserver, DbLibService { - private static Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); - - transient boolean terminating = false; - transient protected long retryInterval = 10000L; - transient boolean recoveryMode = true; - - protected final AtomicBoolean dsSelector = new AtomicBoolean(); - -// Queue dsQueue = new ConcurrentLinkedQueue(); - Queue dsQueue = new PriorityQueue(4, new Comparator(){ - - @Override - public int compare(CachedDataSource left, CachedDataSource right) { - try { - if(!left.isSlave()) - return -1; - if(!right.isSlave()) - return 1; - - } catch (Throwable e) { - LOGGER.warn("", e); - } - return 0; - } - - }); - protected final Set broken = Collections.synchronizedSet(new HashSet()); - protected final Object monitor = new Object(); - protected final Properties configProps; - protected final Thread worker; - - protected final long terminationTimeOut; - protected final boolean monitorDbResponse; - protected final long monitoringInterval; - protected final long monitoringInitialDelay; - protected final long expectedCompletionTime; - protected final long unprocessedFailoverThreshold; - - public DBResourceManager(Properties props){ - this.configProps = props; - - // get retry interval value - retryInterval = getLongFromProperties(props, "org.openecomp.dblib.connection.retry", 10000L); - - // get recovery mode flag - recoveryMode = getBooleanFromProperties(props, "org.openecomp.dblib.connection.recovery", true); - if(!recoveryMode) - { - recoveryMode = false; - LOGGER.info("Recovery Mode disabled"); - } - // get time out value for thread cleanup - terminationTimeOut = getLongFromProperties(props, "org.openecomp.dblib.termination.timeout", 300000L); - // get properties for monitoring - monitorDbResponse = getBooleanFromProperties(props, "org.openecomp.dblib.connection.monitor", false); - monitoringInterval = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.interval", 1000L); - monitoringInitialDelay = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.startdelay", 5000L); - expectedCompletionTime = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.expectedcompletiontime", 5000L); - unprocessedFailoverThreshold = getLongFromProperties(props, "org.openecomp.dblib.connection.monitor.unprocessedfailoverthreshold", 3L); - - // initialize performance monitor - PollingWorker.createInistance(props); - - // initialize recovery thread - worker = new RecoveryMgr(); - worker.setName("DBResourcemanagerWatchThread"); - worker.setDaemon(true); - worker.start(); - } - - private void config(Properties ctx) throws Exception { - - DbConfigPool dbConfig = DBConfigFactory.createConfig(this.configProps); - - 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."); - } - - for(int i=0; i 1){ - handleGetConnectionException(dataSource, new Exception(data.toString())); - } - } - } - } - } - - public void testForceRecovery() - { - CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); - handleGetConnectionException(active, new Exception("test")); - } - - class RecoveryMgr extends Thread { - - public void run() { - while(!terminating) - { - try { - Thread.sleep(retryInterval); - } catch (InterruptedException e1) { } - CachedDataSource brokenSource = null; - try { - if (!broken.isEmpty()) { - CachedDataSource[] sourceArray = broken.toArray(new CachedDataSource[0]); - for (int i = 0; i < sourceArray.length; i++) - { - brokenSource = sourceArray[i]; - if (brokenSource instanceof TerminatingCachedDataSource) - break; - if (resetConnectionPool(brokenSource)) { - broken.remove(brokenSource); - brokenSource.blockImmediateOffLine(); - dsQueue.add(brokenSource); - LOGGER.info("DataSource <" - + brokenSource.getDbConnectionName() - + "> recovered."); - } - brokenSource = null; - } - } - } catch (Exception exc) { - LOGGER.warn(exc.getMessage()); - if(brokenSource != null){ - try { - if(!broken.contains(brokenSource)) - broken.add(brokenSource); - brokenSource = null; - } catch (Exception e1) { } - } - } - } - LOGGER.info("DBResourceManager.RecoveryMgr <"+this.toString() +"> terminated." ); - } - - private boolean resetConnectionPool(CachedDataSource dataSource){ - try { - return dataSource.testConnection(); - } catch (Exception exc) { - LOGGER.info("DataSource <" + dataSource.getDbConnectionName() + "> resetCache failed with error: "+ exc.getMessage()); - return false; - } - } - } - - /* (non-Javadoc) - * @see org.openecomp.sdnc.sli.resource.dblib.DbLibService#getData(java.lang.String, java.util.ArrayList, java.lang.String) - */ - @Override - public CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) throws SQLException { - ArrayList newList=new ArrayList(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - if(recoveryMode) - return requestDataWithRecovery(statement, newList, preferredDS); - else - return requestDataNoRecovery(statement, newList, preferredDS); - } - - private CachedRowSet requestDataWithRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { - Throwable lastException = null; - CachedDataSource active = null; - - // test if there are any connection pools available - LinkedList sources = new LinkedList(this.dsQueue); - if(sources.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); - throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); - } - if(preferredDS != null && !sources.peek().getDbConnectionName().equals(preferredDS)) { - Collections.reverse(sources); - } - - - // loop through available data sources to retrieve data. - while(!sources.isEmpty()) - { - active = sources.peek(); - - long time = System.currentTimeMillis(); - try { - if(!active.isFabric()) { - CachedDataSource master = findMaster(); - if(master != null) { - active = master; - master = null; - } - } - sources.remove(active); - return active.getData(statement, arguments); - } catch(SQLDataException exc){ - throw exc; - } catch(SQLSyntaxErrorException exc){ - throw exc; - } catch(SQLIntegrityConstraintViolationException exc){ - throw exc; - } catch(Throwable exc){ - lastException = exc; - String message = exc.getMessage(); - if(message == null) { - if(exc.getCause() != null) { - message = exc.getCause().getMessage(); - } - if(message == null) - message = exc.getClass().getName(); - } - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); - handleGetConnectionException(active, exc); - } finally { - if(LOGGER.isDebugEnabled()){ - time = (System.currentTimeMillis() - time); - LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); - } - } - } - if(lastException instanceof SQLException){ - throw (SQLException)lastException; - } - // repackage the exception - // you are here because either you run out of available data sources - // or the last exception was not of SQLException type. - // repackage the exception - if(lastException == null) { - throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); - } else { - SQLException exception = new DBLibException(lastException.getMessage()); - exception.setStackTrace(lastException.getStackTrace()); - if(lastException.getCause() instanceof SQLException) { - throw (SQLException)lastException.getCause(); - } - throw exception; - } - } - - private CachedRowSet requestDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { - if(dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); - throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); - } - CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); - long time = System.currentTimeMillis(); - try { - if(!active.isFabric()) { - CachedDataSource master = findMaster(); - if(master != null) - active = master; - } - return active.getData(statement, arguments); -// } catch(SQLDataException exc){ -// throw exc; - } catch(Throwable exc){ - String message = exc.getMessage(); - if(message == null) - message = exc.getClass().getName(); - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); - if(exc instanceof SQLException) - throw (SQLException)exc; - else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } finally { - if(LOGGER.isDebugEnabled()){ - time = (System.currentTimeMillis() - time); - LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); - } - } - } - - - /* (non-Javadoc) - * @see org.openecomp.sdnc.sli.resource.dblib.DbLibService#writeData(java.lang.String, java.util.ArrayList, java.lang.String) - */ - @Override - public boolean writeData(String statement, ArrayList arguments, String preferredDS) throws SQLException - { - ArrayList newList=new ArrayList(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - - return writeDataNoRecovery(statement, newList, preferredDS); - } - - CachedDataSource findMaster() throws PoolExhaustedException, MySQLNonTransientConnectionException { - CachedDataSource master = null; - CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); - for(int i=0; i arguments, String preferredDS) throws SQLException { - if(dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); - throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); - } - - boolean initialRequest = true; - boolean retryAllowed = true; - CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); - long time = System.currentTimeMillis(); - while(initialRequest) { - initialRequest = false; - try { - if(!active.isFabric()) { - CachedDataSource master = findMaster(); - if(master != null) { - active = master; - } - } - - return active.writeData(statement, arguments); - } catch(Throwable exc){ - String message = exc.getMessage(); - if(message == null) - message = exc.getClass().getName(); - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); - if(exc instanceof SQLException) { - SQLException sqlExc = SQLException.class.cast(exc); - // handle read-only exception - if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { - LOGGER.warn("retrying due to: " + sqlExc.getMessage()); - dsQueue.remove(active); - dsQueue.add(active); - if(retryAllowed){ - retryAllowed = false; - initialRequest = true; - continue; - } - } - throw (SQLException)exc; - } else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } finally { - if(LOGGER.isDebugEnabled()){ - time = (System.currentTimeMillis() - time); - LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); - } - } - } - return true; - } - - private void setDataSource(CachedDataSource dataSource) { - if(dataSource.testConnection(true)){ - this.dsQueue.add(dataSource); - } else { - this.broken.add(dataSource); - } - } - - public Connection getConnection() throws SQLException { - Throwable lastException = null; - CachedDataSource active = null; - - if(dsQueue.isEmpty()){ - throw new DBLibException("No active DB connection pools are available in GetConnection call."); - } - - try { - active = dsQueue.peek(); - CachedDataSource tmpActive = findMaster(); - if(tmpActive != null) { - active = tmpActive; - } - return new DBLibConnection(active.getConnection(), active); - } catch(javax.sql.rowset.spi.SyncFactoryException exc){ - LOGGER.debug("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); - LOGGER.warn("CLASSPATH issue. Allowing retry", exc); - lastException = exc; - } catch(PoolExhaustedException exc) { - throw new NoAvailableConnectionsException(exc); - } catch(MySQLNonTransientConnectionException exc){ - throw new NoAvailableConnectionsException(exc); - } catch(Exception exc){ - lastException = exc; - if(recoveryMode){ - handleGetConnectionException(active, exc); - } else { - if(exc instanceof MySQLNonTransientConnectionException) { - throw new NoAvailableConnectionsException(exc); - } if(exc instanceof SQLException) { - throw (SQLException)exc; - } else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } - } catch (Throwable trwb) { - DBLibException excptn = new DBLibException(trwb.getMessage()); - excptn.setStackTrace(trwb.getStackTrace()); - throw excptn; - } finally { - if(LOGGER.isDebugEnabled()){ - displayState(); - } - } - - if(lastException instanceof SQLException){ - throw (SQLException)lastException; - } - // repackage the exception - if(lastException == null) { - throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); - } else { - SQLException exception = new DBLibException(lastException.getMessage()); - exception.setStackTrace(lastException.getStackTrace()); - if(lastException.getCause() instanceof SQLException) { -// exception.setNextException((SQLException)lastException.getCause()); - throw (SQLException)lastException.getCause(); - } - throw exception; - } - } - - public Connection getConnection(String username, String password) - throws SQLException { - CachedDataSource active = null; - - if(dsQueue.isEmpty()){ - throw new DBLibException("No active DB connection pools are available in GetConnection call."); - } - - - try { - active = dsQueue.peek(); - CachedDataSource tmpActive = findMaster(); - if(tmpActive != null) { - active = tmpActive; - } - return active.getConnection(username, password); - } catch(Throwable exc){ - if(recoveryMode){ - handleGetConnectionException(active, exc); - } else { - if(exc instanceof SQLException) - throw (SQLException)exc; - else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } - - } - - throw new DBLibException("No connections available in DBResourceManager in GetConnection call."); - } - - private void handleGetConnectionException(CachedDataSource source, Throwable exc) { - try { - if(!source.canTakeOffLine()) - { - LOGGER.error("Could not switch due to blocking"); - return; - } - - boolean removed = dsQueue.remove(source); - if(!broken.contains(source)) - { - if(broken.add(source)) - { - LOGGER.warn("DB Recovery: DataSource <" + source.getDbConnectionName() + "> put in the recovery mode. Reason : " + exc.getMessage()); - } else { - LOGGER.warn("Error putting DataSource <" +source.getDbConnectionName()+ "> in recovery mode."); - } - } else { - LOGGER.info("DB Recovery: DataSource <" + source.getDbConnectionName() + "> already in recovery queue"); - } - if(removed) - { - if(!dsQueue.isEmpty()) - { - LOGGER.warn("DB DataSource <" + dsQueue.peek().getDbConnectionName() + "> became active"); - } - } - } catch (Exception e) { - LOGGER.error("", e); - } - } - - public void cleanUp() { - for(Iterator it=dsQueue.iterator();it.hasNext();){ - CachedDataSource cds = (CachedDataSource)it.next(); - it.remove(); - cds.cleanUp(); - } - - try { - this.terminating = true; - if(broken != null) - { - try { - broken.add( new TerminatingCachedDataSource(null)); - } catch(Exception exc){ - LOGGER.error("Waiting for Worker to stop", exc); - } - } - worker.join(terminationTimeOut); - LOGGER.info("DBResourceManager.RecoveryMgr <"+worker.toString() +"> termination was successful: " + worker.getState()); - } catch(Exception exc){ - LOGGER.error("Waiting for Worker thread to terminate ", exc); - } - } - - public static DBResourceManager create(Properties props) throws Exception { - DBResourceManager dbmanager = new DBResourceManager(props); - dbmanager.config(props); - return dbmanager; - } - - public PrintWriter getLogWriter() throws SQLException { - return ((CachedDataSource)this.dsQueue.peek()).getLogWriter(); - } - - public int getLoginTimeout() throws SQLException { - return ((CachedDataSource)this.dsQueue.peek()).getLoginTimeout(); - } - - public void setLogWriter(PrintWriter out) throws SQLException { - ((CachedDataSource)this.dsQueue.peek()).setLogWriter(out); - } - - public void setLoginTimeout(int seconds) throws SQLException { - ((CachedDataSource)this.dsQueue.peek()).setLoginTimeout(seconds); - } - - public void displayState(){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); - CachedDataSource current = (CachedDataSource)dsQueue.peek(); - if(current != null) { - LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); - } - } - } - - /* (non-Javadoc) - * @see org.openecomp.sdnc.sli.resource.dblib.DbLibService#isActive() - */ - @Override - public boolean isActive() { - return this.dsQueue.size()>0; - } - - public String getActiveStatus(){ - return "Connected: " + dsQueue.size()+"\tIn-recovery: "+broken.size(); - } - - public String getDBStatus(boolean htmlFormat) { - StringBuilder buffer = new StringBuilder(); - - ArrayList list = new ArrayList(); - list.addAll(dsQueue); - list.addAll(broken); - if (htmlFormat) - { - buffer.append("") - .append("Name:").append(""); - for (int i = 0; i < list.size(); i++) { - buffer.append(""); - buffer.append(((CachedDataSource) list.get(i)).getDbConnectionName()).append(""); - } - buffer.append(""); - - buffer.append("State:"); - for (int i = 0; i < list.size(); i++) { - if (broken.contains(list.get(i))) { - buffer.append("in recovery"); - } - if (dsQueue.contains(list.get(i))) { - if (dsQueue.peek() == list.get(i)) - buffer.append("active"); - else - buffer.append("standby"); - } - } - buffer.append(""); - - } else { - for (int i = 0; i < list.size(); i++) { - buffer.append("Name: ").append(((CachedDataSource) list.get(i)).getDbConnectionName()); - buffer.append("\tState: "); - if (broken.contains(list.get(i))) { - buffer.append("in recovery"); - } else - if (dsQueue.contains(list.get(i))) { - if (dsQueue.peek() == list.get(i)) - buffer.append("active"); - else - buffer.append("standby"); - } - - buffer.append("\n"); - - } - } - return buffer.toString(); - } - - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - public T unwrap(Class iface) throws SQLException { - return null; - } - - /** - * @return the monitorDbResponse - */ - public final boolean isMonitorDbResponse() { - return recoveryMode && monitorDbResponse; - } - - public void test(){ - CachedDataSource obj = dsQueue.peek(); - Exception ption = new Exception(); - try { - for(int i=0; i<5; i++) - { - handleGetConnectionException(obj, ption); - } - } catch(Throwable exc){ - LOGGER.warn("", exc); - } - } - - public String getPreferredDSName(){ - if(isActive()){ - return getPreferredDataSourceName(dsSelector); - } - return ""; - } - - public String getPreferredDataSourceName(AtomicBoolean flipper) { - - LinkedList snapshot = new LinkedList(dsQueue); - if(snapshot.size() > 1){ - CachedDataSource first = snapshot.getFirst(); - CachedDataSource last = snapshot.getLast(); - - int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); - if(delta < 0) { - flipper.set(false); - } else if(delta > 0) { - flipper.set(true); - } else { - // check the last value and return !last - flipper.getAndSet(!flipper.get()); - } - - if (flipper.get()) - Collections.reverse(snapshot); - } - return snapshot.peek().getDbConnectionName(); - } - - public java.util.logging.Logger getParentLogger() - throws SQLFeatureNotSupportedException { - return null; - } - - public String getMasterName() { - if(isActive()){ - return getMasterDataSourceName(dsSelector); - } - return ""; - } - - - private String getMasterDataSourceName(AtomicBoolean flipper) { - - LinkedList snapshot = new LinkedList(dsQueue); - if(snapshot.size() > 1){ - CachedDataSource first = snapshot.getFirst(); - CachedDataSource last = snapshot.getLast(); - - int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); - if(delta < 0) { - flipper.set(false); - } else if(delta > 0) { - flipper.set(true); - } else { - // check the last value and return !last - flipper.getAndSet(!flipper.get()); - } - - if (flipper.get()) - Collections.reverse(snapshot); - } - return snapshot.peek().getDbConnectionName(); - } - - class RemindTask extends TimerTask { - public void run() { - CachedDataSource ds = dsQueue.peek(); - if(ds != null) - ds.getPoolInfo(false); - } - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java deleted file mode 100644 index e06779f35..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DBResourceObserver.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.util.Observer; - -public interface DBResourceObserver extends Observer { - public boolean isMonitorDbResponse(); -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java deleted file mode 100644 index cd054a51d..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataAccessor.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.sql.SQLException; -import java.util.ArrayList; - -import javax.sql.rowset.CachedRowSet; - -public interface DataAccessor { - - public abstract CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) - throws SQLException; - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java deleted file mode 100644 index 37d625136..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DataSourceComparator.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.util.Comparator; - -public interface DataSourceComparator extends Comparator { - - public abstract CachedDataSource getLastUsed(); - - public abstract void setLastUsed(CachedDataSource lastUsed); - - public abstract int compare(CachedDataSource ds1, CachedDataSource ds2); - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java deleted file mode 100644 index 25edd1f07..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DbLibService.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.sql.SQLException; -import java.util.ArrayList; - -import javax.sql.rowset.CachedRowSet; - -public interface DbLibService { - - /* (non-Javadoc) - * @see DataAccessor#getData(java.lang.String, java.util.ArrayList) - */ - public abstract CachedRowSet getData(String statement, - ArrayList arguments, String preferredDS) - throws SQLException; - - /* (non-Javadoc) - * @see DataAccessor#writeData(java.lang.String, java.util.ArrayList) - */ - public abstract boolean writeData(String statement, - ArrayList arguments, String preferredDS) - throws SQLException; - - public abstract boolean isActive(); - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java deleted file mode 100644 index 17700a5ee..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/DblibConfigurationException.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - - -public class DblibConfigurationException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public DblibConfigurationException() - { - super(); - } - - public DblibConfigurationException(String msg) - { - super(msg); - } - - public DblibConfigurationException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java deleted file mode 100644 index 16895b4d5..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/NoAvailableConnectionsException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.sql.SQLException; - -public class NoAvailableConnectionsException extends SQLException { - - /** - * - */ - private static final long serialVersionUID = -6259205931674413018L; - - public NoAvailableConnectionsException(Exception exc) { - super(exc); - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java deleted file mode 100644 index 234bbed0c..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/TerminatingCachedDataSource.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib; - -import java.sql.SQLFeatureNotSupportedException; -import java.util.logging.Logger; - -import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.pm.SQLExecutionMonitorObserver; - - -public class TerminatingCachedDataSource extends CachedDataSource implements SQLExecutionMonitorObserver { - - public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { - super(jdbcElem); - } - - protected void configure(BaseDBConfiguration jdbcElem) throws DBConfigException { - // no action - } - - public long getInterval() { - return 1000; - } - - public long getInitialDelay() { - return 1000; - } - - public long getExpectedCompletionTime() { - return 50; - } - - public void setExpectedCompletionTime(long value) { - - } - - public void setInterval(long value) { - - } - - public void setInitialDelay(long value) { - - } - - public long getUnprocessedFailoverThreshold() { - return 3; - } - - public void setUnprocessedFailoverThreshold(long value) { - - } - - public int compareTo(CachedDataSource ods) - { - return 0; - } - - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java deleted file mode 100644 index 976b1cf2d..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/BaseDBConfiguration.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.config; - -import java.util.Properties; - -public abstract class BaseDBConfiguration { - public static final String DATABASE_TYPE = "org.openecomp.sdnc.sli.dbtype"; - public static final String DATABASE_URL = "org.openecomp.sdnc.sli.jdbc.url"; - public static final String DATABASE_NAME = "org.openecomp.sdnc.sli.jdbc.database"; - public static final String CONNECTION_NAME = "org.openecomp.sdnc.sli.jdbc.connection.name"; - public static final String DATABASE_USER = "org.openecomp.sdnc.sli.jdbc.user"; - public static final String DATABASE_PSSWD = "org.openecomp.sdnc.sli.jdbc.password"; - public static final String CONNECTION_TIMEOUT="org.openecomp.sdnc.sli.jdbc.connection.timeout"; - public static final String REQUEST_TIMEOUT = "org.openecomp.sdnc.sli.jdbc.request.timeout"; - public static final String MIN_LIMIT = "org.openecomp.sdnc.sli.jdbc.limit.min"; - public static final String MAX_LIMIT = "org.openecomp.sdnc.sli.jdbc.limit.max"; - public static final String INIT_LIMIT = "org.openecomp.sdnc.sli.jdbc.limit.init"; - public static final String DATABASE_HOSTS = "org.openecomp.sdnc.sli.jdbc.hosts"; - - - protected final Properties props; - - public BaseDBConfiguration(Properties properties) { - this.props = properties; - } - - public int getConnTimeout() { - try { - String value = props.getProperty(CONNECTION_TIMEOUT); - return Integer.parseInt(value); - } catch(Exception exc) { - return -1; - } - } - - public int getRequestTimeout() { - try { - String value = props.getProperty(REQUEST_TIMEOUT); - if(value == null) - return -1; - return Integer.parseInt(value); - } catch(Exception exc) { - return -1; - } - } - - public String getDbConnectionName() { - return props.getProperty(CONNECTION_NAME); - } - - public String getDatabaseName() { - return props.getProperty(DATABASE_NAME); - } - - public String getDbUserId() { - return props.getProperty(DATABASE_USER); - } - - public String getDbPasswd() { - return props.getProperty(DATABASE_PSSWD); - } - - public int getDbMinLimit() { - String value = props.getProperty(MIN_LIMIT); - return Integer.parseInt(value); - } - - public int getDbMaxLimit() { - String value = props.getProperty(MAX_LIMIT); - return Integer.parseInt(value); - } - - public int getDbInitialLimit() { - String value = props.getProperty(INIT_LIMIT); - return Integer.parseInt(value); - } - - public String getDbUrl() { - return props.getProperty(DATABASE_URL); - } - - public String getServerGroup() { - return null; - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java deleted file mode 100644 index 117f9321d..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/DbConfigPool.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.config; - -import java.util.ArrayList; -import java.util.Properties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DbConfigPool { - private static Logger LOGGER = LoggerFactory.getLogger(DbConfigPool.class); - - private final String type; - - private ArrayList configurations = new ArrayList(); - - public DbConfigPool(Properties properties) { - LOGGER.debug("Initializing DbConfigType"); - type = properties.getProperty(BaseDBConfiguration.DATABASE_TYPE, "JDBC").toUpperCase(); - } - - public int getTimeout() { - // TODO Auto-generated method stub - return 0; - } - - public String getType() { - return type; - } - - public JDBCConfiguration[] getJDBCbSourceArray() { - return configurations.toArray(new JDBCConfiguration[configurations.size()]); - } - - public void addConfiguration(BaseDBConfiguration config) { - configurations.add(config); - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java deleted file mode 100644 index cb6ea3e5c..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/config/JDBCConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.config; - -import java.util.Properties; - -public class JDBCConfiguration extends BaseDBConfiguration { - - public JDBCConfiguration(Properties xmlElem) { - super(xmlElem); - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java deleted file mode 100644 index f4291a7dd..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractDBResourceManagerFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.factory; - -import org.openecomp.sdnc.sli.resource.dblib.jdbc.JdbcDbResourceManagerFactory; - -/** - * @version $Revision: 1.1 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class AbstractDBResourceManagerFactory { - - public static AbstractResourceManagerFactory getFactory(String type) throws FactoryNotDefinedException { - - // JDBC - return JdbcDbResourceManagerFactory.createIntstance(); - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java deleted file mode 100644 index 0f58a3f03..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/AbstractResourceManagerFactory.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.factory; - - -import java.sql.SQLException; -import java.util.Set; -import java.util.concurrent.Callable; - -import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource; -import org.openecomp.sdnc.sli.resource.dblib.CachedDataSourceFactory; -import org.openecomp.sdnc.sli.resource.dblib.DBConfigException; -import org.openecomp.sdnc.sli.resource.dblib.DBResourceManager; -import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; -import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @version $Revision: 1.6 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public abstract class AbstractResourceManagerFactory { - private static Logger LOGGER = LoggerFactory.getLogger(AbstractResourceManagerFactory.class); - - public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager) throws Exception; - public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager dbResourceManager, String sourceName) throws SQLException ; - - - public static AbstractResourceManagerFactory createIntstance() throws FactoryNotDefinedException { - throw new FactoryNotDefinedException("Factory method 'createIntstance' needs to be overriden in DBResourceManagerFactory"); - } - - public class DBInitTask implements Callable - { - private BaseDBConfiguration config = null; - private Set activeTasks; - - public DBInitTask(JDBCConfiguration jdbcconfig, Set tasks) { - this.config = jdbcconfig; - this.activeTasks = tasks; - } - - public CachedDataSource call() throws Exception { - CachedDataSource ds = null; - try { - ds = CachedDataSourceFactory.createDataSource(config); - return ds; - } finally { - synchronized(activeTasks) { - activeTasks.remove(this); - if (activeTasks.isEmpty()) { - final Runnable closure = new Runnable() { - - public void run() { - try { - Thread.sleep(300); - } catch (Exception e) { - } - synchronized(activeTasks) { - activeTasks.notifyAll(); - } - } - }; - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Completed CachedDataSource.Call and notifyAll from " + ds.getDbConnectionName()); - } - Thread worker = new Thread(closure); - worker.setDaemon(true); - worker.start(); - } else { - if (LOGGER.isDebugEnabled()) { - if (ds != null) { - LOGGER.debug("Completed CachedDataSource.Call from " + ds.getDbConnectionName()); - } - } - } - } - } - } - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java deleted file mode 100644 index 8aadcae6b..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/DBConfigFactory.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.factory; - - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Properties; - -import org.slf4j.LoggerFactory; - -import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; -import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; - -/** - * @version $Revision: 1.1 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki 01/17/08 Initial version - */ -public class DBConfigFactory { - - public static DbConfigPool createConfig(Properties resource) { - return getConfigparams(resource); - } - - static DbConfigPool getConfigparams(Properties properties){ - DbConfigPool xmlConfig = new DbConfigPool(properties); - ArrayList propertySets = new ArrayList(); - - if("JDBC".equalsIgnoreCase(xmlConfig.getType())) { - String hosts = properties.getProperty(BaseDBConfiguration.DATABASE_HOSTS); - if(hosts == null || hosts.isEmpty()) { - propertySets.add(properties); - } else { - String[] newhost = hosts.split(","); - for(int i=0; i< newhost.length; i++) { - Properties localset = new Properties(); - localset.putAll(properties); - String url = localset.getProperty(BaseDBConfiguration.DATABASE_URL); - if(url.contains("DBHOST")) - url = url.replace("DBHOST", newhost[i]); - if(url.contains("dbhost")) - url = url.replace("dbhost", newhost[i]); - localset.setProperty(BaseDBConfiguration.DATABASE_URL, url); - localset.setProperty(BaseDBConfiguration.CONNECTION_NAME, newhost[i]); - propertySets.add(localset); - } - } - } else { - propertySets.add(properties); - } - try { - Iterator it = propertySets.iterator(); - while(it.hasNext()) { - BaseDBConfiguration config = parse(it.next()); - xmlConfig.addConfiguration(config); - } - - } catch (Exception e) { - LoggerFactory.getLogger(DBConfigFactory.class).warn("",e); - } - - return xmlConfig; - } - - public static BaseDBConfiguration parse(Properties props) throws Exception { - - String type = props.getProperty(BaseDBConfiguration.DATABASE_TYPE); - - BaseDBConfiguration config = null; - - if("JDBC".equalsIgnoreCase(type)) { - config = new JDBCConfiguration(props); - } - - return config; - - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java deleted file mode 100644 index e38cd3519..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/factory/FactoryNotDefinedException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.factory; - - -/** - * @version 1.3 - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki 01/16/08 Initial version - */ -public class FactoryNotDefinedException extends Exception { - - public FactoryNotDefinedException(String message) { - super(message); - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java deleted file mode 100644 index 90c76f637..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDBCachedDataSource.java +++ /dev/null @@ -1,249 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.jdbc; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLFeatureNotSupportedException; - -import org.apache.tomcat.jdbc.pool.DataSource; -import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource; -import org.openecomp.sdnc.sli.resource.dblib.DBConfigException; -import org.openecomp.sdnc.sli.resource.dblib.config.BaseDBConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; -import com.mysql.jdbc.Driver; - - -/** - * @version $Revision: 1.7 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ - -public class JdbcDBCachedDataSource extends CachedDataSource -{ - private String dbUserId; - private String dbPasswd; - private String dbUrl; - - private int minLimit; - private int maxLimit; - private int initialLimit; - - private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; - - private static Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class); - - /** - * @param jdbcElem - */ - public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem) - { - super(jdbcElem); - } - - @Override - protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException - { - BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem; - if(jdbcConfig.getConnTimeout() > 0){ - this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); - } - if(jdbcConfig.getRequestTimeout() > 0){ - this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); - } - - // set connection pool name - String dbConnectionName = jdbcConfig.getDbConnectionName(); - super.setDbConnectionName(dbConnectionName); - // Configure the JDBC connection - dbUserId = jdbcConfig.getDbUserId(); - if (dbUserId == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - dbPasswd = jdbcConfig.getDbPasswd(); - if (dbPasswd == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - /* - dbDriver = jdbcConfig.getDbDriver(); - if (dbDriver == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new ScpTblUpdateError(errorMsg); - } - */ - - minLimit = jdbcConfig.getDbMinLimit(); -// if (minLimit == null) -// { -// String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); -// } - maxLimit = jdbcConfig.getDbMaxLimit(); -// if (maxLimit == null) -// { -// String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); -// } - initialLimit = jdbcConfig.getDbInitialLimit(); -// if (initialLimit == null) -// { -// String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); -// } - - dbUrl = jdbcConfig.getDbUrl(); - if(dbUrl == null){ - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - try { - Driver dr = new com.mysql.jdbc.Driver(); - Class clazz = Class.forName("com.mysql.jdbc.Driver") ; - - PoolProperties p = new PoolProperties(); - p.setDriverClassName("com.mysql.jdbc.Driver"); - p.setUrl(dbUrl); - p.setUsername(dbUserId); - p.setPassword(dbPasswd); - p.setJmxEnabled(true); - p.setTestWhileIdle(false); - p.setTestOnBorrow(true); - p.setValidationQuery("SELECT 1"); - p.setTestOnReturn(false); - p.setValidationInterval(30000); - p.setTimeBetweenEvictionRunsMillis(30000); - p.setInitialSize(initialLimit); - p.setMaxActive(maxLimit); - p.setMaxIdle(maxLimit); - p.setMaxWait(10000); - p.setRemoveAbandonedTimeout(60); - p.setMinEvictableIdleTimeMillis(30000); - p.setMinIdle(minLimit); - p.setLogAbandoned(true); - p.setRemoveAbandoned(true); - p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" - + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); - - DataSource dataSource = new DataSource(p); - - synchronized(this) - { - this.ds = dataSource; - Connection con = null; - PreparedStatement st = null; - ResultSet rs = null; - - try { - con = dataSource.getConnection(); - st = con.prepareStatement("Select 1 FROM DUAL"); - rs = st.executeQuery(); - } catch(Exception exc) { - LOGGER.error(exc.getMessage()); - } finally { - if(rs != null) rs.close(); - if(st != null) st.close(); - if(con != null) con.close(); - } - - initialized = true; - LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); - } - -// } catch (SQLException exc) { -// initialized = false; -// StringBuffer sb = new StringBuffer(); -// sb.append("Failed to initialize MySQLDataSource<"); -// sb.append(dbConnectionName).append(">. Reason: "); -// sb.append(exc.getMessage()); -// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -//// throw new DBConfigException(e.getMessage()); - } catch (Exception exc) { - initialized = false; - StringBuffer sb = new StringBuffer(); - sb.append("Failed to initialize MySQLCachedDataSource <"); - sb.append(dbConnectionName).append(">. Reason: "); - sb.append(exc.getMessage()); - LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -// throw new DBConfigException(e.getMessage()); - } - } - - public final String getDbUrl() - { - return dbUrl; - } - - public final String getDbUserId() - { - return dbUserId; - } - - public final String getDbPasswd() - { - return dbPasswd; - } - - public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { - return new JdbcDBCachedDataSource(config); - } - - public String toString(){ - return getDbConnectionName(); - } - - public java.util.logging.Logger getParentLogger() - throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub - return null; - } - - public void cleanUp(){ - DataSource dataSource = (DataSource)ds; - dataSource.getPool().purge(); - int active = dataSource.getActive(); - int size = dataSource.getSize(); - dataSource.close(true); - super.cleanUp(); - } - -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java deleted file mode 100644 index 84399dfd9..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/jdbc/JdbcDbResourceManagerFactory.java +++ /dev/null @@ -1,186 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.jdbc; - - -import java.sql.SQLException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; - -import org.openecomp.sdnc.sli.resource.dblib.CachedDataSource; -import org.openecomp.sdnc.sli.resource.dblib.CachedDataSourceFactory; -import org.openecomp.sdnc.sli.resource.dblib.DBResourceManager; -import org.openecomp.sdnc.sli.resource.dblib.DataSourceComparator; -import org.openecomp.sdnc.sli.resource.dblib.config.DbConfigPool; -import org.openecomp.sdnc.sli.resource.dblib.config.JDBCConfiguration; -import org.openecomp.sdnc.sli.resource.dblib.factory.AbstractResourceManagerFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @version $Revision: 1.6 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class JdbcDbResourceManagerFactory extends AbstractResourceManagerFactory { - private static Logger LOGGER = LoggerFactory.getLogger(JdbcDbResourceManagerFactory.class ); - private JdbcDbResourceManagerFactory(){ - - } - - class MyFutureTask extends FutureTask - { - - public MyFutureTask(Callable result) { - super(result); - } - - } - - public CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager, String sourceName) throws SQLException - { - // here create the data sources objects - JDBCConfiguration[] list = dbConfig.getJDBCbSourceArray(); - CachedDataSource[] cachedDS = new CachedDataSource[1]; - - for(int i=0, max=list.length; i tasks = new HashSet(); - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("Creating " + list.length + " datasources."); - } - - for(int i=0, max=list.length; i 0){ - this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); - } - if(jdbcConfig.getRequestTimeout() > 0){ - this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); - } - - // set connection pool name - String dbConnectionName = jdbcConfig.getDbConnectionName(); - super.setDbConnectionName(dbConnectionName); - // Configure the JDBC connection - dbUserId = jdbcConfig.getDbUserId(); - if (dbUserId == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - dbPasswd = jdbcConfig.getDbPasswd(); - if (dbPasswd == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - /* - dbDriver = jdbcConfig.getDbDriver(); - if (dbDriver == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new ScpTblUpdateError(errorMsg); - } - */ - - minLimit = Integer.toString(jdbcConfig.getDbMinLimit()); - if (minLimit == null) - { - String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - maxLimit = Integer.toString(jdbcConfig.getDbMaxLimit()); - if (maxLimit == null) - { - String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - initialLimit = Integer.toString(jdbcConfig.getDbInitialLimit()); - if (initialLimit == null) - { - String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - dbUrl = jdbcConfig.getDbUrl(); - if(dbUrl == null){ - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - try { - - MysqlDataSource dataSource = new MysqlDataSource(); - dataSource.setUser(dbUserId); - dataSource.setPassword(dbPasswd); - dataSource.setURL(dbUrl); -// dataSource.setInitialSize(5); -// dataSource.setMaxTotal(60); -// dataSource.setMaxActive(100); -// dataSource.setMaxWait(10000); -// dataSource.setMaxIdle(10); - - Properties connAttr = new Properties(); - - connAttr.setProperty("MinLimit", minLimit); - connAttr.setProperty("MaxLimit", maxLimit); - connAttr.setProperty("InitialLimit", initialLimit); - connAttr.setProperty("TRANSACTION_ISOLATION","SERIALIZABLE"); - connAttr.setProperty("CONNECTION_TAG", dbConnectionName.toUpperCase()+"_CONNECTION"); - connAttr.setProperty("InactivityTimeout", "900"); - connAttr.setProperty("AbandonedConnectionTimeout", "600"); - connAttr.setProperty("PropertyCheckInterval", "60"); - connAttr.setProperty("ValidateConnection", "true"); - - - synchronized(this) - { - this.ds = dataSource; - - initialized = true; - LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); - } - -// } catch (SQLException exc) { -// initialized = false; -// StringBuffer sb = new StringBuffer(); -// sb.append("Failed to initialize MySQLDataSource<"); -// sb.append(dbConnectionName).append(">. Reason: "); -// sb.append(exc.getMessage()); -// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -//// throw new DBConfigException(e.getMessage()); - } catch (Exception exc) { - initialized = false; - StringBuffer sb = new StringBuffer(); - sb.append("Failed to initialize MySQLCachedDataSource <"); - sb.append(dbConnectionName).append(">. Reason: "); - sb.append(exc.getMessage()); - LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -// throw new DBConfigException(e.getMessage()); - } - } - - public final String getDbUrl() - { - return dbUrl; - } - - public final String getDbUserId() - { - return dbUserId; - } - - public final String getDbPasswd() - { - return dbPasswd; - } - - public static MySQLCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { - return new MySQLCachedDataSource(config); - } - - public String toString(){ - return getDbConnectionName(); - } - - public java.util.logging.Logger getParentLogger() - throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub - return null; - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java deleted file mode 100644 index de87fa7e8..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/PollingWorker.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.pm; - -import java.util.Iterator; -import java.util.Properties; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.TreeSet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicLong; - -public class PollingWorker implements Runnable { - - private Logger LOGGER = LoggerFactory.getLogger(PollingWorker.class); - - private static PollingWorker self = null; - - private LinkedBlockingQueue tasks = new LinkedBlockingQueue(100); - private long interval = 1000L; - private Thread worker = null; - private AtomicLong[] counters = null; - private int[] bucketUnit = null; - private static boolean enabled = false; - private Timer timer = null; - - public static void post(long starttime){ - PollingWorker temp = self; - if(temp != null && enabled) { - temp.register(new TestSample(starttime)); - } - } - - public static void createInistance(Properties props){ - self = new PollingWorker(props); - } - - private PollingWorker(Properties ctxprops){ - if(ctxprops==null || ctxprops.getProperty("org.openecomp.sdnc.dblib.pm") == null){ - enabled = false; - } else { - if("true".equalsIgnoreCase((String)ctxprops.getProperty("org.openecomp.sdnc.dblib.pm"))){ - enabled = true; - } else { - enabled = false; - } - } - - interval = Long.parseLong(( ctxprops == null || ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.interval") == null) ? "60" : (String)ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.interval")); - // '0' bucket is to count exceptions - String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.sampling")==null) ? "0,2,5,10,20,50,100" : (String)ctxprops.getProperty("org.openecomp.sdnc.dblib.pm.sampling")).split(","); - - if(enabled){ - bucketUnit = new int[sampling.length]; - for(int i=0, max = bucketUnit.length; i x.starttime) - return -1; - if(endtime > x.endtime) - return -1; - return 0; - } - return 1; - } - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java deleted file mode 100644 index c58c9db7d..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitor.java +++ /dev/null @@ -1,237 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.pm; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collections; -import java.util.Observable; -import java.util.Observer; -import java.util.SortedSet; -import java.util.Timer; -import java.util.TimerTask; -import java.util.TreeSet; -import java.util.concurrent.atomic.AtomicLong; - -import org.openecomp.sdnc.sli.resource.dblib.DBResourceObserver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SQLExecutionMonitor extends Observable -{ - private static Logger LOGGER = LoggerFactory.getLogger(SQLExecutionMonitor.class); - - final static long MILISECOND = 1000000L; - final static long SECOND = 1000L*MILISECOND; - - private final Timer timer; - // collection - private final SortedSet innerSet; - private SQLExecutionMonitorObserver parent = null; - private final AtomicLong completionCounter; - private boolean activeState = false; - private final long interval; - private final long initialDelay; - private final long EXPECTED_TIME_TO_COMPLETE; - private final long UNPROCESSED_FAILOVER_THRESHOLD; - - private final class MonitoringTask extends TimerTask - { - - public void run() - { - try { - TestObject testObj = new TestObject(); - testObj.setStartTime(testObj.getStartTime() - EXPECTED_TIME_TO_COMPLETE); - - // take a snapshot of the current task list - TestObject[] array = innerSet.toArray(new TestObject[0]); - SortedSet copyCurrent = new TreeSet(Arrays.asList(array)); - // get the list of the tasks that are older than the specified - // interval. - SortedSet unprocessed = copyCurrent.headSet(testObj); - - long succesfulCount = completionCounter.get(); - int unprocessedCount = unprocessed.size(); - - if (!unprocessed.isEmpty() && unprocessedCount > UNPROCESSED_FAILOVER_THRESHOLD && succesfulCount == 0) - { - // switch the Connection Pool to passive - setChanged(); - notifyObservers("Open JDBC requests=" + unprocessedCount+" in "+SQLExecutionMonitor.this.parent.getDbConnectionName()); - } - } catch (Exception exc) { - LOGGER.error("", exc); - } finally { - completionCounter.set(0L); - } - } - } - - public static class TestObject implements Comparable, Serializable - { - - private static final long serialVersionUID = 1L; - private long starttime; - private long randId; - - public TestObject() - { - starttime = System.nanoTime(); - } - - public long getStartTime() - { - return starttime; - } - - public void setStartTime(long newTime) - { - starttime = newTime; - } - - public int compareTo(TestObject o) - { - if( this == o) - return 0; - if(this.starttime > o.getStartTime()) - return 1; - if(this.starttime < o.getStartTime()) - return -1; - - if(this.hashCode() > o.hashCode()) - return 1; - if(this.hashCode() < o.hashCode()) - return -1; - - return 0; - } - - public String toString() - { - return Long.toString(starttime)+"#"+ this.hashCode(); - } - - public boolean equals(Object obj) - { - if (this == obj) - return true; - - return (obj instanceof TestObject - && starttime == ((TestObject) obj).getStartTime() - && hashCode() == ((TestObject) obj).hashCode()); - } - } - - public SQLExecutionMonitor(SQLExecutionMonitorObserver parent) - { - this.parent = parent; - completionCounter = new AtomicLong(0L); - interval = parent.getInterval(); - initialDelay = parent.getInitialDelay(); - this.UNPROCESSED_FAILOVER_THRESHOLD = parent.getUnprocessedFailoverThreshold(); - this.EXPECTED_TIME_TO_COMPLETE = parent.getExpectedCompletionTime()*MILISECOND; - - innerSet = Collections.synchronizedSortedSet(new TreeSet()); - timer = new Timer(); - } - - public void cleanup() - { - timer.cancel(); - } - - // registerRequest - public TestObject registerRequest() - { - if(activeState) - { - TestObject test = new TestObject(); - if(innerSet.add(test)) - return test; - } - return null; - } - - // deregisterSuccessfulReguest - public boolean deregisterReguest(TestObject test) - { - if(test == null) - return false; - // remove from the collection - if(innerSet.remove(test) && activeState) - { - completionCounter.incrementAndGet(); - return true; - } - return false; - } - - public void terminate() { - timer.cancel(); - } - - /** - * @return the parent - */ - public final Object getParent() { - return parent; - } - - public void addObserver(Observer observer) - { - if(observer instanceof DBResourceObserver) - { - DBResourceObserver dbObserver = (DBResourceObserver)observer; - if(dbObserver.isMonitorDbResponse()) - { - if(countObservers() == 0) - { - TimerTask remindTask = new MonitoringTask(); - timer.schedule(remindTask, initialDelay, interval); - activeState = true; - } - } - } - super.addObserver(observer); - } - - public void deleteObserver(Observer observer) - { - super.deleteObserver(observer); - if(observer instanceof DBResourceObserver) - { - DBResourceObserver dbObserver = (DBResourceObserver)observer; - if(dbObserver.isMonitorDbResponse()) - { - if(countObservers() == 0) - { - timer.cancel(); - activeState = false; - } - } - } - } - - public final int getPorcessedConnectionsCount() { - return innerSet.size(); - } -} diff --git a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java b/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java deleted file mode 100644 index 1f329750b..000000000 --- a/dblib/provider/src/main/java/org/openecomp/sdnc/sli/resource/dblib/pm/SQLExecutionMonitorObserver.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openecomp - * ================================================================================ - * Copyright (C) 2016 - 2017 AT&T - * ================================================================================ - * 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.openecomp.sdnc.sli.resource.dblib.pm; - -public interface SQLExecutionMonitorObserver { - public String getDbConnectionName(); - - public long getInterval(); - public void setInterval(long value); - - public long getInitialDelay(); - public void setInitialDelay(long value); - - public long getExpectedCompletionTime(); - public void setExpectedCompletionTime(long value); - - public long getUnprocessedFailoverThreshold(); - public void setUnprocessedFailoverThreshold(long value); -} diff --git a/dblib/provider/src/main/resources/dblib.properties b/dblib/provider/src/main/resources/dblib.properties index ac295c78d..3e62308fc 100755 --- a/dblib/provider/src/main/resources/dblib.properties +++ b/dblib/provider/src/main/resources/dblib.properties @@ -1,13 +1,13 @@ -org.openecomp.sdnc.sli.dbtype=jdbc -org.openecomp.sdnc.sli.jdbc.hosts=sdnctldb01,sdnctldb02 -org.openecomp.sdnc.sli.jdbc.url=jdbc:mysql://DBHOST:3306/sdnctl -org.openecomp.sdnc.sli.jdbc.database=sdnctl -org.openecomp.sdnc.sli.jdbc.user={user for sdnctl} -org.openecomp.sdnc.sli.jdbc.password={password for sdnctl} -org.openecomp.sdnc.sli.jdbc.connection.name=sdnctldb01 +org.onap.ccsdk.sli.dbtype=jdbc +org.onap.ccsdk.sli.jdbc.hosts=sdnctldb01,sdnctldb02 +org.onap.ccsdk.sli.jdbc.url=jdbc:mysql://DBHOST:3306/sdnctl +org.onap.ccsdk.sli.jdbc.database=sdnctl +org.onap.ccsdk.sli.jdbc.user={user for sdnctl} +org.onap.ccsdk.sli.jdbc.password={password for sdnctl} +org.onap.ccsdk.sli.jdbc.connection.name=sdnctldb01 -org.openecomp.sdnc.sli.jdbc.connection.timeout=50 -org.openecomp.sdnc.sli.jdbc.request.timeout=100 -org.openecomp.sdnc.sli.jdbc.limit.init=10 -org.openecomp.sdnc.sli.jdbc.limit.min=10 -org.openecomp.sdnc.sli.jdbc.limit.max=20 +org.onap.ccsdk.sli.jdbc.connection.timeout=50 +org.onap.ccsdk.sli.jdbc.request.timeout=100 +org.onap.ccsdk.sli.jdbc.limit.init=10 +org.onap.ccsdk.sli.jdbc.limit.min=10 +org.onap.ccsdk.sli.jdbc.limit.max=20 diff --git a/filters/features/src/main/resources/features.xml b/filters/features/src/main/resources/features.xml index d0cadff25..6837553d5 100644 --- a/filters/features/src/main/resources/features.xml +++ b/filters/features/src/main/resources/features.xml @@ -1,10 +1,9 @@ true diff --git a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/Activator.java b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/Activator.java new file mode 100644 index 000000000..c97142f1b --- /dev/null +++ b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/Activator.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.filters; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class Activator implements BundleActivator { + + private ServiceRegistration registration = null; + + private static final Logger LOG = LoggerFactory.getLogger(Activator.class); + + @Override + public void start(BundleContext ctx) throws Exception { + + + + Object impl = new String(); + String regName = impl.getClass().getName(); + + if (registration == null) + { + LOG.debug("Registering Filters service "+regName); + registration = ctx.registerService(regName, impl, null); + } + + } + + @Override + public void stop(BundleContext ctx) throws Exception { + + if (registration != null) + { + registration.unregister(); + registration = null; + } + } + +} diff --git a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/LogFilter.java b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/LogFilter.java new file mode 100644 index 000000000..9df74c35a --- /dev/null +++ b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/LogFilter.java @@ -0,0 +1,221 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.filters; + +import java.io.IOException; +import java.util.UUID; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.codec.binary.Base64; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + + + +/** + * Logs IN request according ECOMP Logging Guidelines at https://tspace.web.att.com/viewer/app/lcfiles/ae5f7751-39da-4c6b-8a83-5836c8c815e1/content + */ +public class LogFilter implements Filter { + + //X-ECOMP is shared between audit and metric + public static final String BEGIN_TIMESTAMP = "AUDIT-BeginTimestamp"; + public static final String END_TIMESTAMP = "AUDIT-EndTimestamp"; + public static final String REQUEST_ID = "X-ECOMP-RequestID"; + public static final String SERVICE_INSTANCE = "X-ECOMP-ServiceInstanceID"; + public static final String THREAD_ID ="X-ECOMP-ThreadId"; //optional + public static final String PHYSICAL_SERVER_NAME="X-ECOMP-PhysicalServerName"; //optional + public static final String SERVICE_NAME="X-ECOMP-ServiceName"; + public static final String PARTNER_NAME="X-ECOMP-PartnerName"; + public static final String STATUS_CODE="AUDIT-StatusCode"; + public static final String RESP_CODE="AUDIT-ResponseCode"; + public static final String RESP_DESC="AUDIT-ResponseDescription"; + public static final String INSTANCE_UUID="AUDIT-InstanceUUID"; + public static final String CATEGORY="AUDIT-INFO"; + public static final String SEVERITY ="AUDIT-Severity"; //optional + public static final String SERVER_IP="AUDIT-ServerIP"; //by chef node['ip'] + public static final String ELAPSED_TIME="AUDIT-ElapsedTime"; + public static final String SERVER_HOST="AUDIT-Server";//by chef node['fqdn'] + public static final String CLIENT_IP="AUDIT-ClientIPaddress"; + public static final String CLASS="AUDIT-Classname"; //optional + public static final String UNUSED="AUDIT-Unused"; //empty + public static final String PROCESS_KEY="AUDIT-ProcessKey"; //optional + public static final String CUST_1="AUDIT-CustomField1";//optional + public static final String CUST_2="AUDIT-CustomField2"; //optional + public static final String CUST_3="AUDIT-CustomField3"; //optional + public static final String CUST_4="AUDIT-CustomField4"; //optional + public static final String DETAIL_MESSAGE="AUDIT-DetailMessage";//optional + + + private static final Logger log = LoggerFactory.getLogger(LogFilter.class); + private static final Logger AUDIT = LoggerFactory.getLogger("org.openecomp.sdnc.filters.audit"); + @Override + public void destroy() { + } + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, + final FilterChain filterChain) throws IOException, ServletException { + + long startTime = System.currentTimeMillis(); + try { + + if ( request != null && request instanceof HttpServletRequest ) { + pre((HttpServletRequest)request); + } + filterChain.doFilter(request, response); + + + } finally { + + if (request != null && request instanceof HttpServletRequest ) { + post((HttpServletRequest)request,(HttpServletResponse)response,startTime); + } + MDC.clear(); + } + + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + + + private void pre(HttpServletRequest request) { + + UUID uuid = UUID.randomUUID(); + // check if uuid is in header X-ECOMP-RequestID + + String ecompUUID = request.getHeader(REQUEST_ID); + + if (ecompUUID != null && ecompUUID.length() > 0) { + try { + uuid = UUID.fromString(ecompUUID); + log.info("UUID is ECOMP UUID " + uuid.toString()); + } catch (Exception ex){ + log.warn("Failed to convert ECOMP UUID to java.util.UUID format:" + ecompUUID,ex); + } + } + MDC.put(REQUEST_ID, uuid.toString()); + + String userName="unknown"; + + /* below returning org.opendaylight.aaa.shiro.realm.TokenAuthRealm$ODLPrincipal@745dfcfe + if ( request.getUserPrincipal() != null) { + userName = request.getUserPrincipal().getName(); + } + */ + // going directly after Authorization header + if (request.getHeader("Authorization") != null) { + String authzHeader = request.getHeader("Authorization"); + String usernameAndPassword = new String(Base64.decodeBase64(authzHeader.substring(6).getBytes())); + + int userNameIndex = usernameAndPassword.indexOf(":"); + String username = usernameAndPassword.substring(0, userNameIndex); + userName = username; + + } + + + MDC.put(PARTNER_NAME, userName); + //just to initilaze for metric logger (outbound calls) + MDC.put("X-ECOMP-TargetEntity",""); + MDC.put("X-ECOMP-TargetServiceName",""); + + MDC.put(SERVICE_NAME,request.getRequestURL().toString()); + MDC.put(SERVICE_INSTANCE,""); + + } + + + private void post(HttpServletRequest request,HttpServletResponse response,long startTime) { + + //AUDIT.info("{}|{}|{}{}",request.getRemoteHost(),request.getMethod(),request.getRequestURL().toString(),request.getQueryString()); + //AUDIT.info(request.getRemoteHost() + D + request.getMethod() + D + request.getRequestURL().toString() + D + request.getQueryString()); + //METRIC.info(request.getMethod() + D + response.getStatus() + D + request.getRequestURL().toString() + D + (System.currentTimeMillis() - startTime) + " ms"); + MDC.put(BEGIN_TIMESTAMP,asIso8601(startTime)); + MDC.put(END_TIMESTAMP,asIso8601(System.currentTimeMillis())); + //MDC.put(REQUEST_ID,"already done above"); + MDC.put(SERVICE_NAME,request.getRequestURL().toString()); + int idx = request.getPathInfo().toString().lastIndexOf(":"); + String instance = ""; + if ( idx != -1 ) { + instance = request.getPathInfo().substring(idx+1); + } + MDC.put(SERVICE_INSTANCE,instance); + MDC.put(THREAD_ID,""); + MDC.put(PHYSICAL_SERVER_NAME,""); + //MDC.put(PARTNER_NAME,"already done above"); + if ( response.getStatus() >= 400 ) { + MDC.put(STATUS_CODE,"ERROR"); + } else { + MDC.put(STATUS_CODE,"COMPLETE"); + } + + MDC.put(RESP_CODE,"" + response.getStatus()); + MDC.put(RESP_DESC,""); + MDC.put(INSTANCE_UUID,""); + MDC.put(CATEGORY,""); + MDC.put(SEVERITY,""); + //MDC.put(SERVER_IP,""); //by chef + MDC.put(ELAPSED_TIME,"" + (System.currentTimeMillis() - startTime)); + //MDC.put(SERVER_HOST,""); //by chef + MDC.put(CLIENT_IP,request.getRemoteHost()); + MDC.put(CLASS,""); + MDC.put(UNUSED,""); + MDC.put(PROCESS_KEY,""); + MDC.put(CUST_1,""); + MDC.put(CUST_2,""); + MDC.put(CUST_3,""); + MDC.put(CUST_4,""); + MDC.put(DETAIL_MESSAGE,request.getMethod()); + + AUDIT.info(""); + } + + private String asIso8601(Date date) { + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyy-MM-dd'T'hh:mm:ss:SS'+00:00'"); + df.setTimeZone(tz); + return df.format(date); + } + + private String asIso8601(long tsInMillis) { + return asIso8601(new Date(tsInMillis)); + } + + +} diff --git a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java new file mode 100644 index 000000000..b187d9573 --- /dev/null +++ b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java @@ -0,0 +1,297 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.filters; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.zip.GZIPInputStream; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; + +import org.onap.ccsdk.sli.core.sli.MessageWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RequestResponseDbLoggingFilter implements Filter { + + private static Logger log = LoggerFactory.getLogger(RequestResponseDbLoggingFilter.class); + + public static final String REQUEST_ID = "X-ECOMP-RequestID"; + + private static class ByteArrayServletStream extends ServletOutputStream { + + ByteArrayOutputStream baos; + + ByteArrayServletStream(ByteArrayOutputStream baos) { + this.baos = baos; + } + + @Override + public void write(int param) throws IOException { + baos.write(param); + } + } + + private static class ByteArrayPrintWriter { + + private ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + private PrintWriter pw = new PrintWriter(baos); + + private ServletOutputStream sos = new ByteArrayServletStream(baos); + + public PrintWriter getWriter() { + return pw; + } + + public ServletOutputStream getStream() { + return sos; + } + + byte[] toByteArray() { + return baos.toByteArray(); + } + } + + private class BufferedServletInputStream extends ServletInputStream { + + ByteArrayInputStream bais; + + public BufferedServletInputStream(ByteArrayInputStream bais) { + this.bais = bais; + } + + @Override + public int available() { + return bais.available(); + } + + @Override + public int read() { + return bais.read(); + } + + @Override + public int read(byte[] buf, int off, int len) { + return bais.read(buf, off, len); + } + + } + + private class BufferedRequestWrapper extends HttpServletRequestWrapper { + + ByteArrayInputStream bais; + + ByteArrayOutputStream baos; + + BufferedServletInputStream bsis; + + byte[] buffer; + + public BufferedRequestWrapper(HttpServletRequest req) throws IOException { + super(req); + + InputStream is = req.getInputStream(); + baos = new ByteArrayOutputStream(); + byte buf[] = new byte[1024]; + int letti; + while ((letti = is.read(buf)) > 0) { + baos.write(buf, 0, letti); + } + buffer = baos.toByteArray(); + + } + + @Override + public ServletInputStream getInputStream() { + try { + bais = new ByteArrayInputStream(buffer); + bsis = new BufferedServletInputStream(bais); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return bsis; + } + + public byte[] getBuffer() { + return buffer; + } + + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) + throws IOException, ServletException { + + if (request == null || !(request instanceof HttpServletRequest)) { + filterChain.doFilter(request, response); + return; + } + + long t1 = System.currentTimeMillis(); + + final HttpServletRequest httpRequest = (HttpServletRequest) request; + BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest); + + String requestId = httpRequest.getHeader(REQUEST_ID); + if (requestId == null || requestId.trim().length() == 0) { + log.warn("Could not write request in DB: " + REQUEST_ID + " is missing in the HTTP headers."); + return; + } + + String requestHost = request.getRemoteHost(); + if (requestHost == null) + requestHost = request.getRemoteAddr(); + + String requestStr = new String(bufferedRequest.getBuffer()); + + MessageWriter.saveIncomingRequest(requestId, null, requestHost, requestStr); + + long t2 = System.currentTimeMillis(); + + log.info("Request saved in DB for request-id: " + requestId + ". TIme: " + (t2 - t1)); + + final HttpServletResponse httpResponse = (HttpServletResponse) response; + + final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(); + HttpServletResponse wrappedResp = new HttpServletResponseWrapper(httpResponse) { + + @Override + public PrintWriter getWriter() { + return pw.getWriter(); + } + + @Override + public ServletOutputStream getOutputStream() { + return pw.getStream(); + } + }; + + try { + + filterChain.doFilter(bufferedRequest, wrappedResp); + + } finally { + + if (request != null && request instanceof HttpServletRequest) { + + t1 = System.currentTimeMillis(); + + byte[] bytes = pw.toByteArray(); + response.getOutputStream().write(bytes); + response.getOutputStream().flush(); + + String responseStr = null; + if ("gzip".equals(httpResponse.getHeader("Content-Encoding"))) { + responseStr = decompressGZIPByteArray(bytes); + } else { + responseStr = new String(bytes); + } + + MessageWriter.saveIncomingResponse(requestId, httpResponse.getStatus(), responseStr); + + t2 = System.currentTimeMillis(); + + log.info("Response saved in DB for request-id: " + requestId + ". TIme: " + (t2 - t1)); + } + } + + } + + @Override + public void destroy() { + } + + private String decompressGZIPByteArray(byte[] bytes) { + + BufferedReader in = null; + InputStreamReader inR = null; + ByteArrayInputStream byteS = null; + GZIPInputStream gzS = null; + StringBuilder str = new StringBuilder(); + try { + byteS = new ByteArrayInputStream(bytes); + gzS = new GZIPInputStream(byteS); + inR = new InputStreamReader(gzS); + in = new BufferedReader(inR); + + if (in != null) { + + String content; + + while ((content = in.readLine()) != null) { + str.append(content); + } + } + + } catch (Exception e) { + log.error("Failed get read GZIPInputStream", e); + } finally { + + if (byteS != null) + try { + byteS.close(); + } catch (IOException e1) { + log.error("Failed to close ByteStream", e1); + } + if (gzS != null) + try { + gzS.close(); + } catch (IOException e2) { + log.error("Failed to close GZStream", e2); + } + if (inR != null) + try { + inR.close(); + } catch (IOException e3) { + log.error("Failed to close InputReader", e3); + } + if (in != null) + try { + in.close(); + } catch (IOException e) { + log.error("Failed to close BufferedReader", e); + } + } + return str.toString(); + } +} diff --git a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java new file mode 100644 index 000000000..e4b0b7d1f --- /dev/null +++ b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java @@ -0,0 +1,288 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.filters; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.zip.GZIPInputStream; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; + +public class RequestResponseLoggingFilter implements Filter { + + private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("org.openecomp.sdnc.filters.request.response"); + + private static class ByteArrayServletStream extends ServletOutputStream { + + ByteArrayOutputStream baos; + + ByteArrayServletStream(ByteArrayOutputStream baos) { + this.baos = baos; + } + + @Override + public void write(int param) throws IOException { + baos.write(param); + } + } + + private static class ByteArrayPrintWriter { + + private ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + private PrintWriter pw = new PrintWriter(baos); + + private ServletOutputStream sos = new ByteArrayServletStream(baos); + + public PrintWriter getWriter() { + return pw; + } + + public ServletOutputStream getStream() { + return sos; + } + + byte[] toByteArray() { + return baos.toByteArray(); + } + } + + private class BufferedServletInputStream extends ServletInputStream { + + ByteArrayInputStream bais; + + public BufferedServletInputStream(ByteArrayInputStream bais) { + this.bais = bais; + } + + @Override + public int available() { + return bais.available(); + } + + @Override + public int read() { + return bais.read(); + } + + @Override + public int read(byte[] buf, int off, int len) { + return bais.read(buf, off, len); + } + + } + + private class BufferedRequestWrapper extends HttpServletRequestWrapper { + + ByteArrayInputStream bais; + + ByteArrayOutputStream baos; + + BufferedServletInputStream bsis; + + byte[] buffer; + + public BufferedRequestWrapper(HttpServletRequest req) throws IOException { + super(req); + + InputStream is = req.getInputStream(); + baos = new ByteArrayOutputStream(); + byte buf[] = new byte[1024]; + int letti; + while ((letti = is.read(buf)) > 0) { + baos.write(buf, 0, letti); + } + buffer = baos.toByteArray(); + + } + + @Override + public ServletInputStream getInputStream() { + try { + bais = new ByteArrayInputStream(buffer); + bsis = new BufferedServletInputStream(bais); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return bsis; + } + + public byte[] getBuffer() { + return buffer; + } + + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + + final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest); + + StringBuilder requestHeaders = new StringBuilder("REQUEST|"); + requestHeaders.append(httpRequest.getMethod()); + requestHeaders.append(":"); + requestHeaders.append(httpRequest.getRequestURL().toString()); + requestHeaders.append("|"); + String header; + for (Enumeration e = httpRequest.getHeaderNames(); e.hasMoreElements();) { + header = e.nextElement(); + requestHeaders.append(header); + requestHeaders.append(":"); + requestHeaders.append(httpRequest.getHeader(header)); + requestHeaders.append(";"); + + } + log.info(requestHeaders.toString()); + + log.info("REQUEST BODY|" + new String(bufferedRequest.getBuffer())); + + final HttpServletResponse response = (HttpServletResponse) servletResponse; + + final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(); + HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) { + @Override + public PrintWriter getWriter() { + return pw.getWriter(); + } + + @Override + public ServletOutputStream getOutputStream() { + return pw.getStream(); + } + + }; + + try { + + filterChain.doFilter(bufferedRequest, wrappedResp); + + }catch (Exception e){ + log.error("Chain Exception",e); + throw e; + } finally { + byte[] bytes = pw.toByteArray(); + response.getOutputStream().write(bytes); + response.getOutputStream().flush(); + + StringBuilder responseHeaders = new StringBuilder("RESPONSE HEADERS|"); + + for (String headerName : response.getHeaderNames()) { + responseHeaders.append(headerName); + responseHeaders.append(":"); + responseHeaders.append(response.getHeader(headerName)); + responseHeaders.append(";"); + + } + log.info(responseHeaders.toString()); + + if ("gzip".equals(response.getHeader("Content-Encoding"))) { + + log.info("UNGZIPED RESPONSE BODY|" + decompressGZIPByteArray(bytes)); + + } else { + + log.info("RESPONSE BODY|" + new String(bytes)); + } + } + } + + @Override + public void destroy() { + } + + private String decompressGZIPByteArray(byte[] bytes) { + + BufferedReader in = null; + InputStreamReader inR = null; + ByteArrayInputStream byteS = null; + GZIPInputStream gzS = null; + StringBuilder str = new StringBuilder(); + try { + byteS = new ByteArrayInputStream(bytes); + gzS = new GZIPInputStream(byteS); + inR = new InputStreamReader(gzS); + in = new BufferedReader(inR); + + if (in != null) { + + String content; + + while ((content = in.readLine()) != null) { + str.append(content); + } + } + + } catch (Exception e) { + log.error("Failed get read GZIPInputStream", e); + } finally { + + if (byteS != null) + try { + byteS.close(); + } catch (IOException e1) { + log.error("Failed to close ByteStream", e1); + } + if (gzS != null) + try { + gzS.close(); + } catch (IOException e2) { + log.error("Failed to close GZStream", e2); + } + if (inR != null) + try { + inR.close(); + } catch (IOException e3) { + log.error("Failed to close InputReader", e3); + } + if (in != null) + try { + in.close(); + } catch (IOException e) { + log.error("Failed to close BufferedReader", e); + } + } + return str.toString(); + } +} diff --git a/filters/provider/src/main/java/org/openecomp/sdnc/filters/Activator.java b/filters/provider/src/main/java/org/openecomp/sdnc/filters/Activator.java deleted file mode 100644 index d21b30992..000000000 --- a/filters/provider/src/main/java/org/openecomp/sdnc/filters/Activator.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.filters; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class Activator implements BundleActivator { - - private ServiceRegistration registration = null; - - private static final Logger LOG = LoggerFactory.getLogger(Activator.class); - - @Override - public void start(BundleContext ctx) throws Exception { - - - - Object impl = new String(); - String regName = impl.getClass().getName(); - - if (registration == null) - { - LOG.debug("Registering Filters service "+regName); - registration = ctx.registerService(regName, impl, null); - } - - } - - @Override - public void stop(BundleContext ctx) throws Exception { - - if (registration != null) - { - registration.unregister(); - registration = null; - } - } - -} diff --git a/filters/provider/src/main/java/org/openecomp/sdnc/filters/LogFilter.java b/filters/provider/src/main/java/org/openecomp/sdnc/filters/LogFilter.java deleted file mode 100644 index 809cfb287..000000000 --- a/filters/provider/src/main/java/org/openecomp/sdnc/filters/LogFilter.java +++ /dev/null @@ -1,222 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.filters; - -import java.io.IOException; -import java.util.UUID; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.codec.binary.Base64; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - - - -/** - * Logs IN request according ECOMP Logging Guidelines at https://tspace.web.att.com/viewer/app/lcfiles/ae5f7751-39da-4c6b-8a83-5836c8c815e1/content - */ -public class LogFilter implements Filter { - - //X-ECOMP is shared between audit and metric - public static final String BEGIN_TIMESTAMP = "AUDIT-BeginTimestamp"; - public static final String END_TIMESTAMP = "AUDIT-EndTimestamp"; - public static final String REQUEST_ID = "X-ECOMP-RequestID"; - public static final String SERVICE_INSTANCE = "X-ECOMP-ServiceInstanceID"; - public static final String THREAD_ID ="X-ECOMP-ThreadId"; //optional - public static final String PHYSICAL_SERVER_NAME="X-ECOMP-PhysicalServerName"; //optional - public static final String SERVICE_NAME="X-ECOMP-ServiceName"; - public static final String PARTNER_NAME="X-ECOMP-PartnerName"; - public static final String STATUS_CODE="AUDIT-StatusCode"; - public static final String RESP_CODE="AUDIT-ResponseCode"; - public static final String RESP_DESC="AUDIT-ResponseDescription"; - public static final String INSTANCE_UUID="AUDIT-InstanceUUID"; - public static final String CATEGORY="AUDIT-INFO"; - public static final String SEVERITY ="AUDIT-Severity"; //optional - public static final String SERVER_IP="AUDIT-ServerIP"; //by chef node['ip'] - public static final String ELAPSED_TIME="AUDIT-ElapsedTime"; - public static final String SERVER_HOST="AUDIT-Server";//by chef node['fqdn'] - public static final String CLIENT_IP="AUDIT-ClientIPaddress"; - public static final String CLASS="AUDIT-Classname"; //optional - public static final String UNUSED="AUDIT-Unused"; //empty - public static final String PROCESS_KEY="AUDIT-ProcessKey"; //optional - public static final String CUST_1="AUDIT-CustomField1";//optional - public static final String CUST_2="AUDIT-CustomField2"; //optional - public static final String CUST_3="AUDIT-CustomField3"; //optional - public static final String CUST_4="AUDIT-CustomField4"; //optional - public static final String DETAIL_MESSAGE="AUDIT-DetailMessage";//optional - - - private static final Logger log = LoggerFactory.getLogger(LogFilter.class); - private static final Logger AUDIT = LoggerFactory.getLogger("org.openecomp.sdnc.filters.audit"); - @Override - public void destroy() { - } - - @Override - public void doFilter(final ServletRequest request, final ServletResponse response, - final FilterChain filterChain) throws IOException, ServletException { - - long startTime = System.currentTimeMillis(); - try { - - if ( request != null && request instanceof HttpServletRequest ) { - pre((HttpServletRequest)request); - } - filterChain.doFilter(request, response); - - - } finally { - - if (request != null && request instanceof HttpServletRequest ) { - post((HttpServletRequest)request,(HttpServletResponse)response,startTime); - } - MDC.clear(); - } - - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - - - - private void pre(HttpServletRequest request) { - - UUID uuid = UUID.randomUUID(); - // check if uuid is in header X-ECOMP-RequestID - - String ecompUUID = request.getHeader(REQUEST_ID); - - if (ecompUUID != null && ecompUUID.length() > 0) { - try { - uuid = UUID.fromString(ecompUUID); - log.info("UUID is ECOMP UUID " + uuid.toString()); - } catch (Exception ex){ - log.warn("Failed to convert ECOMP UUID to java.util.UUID format:" + ecompUUID,ex); - } - } - MDC.put(REQUEST_ID, uuid.toString()); - - String userName="unknown"; - - /* below returning org.opendaylight.aaa.shiro.realm.TokenAuthRealm$ODLPrincipal@745dfcfe - if ( request.getUserPrincipal() != null) { - userName = request.getUserPrincipal().getName(); - } - */ - // going directly after Authorization header - if (request.getHeader("Authorization") != null) { - String authzHeader = request.getHeader("Authorization"); - String usernameAndPassword = new String(Base64.decodeBase64(authzHeader.substring(6).getBytes())); - - int userNameIndex = usernameAndPassword.indexOf(":"); - String username = usernameAndPassword.substring(0, userNameIndex); - userName = username; - - } - - - MDC.put(PARTNER_NAME, userName); - //just to initilaze for metric logger (outbound calls) - MDC.put("X-ECOMP-TargetEntity",""); - MDC.put("X-ECOMP-TargetServiceName",""); - - MDC.put(SERVICE_NAME,request.getRequestURL().toString()); - MDC.put(SERVICE_INSTANCE,""); - - } - - - private void post(HttpServletRequest request,HttpServletResponse response,long startTime) { - - //AUDIT.info("{}|{}|{}{}",request.getRemoteHost(),request.getMethod(),request.getRequestURL().toString(),request.getQueryString()); - //AUDIT.info(request.getRemoteHost() + D + request.getMethod() + D + request.getRequestURL().toString() + D + request.getQueryString()); - //METRIC.info(request.getMethod() + D + response.getStatus() + D + request.getRequestURL().toString() + D + (System.currentTimeMillis() - startTime) + " ms"); - MDC.put(BEGIN_TIMESTAMP,asIso8601(startTime)); - MDC.put(END_TIMESTAMP,asIso8601(System.currentTimeMillis())); - //MDC.put(REQUEST_ID,"already done above"); - MDC.put(SERVICE_NAME,request.getRequestURL().toString()); - int idx = request.getPathInfo().toString().lastIndexOf(":"); - String instance = ""; - if ( idx != -1 ) { - instance = request.getPathInfo().substring(idx+1); - } - MDC.put(SERVICE_INSTANCE,instance); - MDC.put(THREAD_ID,""); - MDC.put(PHYSICAL_SERVER_NAME,""); - //MDC.put(PARTNER_NAME,"already done above"); - if ( response.getStatus() >= 400 ) { - MDC.put(STATUS_CODE,"ERROR"); - } else { - MDC.put(STATUS_CODE,"COMPLETE"); - } - - MDC.put(RESP_CODE,"" + response.getStatus()); - MDC.put(RESP_DESC,""); - MDC.put(INSTANCE_UUID,""); - MDC.put(CATEGORY,""); - MDC.put(SEVERITY,""); - //MDC.put(SERVER_IP,""); //by chef - MDC.put(ELAPSED_TIME,"" + (System.currentTimeMillis() - startTime)); - //MDC.put(SERVER_HOST,""); //by chef - MDC.put(CLIENT_IP,request.getRemoteHost()); - MDC.put(CLASS,""); - MDC.put(UNUSED,""); - MDC.put(PROCESS_KEY,""); - MDC.put(CUST_1,""); - MDC.put(CUST_2,""); - MDC.put(CUST_3,""); - MDC.put(CUST_4,""); - MDC.put(DETAIL_MESSAGE,request.getMethod()); - - AUDIT.info(""); - } - - private String asIso8601(Date date) { - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyy-MM-dd'T'hh:mm:ss:SS'+00:00'"); - df.setTimeZone(tz); - return df.format(date); - } - - private String asIso8601(long tsInMillis) { - return asIso8601(new Date(tsInMillis)); - } - - -} diff --git a/filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseDbLoggingFilter.java b/filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseDbLoggingFilter.java deleted file mode 100644 index 183301be5..000000000 --- a/filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseDbLoggingFilter.java +++ /dev/null @@ -1,297 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.filters; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.zip.GZIPInputStream; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletInputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.openecomp.sdnc.sli.MessageWriter; - -public class RequestResponseDbLoggingFilter implements Filter { - - private static Logger log = LoggerFactory.getLogger(RequestResponseDbLoggingFilter.class); - - public static final String REQUEST_ID = "X-ECOMP-RequestID"; - - private static class ByteArrayServletStream extends ServletOutputStream { - - ByteArrayOutputStream baos; - - ByteArrayServletStream(ByteArrayOutputStream baos) { - this.baos = baos; - } - - @Override - public void write(int param) throws IOException { - baos.write(param); - } - } - - private static class ByteArrayPrintWriter { - - private ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - private PrintWriter pw = new PrintWriter(baos); - - private ServletOutputStream sos = new ByteArrayServletStream(baos); - - public PrintWriter getWriter() { - return pw; - } - - public ServletOutputStream getStream() { - return sos; - } - - byte[] toByteArray() { - return baos.toByteArray(); - } - } - - private class BufferedServletInputStream extends ServletInputStream { - - ByteArrayInputStream bais; - - public BufferedServletInputStream(ByteArrayInputStream bais) { - this.bais = bais; - } - - @Override - public int available() { - return bais.available(); - } - - @Override - public int read() { - return bais.read(); - } - - @Override - public int read(byte[] buf, int off, int len) { - return bais.read(buf, off, len); - } - - } - - private class BufferedRequestWrapper extends HttpServletRequestWrapper { - - ByteArrayInputStream bais; - - ByteArrayOutputStream baos; - - BufferedServletInputStream bsis; - - byte[] buffer; - - public BufferedRequestWrapper(HttpServletRequest req) throws IOException { - super(req); - - InputStream is = req.getInputStream(); - baos = new ByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int letti; - while ((letti = is.read(buf)) > 0) { - baos.write(buf, 0, letti); - } - buffer = baos.toByteArray(); - - } - - @Override - public ServletInputStream getInputStream() { - try { - bais = new ByteArrayInputStream(buffer); - bsis = new BufferedServletInputStream(bais); - } catch (Exception ex) { - ex.printStackTrace(); - } - - return bsis; - } - - public byte[] getBuffer() { - return buffer; - } - - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - - @Override - public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) - throws IOException, ServletException { - - if (request == null || !(request instanceof HttpServletRequest)) { - filterChain.doFilter(request, response); - return; - } - - long t1 = System.currentTimeMillis(); - - final HttpServletRequest httpRequest = (HttpServletRequest) request; - BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest); - - String requestId = httpRequest.getHeader(REQUEST_ID); - if (requestId == null || requestId.trim().length() == 0) { - log.warn("Could not write request in DB: " + REQUEST_ID + " is missing in the HTTP headers."); - return; - } - - String requestHost = request.getRemoteHost(); - if (requestHost == null) - requestHost = request.getRemoteAddr(); - - String requestStr = new String(bufferedRequest.getBuffer()); - - MessageWriter.saveIncomingRequest(requestId, null, requestHost, requestStr); - - long t2 = System.currentTimeMillis(); - - log.info("Request saved in DB for request-id: " + requestId + ". TIme: " + (t2 - t1)); - - final HttpServletResponse httpResponse = (HttpServletResponse) response; - - final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(); - HttpServletResponse wrappedResp = new HttpServletResponseWrapper(httpResponse) { - - @Override - public PrintWriter getWriter() { - return pw.getWriter(); - } - - @Override - public ServletOutputStream getOutputStream() { - return pw.getStream(); - } - }; - - try { - - filterChain.doFilter(bufferedRequest, wrappedResp); - - } finally { - - if (request != null && request instanceof HttpServletRequest) { - - t1 = System.currentTimeMillis(); - - byte[] bytes = pw.toByteArray(); - response.getOutputStream().write(bytes); - response.getOutputStream().flush(); - - String responseStr = null; - if ("gzip".equals(httpResponse.getHeader("Content-Encoding"))) { - responseStr = decompressGZIPByteArray(bytes); - } else { - responseStr = new String(bytes); - } - - MessageWriter.saveIncomingResponse(requestId, httpResponse.getStatus(), responseStr); - - t2 = System.currentTimeMillis(); - - log.info("Response saved in DB for request-id: " + requestId + ". TIme: " + (t2 - t1)); - } - } - - } - - @Override - public void destroy() { - } - - private String decompressGZIPByteArray(byte[] bytes) { - - BufferedReader in = null; - InputStreamReader inR = null; - ByteArrayInputStream byteS = null; - GZIPInputStream gzS = null; - StringBuilder str = new StringBuilder(); - try { - byteS = new ByteArrayInputStream(bytes); - gzS = new GZIPInputStream(byteS); - inR = new InputStreamReader(gzS); - in = new BufferedReader(inR); - - if (in != null) { - - String content; - - while ((content = in.readLine()) != null) { - str.append(content); - } - } - - } catch (Exception e) { - log.error("Failed get read GZIPInputStream", e); - } finally { - - if (byteS != null) - try { - byteS.close(); - } catch (IOException e1) { - log.error("Failed to close ByteStream", e1); - } - if (gzS != null) - try { - gzS.close(); - } catch (IOException e2) { - log.error("Failed to close GZStream", e2); - } - if (inR != null) - try { - inR.close(); - } catch (IOException e3) { - log.error("Failed to close InputReader", e3); - } - if (in != null) - try { - in.close(); - } catch (IOException e) { - log.error("Failed to close BufferedReader", e); - } - } - return str.toString(); - } -} diff --git a/filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseLoggingFilter.java b/filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseLoggingFilter.java deleted file mode 100644 index b15932f09..000000000 --- a/filters/provider/src/main/java/org/openecomp/sdnc/filters/RequestResponseLoggingFilter.java +++ /dev/null @@ -1,289 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.filters; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.zip.GZIPInputStream; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletInputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -public class RequestResponseLoggingFilter implements Filter { - - private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("org.openecomp.sdnc.filters.request.response"); - - private static class ByteArrayServletStream extends ServletOutputStream { - - ByteArrayOutputStream baos; - - ByteArrayServletStream(ByteArrayOutputStream baos) { - this.baos = baos; - } - - @Override - public void write(int param) throws IOException { - baos.write(param); - } - } - - private static class ByteArrayPrintWriter { - - private ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - private PrintWriter pw = new PrintWriter(baos); - - private ServletOutputStream sos = new ByteArrayServletStream(baos); - - public PrintWriter getWriter() { - return pw; - } - - public ServletOutputStream getStream() { - return sos; - } - - byte[] toByteArray() { - return baos.toByteArray(); - } - } - - private class BufferedServletInputStream extends ServletInputStream { - - ByteArrayInputStream bais; - - public BufferedServletInputStream(ByteArrayInputStream bais) { - this.bais = bais; - } - - @Override - public int available() { - return bais.available(); - } - - @Override - public int read() { - return bais.read(); - } - - @Override - public int read(byte[] buf, int off, int len) { - return bais.read(buf, off, len); - } - - } - - private class BufferedRequestWrapper extends HttpServletRequestWrapper { - - ByteArrayInputStream bais; - - ByteArrayOutputStream baos; - - BufferedServletInputStream bsis; - - byte[] buffer; - - public BufferedRequestWrapper(HttpServletRequest req) throws IOException { - super(req); - - InputStream is = req.getInputStream(); - baos = new ByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int letti; - while ((letti = is.read(buf)) > 0) { - baos.write(buf, 0, letti); - } - buffer = baos.toByteArray(); - - } - - @Override - public ServletInputStream getInputStream() { - try { - bais = new ByteArrayInputStream(buffer); - bsis = new BufferedServletInputStream(bais); - } catch (Exception ex) { - ex.printStackTrace(); - } - - return bsis; - } - - public byte[] getBuffer() { - return buffer; - } - - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { - - final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; - BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpRequest); - - StringBuilder requestHeaders = new StringBuilder("REQUEST|"); - requestHeaders.append(httpRequest.getMethod()); - requestHeaders.append(":"); - requestHeaders.append(httpRequest.getRequestURL().toString()); - requestHeaders.append("|"); - String header; - for (Enumeration e = httpRequest.getHeaderNames(); e.hasMoreElements();) { - header = e.nextElement(); - requestHeaders.append(header); - requestHeaders.append(":"); - requestHeaders.append(httpRequest.getHeader(header)); - requestHeaders.append(";"); - - } - log.info(requestHeaders.toString()); - - log.info("REQUEST BODY|" + new String(bufferedRequest.getBuffer())); - - final HttpServletResponse response = (HttpServletResponse) servletResponse; - - final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(); - HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) { - @Override - public PrintWriter getWriter() { - return pw.getWriter(); - } - - @Override - public ServletOutputStream getOutputStream() { - return pw.getStream(); - } - - }; - - try { - - filterChain.doFilter(bufferedRequest, wrappedResp); - - }catch (Exception e){ - log.error("Chain Exception",e); - throw e; - } finally { - byte[] bytes = pw.toByteArray(); - response.getOutputStream().write(bytes); - response.getOutputStream().flush(); - - StringBuilder responseHeaders = new StringBuilder("RESPONSE HEADERS|"); - - for (String headerName : response.getHeaderNames()) { - responseHeaders.append(headerName); - responseHeaders.append(":"); - responseHeaders.append(response.getHeader(headerName)); - responseHeaders.append(";"); - - } - log.info(responseHeaders.toString()); - - if ("gzip".equals(response.getHeader("Content-Encoding"))) { - - log.info("UNGZIPED RESPONSE BODY|" + decompressGZIPByteArray(bytes)); - - } else { - - log.info("RESPONSE BODY|" + new String(bytes)); - } - } - } - - @Override - public void destroy() { - } - - private String decompressGZIPByteArray(byte[] bytes) { - - BufferedReader in = null; - InputStreamReader inR = null; - ByteArrayInputStream byteS = null; - GZIPInputStream gzS = null; - StringBuilder str = new StringBuilder(); - try { - byteS = new ByteArrayInputStream(bytes); - gzS = new GZIPInputStream(byteS); - inR = new InputStreamReader(gzS); - in = new BufferedReader(inR); - - if (in != null) { - - String content; - - while ((content = in.readLine()) != null) { - str.append(content); - } - } - - } catch (Exception e) { - log.error("Failed get read GZIPInputStream", e); - } finally { - - if (byteS != null) - try { - byteS.close(); - } catch (IOException e1) { - log.error("Failed to close ByteStream", e1); - } - if (gzS != null) - try { - gzS.close(); - } catch (IOException e2) { - log.error("Failed to close GZStream", e2); - } - if (inR != null) - try { - inR.close(); - } catch (IOException e3) { - log.error("Failed to close InputReader", e3); - } - if (in != null) - try { - in.close(); - } catch (IOException e) { - log.error("Failed to close BufferedReader", e); - } - } - return str.toString(); - } -} diff --git a/pom.xml b/pom.xml index 8e9d10b60..4a1a25010 100755 --- a/pom.xml +++ b/pom.xml @@ -118,10 +118,9 @@ 2017 - AT&T Intellectual Property. All rights - reserved. + ONAP - openECOMP : SDN-C + ONAP : CCSDK true diff --git a/sli/common/pom.xml b/sli/common/pom.xml index 9a49e69e4..8b19891f0 100755 --- a/sli/common/pom.xml +++ b/sli/common/pom.xml @@ -108,8 +108,8 @@ **/*.xsd - org.openecomp.sdnc.sli.SvcLogicParser - org.openecomp.sdnc.sli + org.onap.ccsdk.sli.core.sli.SvcLogicParser + org.onap.ccsdk.sli.core.sli true @@ -121,7 +121,7 @@ true - org.openecomp.sdnc.sli;version=${project.version} + org.onap.ccsdk.sli.core.sli;version=${project.version} * *;scope=compile;artifactId=commons-lang|commons-lang3 true diff --git a/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 b/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 new file mode 100755 index 000000000..1b026bb1a --- /dev/null +++ b/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 @@ -0,0 +1,67 @@ + +grammar ExprGrammar; + +options { + language = Java; +} + + +COMPAREOP : '==' | '!=' | '>' | '<' | '>=' | '<='; + +RELOP : 'and' | 'or'; + +ADDOP : '+' | '-'; + +MULTOP : '/' | '*'; + +NUMBER : ('0'..'9')+; + +STRING : '\'' ~[\']* '\''; + +IDENTIFIER : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'-')*; + +// CONTEXT_VAR : '$' IDENTIFIER; + +WS: [ \n\t\r]+ -> skip; + +constant : NUMBER | STRING ; + +variableLead : ('$')? variableTerm ; + +variableTerm : IDENTIFIER ('[' expr ']')? ; + +variable : variableLead ('.' variableTerm)* ('.')?; + +// variable : CONTEXT_VAR ( '[' expr ']' )? ('.' IDENTIFIER )? ; + +atom : constant | variable; + + +expr : atom + | parenExpr + | multExpr + | addExpr + | compareExpr + | relExpr + | funcExpr; + +parenExpr : '(' expr ')'; + +term : atom | parenExpr | funcExpr; + +multExpr : term (MULTOP term)*; + +addExpr : multExpr (ADDOP multExpr)*; + +compareExpr : addExpr COMPAREOP addExpr; + +relExpr : compareExpr (RELOP expr)*; + +funcExpr : IDENTIFIER '(' expr (',' expr)* ')'; + + + + + + + diff --git a/sli/common/src/main/antlr4/org/openecomp/sdnc/sli/ExprGrammar.g4 b/sli/common/src/main/antlr4/org/openecomp/sdnc/sli/ExprGrammar.g4 deleted file mode 100755 index 51f401690..000000000 --- a/sli/common/src/main/antlr4/org/openecomp/sdnc/sli/ExprGrammar.g4 +++ /dev/null @@ -1,66 +0,0 @@ -grammar ExprGrammar; - -options { - language = Java; -} - - -COMPAREOP : '==' | '!=' | '>' | '<' | '>=' | '<='; - -RELOP : 'and' | 'or'; - -ADDOP : '+' | '-'; - -MULTOP : '/' | '*'; - -NUMBER : ('0'..'9')+; - -STRING : '\'' ~[\']* '\''; - -IDENTIFIER : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'-')*; - -// CONTEXT_VAR : '$' IDENTIFIER; - -WS: [ \n\t\r]+ -> skip; - -constant : NUMBER | STRING ; - -variableLead : ('$')? variableTerm ; - -variableTerm : IDENTIFIER ('[' expr ']')? ; - -variable : variableLead ('.' variableTerm)* ('.')?; - -// variable : CONTEXT_VAR ( '[' expr ']' )? ('.' IDENTIFIER )? ; - -atom : constant | variable; - - -expr : atom - | parenExpr - | multExpr - | addExpr - | compareExpr - | relExpr - | funcExpr; - -parenExpr : '(' expr ')'; - -term : atom | parenExpr | funcExpr; - -multExpr : term (MULTOP term)*; - -addExpr : multExpr (ADDOP multExpr)*; - -compareExpr : addExpr COMPAREOP addExpr; - -relExpr : compareExpr (RELOP expr)*; - -funcExpr : IDENTIFIER '(' expr (',' expr)* ')'; - - - - - - - diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/BreakNodeException.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/BreakNodeException.java new file mode 100644 index 000000000..d85514cbc --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/BreakNodeException.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +public class BreakNodeException extends SvcLogicException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public BreakNodeException() + { + super(); + } + + public BreakNodeException(String message) + { + super(message); + } + + public BreakNodeException(String message, Throwable t) + { + super(message, t); + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ConfigurationException.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ConfigurationException.java new file mode 100644 index 000000000..7a8531008 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ConfigurationException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +public class ConfigurationException extends SvcLogicException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public ConfigurationException() + { + super(); + } + + public ConfigurationException(String msg) + { + super(msg); + } + + public ConfigurationException(String msg, Throwable t) + { + super(msg, t); + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/DuplicateValueException.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/DuplicateValueException.java new file mode 100644 index 000000000..24d06a211 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/DuplicateValueException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +public class DuplicateValueException extends SvcLogicException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public DuplicateValueException() + { + super(); + } + + public DuplicateValueException(String message) + { + super(message); + } + + public DuplicateValueException(String message, Throwable t) + { + super(message, t); + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java new file mode 100644 index 000000000..b9f9e5347 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java @@ -0,0 +1,301 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.File; +import java.io.FileInputStream; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; + +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class MessageWriter { + + private static final Logger LOG = LoggerFactory.getLogger(MessageWriter.class); + + private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DBResourceManager"; + private static final String SVCLOGIC_PROP_VAR = "SDNC_SLI_PROPERTIES"; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + + private static final String INCOMING_PROPERTY_NAME = "org.onap.ccsdk.sli.MessageWriter.writeIncomingRequests"; + private static final String OUTGOING_PROPERTY_NAME = "org.onap.ccsdk.sli.MessageWriter.writeOutgoingRequests"; + + private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + + private static DbLibService dbLibService = null; + + private static boolean incomingEnabled = false; + private static boolean outgoingEnabled = false; + + private static boolean initialized = false; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static void init() { + if (initialized) + return; + + initialized = true; + + // Read properties + Properties props = new Properties(); + String propPath = System.getenv(SVCLOGIC_PROP_VAR); + + if (propPath == null) { + String propDir = System.getenv(SDNC_CONFIG_DIR); + if (propDir == null) { + propDir = "/opt/sdnc/data/properties"; + } + propPath = propDir + "/svclogic.properties"; + LOG.warn("Environment variable " + SVCLOGIC_PROP_VAR + " unset - defaulting to " + propPath); + } + + File propFile = new File(propPath); + + if (!propFile.exists()) { + LOG.warn("Property file does not exist: " + propPath); + } + + try { + props.load(new FileInputStream(propFile)); + } catch (Exception e) { + LOG.warn("Error loading property file: " + propPath, e); + } + + incomingEnabled = Boolean.valueOf(props.getProperty(INCOMING_PROPERTY_NAME, "false")); + outgoingEnabled = Boolean.valueOf(props.getProperty(OUTGOING_PROPERTY_NAME, "false")); + + LOG.info(INCOMING_PROPERTY_NAME + ": " + incomingEnabled); + LOG.info(OUTGOING_PROPERTY_NAME + ": " + outgoingEnabled); + + if (dbLibService != null) + return; + + BundleContext bctx = FrameworkUtil.getBundle(MessageWriter.class).getBundleContext(); + + ServiceReference sref = bctx.getServiceReference(DBLIB_SERVICE); + + if (sref == null) { + LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")"); + } else { + dbLibService = (DbLibService) bctx.getService(sref); + if (dbLibService == null) { + LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")"); + } + } + } + + public static void saveOutgoingRequest( + String requestId, + String serviceInstanceId, + String targetUrl, + String request) { + try { + init(); + + if (!outgoingEnabled) + return; + + if (serviceInstanceId == null || serviceInstanceId.trim().length() == 0) + serviceInstanceId = "NA"; + + int seqnum = getLastSequenceNumber("OUTGOING_MESSAGE", requestId) + 1; + String now = df.format(new Date()); + + String sql = "INSERT INTO OUTGOING_MESSAGE (\n" + + " request_id, sequence_number, service_instance_id, target_url, request, start_time)\n" + + "VALUES (?, ?, ?, ?, ?, ?)"; + + ArrayList data = new ArrayList<>(); + data.add(requestId); + data.add(String.valueOf(seqnum)); + data.add(serviceInstanceId); + data.add(targetUrl); + data.add(request); + data.add(now); + + dbLibService.writeData(sql, data, null); + + } catch (Exception e) { + LOG.warn("Failed to save outgoing request for request-id: " + requestId, e); + } + } + + public static void saveOutgoingResponse(String requestId, int httpResponseCode, String response) { + try { + init(); + + if (!outgoingEnabled) + return; + + int seqnum = getLastSequenceNumber("OUTGOING_MESSAGE", requestId); + if (seqnum == 0) { + LOG.warn("Failed to save outgoing response for request-id: " + requestId + + ": Request record not found in OUTGOING_MESSAGE"); + return; + } + + String now = df.format(new Date()); + + String sql = "UPDATE OUTGOING_MESSAGE SET http_response_code = ?, response = ?,\n" + + " duration = timestampdiff(MICROSECOND, start_time, ?) / 1000\n" + + "WHERE request_id = ? AND sequence_number = ?"; + + ArrayList data = new ArrayList<>(); + data.add(String.valueOf(httpResponseCode)); + data.add(response); + data.add(now); + data.add(requestId); + data.add(String.valueOf(seqnum)); + + dbLibService.writeData(sql, data, null); + + } catch (Exception e) { + LOG.warn("Failed to save outgoing response for request-id: " + requestId, e); + } + } + + public static void saveIncomingRequest( + String requestId, + String serviceInstanceId, + String requestHost, + String request) { + try { + init(); + + if (!incomingEnabled) + return; + + if (serviceInstanceId == null || serviceInstanceId.trim().length() == 0) + serviceInstanceId = "NA"; + + int seqnum = getLastSequenceNumber("INCOMING_MESSAGE", requestId) + 1; + String now = df.format(new Date()); + + String sql = "INSERT INTO INCOMING_MESSAGE (\n" + + " request_id, sequence_number, service_instance_id, request_host, request, start_time)\n" + + "VALUES (?, ?, ?, ?, ?, ?)"; + + ArrayList data = new ArrayList<>(); + data.add(requestId); + data.add(String.valueOf(seqnum)); + data.add(serviceInstanceId); + data.add(requestHost); + data.add(request); + data.add(now); + + dbLibService.writeData(sql, data, null); + + } catch (Exception e) { + LOG.warn("Failed to save incoming request for request-id: " + requestId, e); + } + } + + public static void saveIncomingResponse(String requestId, int httpResponseCode, String response) { + try { + init(); + + if (!incomingEnabled) + return; + + int seqnum = getLastSequenceNumber("INCOMING_MESSAGE", requestId); + if (seqnum == 0) { + LOG.warn("Failed to save response for request-id: " + requestId + + ": Request record not found in INCOMING_MESSAGE"); + return; + } + + String now = df.format(new Date()); + + String sql = "UPDATE INCOMING_MESSAGE SET http_response_code = ?, response = ?,\n" + + " duration = timestampdiff(MICROSECOND, start_time, ?) / 1000\n" + + "WHERE request_id = ? AND sequence_number = ?"; + + ArrayList data = new ArrayList<>(); + data.add(String.valueOf(httpResponseCode)); + data.add(response); + data.add(now); + data.add(requestId); + data.add(String.valueOf(seqnum)); + + dbLibService.writeData(sql, data, null); + + } catch (Exception e) { + LOG.warn("Failed to save response for request-id: " + requestId, e); + } + } + + public static String getServiceInstanceId(String requestId) throws SQLException { + init(); + + String sql = "SELECT service_instance_id FROM OUTGOING_MESSAGE WHERE request_id = '" + requestId + + "' ORDER BY sequence_number DESC"; + + CachedRowSet rs = null; + try { + rs = dbLibService.getData(sql, null, null); + if (rs.next()) { + return rs.getString("service_instance_id"); + } + } finally { + if (rs != null) { + try { + rs.close(); + } catch (Exception e) { + LOG.warn("Failed to close CachedRowSet", e); + } + } + } + return null; + } + + private static int getLastSequenceNumber(String tableName, String requestId) throws SQLException { + String sql = "SELECT sequence_number FROM " + tableName + " WHERE request_id = '" + requestId + + "' ORDER BY sequence_number DESC"; + + CachedRowSet rs = null; + try { + rs = dbLibService.getData(sql, null, null); + if (rs.next()) { + return rs.getInt("sequence_number"); + } + } finally { + if (rs != null) { + try { + rs.close(); + } catch (Exception e) { + LOG.warn("Failed to close CachedRowSet", e); + } + } + } + return 0; + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MetricLogger.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MetricLogger.java new file mode 100644 index 000000000..7d1250c03 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MetricLogger.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.net.InetAddress; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +/** + * @author dt5972 + * + */ +public class MetricLogger { + + private static final Logger KARAF = LoggerFactory.getLogger(MetricLogger.class); + private static final Logger METRIC = LoggerFactory.getLogger("org.onap.ccsdk.sli.filters.metric"); + + public static final String BEGIN_TIMESTAMP = "X-ECOMP-BeginTimestamp"; + public static final String END_TIMESTAMP = "X-ECOMP-EndTimestamp"; + public static final String REQUEST_ID = "X-ECOMP-RequestID"; + public static final String SERVICE_INSTANCE_ID = "X-ECOMP-ServiceInstanceID"; + public static final String SERVICE_NAME = "X-ECOMP-ServiceName"; + public static final String PARTNER_NAME = "X-ECOMP-PartnerName"; + public static final String TARGET_ENTITY = "X-ECOMP-TargetEntity"; + public static final String TARGET_SERVICE_NAME = "X-ECOMP-TargetServiceName"; + public static final String STATUS_CODE = "X-ECOMP-StatusCode"; + public static final String RESPONSE_CODE = "X-ECOMP-ResponseCode"; + public static final String RESPONSE_DESCRIPTION = "X-ECOMP-ResponseDescription"; + public static final String INSTANCE_UUID = "X-ECOMP-InstanceUUID"; + public static final String CATEGORY_LOG_LEVEL = "X-ECOMP-CategoryLogLevel"; + public static final String SEVERITY = "X-ECOMP-Severity"; + public static final String SERVER_IP_ADDRESS = "X-ECOMP-ServerIpAddress"; + public static final String ELAPSED_TIME = "X-ECOMP-ElapsedTime"; + public static final String SERVER = "X-ECOMP-Server"; + public static final String CLIENT_IP = "X-ECOMP-ClientIp"; + public static final String CLASS_NAME = "X-ECOMP-ClassName"; + public static final String TARGET_VIRTUAL_ENTITY = "X-ECOMP-TargetVirtualEntity"; + + private long beginTimestamp; + private String lastMsg = null; + + public MetricLogger() { + beginTimestamp = System.currentTimeMillis(); + + try { + InetAddress localhost = InetAddress.getLocalHost(); + setServerIpAddress(localhost.getHostAddress()); + setServer(localhost.getCanonicalHostName()); + } catch (Exception e) { + KARAF.error("Could not get localhost", e); + } + + } + + + public String getBeginTimestamp() { + return MDC.get(BEGIN_TIMESTAMP); + } + + private void setBeginTimestamp(long beginTimestamp) { + this.beginTimestamp = beginTimestamp; + MDC.put(BEGIN_TIMESTAMP, MetricLogger.asIso8601(beginTimestamp)); + } + + public String getEndTimestamp() { + return MDC.get(END_TIMESTAMP); + } + + private void setEndTimestamp(long endTimestamp) { + // Set MDC with formatted time stamp + MDC.put(END_TIMESTAMP, MetricLogger.asIso8601(endTimestamp)); + + // Set elapsed time + setElapsedTime(endTimestamp - beginTimestamp); + + } + + public String getRequestID() { + return MDC.get(REQUEST_ID); + } + + + public String getServiceInstanceID() { + return MDC.get(SERVICE_INSTANCE_ID); + } + + private void setServiceInstanceID(String svcInstanceId) { + MDC.put(SERVICE_INSTANCE_ID, svcInstanceId); + } + + public String getServiceName() { + return MDC.get(SERVICE_NAME); + } + + private void setServiceName(String svcName) { + MDC.put(SERVICE_NAME, svcName); + } + + public String getPartnerName() { + return MDC.get(PARTNER_NAME); + } + + private void setPartnerName(String partnerName) { + MDC.put(PARTNER_NAME, partnerName); + } + + public String getTargetEntity() { + return MDC.get(TARGET_ENTITY); + } + + private void setTargetEntity(String targetEntity) { + MDC.put(TARGET_ENTITY, targetEntity); + } + + public String getTargetServiceName() { + return MDC.get(TARGET_SERVICE_NAME); + } + + private void setTargetServiceName(String targetServiceName) { + MDC.put(TARGET_SERVICE_NAME, targetServiceName); + } + + public String getStatusCode() { + return MDC.get(STATUS_CODE); + } + + private void setStatusCode(String statusCode) { + MDC.put(STATUS_CODE, statusCode); + } + + public String getResponseCode() { + return MDC.get(RESPONSE_CODE); + } + + private void setResponseCode(String responseCode) { + MDC.put(RESPONSE_CODE, responseCode); + } + + public String getResponseDescription() { + return MDC.get(RESPONSE_DESCRIPTION); + } + + private void setResponseDescription(String responseDesc) { + MDC.put(RESPONSE_DESCRIPTION, responseDesc); + } + + public String getInstanceUUID() { + return MDC.get(INSTANCE_UUID); + } + + private void setInstanceUUID(String instanceUUID) { + MDC.put(INSTANCE_UUID, instanceUUID); + } + + public String getCategoryLogLevel() { + return MDC.get(CATEGORY_LOG_LEVEL); + } + + private void setCategoryLogLevel(String categoryLogLevel) { + MDC.put(CATEGORY_LOG_LEVEL, categoryLogLevel); + } + + public String getSeverity() { + return MDC.get(SEVERITY); + } + + private void setSeverity(String severity) { + MDC.put(SEVERITY, severity); + } + + public String getServerIpAddress() { + return MDC.get(SERVER_IP_ADDRESS); + } + + private void setServerIpAddress(String serverIpAddress) { + MDC.put(SERVER_IP_ADDRESS, serverIpAddress); + } + + public String getElapsedTime() { + return MDC.get(ELAPSED_TIME); + } + + private void setElapsedTime(long elapsedTime) { + MDC.put(ELAPSED_TIME, ""+elapsedTime); + } + + public String getServer() { + return MDC.get(SERVER); + } + + private void setServer(String server) { + MDC.put(SERVER, server); + } + + public String getClientIp() { + return MDC.get(CLIENT_IP); + } + + private void setClientIp(String clientIp) { + MDC.put(CLIENT_IP, clientIp); + } + + public String getClassName() { + return MDC.get(CLASS_NAME); + } + + private void setClassName(String className) { + MDC.put(CLASS_NAME, className); + } + + public String getTargetVirtualEntity() { + return MDC.get(TARGET_VIRTUAL_ENTITY); + } + + private void setTargetVirtualEntity(String targetVirtualEntity) { + MDC.put(TARGET_VIRTUAL_ENTITY, targetVirtualEntity); + } + + public static String asIso8601(Date date) { + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss:SS'+00:00'"); + df.setTimeZone(tz); + return df.format(date); + } + + public static String asIso8601(long tsInMillis) { + return MetricLogger.asIso8601(new Date(tsInMillis)); + } + + public void logRequest(String svcInstanceId, String svcName, String partnerName, String targetEntity, String targetServiceName, String targetVirtualEntity, String msg) { + + setBeginTimestamp(System.currentTimeMillis()); + + if (svcInstanceId != null) { + setServiceInstanceID(svcInstanceId); + } + + if (svcName != null) { + setServiceName(svcName); + } + + if (partnerName != null) { + setPartnerName(partnerName); + } + + if (targetEntity != null) { + setTargetEntity(targetEntity); + } + + if (targetServiceName != null) { + setTargetServiceName(targetServiceName); + } + + if (targetVirtualEntity != null) { + setTargetVirtualEntity(targetVirtualEntity); + } + + this.lastMsg = msg; + + + } + + public void logResponse(String statusCode, String responseCode, String responseDescription) { + setEndTimestamp(System.currentTimeMillis()); + + setStatusCode(statusCode); + setResponseCode(responseCode); + setResponseDescription(responseDescription); + + METRIC.info(lastMsg); + + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAdaptor.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAdaptor.java new file mode 100644 index 000000000..3a3dd75d3 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAdaptor.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.Map; + +public interface SvcLogicAdaptor { + + public enum ConfigStatus { + SUCCESS, + ALREADY_ACTIVE, + NOT_FOUND, + NOT_READY, + FAILURE + } + + public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx); + + public ConfigStatus activate(String key, SvcLogicContext ctx); + + public ConfigStatus deactivate(String key, SvcLogicContext ctx); + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java new file mode 100644 index 000000000..47912397c --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +public class SvcLogicAtom extends SvcLogicExpression { + + public enum AtomType { + NUMBER, + STRING, + IDENTIFIER, + CONTEXT_VAR + + } + + private AtomType atomType; + private String atom; + + + public SvcLogicAtom(String atomType, String atom) + { + this.atomType = AtomType.valueOf(atomType); + this.atom = atom; + + } + + public SvcLogicAtom(String atom) + { + + if (atom == null) + { + this.atomType = null; + this.atom = null; + } + else + { + if (atom.startsWith("$")) + { + this.atomType = AtomType.CONTEXT_VAR; + this.atom = atom.substring(1); + } + else + { + if (Character.isDigit(atom.charAt(0))) + { + this.atomType = AtomType.NUMBER; + this.atom = atom; + } + else if (atom.charAt(0) == '\'') + { + this.atomType = AtomType.STRING; + this.atom = atom.substring(1, atom.length()-1); + } + else + { + this.atomType = AtomType.IDENTIFIER; + this.atom = atom; + + } + + } + } + } + + public AtomType getAtomType() { + return atomType; + } + + public void setAtomType(String newType) + { + atomType = AtomType.valueOf(newType); + } + + public String getAtom() { + return atom; + } + + + + public void setAtomType(AtomType atomType) { + this.atomType = atomType; + } + + public void setAtom(String atom) { + this.atom = atom; + } + + + + public String toString() + { + StringBuffer sbuff = new StringBuffer(); + switch(getAtomType()) + { + case CONTEXT_VAR: + sbuff.append("$"); + case IDENTIFIER: + boolean needDot = false; + for (SvcLogicExpression term: this.getOperands()) + { + if (needDot) + { + sbuff.append("."); + } + sbuff.append(term.toString()); + needDot = true; + } + return(sbuff.toString()); + case STRING: + case NUMBER: + default: + return(atom); + } + } + + public String asParsedExpr() + { + // simplify debugging output for NUMBER type + if (atomType == AtomType.NUMBER) { + return atom; + } + + StringBuffer sbuff = new StringBuffer(); + + sbuff.append("(atom"); + sbuff.append("<"); + sbuff.append(atomType.toString()); + sbuff.append(">"); + + switch(atomType) + { + case IDENTIFIER: + case CONTEXT_VAR: + for (SvcLogicExpression term : getOperands()) + { + sbuff.append(" "); + sbuff.append(term.asParsedExpr()); + + } + break; + default: + sbuff.append(" "); + sbuff.append(atom); + } + + sbuff.append(")"); + return(sbuff.toString()); + } + + + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicBinaryExpression.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicBinaryExpression.java new file mode 100644 index 000000000..ee2a24358 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicBinaryExpression.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.LinkedList; +import java.util.List; + +public class SvcLogicBinaryExpression extends SvcLogicExpression { + + + public enum OperatorType { + addOp("+"), + subOp("-"), + multOp("*"), + divOp("/"), + equalOp("=="), + ltOp("<"), + leOp("<="), + gtOp(">"), + geOp(">="), + neOp("!="), + andOp("and"), + orOp("or"); + + private String text; + + private OperatorType(String text) + { + this.text = text; + } + + public String getText() + { + return(text); + } + + public static OperatorType fromString(String text) + { + if (text != null) + { + for (OperatorType t : OperatorType.values()) + { + if (text.equalsIgnoreCase(t.getText())) { + + return(t); + } + } + } + return(null); + } + + public String toString() + { + return(text); + } + } + private List operators; + + public List getOperators() { + return operators; + } + + public SvcLogicBinaryExpression() + { + operators = new LinkedList(); + } + + public void addOperator(String operator) + { + operators.add(OperatorType.fromString(operator)); + } + + + public String toString() + { + + Listoperands = getOperands(); + StringBuffer sbuff = new StringBuffer(); + + sbuff.append(operands.get(0).toString()); + for (int i = 0 ; i < operators.size(); i++) + { + sbuff.append(" "); + sbuff.append(operators.get(i)); + sbuff.append(" "); + if (i + 1 < operands.size()) { + sbuff.append(operands.get(i + 1).toString()); + } else { + // expression incomplete; operand not bound yet + sbuff.append("?"); + } + } + + return(sbuff.toString()); + + } + + public String asParsedExpr() { + + List operands = getOperands(); + + if (operators.isEmpty()) { + return operands.get(0).asParsedExpr(); + } else { + StringBuffer sbuff = new StringBuffer(); + // operators in reverse order for left associativity + for (int i = operators.size() - 1; i >= 0; --i) { + sbuff.append("("); + sbuff.append(operators.get(i).getText()); + sbuff.append(" "); + } + for (int i = 0; i < operators.size() + 1; ++i) { + if (i < operands.size()) { + sbuff.append(operands.get(i).asParsedExpr()); + } else { + // expression incomplete; operand not bound yet + sbuff.append("?"); + } + if (i != 0) { + sbuff.append(")"); + } + if (i < operators.size()) { + sbuff.append(" "); + } + } + return sbuff.toString(); + } + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicContext.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicContext.java new file mode 100644 index 000000000..b5892eff5 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicContext.java @@ -0,0 +1,247 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; + + +public class SvcLogicContext { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicContext.class); + + private HashMap attributes; + + private DOMDataBroker domDataBroker; + + private String status = "success"; + + public SvcLogicContext() + { + this.attributes = new HashMap (); + + } + + public SvcLogicContext(Properties props) + { + this.attributes = new HashMap (); + + if (props.containsKey("SvcLogic.status")) + { + this.status = props.getProperty("SvcLogic.status"); + } + + for (Object nameObj : props.keySet()) + { + String propName = (String) nameObj; + attributes.put(propName, props.getProperty(propName)); + } + } + + + + public DOMDataBroker getDomDataBroker() { + return domDataBroker; + } + + public void setDomDataBroker(DOMDataBroker domDataBroker) { + this.domDataBroker = domDataBroker; + } + + public String getAttribute(String name) + { + if (attributes.containsKey(name)) + { + return(attributes.get(name)); + } + else + { + return(null); + } + } + + public void setAttribute(String name, String value) + { + if (value == null) { + if (attributes.containsKey(name)) { + attributes.remove(name); + } + } else { + attributes.put(name, value); + } + } + + public Set getAttributeKeySet() + { + return(attributes.keySet()); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Properties toProperties() + { + Properties props = new Properties(); + + if (status != null) + { + props.setProperty("SvcLogic.status", status); + } + + for (String attrName : attributes.keySet()) + { + String attrVal = attributes.get(attrName); + if (attrVal == null) { + LOG.warn("attribute " + attrName + + "null - setting to empty string"); + props.setProperty(attrName, ""); + } else { + props.setProperty(attrName, attributes.get(attrName)); + } + } + + return(props); + } + + public void mergeDocument(String pfx, Document doc) { + String prefix = ""; + + if (pfx != null) { + prefix = pfx; + } + + Element root = doc.getDocumentElement(); + + mergeElement(prefix, root, null); + } + + public void mergeElement(String pfx, Element element, Map nodeMap) { + + // In XML, cannot tell the difference between containers and lists. + // So, have to treat each element as both (ugly but necessary). + // We do this by passing a nodeMap to be used to count instance of each tag, + // which will be used to set _length and to set index + + LOG.trace("mergeElement("+pfx+","+element.getTagName()+","+nodeMap+")"); + + String curTagName = element.getTagName(); + String prefix = curTagName; + + if (pfx != null) { + prefix = pfx + "." + prefix; + } + + int myIdx = 0; + + if (nodeMap != null) { + if (nodeMap.containsKey(curTagName)) { + myIdx = nodeMap.get(curTagName).intValue(); + } + + nodeMap.put(curTagName, new Integer(myIdx+1)); + this.setAttribute(prefix+"_length", ""+(myIdx+1)); + } + + NodeList children = element.getChildNodes(); + + int numChildren = children.getLength(); + + Map childMap = new HashMap(); + Map idxChildMap = new HashMap(); + + for (int i = 0 ; i < numChildren ; i++) { + Node curNode = children.item(i); + + if (curNode instanceof Text) { + Text curText = (Text) curNode; + String curTextValue = curText.getTextContent(); + LOG.trace("Setting ctx variable "+prefix+" = "+curTextValue); + this.setAttribute(prefix, curText.getTextContent()); + + + } else if (curNode instanceof Element) { + mergeElement(prefix, (Element) curNode, childMap); + if (nodeMap != null) { + + mergeElement(prefix+"["+myIdx+"]", (Element)curNode, idxChildMap); + + } + } + } + + } + + public String resolve(String ctxVarName) { + + if (ctxVarName.indexOf('[') == -1) { + // Ctx variable contains no arrays + return (this.getAttribute(ctxVarName)); + } + + // Resolve any array references + StringBuffer sbuff = new StringBuffer(); + String[] ctxVarParts = ctxVarName.split("\\["); + sbuff.append(ctxVarParts[0]); + for (int i = 1; i < ctxVarParts.length; i++) { + if (ctxVarParts[i].startsWith("$")) { + int endBracketLoc = ctxVarParts[i].indexOf("]"); + if (endBracketLoc == -1) { + // Missing end bracket ... give up parsing + LOG.warn("Variable reference " + ctxVarName + + " seems to be missing a ']'"); + return (this.getAttribute(ctxVarName)); + } + + String idxVarName = ctxVarParts[i].substring(1, endBracketLoc); + String remainder = ctxVarParts[i].substring(endBracketLoc); + + sbuff.append("["); + sbuff.append(this.getAttribute(idxVarName)); + sbuff.append(remainder); + + } else { + // Index is not a variable reference + sbuff.append("["); + sbuff.append(ctxVarParts[i]); + } + } + + return (this.getAttribute(sbuff.toString())); + } + +} 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 new file mode 100644 index 000000000..ac656ffa8 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicDblibStore.java @@ -0,0 +1,532 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Properties; + +import javax.sql.rowset.CachedRowSet; + +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SvcLogicDblibStore implements SvcLogicStore { + + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicDblibStore.class); + + private static final String DBLIB_SERVICE = + // "org.openecomp.sdnc.sli.resource.dblib.DBLibService"; + "org.openecomp.sdnc.sli.resource.dblib.DBResourceManager"; + + Properties props = null; + + public void init(Properties props) throws ConfigurationException { + + DbLibService dbSvc = getDbLibService(); + if(dbSvc == null) { + LOG.error("SvcLogic cannot acquire DBLIB_SERVICE"); + return; + } + try { + dbSvc.getData("select 1 from DUAL", new ArrayList(), null); + LOG.debug("SQL test was successful"); + } catch (SQLException e) { + LOG.error("Failed SQL test", e); + } + } + + public boolean hasGraph(String module, String rpc, String version, + String mode) throws SvcLogicException { + + DbLibService dbSvc = getDbLibService(); + + boolean retval = false; + CachedRowSet results = null; + String hasVersionGraphSql = "SELECT count(*) FROM SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; + + String hasActiveGraphSql = "SELECT count(*) FROM SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; + + PreparedStatement hasGraphStmt = null; + + ArrayList args = new ArrayList(); + args.add(module); + args.add(rpc); + args.add(mode); + + try { + + if (version == null) { + results = dbSvc.getData(hasActiveGraphSql, args, null); + } else { + args.add(version); + results = dbSvc.getData(hasVersionGraphSql, args, null); + } + + if (results.next()) { + int cnt = results.getInt(1); + + if (cnt > 0) { + retval = true; + } + + } + } catch (Exception e) { + throw new ConfigurationException("SQL query failed", e); + } finally { + if (results != null) { + try { + + results.close(); + } catch (SQLException x) { + } + } + + } + + return (retval); + + } + + public SvcLogicGraph fetch(String module, String rpc, String version, + String mode) throws SvcLogicException { + + DbLibService dbSvc = getDbLibService(); + + Connection dbConn = null; + SvcLogicGraph retval = null; + ResultSet results = null; + + String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; + + String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; + + + try { + dbConn = ((DBResourceManager) dbSvc).getConnection(); + PreparedStatement fetchGraphStmt; + + ArrayList args = new ArrayList(); + args.add(module); + args.add(rpc); + args.add(mode); + + if (version == null) { + fetchGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql); + } else { + fetchGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql); + } + + fetchGraphStmt.setString(1, module); + fetchGraphStmt.setString(2, rpc); + fetchGraphStmt.setString(3, mode); + if (version != null) { + fetchGraphStmt.setString(4,version); + } + + results = fetchGraphStmt.executeQuery(); + + if (results.next()) { + Blob graphBlob = results.getBlob("graph"); + + ObjectInputStream gStream = new ObjectInputStream( + graphBlob.getBinaryStream()); + + Object graphObj = gStream.readObject(); + gStream.close(); + + if (graphObj instanceof SvcLogicGraph) { + retval = (SvcLogicGraph) graphObj; + } else { + throw new ConfigurationException("invalid type for graph (" + + graphObj.getClass().getName()); + + } + + } else { + return (null); + } + } catch (SQLException e) { + throw new ConfigurationException("SQL query failed", e); + } catch (Exception e) { + throw new ConfigurationException("Graph processing failed", e); + } finally { + if (results != null) { + try { + results.close(); + } catch (SQLException x) { + } + } + try { + if (dbConn != null && !dbConn.isClosed()) { + dbConn.close(); + } + } catch (Throwable exc) { + // the exception not monitored + } finally { + dbConn = null; + } + + } + + return (retval); + + } + + public void store(SvcLogicGraph graph) throws SvcLogicException { + + DbLibService dbSvc = getDbLibService(); + + String storeGraphSql = "INSERT INTO SVC_LOGIC (module, rpc, version, mode, active, graph)" + + " VALUES(?, ?, ?, ?, ?, ?)"; + + if (graph == null) { + throw new SvcLogicException("graph cannot be null"); + } + + byte[] graphBytes = null; + + ByteArrayOutputStream byteStr = null; + ObjectOutputStream goutStr = null; + + try { + byteStr = new ByteArrayOutputStream(); + goutStr = new ObjectOutputStream(byteStr); + goutStr.writeObject(graph); + + graphBytes = byteStr.toByteArray(); + + } catch (Exception e) { + throw new SvcLogicException("could not serialize graph", e); + } finally { + + if (goutStr != null) { + try { + goutStr.close(); + } catch (IOException e) { + + } + } + + if (byteStr != null) { + try { + byteStr.close(); + } catch (IOException e) { + + } + } + } + + // If object already stored in database, delete it + if (hasGraph(graph.getModule(), graph.getRpc(), graph.getVersion(), + graph.getMode())) { + delete(graph.getModule(), graph.getRpc(), graph.getVersion(), + graph.getMode()); + } + + Connection dbConn = null; + + try { + dbConn = ((DBResourceManager) dbSvc).getConnection(); + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + PreparedStatement storeGraphStmt = dbConn + .prepareStatement(storeGraphSql); + storeGraphStmt.setString(1, graph.getModule()); + storeGraphStmt.setString(2, graph.getRpc()); + storeGraphStmt.setString(3, graph.getVersion()); + storeGraphStmt.setString(4, graph.getMode()); + storeGraphStmt.setString(5, "N"); + storeGraphStmt.setBlob(6, new ByteArrayInputStream(graphBytes)); + + storeGraphStmt.executeUpdate(); + dbConn.commit(); + + dbConn.setAutoCommit(oldAutoCommit); + } catch (Exception e) { + throw new SvcLogicException("Could not write object to database", e); + } finally { + try { + if (dbConn != null && !dbConn.isClosed()) { + dbConn.close(); + } + } catch (Throwable exc) { + // the exception not monitored + } finally { + dbConn = null; + } + + } + } + + public void delete(String module, String rpc, String version, String mode) + throws SvcLogicException { + + DbLibService dbSvc = getDbLibService(); + + String deleteGraphSql = "DELETE FROM SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; + + ArrayList args = new ArrayList(); + + args.add(module); + args.add(rpc); + args.add(version); + args.add(mode); + + try { + dbSvc.writeData(deleteGraphSql, args, null); + } catch (Exception e) { + throw new SvcLogicException( + "Could not delete object from database", e); + } + } + + public void activate(SvcLogicGraph graph) throws SvcLogicException { + DbLibService dbSvc = getDbLibService(); + + String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; + + String activateSql = "UPDATE SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; + + ArrayList args = new ArrayList(); + + args.add(graph.getModule()); + args.add(graph.getRpc()); + args.add(graph.getMode()); + + try { + + dbSvc.writeData(deactivateSql, args, null); + + args.add(graph.getVersion()); + dbSvc.writeData(activateSql, args, null); + + } catch (Exception e) { + throw new SvcLogicException("Could not activate graph", e); + } + } + + @Override + public void registerNodeType(String nodeType) throws SvcLogicException { + + String registerNodeSql = "INSERT INTO NODE_TYPES (nodetype) VALUES(?)"; + + if (isValidNodeType(nodeType)) { + return; + } + + DbLibService dbSvc = getDbLibService(); + ArrayList args = new ArrayList(); + + args.add(nodeType); + + try { + dbSvc.writeData(registerNodeSql, args, null); + } catch (Exception e) { + throw new SvcLogicException("Could not add node type to database", + e); + } + + } + + @Override + public void unregisterNodeType(String nodeType) throws SvcLogicException { + + if (!isValidNodeType(nodeType)) { + return; + } + + String unregisterNodeSql = "DELETE FROM NODE_TYPES WHERE nodetype = ?"; + + DbLibService dbSvc = getDbLibService(); + ArrayList args = new ArrayList(); + + args.add(nodeType); + + try { + dbSvc.writeData(unregisterNodeSql, args, null); + } catch (Exception e) { + throw new SvcLogicException( + "Could not delete node type from database", e); + } + + } + + @Override + public boolean isValidNodeType(String nodeType) throws SvcLogicException { + + String validateNodeSql = "SELECT count(*) FROM NODE_TYPES WHERE nodetype = ?"; + + DbLibService dbSvc = getDbLibService(); + + ArrayList args = new ArrayList(); + + args.add(nodeType); + + boolean isValid = false; + + CachedRowSet results = null; + try { + results = dbSvc.getData(validateNodeSql, args, null); + if (results != null) { + if (results.next()) { + int cnt = results.getInt(1); + + if (cnt > 0) { + isValid = true; + } + } + } + } catch (Exception e) { + throw new SvcLogicException( + "Cannot select node type from database", e); + } finally { + if (results != null) { + try { + results.close(); + } catch (SQLException x) { + } + } + + } + + return (isValid); + } + + private DbLibService getDbLibService() { + + // Get DbLibService interface object. + DbLibService dblibSvc = null; + ServiceReference sref = null; + BundleContext bctx = null; + + Bundle bundle = FrameworkUtil.getBundle(SvcLogicDblibStore.class); + + if (bundle != null) { + bctx = bundle.getBundleContext(); + + if (bctx != null) { + sref = bctx.getServiceReference(DBLIB_SERVICE); + } + + if (sref == null) { + LOG.warn("Could not find service reference for DBLIB service (" + + DBLIB_SERVICE + ")"); + } else { + dblibSvc = (DbLibService) bctx.getService(sref); + if (dblibSvc == null) { + + LOG.warn("Could not find service reference for DBLIB service (" + + DBLIB_SERVICE + ")"); + } + } + } + + // initialize a stand-alone instance of dblib resource + else { + // Try to create a DbLibService object from dblib properties + if(JavaSingleton.getInstance() == null){ + Properties dblibProps = new Properties(); + + String propDir = System.getenv(SDNC_CONFIG_DIR); + if (propDir == null) { + + propDir = "/opt/sdnc/data/properties"; + } + String propPath = propDir + "/dblib.properties"; + + File propFile = new File(propPath); + + if (!propFile.exists()) { + + LOG.warn( + "Missing configuration properties file : " + + propFile); + return(null); + } + + try { + + dblibProps.load(new FileInputStream(propFile)); + } catch (Exception e) { + LOG.warn( + "Could not load properties file " + propPath, e); + return(null); + + } + + try { + dblibSvc = DBResourceManager.create(dblibProps); + JavaSingleton.setInstance(dblibSvc); + } catch (Exception e) { + LOG.warn("Caught exception trying to create DBResourceManager", e); + } + } else { + dblibSvc = JavaSingleton.getInstance(); + } + } + return (dblibSvc); + } + + + static class JavaSingleton { + /* Private constructor */ + private JavaSingleton() { + /* the body of the constructor here */ + } + + /* instance of the singleton declaration */ + private static volatile DbLibService INSTANCE ; + + /* Access point to the unique instance of the singleton */ + public static DbLibService getInstance() { + return INSTANCE; + } + + public static void setInstance(DbLibService dbresource) { + INSTANCE = dbresource; + } + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicException.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicException.java new file mode 100644 index 000000000..198f8d577 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicException.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +public class SvcLogicException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public SvcLogicException() + { + super(); + } + + public SvcLogicException(String message) + { + super(message); + } + + public SvcLogicException(String message, Throwable t) + { + super(message, t); + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprListener.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprListener.java new file mode 100644 index 000000000..0dda84697 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprListener.java @@ -0,0 +1,315 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.LinkedList; +import java.util.List; + +import org.antlr.v4.runtime.tree.TerminalNode; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.AddExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.AtomContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.CompareExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.ConstantContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.ExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.FuncExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.MultExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.ParenExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.RelExprContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.VariableContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.VariableLeadContext; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.VariableTermContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SvcLogicExprListener extends ExprGrammarBaseListener +{ + + + + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicExprListener.class); + + private SvcLogicExpression curExpr; + private SvcLogicExpression topExpr; + private LinkedList exprStack; + + public SvcLogicExprListener() + { + exprStack = new LinkedList(); + } + + public SvcLogicExpression getParsedExpr() + { + return(curExpr); + } + + private void pushOperand(SvcLogicExpression operand) + { + if (curExpr == null) + { + curExpr = operand; + } + else + { + curExpr.addOperand(operand); + } + } + + private void pushExpr(SvcLogicExpression expr) + { + LOG.trace("Pushing expression ["+expr.getClass().getName()+"]"); + if (curExpr != null) + { + exprStack.push(curExpr); + } + curExpr = expr; + } + + private void popExpr() + { + if (exprStack.isEmpty()) + { + LOG.trace("Popping last expression"); + topExpr = curExpr; + } + else + { + SvcLogicExpression lastExpr = curExpr; + curExpr = exprStack.pop(); + curExpr.addOperand(lastExpr); + LOG.trace("New curExpr is ["+curExpr.getClass().getName()+"]"); + } + + } + + @Override + public void enterAtom(AtomContext ctx) { + + String atomText = ctx.getText(); + + LOG.trace("enterAtom: text = "+atomText); + + + SvcLogicAtom newAtom = new SvcLogicAtom(atomText); + + pushExpr(newAtom); + } + + + @Override + public void enterMultExpr(MultExprContext ctx) { + LOG.trace("enterMultExpr: text = "+ctx.getText()); + + SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); + pushExpr(curBinExpr); + + List opList = ctx.MULTOP(); + + for (TerminalNode nd : opList) + { + LOG.trace("enterMultExpr: operator - "+nd.getText()); + curBinExpr.addOperator(nd.getText()); + } + + } + + @Override + public void exitMultExpr(MultExprContext ctx) { + + LOG.trace("exitMultExpr: text = "+ctx.getText()); + + popExpr(); + + } + + @Override + public void exitAtom(AtomContext ctx) { + LOG.trace("exitAtom: text = "+ctx.getText()); + popExpr(); + } + + @Override + public void enterAddExpr(AddExprContext ctx) { + LOG.trace("enterAddExpr: text = "+ctx.getText()); + List opList = ctx.ADDOP(); + + + SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); + pushExpr(curBinExpr); + + + for (TerminalNode nd : opList) + { + LOG.trace("enterAddExpr: operator - "+nd.getText()); + curBinExpr.addOperator(nd.getText()); + } + + } + + @Override + public void exitAddExpr(AddExprContext ctx) { + LOG.trace("exitAddExpr: text = "+ctx.getText()); + + popExpr(); + } + + @Override + public void enterFuncExpr(FuncExprContext ctx) { + LOG.trace("enterFuncExpr: text = "+ctx.getText()); + LOG.trace("enterFuncExpr - IDENTIFIER : "+ctx.IDENTIFIER().getText()); + + for (ExprContext expr: ctx.expr()) + { + LOG.trace("enterFuncExpr - expr = "+expr.getText()); + } + + + pushExpr(new SvcLogicFunctionCall(ctx.IDENTIFIER().getText())); + } + + @Override + public void exitFuncExpr(FuncExprContext ctx) { + LOG.trace("exitFuncExpr: text = "+ctx.getText()); + + popExpr(); + } + + @Override + public void enterParenExpr(ParenExprContext ctx) { + LOG.trace("enterParenExpr: text = "+ctx.getText()); + LOG.trace("enterParenExpr: expr = "+ctx.expr().getText()); + } + + @Override + public void exitParenExpr(ParenExprContext ctx) { + LOG.trace("exitParenExpr: text = "+ctx.getText()); + } + + @Override + public void enterRelExpr(RelExprContext ctx) { + LOG.trace("enterRelExpr: text = "+ctx.getText()); + + List opList = ctx.RELOP(); + + + SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); + pushExpr(curBinExpr); + + + for (TerminalNode nd : opList) + { + LOG.trace("enterRelExpr: operator - "+nd.getText()); + curBinExpr.addOperator(nd.getText()); + } + + } + + @Override + public void exitRelExpr(RelExprContext ctx) { + LOG.trace("exitRelExpr: text = "+ctx.getText()); + + popExpr(); + } + + @Override + public void enterCompareExpr(CompareExprContext ctx) { + LOG.trace("enterCompareExpr: text = "+ctx.getText()); + + TerminalNode nd = ctx.COMPAREOP(); + + SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); + pushExpr(curBinExpr); + + LOG.trace("enterCompareExpr: operator - "+nd.getText()); + curBinExpr.addOperator(nd.getText()); + + } + + @Override + public void exitCompareExpr(CompareExprContext ctx) { + LOG.trace("exitCompareExpr : text = "+ctx.getText()); + + popExpr(); + } + + + + @Override + public void enterConstant(ConstantContext ctx) { + LOG.trace("enterConstant: text = "+ctx.getText()); + } + + @Override + public void exitConstant(ConstantContext ctx) { + LOG.trace("exitConstant: text = "+ctx.getText()); + } + + + @Override + public void enterVariable(VariableContext ctx) { + LOG.trace("enterVariable: text = "+ctx.getText()); + + + } + + @Override + public void exitVariable(VariableContext ctx) { + LOG.debug("exitVariable: text ="+ctx.getText()); + + } + + + @Override + public void enterVariableLead(VariableLeadContext ctx) { + + LOG.debug("enterVariableLead: text ="+ctx.getText()); + + + } + + @Override + public void exitVariableLead(VariableLeadContext ctx) { + + LOG.trace("exitVariableLead: text ="+ctx.getText()); + } + + @Override + public void enterVariableTerm(VariableTermContext ctx) { + LOG.trace("enterVariableTerm: text ="+ctx.getText()); + + String name = ctx.getText(); + + int subscrStart = name.indexOf("["); + if (subscrStart > -1) + { + name = name.substring(0, subscrStart); + } + SvcLogicVariableTerm vterm = new SvcLogicVariableTerm(name); + pushExpr(vterm); + } + + @Override + public void exitVariableTerm(VariableTermContext ctx) { + LOG.trace("exitVariableTerm: text="+ctx.getText()); + popExpr(); + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprParserErrorListener.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprParserErrorListener.java new file mode 100644 index 000000000..79979e75f --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExprParserErrorListener.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; +import org.antlr.v4.runtime.misc.ParseCancellationException; + +public class SvcLogicExprParserErrorListener extends BaseErrorListener { + + private static final SvcLogicExprParserErrorListener instance = new SvcLogicExprParserErrorListener(); + + public static SvcLogicExprParserErrorListener getInstance() { + return(instance); + } + + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, + String msg, RecognitionException e) throws ParseCancellationException { + throw new ParseCancellationException(msg); + } + + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java new file mode 100644 index 000000000..72a438454 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + + +public abstract class SvcLogicExpression implements Serializable { + + private List operands = new LinkedList(); + + + public void addOperand(SvcLogicExpression expr) + { + operands.add(expr); + } + + public List getOperands() { + return operands; + } + + public int numOperands() + { + return(operands.size()); + } + + public abstract String asParsedExpr(); + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java new file mode 100644 index 000000000..18a433f64 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.antlr.v4.runtime.ANTLRInputStream; +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.onap.ccsdk.sli.core.sli.ExprGrammarParser.ExprContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class SvcLogicExpressionFactory { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicExpressionFactory.class); + + + public static SvcLogicExpression parse(String exprStr) throws IOException + { + LOG.trace("parse("+exprStr+")"); + InputStream exprStream = new ByteArrayInputStream(exprStr.getBytes()); + CharStream input = new ANTLRInputStream(exprStream); + ExprGrammarLexer lexer = new ExprGrammarLexer(input); + CommonTokenStream tokens = new CommonTokenStream(lexer); + ExprGrammarParser parser = new ExprGrammarParser(tokens); + + lexer.removeErrorListeners(); + lexer.addErrorListener(SvcLogicExprParserErrorListener.getInstance()); + parser.removeErrorListeners(); + parser.addErrorListener(SvcLogicExprParserErrorListener.getInstance()); + + ExprContext expression = null; + + try { + expression = parser.expr(); + } catch (Exception e) { + String errorMsg = e.getMessage(); + + LOG.error(errorMsg); + throw new SvcLogicParserException(errorMsg); + } + + + ParseTreeWalker walker = new ParseTreeWalker(); + SvcLogicExprListener listener = new SvcLogicExprListener(); + walker.walk(listener, expression); + + + return(listener.getParsedExpr()); + } + + public static void main(String argv[]) { + + + System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "debug"); + + StringBuffer sbuff = new StringBuffer(); + + for (int i = 0 ; i < argv.length ; i++) + { + if (sbuff.length() > 0) + { + sbuff.append(" "); + } + sbuff.append(argv[i]); + } + + try { + SvcLogicExpressionFactory.parse(sbuff.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicFunctionCall.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicFunctionCall.java new file mode 100644 index 000000000..fc899704f --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicFunctionCall.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +public class SvcLogicFunctionCall extends SvcLogicExpression { + + private String functionName; + + public SvcLogicFunctionCall(String functionName) + { + this.functionName = functionName; + } + + public String getFunctionName() { + return functionName; + } + + public void setFunctionName(String functionName) { + this.functionName = functionName; + } + + public String toString() + { + StringBuffer sbuff = new StringBuffer(); + + sbuff.append(functionName); + sbuff.append("("); + boolean needComma = false; + for (SvcLogicExpression operand: getOperands()) + { + if (needComma) + { + sbuff.append(","); + } + else + { + needComma = true; + } + sbuff.append(operand.toString()); + + } + sbuff.append(")"); + return(sbuff.toString()); + } + + public String asParsedExpr() + { + StringBuffer sbuff = new StringBuffer(); + + sbuff.append("("); + sbuff.append(functionName); + for (SvcLogicExpression operand: getOperands()) + { + sbuff.append(" "); + sbuff.append(operand.asParsedExpr()); + } + sbuff.append(")"); + return(sbuff.toString()); + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicGraph.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicGraph.java new file mode 100644 index 000000000..158d815b0 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicGraph.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.PrintStream; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +public class SvcLogicGraph implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private String module = null; + private String rpc = null; + private String mode = null; + private String version = null; + + private Map attributes; + private Map namedNodes; + private SvcLogicNode rootNode; + + public SvcLogicGraph() + { + attributes = new HashMap(); + namedNodes = new HashMap(); + rootNode = null; + } + + + public String getModule() { + return module; + } + + + public void setModule(String module) { + this.module = module; + } + + + public String getRpc() { + return rpc; + } + + + public void setRpc(String rpc) { + this.rpc = rpc; + } + + + + + public String getMode() { + return mode; + } + + + public void setMode(String mode) { + this.mode = mode; + } + + + public String getVersion() { + return version; + } + + + public void setVersion(String version) { + this.version = version; + } + + + public void setRootNode(SvcLogicNode rootNode) + { + this.rootNode = rootNode; + } + + public SvcLogicNode getRootNode() + { + return(rootNode); + } + + public Serializable getAttribute(String name) + { + if (attributes.containsKey(name)) + { + return(attributes.get(name)); + } + else + { + return(null); + } + + } + + public void setAttribute(String name, Serializable value) throws DuplicateValueException + { + if (attributes.containsKey(name)) + { + throw new DuplicateValueException("Duplicate attribute "+name); + } + + attributes.put(name, value); + } + + public SvcLogicNode getNamedNode(String nodeName) + { + if (namedNodes.containsKey(nodeName)) + { + return(namedNodes.get(nodeName)); + } + else + { + return(null); + } + } + + public void setNamedNode(String nodeName, SvcLogicNode node) throws DuplicateValueException + { + if (namedNodes.containsKey(nodeName)) + { + throw new DuplicateValueException("Duplicate node name "+nodeName); + } + + namedNodes.put(nodeName, node); + } + + + + public void printAsGv(PrintStream pstr) + { + pstr.println("digraph g {"); + pstr.println("START [label=\"START\\n"+module+":"+rpc+"\"];"); + + if (rootNode != null) + { + pstr.println("START -> node"+rootNode.getNodeId()+";"); + rootNode.setVisited(false, true); + rootNode.printAsGv(pstr); + } + pstr.println("}"); + } + + public void printAsXml(PrintStream pstr) + { + pstr.println(""); + pstr.println(" "); + if (rootNode != null) + { + rootNode.setVisited(false, true); + rootNode.printAsXml(pstr, 2); + } + pstr.println(" "); + pstr.println(""); + } + + @Override + public String toString() { + return "SvcLogicGraph [module=" + module + ", rpc=" + rpc + ", mode=" + mode + ", version=" + version + "]"; + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java new file mode 100644 index 000000000..eaf4c7196 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.Map; + +public interface SvcLogicJavaPlugin { + + /** + * A marker interface, used to indicate that a class exposes methods that can be + * called from an node. Such methods must have the signature: + * void methodName(Map, SvcLogicContext) + */ + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java new file mode 100644 index 000000000..9aa0ddfb5 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java @@ -0,0 +1,894 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class SvcLogicJdbcStore implements SvcLogicStore { + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicJdbcStore.class); + + private String dbUrl = null; + private String dbName = null; + private String dbUser = null; + private String dbPasswd = null; + private String dbDriver = null; + + private Connection dbConn; + private PreparedStatement hasActiveGraphStmt = null; + private PreparedStatement hasVersionGraphStmt = null; + private PreparedStatement fetchActiveGraphStmt = null; + private PreparedStatement fetchVersionGraphStmt = null; + private PreparedStatement storeGraphStmt = null; + private PreparedStatement deleteGraphStmt = null; + + private PreparedStatement deactivateStmt = null; + private PreparedStatement activateStmt = null; + + private PreparedStatement registerNodeStmt = null; + private PreparedStatement unregisterNodeStmt = null; + private PreparedStatement validateNodeStmt = null; + + private void getConnection() throws ConfigurationException + { + + Properties jdbcProps = new Properties(); + + jdbcProps.setProperty("user", dbUser); + jdbcProps.setProperty("password", dbPasswd); + + try { + Driver dvr = new com.mysql.jdbc.Driver(); + if (dvr.acceptsURL(dbUrl)) + { + LOG.debug("Driver com.mysql.jdbc.Driver accepts "+dbUrl); + } + else + { + LOG.warn("Driver com.mysql.jdbc.Driver does not accept "+dbUrl); + } + } catch (SQLException e1) { + LOG.error("Caught exception trying to load com.mysql.jdbc.Driver", e1); + + + } + + + try + { + this.dbConn = DriverManager.getConnection(dbUrl, jdbcProps); + } + catch (Exception e) + { + throw new ConfigurationException("failed to get database connection ["+dbUrl+"]", e); + } + + } + + private void createTable() throws ConfigurationException + { + + + DatabaseMetaData dbm = null; + + + try { + dbm = dbConn.getMetaData(); + } catch (SQLException e) { + + throw new ConfigurationException("could not get databse metadata", e); + } + + // See if table SVC_LOGIC exists. If not, create it. + try + { + + + ResultSet tables = dbm.getTables(null, null, "SVC_LOGIC", null); + if (tables.next()) { + // Table exists + } + else { + + String crTableCmd = "CREATE TABLE "+dbName+".SVC_LOGIC (" + + "module varchar(80) NOT NULL," + + "rpc varchar(80) NOT NULL," + + "version varchar(40) NOT NULL," + + "mode varchar(5) NOT NULL," + + "active varchar(1) NOT NULL," + + "graph BLOB," + + "CONSTRAINT P_SVC_LOGIC PRIMARY KEY(module, rpc, version, mode))"; + + Statement stmt = null; + ConfigurationException myExc = null; + try + { + stmt = dbConn.createStatement(); + stmt.executeUpdate(crTableCmd); + } + catch (SQLException e1) + { + myExc = new ConfigurationException("cannot create SVC_LOGIC table", e1); + } + finally + { + if (stmt != null) + { + stmt.close(); + } + } + + if (myExc != null) + { + throw myExc; + } + } + } + catch (Exception e) + { + throw new ConfigurationException("could not create SVC_LOGIC table", e); + } + + // See if NODE_TYPES table exists and, if not, create it + + try + { + + + ResultSet tables = dbm.getTables(null, null, "NODE_TYPES", null); + if (tables.next()) { + // Table exists + } + else { + + String crTableCmd = "CREATE TABLE "+dbName+".NODE_TYPES (" + + "nodetype varchar(80) NOT NULL," + + "CONSTRAINT P_NODE_TYPES PRIMARY KEY(nodetype))"; + + Statement stmt = null; + ConfigurationException myExc = null; + try + { + stmt = dbConn.createStatement(); + stmt.executeUpdate(crTableCmd); + } + catch (SQLException e1) + { + myExc = new ConfigurationException("cannot create SVC_LOGIC table", e1); + } + finally + { + if (stmt != null) + { + stmt.close(); + } + } + + if (myExc != null) + { + throw myExc; + } + } + } + catch (Exception e) + { + throw new ConfigurationException("could not create SVC_LOGIC table", e); + } + } + + private void prepStatements() throws ConfigurationException + { + + // Prepare statements + String hasVersionGraphSql = "SELECT count(*) FROM "+dbName+".SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; + + try + { + hasVersionGraphStmt = dbConn.prepareStatement(hasVersionGraphSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+hasVersionGraphSql, e); + + } + + String hasActiveGraphSql = "SELECT count(*) FROM "+dbName+".SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; + + try + { + hasActiveGraphStmt = dbConn.prepareStatement(hasActiveGraphSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+hasVersionGraphSql, e); + + } + + String fetchVersionGraphSql = "SELECT graph FROM "+dbName+".SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; + + try + { + fetchVersionGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+fetchVersionGraphSql, e); + + } + + String fetchActiveGraphSql = "SELECT graph FROM "+dbName+".SVC_LOGIC" + + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; + + try + { + fetchActiveGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+fetchVersionGraphSql, e); + + } + + String storeGraphSql = "INSERT INTO "+dbName+".SVC_LOGIC (module, rpc, version, mode, active, graph)" + + " VALUES(?, ?, ?, ?, ?, ?)"; + + try + { + storeGraphStmt = dbConn.prepareStatement(storeGraphSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+storeGraphSql, e); + } + + String deleteGraphSql = "DELETE FROM "+dbName+".SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; + + try + { + deleteGraphStmt = dbConn.prepareStatement(deleteGraphSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+deleteGraphSql, e); + } + + String deactivateSql = "UPDATE "+dbName+".SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; + + try + { + deactivateStmt = dbConn.prepareStatement(deactivateSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+deactivateSql, e); + } + + String activateSql = "UPDATE "+dbName+".SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; + + try + { + activateStmt = dbConn.prepareStatement(activateSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+activateSql, e); + } + + String registerNodeSql = "INSERT INTO "+dbName+".NODE_TYPES (nodetype) VALUES(?)"; + try + { + registerNodeStmt = dbConn.prepareStatement(registerNodeSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+registerNodeSql, e); + } + + String unregisterNodeSql = "DELETE FROM "+dbName+".NODE_TYPES WHERE nodetype = ?"; + try + { + unregisterNodeStmt = dbConn.prepareStatement(unregisterNodeSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+unregisterNodeSql, e); + } + + String validateNodeSql = "SELECT count(*) FROM "+dbName+".NODE_TYPES WHERE nodetype = ?"; + try + { + validateNodeStmt = dbConn.prepareStatement(validateNodeSql); + } + catch (Exception e) + { + throw new ConfigurationException("could not prepare statement "+validateNodeSql, e); + } + } + + private void initDbResources() throws ConfigurationException + { + if ((dbDriver != null) && (dbDriver.length() > 0)) + { + + try + { + Class.forName(dbDriver); + } + catch (Exception e) + { + throw new ConfigurationException("could not load driver class "+dbDriver, e); + } + } + getConnection(); + createTable(); + prepStatements(); + } + + + public void init(Properties props) throws ConfigurationException { + + + dbUrl = props.getProperty("org.openecomp.sdnc.sli.jdbc.url"); + if ((dbUrl == null) || (dbUrl.length() == 0)) + { + throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.url unset"); + } + + dbName = props.getProperty("org.openecomp.sdnc.sli.jdbc.database"); + if ((dbName == null) || (dbName.length() == 0)) + { + throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.database unset"); + } + + dbUser = props.getProperty("org.openecomp.sdnc.sli.jdbc.user"); + if ((dbUser == null) || (dbUser.length() == 0)) + { + throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.user unset"); + } + + + dbPasswd = props.getProperty("org.openecomp.sdnc.sli.jdbc.password"); + if ((dbPasswd == null) || (dbPasswd.length() == 0)) + { + throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.password unset"); + } + + dbDriver = props.getProperty("org.openecomp.sdnc.sli.jdbc.driver"); + + + initDbResources(); + + } + + private boolean isDbConnValid() + { + + boolean isValid = false; + + try + { + if (dbConn != null) + { + isValid = dbConn.isValid(1); + } + } + catch (SQLException e) + {} + + return(isValid); + } +public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { + + + + + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + + + boolean retval = false; + ResultSet results = null; + + PreparedStatement hasGraphStmt = null; + if (version == null) + { + hasGraphStmt = hasActiveGraphStmt; + } + else + { + hasGraphStmt = hasVersionGraphStmt; + } + + + + try + { + hasGraphStmt.setString(1, module); + hasGraphStmt.setString(2, rpc); + hasGraphStmt.setString(3, mode); + + + if (version != null) + { + hasGraphStmt.setString(4, version); + } + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + results = hasGraphStmt.executeQuery(); + dbConn.commit(); + dbConn.setAutoCommit(oldAutoCommit); + + if (results.next()) + { + int cnt = results.getInt(1); + + if (cnt > 0) + { + retval = true; + } + + } + } + catch (Exception e) + { + throw new ConfigurationException("SQL query failed", e); + } + finally + { + if (results != null) + { + try + { + + results.close(); + } + catch (SQLException x) + {} + } + + } + + + return(retval); + + + } + + public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException { + + + + + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + + + SvcLogicGraph retval = null; + ResultSet results = null; + + PreparedStatement fetchGraphStmt = null; + if (version == null) + { + fetchGraphStmt = fetchActiveGraphStmt; + } + else + { + fetchGraphStmt = fetchVersionGraphStmt; + } + try + { + fetchGraphStmt.setString(1, module); + fetchGraphStmt.setString(2, rpc); + fetchGraphStmt.setString(3, mode); + + + if (version != null) + { + fetchGraphStmt.setString(4, version); + } + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + results = fetchGraphStmt.executeQuery(); + dbConn.commit(); + dbConn.setAutoCommit(oldAutoCommit); + + if (results.next()) + { + Blob graphBlob = results.getBlob("graph"); + + ObjectInputStream gStream = new ObjectInputStream(graphBlob.getBinaryStream()); + + Object graphObj = gStream.readObject(); + gStream.close(); + + if (graphObj instanceof SvcLogicGraph) + { + retval = (SvcLogicGraph) graphObj; + } + else + { + throw new ConfigurationException("invalid type for graph ("+graphObj.getClass().getName()); + + } + + } + else + { + return(null); + } + } + catch (Exception e) + { + throw new ConfigurationException("SQL query failed", e); + } + finally + { + if (results != null) + { + try + { + results.close(); + } + catch (SQLException x) + {} + } + + } + + + return(retval); + + + } + + public void store(SvcLogicGraph graph) throws SvcLogicException { + + + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + if (graph == null) + { + throw new SvcLogicException("graph cannot be null"); + } + + byte[] graphBytes = null; + + ByteArrayOutputStream byteStr = null; + ObjectOutputStream goutStr = null; + + try + { + byteStr = new ByteArrayOutputStream(); + goutStr = new ObjectOutputStream(byteStr); + goutStr.writeObject(graph); + + graphBytes = byteStr.toByteArray(); + + } + catch (Exception e) + { + throw new SvcLogicException("could not serialize graph", e); + } + finally + { + + if (goutStr != null) + { + try { + goutStr.close(); + } catch (IOException e) { + + } + } + + if (byteStr != null) + { + try { + byteStr.close(); + } catch (IOException e) { + + } + } + } + + + // If object already stored in database, delete it + if (hasGraph(graph.getModule(), graph.getRpc(), graph.getVersion(), graph.getMode())) + { + delete(graph.getModule(), graph.getRpc(), graph.getVersion(), graph.getMode()); + } + + try + { + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + storeGraphStmt.setString(1, graph.getModule()); + storeGraphStmt.setString(2, graph.getRpc()); + storeGraphStmt.setString(3, graph.getVersion()); + storeGraphStmt.setString(4, graph.getMode()); + storeGraphStmt.setString(5, "N"); + storeGraphStmt.setBlob(6, new ByteArrayInputStream(graphBytes)); + + storeGraphStmt.executeUpdate(); + dbConn.commit(); + + dbConn.setAutoCommit(oldAutoCommit); + } + catch (Exception e) + { + throw new SvcLogicException("Could not write object to database", e); + } + } + + public void delete(String module, String rpc, String version, String mode) throws SvcLogicException + { + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + try + { + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + deleteGraphStmt.setString(1, module); + deleteGraphStmt.setString(2, rpc); + deleteGraphStmt.setString(3, version); + deleteGraphStmt.setString(4, mode); + + + deleteGraphStmt.executeUpdate(); + dbConn.commit(); + dbConn.setAutoCommit(oldAutoCommit); + } + catch (Exception e) + { + throw new SvcLogicException("Could not delete object from database", e); + } + } + + public void activate(SvcLogicGraph graph) throws SvcLogicException + { + try + { + boolean oldAutoCommit = dbConn.getAutoCommit(); + + dbConn.setAutoCommit(false); + + // Deactivate any current active version + deactivateStmt.setString(1, graph.getModule()); + deactivateStmt.setString(2, graph.getRpc()); + deactivateStmt.setString(3, graph.getMode()); + deactivateStmt.executeUpdate(); + + // Activate this version + activateStmt.setString(1, graph.getModule()); + activateStmt.setString(2, graph.getRpc()); + activateStmt.setString(3, graph.getVersion()); + activateStmt.setString(4, graph.getMode()); + activateStmt.executeUpdate(); + + dbConn.commit(); + + dbConn.setAutoCommit(oldAutoCommit); + + } + catch (Exception e) + { + throw new SvcLogicException("Could not activate graph", e); + } + } + + @Override + public void registerNodeType(String nodeType) throws SvcLogicException { + + if (isValidNodeType(nodeType)) + { + return; + } + + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + try + { + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + registerNodeStmt.setString(1, nodeType); + registerNodeStmt.executeUpdate(); + dbConn.commit(); + dbConn.setAutoCommit(oldAutoCommit); + } + catch (Exception e) + { + throw new SvcLogicException("Could not add node type to database", e); + } + + } + + @Override + public void unregisterNodeType(String nodeType) throws SvcLogicException { + + if (!isValidNodeType(nodeType)) + { + return; + } + + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + try + { + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + unregisterNodeStmt.setString(1, nodeType); + unregisterNodeStmt.executeUpdate(); + dbConn.commit(); + dbConn.setAutoCommit(oldAutoCommit); + } + catch (Exception e) + { + throw new SvcLogicException("Could not delete node type from database", e); + } + + } + + @Override + public boolean isValidNodeType(String nodeType) throws SvcLogicException { + + boolean isValid = false; + + if (!isDbConnValid()) + { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) + { + throw new ConfigurationException("no jdbc connection"); + } + } + + ResultSet results = null; + try + { + validateNodeStmt.setString(1, nodeType); + + boolean oldAutoCommit = dbConn.getAutoCommit(); + dbConn.setAutoCommit(false); + results = validateNodeStmt.executeQuery(); + dbConn.commit(); + dbConn.setAutoCommit(oldAutoCommit); + + if (results != null) + { + if (results.next()) + { + int cnt = results.getInt(1); + + if (cnt > 0) + { + isValid = true; + } + } + } + + } + catch (Exception e) + { + throw new SvcLogicException("Cannot select node type from database", e); + } + finally + { + if (results != null) + { + try + { + results.close(); + } + catch (SQLException x) + {} + } + + } + + return(isValid); + } + + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java new file mode 100644 index 000000000..3aab21f2f --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java @@ -0,0 +1,455 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.IOException; +import java.io.PrintStream; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.Locator; + + +public class SvcLogicNode implements Serializable { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicExprListener.class); + + private static final long serialVersionUID = 2L; + + private String nodeName; + private int nodeId; + private String nodeType; + private boolean visited; + private SvcLogicGraph graph; + + + private HashMap attributes; + private HashMap outcomes; + private HashMap parameters; + + public SvcLogicNode(int nodeId, String nodeType, SvcLogicGraph graph) + { + this.nodeId = nodeId; + nodeName = ""; + this.nodeType = nodeType; + this.graph = graph; + attributes = new HashMap (); + parameters = new HashMap (); + outcomes = null; + + } + + public SvcLogicNode(int nodeId, String nodeType, String nodeName, SvcLogicGraph graph) throws DuplicateValueException + { + this.nodeId = nodeId; + this.nodeName = nodeName; + this.nodeType = nodeType; + this.graph = graph; + attributes = new HashMap (); + parameters = new HashMap (); + outcomes = null; + graph.setNamedNode(nodeName, this); + } + + + public int getNodeId() + { + return nodeId; + } + + public String getNodeName() + { + return(nodeName); + } + + public String getNodeType() + { + return(nodeType); + } + + public SvcLogicGraph getGraph() + { + return(graph); + } + + public int getNumOutcomes() + { + if (outcomes == null) + { + return(0); + } + else + { + return(outcomes.size()); + } + } + + public SvcLogicExpression getAttribute(String name) + { + if (attributes.containsKey(name)) + { + return(attributes.get(name)); + } + else + { + return(null); + } + + } + + public void setAttribute(String name, String value) throws SvcLogicException + { + setAttribute(name, new SvcLogicAtom("STRING", value)); + } + + public void setAttribute(String name, SvcLogicExpression value) throws SvcLogicException + { + if (attributes.containsKey(name)) + { + throw new DuplicateValueException("Duplicate attribute "+name); + } + + attributes.put(name, value); + } + + + public void mapParameter(String name, String value) throws SvcLogicException + { + + if (parameters.containsKey(name)) + { + throw new DuplicateValueException("Duplicate parameter "+name); + } + try + { + SvcLogicExpression parmValue; + if ((value == null) || (value.length() == 0)) + { + parmValue = new SvcLogicAtom("STRING", ""); + } + else if (value.trim().startsWith("`")) + { + int lastParen = value.lastIndexOf("`"); + String evalExpr = value.trim().substring(1, lastParen); + parmValue = SvcLogicExpressionFactory.parse(evalExpr); + + } + else + { + if (Character.isDigit(value.charAt(0))) + { + parmValue = new SvcLogicAtom("NUMBER", value); + } + else + { + parmValue = new SvcLogicAtom("STRING", value); + } + } + LOG.debug("Setting parameter "+name+" = "+value+" = "+parmValue.asParsedExpr()); + parameters.put(name, parmValue); + } + catch (IOException e) { + + LOG.error("Invalid parameter value expression ("+value+")"); + throw new SvcLogicException(e.getMessage()); + } + } + + public SvcLogicExpression getParameter(String name) + { + if (parameters.containsKey(name)) + { + return(parameters.get(name)); + } + else + { + return(null); + } + } + + public boolean isVisited() { + return visited; + } + + public void setVisited(boolean visited, boolean recursive) { + this.visited = visited; + + if (recursive) + { + Set> outcomeSet = getOutcomeSet(); + + if (outcomeSet == null) + { + return; + } + + for (Iterator> iter = outcomeSet.iterator(); iter.hasNext();) + { + Map.Entry curOutcome = iter.next(); + SvcLogicNode outNode = curOutcome.getValue(); + outNode.setVisited(visited, recursive); + } + } + } + + public void addOutcome(String outcomeValue, SvcLogicNode node) throws SvcLogicException + { + if (outcomes == null) + { + outcomes = new HashMap(); + } + + if (outcomeValue.length() == 0) { + outcomeValue = "\"\""; + } + if (outcomes.containsKey(outcomeValue)) + { + throw new DuplicateValueException("Duplicate outcome value "+outcomeValue); + } + + outcomes.put(outcomeValue, node); + } + + public Set> getOutcomeSet() + { + if (outcomes == null) + { + return null; + } + + return(outcomes.entrySet()); + + } + + public Set> getParameterSet() + { + if (parameters == null) + { + return null; + } + + return(parameters.entrySet()); + + } + + public void printAsGv(PrintStream pstr) + { + + if (visited) + { + return; + } + else + { + visited = true; + } + + StringBuffer sbuff = new StringBuffer(); + + sbuff.append("node"); + sbuff.append(nodeId); + sbuff.append(" [ shape=none, margin=0, label=<"); + sbuff.append(""); + + if (nodeName.length() > 0) + { + sbuff.append(""); + } + + Set> attrSet = attributes.entrySet(); + for (Iterator> iter = attrSet.iterator() ; iter.hasNext();) + { + Map.Entry curAttr = iter.next(); + sbuff.append(""); + } + sbuff.append("
"); + sbuff.append(nodeId); + sbuff.append(" : "); + sbuff.append(nodeType); + sbuff.append("
AttributeValue
name"); + sbuff.append(nodeName); + sbuff.append("
"); + sbuff.append(curAttr.getKey()); + sbuff.append(""); + sbuff.append(StringEscapeUtils.escapeHtml3(curAttr.getValue().toString())); + sbuff.append("
>];"); + + pstr.println(sbuff.toString()); + + + if (outcomes != null) + { + TreeMap sortedOutcomes = new TreeMap(outcomes); + Set> outcomeSet = sortedOutcomes.entrySet(); + + for (Iterator> iter = outcomeSet.iterator(); iter.hasNext();) + { + Map.Entry curOutcome = iter.next(); + String outValue = curOutcome.getKey(); + SvcLogicNode outNode = curOutcome.getValue(); + pstr.println("node"+nodeId+" -> node"+outNode.getNodeId()+" [label=\""+outValue+"\"];"); + outNode.printAsGv(pstr); + } + } + } + + public void printAsXml(PrintStream pstr, int indentLvl) + { + if (visited) + { + return; + } + // Print node tag + for (int i = 0 ; i < indentLvl ; i++) + { + pstr.print(" "); + } + pstr.print("<"); + pstr.print(this.getNodeType()); + + Set> attrSet = attributes.entrySet(); + for (Iterator> iter = attrSet.iterator() ; iter.hasNext();) + { + Map.Entry curAttr = iter.next(); + pstr.print(" "); + pstr.print(curAttr.getKey()); + pstr.print("='`"); + pstr.print(curAttr.getValue()); + pstr.print("'`"); + } + + if (((parameters == null) || (parameters.isEmpty())) && + ((outcomes == null) || outcomes.isEmpty())) + { + pstr.print("/>\n"); + pstr.flush(); + return; + } + else + { + pstr.print(">\n"); + } + + // Print parameters (if any) + if (parameters != null) + { + Set> paramSet = parameters.entrySet(); + for (Iterator> iter = paramSet.iterator() ; iter.hasNext();) + { + for (int i = 0 ; i < indentLvl+1 ; i++) + { + pstr.print(" "); + } + pstr.print(" curAttr = iter.next(); + pstr.print(" name='"); + pstr.print(curAttr.getKey()); + pstr.print("' value='`"); + pstr.print(curAttr.getValue().toString()); + pstr.print("`'/>\n"); + } + } + + // Print outcomes (if any) + if (outcomes != null) + { + Set> outcomeSet = outcomes.entrySet(); + for (Iterator> iter = outcomeSet.iterator() ; iter.hasNext();) + { + for (int i = 0 ; i < indentLvl+1 ; i++) + { + pstr.print(" "); + } + pstr.print(" curAttr = iter.next(); + pstr.print(" value='"); + pstr.print(curAttr.getKey()); + pstr.print("'>\n"); + SvcLogicNode outNode = curAttr.getValue(); + outNode.printAsXml(pstr, indentLvl+2); + for (int i = 0 ; i < indentLvl+1 ; i++) + { + pstr.print(" "); + } + pstr.print("\n"); + } + } + + // Print node end tag + for (int i = 0 ; i < indentLvl ; i++) + { + pstr.print(" "); + } + pstr.print("\n"); + pstr.flush(); + + } + + + public SvcLogicNode getOutcomeValue(String value) + { + + if (value.length() == 0) { + value = "\"\""; + } + if (outcomes == null) + { + return(null); + } + + if (outcomes.containsKey(value)) + { + return(outcomes.get(value)); + } + else + { + StringBuffer keyBuffer = new StringBuffer(); + keyBuffer.append("{"); + for (String key : outcomes.keySet()) { + keyBuffer.append(" ("+key+")"); + } + keyBuffer.append("}"); + LOG.info("Outcome (" + value + ") not found, keys are " + keyBuffer.toString()); + + if (outcomes.containsKey("Other")) + { + return(outcomes.get("Other")); + } + else + { + return(null); + } + } + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java new file mode 100644 index 000000000..9ba502666 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java @@ -0,0 +1,597 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.File; +import java.io.InputStream; +import java.net.URL; +import java.util.LinkedList; + +import javax.xml.XMLConstants; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.Attributes; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.SAXNotRecognizedException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * @author dt5972 + * + */ +public class SvcLogicParser { + + SvcLogicStore store = null; + static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; + static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; + static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; + static final String JAXP_DYNAMIC_VALIDATION = "http://apache.org/xml/features/validation/dynamic"; + static final String JAXP_SCHEMA_VALIDATION = "http://apache.org/xml/features/validation/schema"; + + private static final String LOAD_MESSAGE = "Getting SvcLogicGraph from database - "; + private static final String LOAD_ERROR_MESSAGE = "SvcLogicGraph not found - "; + private static final String ACTIVATION_ERROR_MESSAGE = "Could not activate SvcLogicGraph - "; + private static final String PRINT_ERROR_MESSAGE = "Could not print SvcLogicGraph - "; + private static final String SVC_LOGIC_STORE_ERROR = "Could not get service logic store"; + + private static final Logger LOGGER = LoggerFactory.getLogger(SvcLogicParser.class); + private static final String SLI_VALIDATING_PARSER = "org.openecomp.sdnc.sli.parser.validate"; + private static final String SVCLOGIC_XSD = "/svclogic.xsd"; + + private class SvcLogicHandler extends DefaultHandler { + private Locator locator = null; + private String module = null; + private String version = null; + private LinkedList graphs = null; + private SvcLogicGraph curGraph = null; + private SvcLogicNode curNode = null; + private LinkedList nodeStack = null; + private int curNodeId = 0; + private String outcomeValue = null; + private LinkedList outcomeStack = null; + private SvcLogicStore svcLogicStore = null; + + public SvcLogicHandler(LinkedList graphs, SvcLogicStore store) { + this.graphs = graphs; + this.curNode = null; + this.nodeStack = new LinkedList<>(); + this.outcomeStack = new LinkedList<>(); + this.curNodeId = 1; + this.outcomeValue = null; + this.svcLogicStore = store; + + } + + @Override + public void setDocumentLocator(Locator locator) { + this.locator = locator; + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + + // Handle service-logic (graph) tag + if ("service-logic".equalsIgnoreCase(qName)) { + + module = attributes.getValue("module"); + if (module == null || module.length() == 0) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'module' attribute from service-logic tag"); + } + + version = attributes.getValue("version"); + if (version == null || version.length() == 0) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'version' attribute from service-logic tag"); + } + + return; + } + + if ("method".equalsIgnoreCase(qName)) { + if (curGraph != null) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot nest module tags"); + } + curGraph = new SvcLogicGraph(); + curGraph.setModule(module); + curGraph.setVersion(version); + this.curNodeId = 1; + + String attrValue = attributes.getValue("rpc"); + if (attrValue == null || attrValue.length() == 0) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'rpc' attribute for method tag"); + } + curGraph.setRpc(attrValue); + + attrValue = attributes.getValue("mode"); + if (attrValue == null || attrValue.length() == 0) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'mode' attribute for method tag"); + } + curGraph.setMode(attrValue); + + return; + + } + + // Handle outcome (edge) tag + if ("outcome".equalsIgnoreCase(qName)) { + String refValue = attributes.getValue("ref"); + + if (refValue != null) { + SvcLogicNode refNode = curGraph.getNamedNode(refValue); + + if (refNode != null) { + try { + curNode.addOutcome(attributes.getValue("value"), refNode); + } catch (SvcLogicException e) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot add outcome", e); + } + } else { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "ref to unknown node " + refValue); + } + return; + } + + if (outcomeValue != null) { + outcomeStack.push(outcomeValue); + } + outcomeValue = attributes.getValue("value"); + + return; + } + + // Handle parameter tag + if ("parameter".equalsIgnoreCase(qName)) { + String parmName = attributes.getValue("name"); + String parmValue = attributes.getValue("value"); + + if (parmName != null && parmName.length() > 0 && parmValue != null) { + try { + + curNode.mapParameter(parmName, parmValue); + } catch (Exception e) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + " cannot set parameter " + parmName + " to " + parmValue + " [" + e.getMessage() + "]"); + } + } + + return; + } + + // Handle node tags + + String nodeName = attributes.getValue("name"); + SvcLogicNode thisNode = null; + + try { + if (!svcLogicStore.isValidNodeType(qName)) { + throw new SAXNotRecognizedException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Unknown tag " + qName); + } + } catch (Exception e) { + throw new SAXNotRecognizedException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot validate node type " + qName); + } + + try { + if (nodeName != null && nodeName.length() > 0) { + thisNode = new SvcLogicNode(curNodeId++, qName, nodeName, curGraph); + } else { + thisNode = new SvcLogicNode(curNodeId++, qName, curGraph); + } + + if (curGraph.getRootNode() == null) { + curGraph.setRootNode(thisNode); + } + } catch (SvcLogicException e) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + e.getMessage()); + + } + + int numAttributes = attributes.getLength(); + + for (int i = 0; i < numAttributes; i++) { + String attrName = attributes.getQName(i); + if (!"name".equalsIgnoreCase(attrName)) { + try { + + String attrValueStr = attributes.getValue(i); + SvcLogicExpression attrValue = null; + if (attrValueStr.trim().startsWith("`")) { + int lastParen = attrValueStr.lastIndexOf("`"); + String evalExpr = attrValueStr.trim().substring(1, lastParen); + attrValue = SvcLogicExpressionFactory.parse(evalExpr); + + } else { + if (Character.isDigit(attrValueStr.charAt(0))) { + attrValue = new SvcLogicAtom("NUMBER", attrValueStr); + } else { + attrValue = new SvcLogicAtom("STRING", attrValueStr); + } + } + thisNode.setAttribute(attrName, attrValue); + } catch (Exception e) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot set attribute " + attrName, e); + } + } + } + + if (curNode != null) { + try { + if ("block".equalsIgnoreCase(curNode.getNodeType()) || "for".equalsIgnoreCase(curNode.getNodeType()) || "while".equalsIgnoreCase(curNode.getNodeType())) { + curNode.addOutcome("" + (curNode.getNumOutcomes() + 1), thisNode); + } else { + if (outcomeValue == null) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + curNode.getNodeType() + " node expects outcome, instead found " + thisNode.getNodeType()); + } + curNode.addOutcome(outcomeValue, thisNode); + } + } catch (SvcLogicException e) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + e.getMessage()); + } + nodeStack.push(curNode); + } + curNode = thisNode; + + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + + // Handle close of service-logic tag + if ("service-logic".equalsIgnoreCase(qName)) { + // Nothing more to do + return; + } + + // Handle close of method tag + if ("method".equalsIgnoreCase(qName)) { + graphs.add(curGraph); + curGraph = null; + return; + } + + // Handle close of outcome tag + if ("outcome".equalsIgnoreCase(qName)) { + // Finished this outcome - pop the outcome stack + if (outcomeStack.isEmpty()) { + outcomeValue = null; + } else { + outcomeValue = outcomeStack.pop(); + } + return; + } + + // Handle close of parameter tag - do nothing + if ("parameter".equalsIgnoreCase(qName)) { + return; + } + + // Handle close of a node tag + if (nodeStack.isEmpty()) { + curNode = null; + } else { + curNode = nodeStack.pop(); + } + } + + @Override + public void error(SAXParseException arg0) throws SAXException { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + arg0.getMessage()); + } + + } + + public SvcLogicParser(SvcLogicStore store) { + this.store = store; + } + + public SvcLogicParser(String propFile) { + + try { + this.store = SvcLogicStoreFactory.getSvcLogicStore(propFile); + } catch (Exception e) { + LOGGER.error(SVC_LOGIC_STORE_ERROR, e); + + } + + } + + public SvcLogicParser(InputStream propStr) { + + try { + this.store = SvcLogicStoreFactory.getSvcLogicStore(propStr); + } catch (Exception e) { + LOGGER.error(SVC_LOGIC_STORE_ERROR, e); + + } + + } + + public LinkedList parse(String fileName) throws SvcLogicException { + LinkedList graphs = null; + + URL xsdUrl = null; + Schema schema = null; + String validateSchema = System.getProperty(SLI_VALIDATING_PARSER, "true"); + + if (validateSchema != null || validateSchema.equalsIgnoreCase("true")) { + xsdUrl = getClass().getResource(SVCLOGIC_XSD); + + } + + if (xsdUrl != null) { + try { + SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + schema = schemaFactory.newSchema(xsdUrl); + } catch (Exception e) { + LOGGER.warn("Could not validate using schema " + xsdUrl.getPath(), e); + } + } else { + LOGGER.warn("Could not find resource " + SVCLOGIC_XSD); + } + + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + + if (schema != null) { + factory.setNamespaceAware(true); + factory.setSchema(schema); + } + SAXParser saxParser = factory.newSAXParser(); + + if (saxParser.isValidating()) { + LOGGER.info("Validating against schema " + xsdUrl.getPath()); + } + graphs = new LinkedList<>(); + + saxParser.parse(fileName, new SvcLogicHandler(graphs, store)); + + } catch (Exception e) { + String msg = e.getMessage(); + if (msg != null) { + LOGGER.error(msg); + throw new SvcLogicException("Compiler error: " + fileName + " @ " + msg); + } else { + LOGGER.info("Caught exception parsing " + fileName, e); + throw new SvcLogicException("Compiler error: " + fileName, e); + } + } + + return graphs; + } + + public static void main(String argv[]) { + + if (argv.length == 0) { + SvcLogicParser.usage(); + } + + if ("load".equalsIgnoreCase(argv[0])) { + if (argv.length == 3) { + String xmlfile = argv[1]; + String propfile = argv[2]; + + SvcLogicStore store = SvcLogicParser.getStore(propfile); + try { + SvcLogicParser.load(xmlfile, store); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + } else { + SvcLogicParser.usage(); + } + } else if ("print".equalsIgnoreCase(argv[0])) { + String version = null; + String propfile = null; + + switch (argv.length) { + case 6: + version = argv[4]; + propfile = argv[5]; + case 5: + if (propfile == null) { + propfile = argv[4]; + } + SvcLogicStore store = SvcLogicParser.getStore(propfile); + SvcLogicParser.print(argv[1], argv[2], argv[3], version, store); + break; + default: + SvcLogicParser.usage(); + } + } else if ("get-source".equalsIgnoreCase(argv[0])) { + + switch (argv.length) { + case 6: + SvcLogicStore store = SvcLogicParser.getStore(argv[5]); + SvcLogicParser.getSource(argv[1], argv[2], argv[3], argv[4], store); + break; + default: + SvcLogicParser.usage(); + } + } else if ("activate".equalsIgnoreCase(argv[0])) { + if (argv.length == 6) { + SvcLogicStore store = SvcLogicParser.getStore(argv[5]); + SvcLogicParser.activate(argv[1], argv[2], argv[3], argv[4], store); + } else { + SvcLogicParser.usage(); + } + } else if ("validate".equalsIgnoreCase(argv[0])) { + if (argv.length == 3) { + String xmlfile = argv[1]; + String propfile = argv[2]; + + System.setProperty(SLI_VALIDATING_PARSER, "true"); + SvcLogicStore store = SvcLogicParser.getStore(propfile); + try { + SvcLogicParser.validate(xmlfile, store); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + } else { + SvcLogicParser.usage(); + } + } + + System.exit(0); + } + + private static SvcLogicStore getStore(String propfile) { + + SvcLogicStore store = null; + + try { + store = SvcLogicStoreFactory.getSvcLogicStore(propfile); + } catch (Exception e) { + LOGGER.error(SVC_LOGIC_STORE_ERROR, e); + System.exit(1); + } + + return store; + + } + + public static void load(String xmlfile, SvcLogicStore store) throws SvcLogicException { + File xmlFile = new File(xmlfile); + if (!xmlFile.canRead()) { + throw new ConfigurationException("Cannot read xml file (" + xmlfile + ")"); + } + + SvcLogicParser parser = new SvcLogicParser(store); + LinkedList graphs = null; + try { + graphs = parser.parse(xmlfile); + } catch (Exception e) { + throw new SvcLogicException(e.getMessage(), e); + } + + if (graphs == null) { + throw new SvcLogicException("Could not parse " + xmlfile); + } + + for (SvcLogicGraph graph : graphs) { + + String module = graph.getModule(); + String rpc = graph.getRpc(); + String version = graph.getVersion(); + String mode = graph.getMode(); + try { + LOGGER.info("Saving SvcLogicGraph to database (module:" + module + ",rpc:" + rpc + ",version:" + version + ",mode:" + mode + ")"); + store.store(graph); + } catch (Exception e) { + throw new SvcLogicException(e.getMessage(), e); + } + + } + + } + + public static void validate(String xmlfile, SvcLogicStore store) throws SvcLogicException { + File xmlFile = new File(xmlfile); + if (!xmlFile.canRead()) { + throw new ConfigurationException("Cannot read xml file (" + xmlfile + ")"); + } + + SvcLogicParser parser = new SvcLogicParser(store); + LinkedList graphs = null; + try { + LOGGER.info("Validating " + xmlfile); + graphs = parser.parse(xmlfile); + } catch (Exception e) { + throw new SvcLogicException(e.getMessage(), e); + } + + if (graphs == null) { + throw new SvcLogicException("Could not parse " + xmlfile); + } else { + LOGGER.info("Compilation successful for " + xmlfile); + } + + } + + private static void print(String module, String rpc, String mode, String version, SvcLogicStore store) { + String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; + + try { + LOGGER.info(LOAD_MESSAGE + details); + + SvcLogicGraph graph = store.fetch(module, rpc, version, mode); + if (graph == null) { + LOGGER.error(LOAD_ERROR_MESSAGE + details); + System.exit(1); + } + graph.printAsGv(System.out); + } catch (Exception e) { + LOGGER.error(PRINT_ERROR_MESSAGE + details, e); + System.exit(1); + } + + } + + private static void getSource(String module, String rpc, String mode, String version, SvcLogicStore store) { + String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; + + try { + LOGGER.info(LOAD_MESSAGE + details); + + SvcLogicGraph graph = store.fetch(module, rpc, version, mode); + if (graph == null) { + LOGGER.error(LOAD_ERROR_MESSAGE + details); + System.exit(1); + } + graph.printAsXml(System.out); + } catch (Exception e) { + LOGGER.error(PRINT_ERROR_MESSAGE + details, e); + System.exit(1); + } + + } + + private static void activate(String module, String rpc, String version, String mode, SvcLogicStore store) { + String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; + + try { + LOGGER.info(LOAD_MESSAGE + details); + + SvcLogicGraph graph = store.fetch(module, rpc, version, mode); + if (graph == null) { + LOGGER.error(LOAD_ERROR_MESSAGE + details); + System.exit(1); + } + store.activate(graph); + } catch (Exception e) { + LOGGER.error(ACTIVATION_ERROR_MESSAGE + details, e); + System.exit(1); + } + + } + + private static void usage() { + System.err.println("Usage: SvcLogicParser load "); + System.err.println(" OR SvcLogicParser print [] "); + System.err.println(" OR SvcLogicParser get-source "); + System.err.println(" OR SvcLogicParser activate "); + System.exit(1); + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserException.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserException.java new file mode 100644 index 000000000..a2d2ac4c4 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserException.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.IOException; + +public class SvcLogicParserException extends IOException { + + public SvcLogicParserException() { + super(); + } + + public SvcLogicParserException(String msg) { + super(msg); + } + + public SvcLogicParserException(Throwable t) { + super(t); + } + + public SvcLogicParserException(String msg, Throwable t) { + super(msg, t); + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicRecorder.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicRecorder.java new file mode 100644 index 000000000..1c85394b2 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicRecorder.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.Map; + +public interface SvcLogicRecorder { + + void record(Map parmMap) throws SvcLogicException; + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java new file mode 100644 index 000000000..10d31f56e --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.sql.SQLException; +import java.util.Map; + +public interface SvcLogicResource { + + public enum QueryStatus { + SUCCESS, + NOT_FOUND, + FAILURE + } + + public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus reserve(String resource, String select, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map parms, String prefix, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) throws SvcLogicException; + + public QueryStatus update(String resource, String key, Map parms, String prefix, SvcLogicContext ctx) throws SvcLogicException; + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStore.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStore.java new file mode 100644 index 000000000..6d2b99c57 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStore.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.util.Properties; + +public interface SvcLogicStore { + + public void init(Properties props) throws SvcLogicException; + public void registerNodeType(String nodeType) throws SvcLogicException; + public void unregisterNodeType(String nodeType) throws SvcLogicException; + public boolean isValidNodeType(String nodeType) throws SvcLogicException; + public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException; + public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException; + public void store(SvcLogicGraph graph) throws SvcLogicException; + public void delete(String module, String rpc, String version, String mode) throws SvcLogicException; + public void activate(SvcLogicGraph graph) throws SvcLogicException; +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStoreFactory.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStoreFactory.java new file mode 100644 index 000000000..38b5b69d6 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicStoreFactory.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SvcLogicStoreFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SvcLogicStoreFactory.class); + + public static SvcLogicStore getSvcLogicStore(String propfile) + throws SvcLogicException { + File propFile = new File(propfile); + if (!propFile.canRead()) { + throw new ConfigurationException("Cannot read property file " + + propfile); + + } + + try { + return (getSvcLogicStore(new FileInputStream(propFile))); + } catch (Exception e) { + throw new ConfigurationException( + "Could load service store from properties file " + propfile, + e); + } + + } + + public static SvcLogicStore getSvcLogicStore(InputStream inStr) throws SvcLogicException + { + Properties props = new Properties(); + + try { + props.load(inStr); + } catch (Exception e) { + throw new ConfigurationException("Could not get load properties from input stream", e); + } + + return(getSvcLogicStore(props)); + } + + public static SvcLogicStore getSvcLogicStore(Properties props) + throws SvcLogicException { + String storeType = props.getProperty("org.openecomp.sdnc.sli.dbtype"); + if ((storeType == null) || (storeType.length() == 0)) { + throw new ConfigurationException( + "property org.openecomp.sdnc.sli.dbtype unset"); + + } + + SvcLogicStore retval = null; + LOG.debug(String.format("Using org.openecomp.sdnc.sli.dbtype=%s", storeType)); + + if ("jdbc".equalsIgnoreCase(storeType)) { + retval = new SvcLogicJdbcStore(); + + } else if ("dblib".equalsIgnoreCase(storeType)) { + retval = new SvcLogicDblibStore(); + } else { + throw new ConfigurationException("unsupported dbtype (" + storeType + + ")"); + + } + + + retval.init(props); + return (retval); + } + +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicVariableTerm.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicVariableTerm.java new file mode 100644 index 000000000..ac642a2d9 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicVariableTerm.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +public class SvcLogicVariableTerm extends SvcLogicExpression { + + private String name = null; + + public String getName() { + return name; + } + + + public SvcLogicVariableTerm(String identifier) + { + this.name = identifier; + } + + public SvcLogicExpression getSubscript() + { + if (numOperands() > 0) + { + return(getOperands().get(0)); + } + else + { + return(null); + } + } + + + public String toString() + { + String retval = ""; + + if (numOperands() > 0) + { + retval = name + "[" + getSubscript().toString() + "]"; + } + else + { + retval = name; + } + return(retval); + } + + @Override + public String asParsedExpr() { + if (numOperands() == 0) { + return("(variable-term "+name+")"); + } + else + { + return("(variable-term "+name+" "+getSubscript().asParsedExpr()+")"); + } + } + +} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/BreakNodeException.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/BreakNodeException.java deleted file mode 100644 index 3e355baad..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/BreakNodeException.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -public class BreakNodeException extends SvcLogicException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public BreakNodeException() - { - super(); - } - - public BreakNodeException(String message) - { - super(message); - } - - public BreakNodeException(String message, Throwable t) - { - super(message, t); - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/ConfigurationException.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/ConfigurationException.java deleted file mode 100644 index fa1308f0e..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/ConfigurationException.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -public class ConfigurationException extends SvcLogicException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public ConfigurationException() - { - super(); - } - - public ConfigurationException(String msg) - { - super(msg); - } - - public ConfigurationException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/DuplicateValueException.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/DuplicateValueException.java deleted file mode 100644 index beb22b0b8..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/DuplicateValueException.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -public class DuplicateValueException extends SvcLogicException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public DuplicateValueException() - { - super(); - } - - public DuplicateValueException(String message) - { - super(message); - } - - public DuplicateValueException(String message, Throwable t) - { - super(message, t); - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/MessageWriter.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/MessageWriter.java deleted file mode 100644 index 5e5b621b0..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/MessageWriter.java +++ /dev/null @@ -1,302 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.File; -import java.io.FileInputStream; -import java.sql.SQLException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Properties; - -import javax.sql.rowset.CachedRowSet; - -import org.openecomp.sdnc.sli.resource.dblib.DbLibService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class MessageWriter { - - private static final Logger LOG = LoggerFactory.getLogger(MessageWriter.class); - - private static final String DBLIB_SERVICE = "org.openecomp.sdnc.sli.resource.dblib.DBResourceManager"; - private static final String SVCLOGIC_PROP_VAR = "SDNC_SLI_PROPERTIES"; - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final String INCOMING_PROPERTY_NAME = "org.openecomp.sdnc.sli.MessageWriter.writeIncomingRequests"; - private static final String OUTGOING_PROPERTY_NAME = "org.openecomp.sdnc.sli.MessageWriter.writeOutgoingRequests"; - - private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - private static DbLibService dbLibService = null; - - private static boolean incomingEnabled = false; - private static boolean outgoingEnabled = false; - - private static boolean initialized = false; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private static void init() { - if (initialized) - return; - - initialized = true; - - // Read properties - Properties props = new Properties(); - String propPath = System.getenv(SVCLOGIC_PROP_VAR); - - if (propPath == null) { - String propDir = System.getenv(SDNC_CONFIG_DIR); - if (propDir == null) { - propDir = "/opt/sdnc/data/properties"; - } - propPath = propDir + "/svclogic.properties"; - LOG.warn("Environment variable " + SVCLOGIC_PROP_VAR + " unset - defaulting to " + propPath); - } - - File propFile = new File(propPath); - - if (!propFile.exists()) { - LOG.warn("Property file does not exist: " + propPath); - } - - try { - props.load(new FileInputStream(propFile)); - } catch (Exception e) { - LOG.warn("Error loading property file: " + propPath, e); - } - - incomingEnabled = Boolean.valueOf(props.getProperty(INCOMING_PROPERTY_NAME, "false")); - outgoingEnabled = Boolean.valueOf(props.getProperty(OUTGOING_PROPERTY_NAME, "false")); - - LOG.info(INCOMING_PROPERTY_NAME + ": " + incomingEnabled); - LOG.info(OUTGOING_PROPERTY_NAME + ": " + outgoingEnabled); - - if (dbLibService != null) - return; - - BundleContext bctx = FrameworkUtil.getBundle(MessageWriter.class).getBundleContext(); - - ServiceReference sref = bctx.getServiceReference(DBLIB_SERVICE); - - if (sref == null) { - LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")"); - } else { - dbLibService = (DbLibService) bctx.getService(sref); - if (dbLibService == null) { - LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")"); - } - } - } - - public static void saveOutgoingRequest( - String requestId, - String serviceInstanceId, - String targetUrl, - String request) { - try { - init(); - - if (!outgoingEnabled) - return; - - if (serviceInstanceId == null || serviceInstanceId.trim().length() == 0) - serviceInstanceId = "NA"; - - int seqnum = getLastSequenceNumber("OUTGOING_MESSAGE", requestId) + 1; - String now = df.format(new Date()); - - String sql = "INSERT INTO OUTGOING_MESSAGE (\n" + - " request_id, sequence_number, service_instance_id, target_url, request, start_time)\n" + - "VALUES (?, ?, ?, ?, ?, ?)"; - - ArrayList data = new ArrayList<>(); - data.add(requestId); - data.add(String.valueOf(seqnum)); - data.add(serviceInstanceId); - data.add(targetUrl); - data.add(request); - data.add(now); - - dbLibService.writeData(sql, data, null); - - } catch (Exception e) { - LOG.warn("Failed to save outgoing request for request-id: " + requestId, e); - } - } - - public static void saveOutgoingResponse(String requestId, int httpResponseCode, String response) { - try { - init(); - - if (!outgoingEnabled) - return; - - int seqnum = getLastSequenceNumber("OUTGOING_MESSAGE", requestId); - if (seqnum == 0) { - LOG.warn("Failed to save outgoing response for request-id: " + requestId + - ": Request record not found in OUTGOING_MESSAGE"); - return; - } - - String now = df.format(new Date()); - - String sql = "UPDATE OUTGOING_MESSAGE SET http_response_code = ?, response = ?,\n" + - " duration = timestampdiff(MICROSECOND, start_time, ?) / 1000\n" + - "WHERE request_id = ? AND sequence_number = ?"; - - ArrayList data = new ArrayList<>(); - data.add(String.valueOf(httpResponseCode)); - data.add(response); - data.add(now); - data.add(requestId); - data.add(String.valueOf(seqnum)); - - dbLibService.writeData(sql, data, null); - - } catch (Exception e) { - LOG.warn("Failed to save outgoing response for request-id: " + requestId, e); - } - } - - public static void saveIncomingRequest( - String requestId, - String serviceInstanceId, - String requestHost, - String request) { - try { - init(); - - if (!incomingEnabled) - return; - - if (serviceInstanceId == null || serviceInstanceId.trim().length() == 0) - serviceInstanceId = "NA"; - - int seqnum = getLastSequenceNumber("INCOMING_MESSAGE", requestId) + 1; - String now = df.format(new Date()); - - String sql = "INSERT INTO INCOMING_MESSAGE (\n" + - " request_id, sequence_number, service_instance_id, request_host, request, start_time)\n" + - "VALUES (?, ?, ?, ?, ?, ?)"; - - ArrayList data = new ArrayList<>(); - data.add(requestId); - data.add(String.valueOf(seqnum)); - data.add(serviceInstanceId); - data.add(requestHost); - data.add(request); - data.add(now); - - dbLibService.writeData(sql, data, null); - - } catch (Exception e) { - LOG.warn("Failed to save incoming request for request-id: " + requestId, e); - } - } - - public static void saveIncomingResponse(String requestId, int httpResponseCode, String response) { - try { - init(); - - if (!incomingEnabled) - return; - - int seqnum = getLastSequenceNumber("INCOMING_MESSAGE", requestId); - if (seqnum == 0) { - LOG.warn("Failed to save response for request-id: " + requestId + - ": Request record not found in INCOMING_MESSAGE"); - return; - } - - String now = df.format(new Date()); - - String sql = "UPDATE INCOMING_MESSAGE SET http_response_code = ?, response = ?,\n" + - " duration = timestampdiff(MICROSECOND, start_time, ?) / 1000\n" + - "WHERE request_id = ? AND sequence_number = ?"; - - ArrayList data = new ArrayList<>(); - data.add(String.valueOf(httpResponseCode)); - data.add(response); - data.add(now); - data.add(requestId); - data.add(String.valueOf(seqnum)); - - dbLibService.writeData(sql, data, null); - - } catch (Exception e) { - LOG.warn("Failed to save response for request-id: " + requestId, e); - } - } - - public static String getServiceInstanceId(String requestId) throws SQLException { - init(); - - String sql = "SELECT service_instance_id FROM OUTGOING_MESSAGE WHERE request_id = '" + requestId + - "' ORDER BY sequence_number DESC"; - - CachedRowSet rs = null; - try { - rs = dbLibService.getData(sql, null, null); - if (rs.next()) { - return rs.getString("service_instance_id"); - } - } finally { - if (rs != null) { - try { - rs.close(); - } catch (Exception e) { - LOG.warn("Failed to close CachedRowSet", e); - } - } - } - return null; - } - - private static int getLastSequenceNumber(String tableName, String requestId) throws SQLException { - String sql = "SELECT sequence_number FROM " + tableName + " WHERE request_id = '" + requestId + - "' ORDER BY sequence_number DESC"; - - CachedRowSet rs = null; - try { - rs = dbLibService.getData(sql, null, null); - if (rs.next()) { - return rs.getInt("sequence_number"); - } - } finally { - if (rs != null) { - try { - rs.close(); - } catch (Exception e) { - LOG.warn("Failed to close CachedRowSet", e); - } - } - } - return 0; - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/MetricLogger.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/MetricLogger.java deleted file mode 100644 index 14b1f008b..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/MetricLogger.java +++ /dev/null @@ -1,301 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.openecomp.sdnc.sli; - -import java.net.InetAddress; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -/** - * @author dt5972 - * - */ -public class MetricLogger { - - private static final Logger KARAF = LoggerFactory.getLogger(MetricLogger.class); - private static final Logger METRIC = LoggerFactory.getLogger("org.openecomp.sdnc.filters.metric"); - - public static final String BEGIN_TIMESTAMP = "X-ECOMP-BeginTimestamp"; - public static final String END_TIMESTAMP = "X-ECOMP-EndTimestamp"; - public static final String REQUEST_ID = "X-ECOMP-RequestID"; - public static final String SERVICE_INSTANCE_ID = "X-ECOMP-ServiceInstanceID"; - public static final String SERVICE_NAME = "X-ECOMP-ServiceName"; - public static final String PARTNER_NAME = "X-ECOMP-PartnerName"; - public static final String TARGET_ENTITY = "X-ECOMP-TargetEntity"; - public static final String TARGET_SERVICE_NAME = "X-ECOMP-TargetServiceName"; - public static final String STATUS_CODE = "X-ECOMP-StatusCode"; - public static final String RESPONSE_CODE = "X-ECOMP-ResponseCode"; - public static final String RESPONSE_DESCRIPTION = "X-ECOMP-ResponseDescription"; - public static final String INSTANCE_UUID = "X-ECOMP-InstanceUUID"; - public static final String CATEGORY_LOG_LEVEL = "X-ECOMP-CategoryLogLevel"; - public static final String SEVERITY = "X-ECOMP-Severity"; - public static final String SERVER_IP_ADDRESS = "X-ECOMP-ServerIpAddress"; - public static final String ELAPSED_TIME = "X-ECOMP-ElapsedTime"; - public static final String SERVER = "X-ECOMP-Server"; - public static final String CLIENT_IP = "X-ECOMP-ClientIp"; - public static final String CLASS_NAME = "X-ECOMP-ClassName"; - public static final String TARGET_VIRTUAL_ENTITY = "X-ECOMP-TargetVirtualEntity"; - - private long beginTimestamp; - private String lastMsg = null; - - public MetricLogger() { - beginTimestamp = System.currentTimeMillis(); - - try { - InetAddress localhost = InetAddress.getLocalHost(); - setServerIpAddress(localhost.getHostAddress()); - setServer(localhost.getCanonicalHostName()); - } catch (Exception e) { - KARAF.error("Could not get localhost", e); - } - - } - - - public String getBeginTimestamp() { - return MDC.get(BEGIN_TIMESTAMP); - } - - private void setBeginTimestamp(long beginTimestamp) { - this.beginTimestamp = beginTimestamp; - MDC.put(BEGIN_TIMESTAMP, MetricLogger.asIso8601(beginTimestamp)); - } - - public String getEndTimestamp() { - return MDC.get(END_TIMESTAMP); - } - - private void setEndTimestamp(long endTimestamp) { - // Set MDC with formatted time stamp - MDC.put(END_TIMESTAMP, MetricLogger.asIso8601(endTimestamp)); - - // Set elapsed time - setElapsedTime(endTimestamp - beginTimestamp); - - } - - public String getRequestID() { - return MDC.get(REQUEST_ID); - } - - - public String getServiceInstanceID() { - return MDC.get(SERVICE_INSTANCE_ID); - } - - private void setServiceInstanceID(String svcInstanceId) { - MDC.put(SERVICE_INSTANCE_ID, svcInstanceId); - } - - public String getServiceName() { - return MDC.get(SERVICE_NAME); - } - - private void setServiceName(String svcName) { - MDC.put(SERVICE_NAME, svcName); - } - - public String getPartnerName() { - return MDC.get(PARTNER_NAME); - } - - private void setPartnerName(String partnerName) { - MDC.put(PARTNER_NAME, partnerName); - } - - public String getTargetEntity() { - return MDC.get(TARGET_ENTITY); - } - - private void setTargetEntity(String targetEntity) { - MDC.put(TARGET_ENTITY, targetEntity); - } - - public String getTargetServiceName() { - return MDC.get(TARGET_SERVICE_NAME); - } - - private void setTargetServiceName(String targetServiceName) { - MDC.put(TARGET_SERVICE_NAME, targetServiceName); - } - - public String getStatusCode() { - return MDC.get(STATUS_CODE); - } - - private void setStatusCode(String statusCode) { - MDC.put(STATUS_CODE, statusCode); - } - - public String getResponseCode() { - return MDC.get(RESPONSE_CODE); - } - - private void setResponseCode(String responseCode) { - MDC.put(RESPONSE_CODE, responseCode); - } - - public String getResponseDescription() { - return MDC.get(RESPONSE_DESCRIPTION); - } - - private void setResponseDescription(String responseDesc) { - MDC.put(RESPONSE_DESCRIPTION, responseDesc); - } - - public String getInstanceUUID() { - return MDC.get(INSTANCE_UUID); - } - - private void setInstanceUUID(String instanceUUID) { - MDC.put(INSTANCE_UUID, instanceUUID); - } - - public String getCategoryLogLevel() { - return MDC.get(CATEGORY_LOG_LEVEL); - } - - private void setCategoryLogLevel(String categoryLogLevel) { - MDC.put(CATEGORY_LOG_LEVEL, categoryLogLevel); - } - - public String getSeverity() { - return MDC.get(SEVERITY); - } - - private void setSeverity(String severity) { - MDC.put(SEVERITY, severity); - } - - public String getServerIpAddress() { - return MDC.get(SERVER_IP_ADDRESS); - } - - private void setServerIpAddress(String serverIpAddress) { - MDC.put(SERVER_IP_ADDRESS, serverIpAddress); - } - - public String getElapsedTime() { - return MDC.get(ELAPSED_TIME); - } - - private void setElapsedTime(long elapsedTime) { - MDC.put(ELAPSED_TIME, ""+elapsedTime); - } - - public String getServer() { - return MDC.get(SERVER); - } - - private void setServer(String server) { - MDC.put(SERVER, server); - } - - public String getClientIp() { - return MDC.get(CLIENT_IP); - } - - private void setClientIp(String clientIp) { - MDC.put(CLIENT_IP, clientIp); - } - - public String getClassName() { - return MDC.get(CLASS_NAME); - } - - private void setClassName(String className) { - MDC.put(CLASS_NAME, className); - } - - public String getTargetVirtualEntity() { - return MDC.get(TARGET_VIRTUAL_ENTITY); - } - - private void setTargetVirtualEntity(String targetVirtualEntity) { - MDC.put(TARGET_VIRTUAL_ENTITY, targetVirtualEntity); - } - - public static String asIso8601(Date date) { - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat df = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss:SS'+00:00'"); - df.setTimeZone(tz); - return df.format(date); - } - - public static String asIso8601(long tsInMillis) { - return MetricLogger.asIso8601(new Date(tsInMillis)); - } - - public void logRequest(String svcInstanceId, String svcName, String partnerName, String targetEntity, String targetServiceName, String targetVirtualEntity, String msg) { - - setBeginTimestamp(System.currentTimeMillis()); - - if (svcInstanceId != null) { - setServiceInstanceID(svcInstanceId); - } - - if (svcName != null) { - setServiceName(svcName); - } - - if (partnerName != null) { - setPartnerName(partnerName); - } - - if (targetEntity != null) { - setTargetEntity(targetEntity); - } - - if (targetServiceName != null) { - setTargetServiceName(targetServiceName); - } - - if (targetVirtualEntity != null) { - setTargetVirtualEntity(targetVirtualEntity); - } - - this.lastMsg = msg; - - - } - - public void logResponse(String statusCode, String responseCode, String responseDescription) { - setEndTimestamp(System.currentTimeMillis()); - - setStatusCode(statusCode); - setResponseCode(responseCode); - setResponseDescription(responseDescription); - - METRIC.info(lastMsg); - - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAdaptor.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAdaptor.java deleted file mode 100644 index b4d62ab48..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAdaptor.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.Map; - -public interface SvcLogicAdaptor { - - public enum ConfigStatus { - SUCCESS, - ALREADY_ACTIVE, - NOT_FOUND, - NOT_READY, - FAILURE - } - - public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx); - - public ConfigStatus activate(String key, SvcLogicContext ctx); - - public ConfigStatus deactivate(String key, SvcLogicContext ctx); - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAtom.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAtom.java deleted file mode 100644 index 9ac648933..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicAtom.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - -public class SvcLogicAtom extends SvcLogicExpression { - - public enum AtomType { - NUMBER, - STRING, - IDENTIFIER, - CONTEXT_VAR - - } - - private AtomType atomType; - private String atom; - - - public SvcLogicAtom(String atomType, String atom) - { - this.atomType = AtomType.valueOf(atomType); - this.atom = atom; - - } - - public SvcLogicAtom(String atom) - { - - if (atom == null) - { - this.atomType = null; - this.atom = null; - } - else - { - if (atom.startsWith("$")) - { - this.atomType = AtomType.CONTEXT_VAR; - this.atom = atom.substring(1); - } - else - { - if (Character.isDigit(atom.charAt(0))) - { - this.atomType = AtomType.NUMBER; - this.atom = atom; - } - else if (atom.charAt(0) == '\'') - { - this.atomType = AtomType.STRING; - this.atom = atom.substring(1, atom.length()-1); - } - else - { - this.atomType = AtomType.IDENTIFIER; - this.atom = atom; - - } - - } - } - } - - public AtomType getAtomType() { - return atomType; - } - - public void setAtomType(String newType) - { - atomType = AtomType.valueOf(newType); - } - - public String getAtom() { - return atom; - } - - - - public void setAtomType(AtomType atomType) { - this.atomType = atomType; - } - - public void setAtom(String atom) { - this.atom = atom; - } - - - - public String toString() - { - StringBuffer sbuff = new StringBuffer(); - switch(getAtomType()) - { - case CONTEXT_VAR: - sbuff.append("$"); - case IDENTIFIER: - boolean needDot = false; - for (SvcLogicExpression term: this.getOperands()) - { - if (needDot) - { - sbuff.append("."); - } - sbuff.append(term.toString()); - needDot = true; - } - return(sbuff.toString()); - case STRING: - case NUMBER: - default: - return(atom); - } - } - - public String asParsedExpr() - { - // simplify debugging output for NUMBER type - if (atomType == AtomType.NUMBER) { - return atom; - } - - StringBuffer sbuff = new StringBuffer(); - - sbuff.append("(atom"); - sbuff.append("<"); - sbuff.append(atomType.toString()); - sbuff.append(">"); - - switch(atomType) - { - case IDENTIFIER: - case CONTEXT_VAR: - for (SvcLogicExpression term : getOperands()) - { - sbuff.append(" "); - sbuff.append(term.asParsedExpr()); - - } - break; - default: - sbuff.append(" "); - sbuff.append(atom); - } - - sbuff.append(")"); - return(sbuff.toString()); - } - - - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicBinaryExpression.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicBinaryExpression.java deleted file mode 100644 index 1d780d7e7..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicBinaryExpression.java +++ /dev/null @@ -1,149 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.LinkedList; -import java.util.List; - -public class SvcLogicBinaryExpression extends SvcLogicExpression { - - - public enum OperatorType { - addOp("+"), - subOp("-"), - multOp("*"), - divOp("/"), - equalOp("=="), - ltOp("<"), - leOp("<="), - gtOp(">"), - geOp(">="), - neOp("!="), - andOp("and"), - orOp("or"); - - private String text; - - private OperatorType(String text) - { - this.text = text; - } - - public String getText() - { - return(text); - } - - public static OperatorType fromString(String text) - { - if (text != null) - { - for (OperatorType t : OperatorType.values()) - { - if (text.equalsIgnoreCase(t.getText())) { - - return(t); - } - } - } - return(null); - } - - public String toString() - { - return(text); - } - } - private List operators; - - public List getOperators() { - return operators; - } - - public SvcLogicBinaryExpression() - { - operators = new LinkedList(); - } - - public void addOperator(String operator) - { - operators.add(OperatorType.fromString(operator)); - } - - - public String toString() - { - - Listoperands = getOperands(); - StringBuffer sbuff = new StringBuffer(); - - sbuff.append(operands.get(0).toString()); - for (int i = 0 ; i < operators.size(); i++) - { - sbuff.append(" "); - sbuff.append(operators.get(i)); - sbuff.append(" "); - if (i + 1 < operands.size()) { - sbuff.append(operands.get(i + 1).toString()); - } else { - // expression incomplete; operand not bound yet - sbuff.append("?"); - } - } - - return(sbuff.toString()); - - } - - public String asParsedExpr() { - - List operands = getOperands(); - - if (operators.isEmpty()) { - return operands.get(0).asParsedExpr(); - } else { - StringBuffer sbuff = new StringBuffer(); - // operators in reverse order for left associativity - for (int i = operators.size() - 1; i >= 0; --i) { - sbuff.append("("); - sbuff.append(operators.get(i).getText()); - sbuff.append(" "); - } - for (int i = 0; i < operators.size() + 1; ++i) { - if (i < operands.size()) { - sbuff.append(operands.get(i).asParsedExpr()); - } else { - // expression incomplete; operand not bound yet - sbuff.append("?"); - } - if (i != 0) { - sbuff.append(")"); - } - if (i < operators.size()) { - sbuff.append(" "); - } - } - return sbuff.toString(); - } - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicContext.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicContext.java deleted file mode 100644 index 79082af29..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicContext.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; - - -public class SvcLogicContext { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicContext.class); - - private HashMap attributes; - - private DOMDataBroker domDataBroker; - - private String status = "success"; - - public SvcLogicContext() - { - this.attributes = new HashMap (); - - } - - public SvcLogicContext(Properties props) - { - this.attributes = new HashMap (); - - if (props.containsKey("SvcLogic.status")) - { - this.status = props.getProperty("SvcLogic.status"); - } - - for (Object nameObj : props.keySet()) - { - String propName = (String) nameObj; - attributes.put(propName, props.getProperty(propName)); - } - } - - - - public DOMDataBroker getDomDataBroker() { - return domDataBroker; - } - - public void setDomDataBroker(DOMDataBroker domDataBroker) { - this.domDataBroker = domDataBroker; - } - - public String getAttribute(String name) - { - if (attributes.containsKey(name)) - { - return(attributes.get(name)); - } - else - { - return(null); - } - } - - public void setAttribute(String name, String value) - { - if (value == null) { - if (attributes.containsKey(name)) { - attributes.remove(name); - } - } else { - attributes.put(name, value); - } - } - - public Set getAttributeKeySet() - { - return(attributes.keySet()); - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public Properties toProperties() - { - Properties props = new Properties(); - - if (status != null) - { - props.setProperty("SvcLogic.status", status); - } - - for (String attrName : attributes.keySet()) - { - String attrVal = attributes.get(attrName); - if (attrVal == null) { - LOG.warn("attribute " + attrName - + "null - setting to empty string"); - props.setProperty(attrName, ""); - } else { - props.setProperty(attrName, attributes.get(attrName)); - } - } - - return(props); - } - - public void mergeDocument(String pfx, Document doc) { - String prefix = ""; - - if (pfx != null) { - prefix = pfx; - } - - Element root = doc.getDocumentElement(); - - mergeElement(prefix, root, null); - } - - public void mergeElement(String pfx, Element element, Map nodeMap) { - - // In XML, cannot tell the difference between containers and lists. - // So, have to treat each element as both (ugly but necessary). - // We do this by passing a nodeMap to be used to count instance of each tag, - // which will be used to set _length and to set index - - LOG.trace("mergeElement("+pfx+","+element.getTagName()+","+nodeMap+")"); - - String curTagName = element.getTagName(); - String prefix = curTagName; - - if (pfx != null) { - prefix = pfx + "." + prefix; - } - - int myIdx = 0; - - if (nodeMap != null) { - if (nodeMap.containsKey(curTagName)) { - myIdx = nodeMap.get(curTagName).intValue(); - } - - nodeMap.put(curTagName, new Integer(myIdx+1)); - this.setAttribute(prefix+"_length", ""+(myIdx+1)); - } - - NodeList children = element.getChildNodes(); - - int numChildren = children.getLength(); - - Map childMap = new HashMap(); - Map idxChildMap = new HashMap(); - - for (int i = 0 ; i < numChildren ; i++) { - Node curNode = children.item(i); - - if (curNode instanceof Text) { - Text curText = (Text) curNode; - String curTextValue = curText.getTextContent(); - LOG.trace("Setting ctx variable "+prefix+" = "+curTextValue); - this.setAttribute(prefix, curText.getTextContent()); - - - } else if (curNode instanceof Element) { - mergeElement(prefix, (Element) curNode, childMap); - if (nodeMap != null) { - - mergeElement(prefix+"["+myIdx+"]", (Element)curNode, idxChildMap); - - } - } - } - - } - - public String resolve(String ctxVarName) { - - if (ctxVarName.indexOf('[') == -1) { - // Ctx variable contains no arrays - return (this.getAttribute(ctxVarName)); - } - - // Resolve any array references - StringBuffer sbuff = new StringBuffer(); - String[] ctxVarParts = ctxVarName.split("\\["); - sbuff.append(ctxVarParts[0]); - for (int i = 1; i < ctxVarParts.length; i++) { - if (ctxVarParts[i].startsWith("$")) { - int endBracketLoc = ctxVarParts[i].indexOf("]"); - if (endBracketLoc == -1) { - // Missing end bracket ... give up parsing - LOG.warn("Variable reference " + ctxVarName - + " seems to be missing a ']'"); - return (this.getAttribute(ctxVarName)); - } - - String idxVarName = ctxVarParts[i].substring(1, endBracketLoc); - String remainder = ctxVarParts[i].substring(endBracketLoc); - - sbuff.append("["); - sbuff.append(this.getAttribute(idxVarName)); - sbuff.append(remainder); - - } else { - // Index is not a variable reference - sbuff.append("["); - sbuff.append(ctxVarParts[i]); - } - } - - return (this.getAttribute(sbuff.toString())); - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicDblibStore.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicDblibStore.java deleted file mode 100644 index d494eaab2..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicDblibStore.java +++ /dev/null @@ -1,533 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Properties; - -import javax.sql.rowset.CachedRowSet; - -import org.openecomp.sdnc.sli.resource.dblib.DBResourceManager; -import org.openecomp.sdnc.sli.resource.dblib.DbLibService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SvcLogicDblibStore implements SvcLogicStore { - - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicDblibStore.class); - - private static final String DBLIB_SERVICE = - // "org.openecomp.sdnc.sli.resource.dblib.DBLibService"; - "org.openecomp.sdnc.sli.resource.dblib.DBResourceManager"; - - Properties props = null; - - public void init(Properties props) throws ConfigurationException { - - DbLibService dbSvc = getDbLibService(); - if(dbSvc == null) { - LOG.error("SvcLogic cannot acquire DBLIB_SERVICE"); - return; - } - try { - dbSvc.getData("select 1 from DUAL", new ArrayList(), null); - LOG.debug("SQL test was successful"); - } catch (SQLException e) { - LOG.error("Failed SQL test", e); - } - } - - public boolean hasGraph(String module, String rpc, String version, - String mode) throws SvcLogicException { - - DbLibService dbSvc = getDbLibService(); - - boolean retval = false; - CachedRowSet results = null; - String hasVersionGraphSql = "SELECT count(*) FROM SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; - - String hasActiveGraphSql = "SELECT count(*) FROM SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; - - PreparedStatement hasGraphStmt = null; - - ArrayList args = new ArrayList(); - args.add(module); - args.add(rpc); - args.add(mode); - - try { - - if (version == null) { - results = dbSvc.getData(hasActiveGraphSql, args, null); - } else { - args.add(version); - results = dbSvc.getData(hasVersionGraphSql, args, null); - } - - if (results.next()) { - int cnt = results.getInt(1); - - if (cnt > 0) { - retval = true; - } - - } - } catch (Exception e) { - throw new ConfigurationException("SQL query failed", e); - } finally { - if (results != null) { - try { - - results.close(); - } catch (SQLException x) { - } - } - - } - - return (retval); - - } - - public SvcLogicGraph fetch(String module, String rpc, String version, - String mode) throws SvcLogicException { - - DbLibService dbSvc = getDbLibService(); - - Connection dbConn = null; - SvcLogicGraph retval = null; - ResultSet results = null; - - String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; - - String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; - - - try { - dbConn = ((DBResourceManager) dbSvc).getConnection(); - PreparedStatement fetchGraphStmt; - - ArrayList args = new ArrayList(); - args.add(module); - args.add(rpc); - args.add(mode); - - if (version == null) { - fetchGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql); - } else { - fetchGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql); - } - - fetchGraphStmt.setString(1, module); - fetchGraphStmt.setString(2, rpc); - fetchGraphStmt.setString(3, mode); - if (version != null) { - fetchGraphStmt.setString(4,version); - } - - results = fetchGraphStmt.executeQuery(); - - if (results.next()) { - Blob graphBlob = results.getBlob("graph"); - - ObjectInputStream gStream = new ObjectInputStream( - graphBlob.getBinaryStream()); - - Object graphObj = gStream.readObject(); - gStream.close(); - - if (graphObj instanceof SvcLogicGraph) { - retval = (SvcLogicGraph) graphObj; - } else { - throw new ConfigurationException("invalid type for graph (" - + graphObj.getClass().getName()); - - } - - } else { - return (null); - } - } catch (SQLException e) { - throw new ConfigurationException("SQL query failed", e); - } catch (Exception e) { - throw new ConfigurationException("Graph processing failed", e); - } finally { - if (results != null) { - try { - results.close(); - } catch (SQLException x) { - } - } - try { - if (dbConn != null && !dbConn.isClosed()) { - dbConn.close(); - } - } catch (Throwable exc) { - // the exception not monitored - } finally { - dbConn = null; - } - - } - - return (retval); - - } - - public void store(SvcLogicGraph graph) throws SvcLogicException { - - DbLibService dbSvc = getDbLibService(); - - String storeGraphSql = "INSERT INTO SVC_LOGIC (module, rpc, version, mode, active, graph)" - + " VALUES(?, ?, ?, ?, ?, ?)"; - - if (graph == null) { - throw new SvcLogicException("graph cannot be null"); - } - - byte[] graphBytes = null; - - ByteArrayOutputStream byteStr = null; - ObjectOutputStream goutStr = null; - - try { - byteStr = new ByteArrayOutputStream(); - goutStr = new ObjectOutputStream(byteStr); - goutStr.writeObject(graph); - - graphBytes = byteStr.toByteArray(); - - } catch (Exception e) { - throw new SvcLogicException("could not serialize graph", e); - } finally { - - if (goutStr != null) { - try { - goutStr.close(); - } catch (IOException e) { - - } - } - - if (byteStr != null) { - try { - byteStr.close(); - } catch (IOException e) { - - } - } - } - - // If object already stored in database, delete it - if (hasGraph(graph.getModule(), graph.getRpc(), graph.getVersion(), - graph.getMode())) { - delete(graph.getModule(), graph.getRpc(), graph.getVersion(), - graph.getMode()); - } - - Connection dbConn = null; - - try { - dbConn = ((DBResourceManager) dbSvc).getConnection(); - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - PreparedStatement storeGraphStmt = dbConn - .prepareStatement(storeGraphSql); - storeGraphStmt.setString(1, graph.getModule()); - storeGraphStmt.setString(2, graph.getRpc()); - storeGraphStmt.setString(3, graph.getVersion()); - storeGraphStmt.setString(4, graph.getMode()); - storeGraphStmt.setString(5, "N"); - storeGraphStmt.setBlob(6, new ByteArrayInputStream(graphBytes)); - - storeGraphStmt.executeUpdate(); - dbConn.commit(); - - dbConn.setAutoCommit(oldAutoCommit); - } catch (Exception e) { - throw new SvcLogicException("Could not write object to database", e); - } finally { - try { - if (dbConn != null && !dbConn.isClosed()) { - dbConn.close(); - } - } catch (Throwable exc) { - // the exception not monitored - } finally { - dbConn = null; - } - - } - } - - public void delete(String module, String rpc, String version, String mode) - throws SvcLogicException { - - DbLibService dbSvc = getDbLibService(); - - String deleteGraphSql = "DELETE FROM SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; - - ArrayList args = new ArrayList(); - - args.add(module); - args.add(rpc); - args.add(version); - args.add(mode); - - try { - dbSvc.writeData(deleteGraphSql, args, null); - } catch (Exception e) { - throw new SvcLogicException( - "Could not delete object from database", e); - } - } - - public void activate(SvcLogicGraph graph) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); - - String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; - - String activateSql = "UPDATE SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; - - ArrayList args = new ArrayList(); - - args.add(graph.getModule()); - args.add(graph.getRpc()); - args.add(graph.getMode()); - - try { - - dbSvc.writeData(deactivateSql, args, null); - - args.add(graph.getVersion()); - dbSvc.writeData(activateSql, args, null); - - } catch (Exception e) { - throw new SvcLogicException("Could not activate graph", e); - } - } - - @Override - public void registerNodeType(String nodeType) throws SvcLogicException { - - String registerNodeSql = "INSERT INTO NODE_TYPES (nodetype) VALUES(?)"; - - if (isValidNodeType(nodeType)) { - return; - } - - DbLibService dbSvc = getDbLibService(); - ArrayList args = new ArrayList(); - - args.add(nodeType); - - try { - dbSvc.writeData(registerNodeSql, args, null); - } catch (Exception e) { - throw new SvcLogicException("Could not add node type to database", - e); - } - - } - - @Override - public void unregisterNodeType(String nodeType) throws SvcLogicException { - - if (!isValidNodeType(nodeType)) { - return; - } - - String unregisterNodeSql = "DELETE FROM NODE_TYPES WHERE nodetype = ?"; - - DbLibService dbSvc = getDbLibService(); - ArrayList args = new ArrayList(); - - args.add(nodeType); - - try { - dbSvc.writeData(unregisterNodeSql, args, null); - } catch (Exception e) { - throw new SvcLogicException( - "Could not delete node type from database", e); - } - - } - - @Override - public boolean isValidNodeType(String nodeType) throws SvcLogicException { - - String validateNodeSql = "SELECT count(*) FROM NODE_TYPES WHERE nodetype = ?"; - - DbLibService dbSvc = getDbLibService(); - - ArrayList args = new ArrayList(); - - args.add(nodeType); - - boolean isValid = false; - - CachedRowSet results = null; - try { - results = dbSvc.getData(validateNodeSql, args, null); - if (results != null) { - if (results.next()) { - int cnt = results.getInt(1); - - if (cnt > 0) { - isValid = true; - } - } - } - } catch (Exception e) { - throw new SvcLogicException( - "Cannot select node type from database", e); - } finally { - if (results != null) { - try { - results.close(); - } catch (SQLException x) { - } - } - - } - - return (isValid); - } - - private DbLibService getDbLibService() { - - // Get DbLibService interface object. - DbLibService dblibSvc = null; - ServiceReference sref = null; - BundleContext bctx = null; - - Bundle bundle = FrameworkUtil.getBundle(SvcLogicDblibStore.class); - - if (bundle != null) { - bctx = bundle.getBundleContext(); - - if (bctx != null) { - sref = bctx.getServiceReference(DBLIB_SERVICE); - } - - if (sref == null) { - LOG.warn("Could not find service reference for DBLIB service (" - + DBLIB_SERVICE + ")"); - } else { - dblibSvc = (DbLibService) bctx.getService(sref); - if (dblibSvc == null) { - - LOG.warn("Could not find service reference for DBLIB service (" - + DBLIB_SERVICE + ")"); - } - } - } - - // initialize a stand-alone instance of dblib resource - else { - // Try to create a DbLibService object from dblib properties - if(JavaSingleton.getInstance() == null){ - Properties dblibProps = new Properties(); - - String propDir = System.getenv(SDNC_CONFIG_DIR); - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - String propPath = propDir + "/dblib.properties"; - - File propFile = new File(propPath); - - if (!propFile.exists()) { - - LOG.warn( - "Missing configuration properties file : " - + propFile); - return(null); - } - - try { - - dblibProps.load(new FileInputStream(propFile)); - } catch (Exception e) { - LOG.warn( - "Could not load properties file " + propPath, e); - return(null); - - } - - try { - dblibSvc = DBResourceManager.create(dblibProps); - JavaSingleton.setInstance(dblibSvc); - } catch (Exception e) { - LOG.warn("Caught exception trying to create DBResourceManager", e); - } - } else { - dblibSvc = JavaSingleton.getInstance(); - } - } - return (dblibSvc); - } - - - static class JavaSingleton { - /* Private constructor */ - private JavaSingleton() { - /* the body of the constructor here */ - } - - /* instance of the singleton declaration */ - private static volatile DbLibService INSTANCE ; - - /* Access point to the unique instance of the singleton */ - public static DbLibService getInstance() { - return INSTANCE; - } - - public static void setInstance(DbLibService dbresource) { - INSTANCE = dbresource; - } - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicException.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicException.java deleted file mode 100644 index c087b8ad8..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicException.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -public class SvcLogicException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public SvcLogicException() - { - super(); - } - - public SvcLogicException(String message) - { - super(message); - } - - public SvcLogicException(String message, Throwable t) - { - super(message, t); - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprListener.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprListener.java deleted file mode 100644 index 4fef12fbc..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprListener.java +++ /dev/null @@ -1,316 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.LinkedList; -import java.util.List; - -import org.antlr.v4.runtime.tree.TerminalNode; -import org.openecomp.sdnc.sli.ExprGrammarParser.AddExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.AtomContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.CompareExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.ConstantContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.ExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.FuncExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.MultExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.ParenExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.RelExprContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.VariableContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.VariableLeadContext; -import org.openecomp.sdnc.sli.ExprGrammarParser.VariableTermContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SvcLogicExprListener extends ExprGrammarBaseListener -{ - - - - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicExprListener.class); - - private SvcLogicExpression curExpr; - private SvcLogicExpression topExpr; - private LinkedList exprStack; - - public SvcLogicExprListener() - { - exprStack = new LinkedList(); - } - - public SvcLogicExpression getParsedExpr() - { - return(curExpr); - } - - private void pushOperand(SvcLogicExpression operand) - { - if (curExpr == null) - { - curExpr = operand; - } - else - { - curExpr.addOperand(operand); - } - } - - private void pushExpr(SvcLogicExpression expr) - { - LOG.trace("Pushing expression ["+expr.getClass().getName()+"]"); - if (curExpr != null) - { - exprStack.push(curExpr); - } - curExpr = expr; - } - - private void popExpr() - { - if (exprStack.isEmpty()) - { - LOG.trace("Popping last expression"); - topExpr = curExpr; - } - else - { - SvcLogicExpression lastExpr = curExpr; - curExpr = exprStack.pop(); - curExpr.addOperand(lastExpr); - LOG.trace("New curExpr is ["+curExpr.getClass().getName()+"]"); - } - - } - - @Override - public void enterAtom(AtomContext ctx) { - - String atomText = ctx.getText(); - - LOG.trace("enterAtom: text = "+atomText); - - - SvcLogicAtom newAtom = new SvcLogicAtom(atomText); - - pushExpr(newAtom); - } - - - @Override - public void enterMultExpr(MultExprContext ctx) { - LOG.trace("enterMultExpr: text = "+ctx.getText()); - - SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); - pushExpr(curBinExpr); - - List opList = ctx.MULTOP(); - - for (TerminalNode nd : opList) - { - LOG.trace("enterMultExpr: operator - "+nd.getText()); - curBinExpr.addOperator(nd.getText()); - } - - } - - @Override - public void exitMultExpr(MultExprContext ctx) { - - LOG.trace("exitMultExpr: text = "+ctx.getText()); - - popExpr(); - - } - - @Override - public void exitAtom(AtomContext ctx) { - LOG.trace("exitAtom: text = "+ctx.getText()); - popExpr(); - } - - @Override - public void enterAddExpr(AddExprContext ctx) { - LOG.trace("enterAddExpr: text = "+ctx.getText()); - List opList = ctx.ADDOP(); - - - SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); - pushExpr(curBinExpr); - - - for (TerminalNode nd : opList) - { - LOG.trace("enterAddExpr: operator - "+nd.getText()); - curBinExpr.addOperator(nd.getText()); - } - - } - - @Override - public void exitAddExpr(AddExprContext ctx) { - LOG.trace("exitAddExpr: text = "+ctx.getText()); - - popExpr(); - } - - @Override - public void enterFuncExpr(FuncExprContext ctx) { - LOG.trace("enterFuncExpr: text = "+ctx.getText()); - LOG.trace("enterFuncExpr - IDENTIFIER : "+ctx.IDENTIFIER().getText()); - - for (ExprContext expr: ctx.expr()) - { - LOG.trace("enterFuncExpr - expr = "+expr.getText()); - } - - - pushExpr(new SvcLogicFunctionCall(ctx.IDENTIFIER().getText())); - } - - @Override - public void exitFuncExpr(FuncExprContext ctx) { - LOG.trace("exitFuncExpr: text = "+ctx.getText()); - - popExpr(); - } - - @Override - public void enterParenExpr(ParenExprContext ctx) { - LOG.trace("enterParenExpr: text = "+ctx.getText()); - LOG.trace("enterParenExpr: expr = "+ctx.expr().getText()); - } - - @Override - public void exitParenExpr(ParenExprContext ctx) { - LOG.trace("exitParenExpr: text = "+ctx.getText()); - } - - @Override - public void enterRelExpr(RelExprContext ctx) { - LOG.trace("enterRelExpr: text = "+ctx.getText()); - - List opList = ctx.RELOP(); - - - SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); - pushExpr(curBinExpr); - - - for (TerminalNode nd : opList) - { - LOG.trace("enterRelExpr: operator - "+nd.getText()); - curBinExpr.addOperator(nd.getText()); - } - - } - - @Override - public void exitRelExpr(RelExprContext ctx) { - LOG.trace("exitRelExpr: text = "+ctx.getText()); - - popExpr(); - } - - @Override - public void enterCompareExpr(CompareExprContext ctx) { - LOG.trace("enterCompareExpr: text = "+ctx.getText()); - - TerminalNode nd = ctx.COMPAREOP(); - - SvcLogicBinaryExpression curBinExpr = new SvcLogicBinaryExpression(); - pushExpr(curBinExpr); - - LOG.trace("enterCompareExpr: operator - "+nd.getText()); - curBinExpr.addOperator(nd.getText()); - - } - - @Override - public void exitCompareExpr(CompareExprContext ctx) { - LOG.trace("exitCompareExpr : text = "+ctx.getText()); - - popExpr(); - } - - - - @Override - public void enterConstant(ConstantContext ctx) { - LOG.trace("enterConstant: text = "+ctx.getText()); - } - - @Override - public void exitConstant(ConstantContext ctx) { - LOG.trace("exitConstant: text = "+ctx.getText()); - } - - - @Override - public void enterVariable(VariableContext ctx) { - LOG.trace("enterVariable: text = "+ctx.getText()); - - - } - - @Override - public void exitVariable(VariableContext ctx) { - LOG.debug("exitVariable: text ="+ctx.getText()); - - } - - - @Override - public void enterVariableLead(VariableLeadContext ctx) { - - LOG.debug("enterVariableLead: text ="+ctx.getText()); - - - } - - @Override - public void exitVariableLead(VariableLeadContext ctx) { - - LOG.trace("exitVariableLead: text ="+ctx.getText()); - } - - @Override - public void enterVariableTerm(VariableTermContext ctx) { - LOG.trace("enterVariableTerm: text ="+ctx.getText()); - - String name = ctx.getText(); - - int subscrStart = name.indexOf("["); - if (subscrStart > -1) - { - name = name.substring(0, subscrStart); - } - SvcLogicVariableTerm vterm = new SvcLogicVariableTerm(name); - pushExpr(vterm); - } - - @Override - public void exitVariableTerm(VariableTermContext ctx) { - LOG.trace("exitVariableTerm: text="+ctx.getText()); - popExpr(); - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprParserErrorListener.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprParserErrorListener.java deleted file mode 100644 index 4c7dd22be..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExprParserErrorListener.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import org.antlr.v4.runtime.BaseErrorListener; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Recognizer; -import org.antlr.v4.runtime.misc.ParseCancellationException; - -public class SvcLogicExprParserErrorListener extends BaseErrorListener { - - private static final SvcLogicExprParserErrorListener instance = new SvcLogicExprParserErrorListener(); - - public static SvcLogicExprParserErrorListener getInstance() { - return(instance); - } - - @Override - public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, - String msg, RecognitionException e) throws ParseCancellationException { - throw new ParseCancellationException(msg); - } - - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpression.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpression.java deleted file mode 100644 index a6af82018..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpression.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - - -public abstract class SvcLogicExpression implements Serializable { - - private List operands = new LinkedList(); - - - public void addOperand(SvcLogicExpression expr) - { - operands.add(expr); - } - - public List getOperands() { - return operands; - } - - public int numOperands() - { - return(operands.size()); - } - - public abstract String asParsedExpr(); - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpressionFactory.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpressionFactory.java deleted file mode 100644 index cce8e044d..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicExpressionFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.antlr.v4.runtime.ANTLRInputStream; -import org.antlr.v4.runtime.CharStream; -import org.antlr.v4.runtime.CommonTokenStream; -import org.antlr.v4.runtime.tree.ParseTreeWalker; -import org.openecomp.sdnc.sli.ExprGrammarParser.ExprContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class SvcLogicExpressionFactory { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicExpressionFactory.class); - - - public static SvcLogicExpression parse(String exprStr) throws IOException - { - LOG.trace("parse("+exprStr+")"); - InputStream exprStream = new ByteArrayInputStream(exprStr.getBytes()); - CharStream input = new ANTLRInputStream(exprStream); - ExprGrammarLexer lexer = new ExprGrammarLexer(input); - CommonTokenStream tokens = new CommonTokenStream(lexer); - ExprGrammarParser parser = new ExprGrammarParser(tokens); - - lexer.removeErrorListeners(); - lexer.addErrorListener(SvcLogicExprParserErrorListener.getInstance()); - parser.removeErrorListeners(); - parser.addErrorListener(SvcLogicExprParserErrorListener.getInstance()); - - ExprContext expression = null; - - try { - expression = parser.expr(); - } catch (Exception e) { - String errorMsg = e.getMessage(); - - LOG.error(errorMsg); - throw new SvcLogicParserException(errorMsg); - } - - - ParseTreeWalker walker = new ParseTreeWalker(); - SvcLogicExprListener listener = new SvcLogicExprListener(); - walker.walk(listener, expression); - - - return(listener.getParsedExpr()); - } - - public static void main(String argv[]) { - - - System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "debug"); - - StringBuffer sbuff = new StringBuffer(); - - for (int i = 0 ; i < argv.length ; i++) - { - if (sbuff.length() > 0) - { - sbuff.append(" "); - } - sbuff.append(argv[i]); - } - - try { - SvcLogicExpressionFactory.parse(sbuff.toString()); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicFunctionCall.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicFunctionCall.java deleted file mode 100644 index a98cf6b22..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicFunctionCall.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -public class SvcLogicFunctionCall extends SvcLogicExpression { - - private String functionName; - - public SvcLogicFunctionCall(String functionName) - { - this.functionName = functionName; - } - - public String getFunctionName() { - return functionName; - } - - public void setFunctionName(String functionName) { - this.functionName = functionName; - } - - public String toString() - { - StringBuffer sbuff = new StringBuffer(); - - sbuff.append(functionName); - sbuff.append("("); - boolean needComma = false; - for (SvcLogicExpression operand: getOperands()) - { - if (needComma) - { - sbuff.append(","); - } - else - { - needComma = true; - } - sbuff.append(operand.toString()); - - } - sbuff.append(")"); - return(sbuff.toString()); - } - - public String asParsedExpr() - { - StringBuffer sbuff = new StringBuffer(); - - sbuff.append("("); - sbuff.append(functionName); - for (SvcLogicExpression operand: getOperands()) - { - sbuff.append(" "); - sbuff.append(operand.asParsedExpr()); - } - sbuff.append(")"); - return(sbuff.toString()); - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicGraph.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicGraph.java deleted file mode 100644 index d3d6d9504..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicGraph.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.PrintStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -public class SvcLogicGraph implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - private String module = null; - private String rpc = null; - private String mode = null; - private String version = null; - - private Map attributes; - private Map namedNodes; - private SvcLogicNode rootNode; - - public SvcLogicGraph() - { - attributes = new HashMap(); - namedNodes = new HashMap(); - rootNode = null; - } - - - public String getModule() { - return module; - } - - - public void setModule(String module) { - this.module = module; - } - - - public String getRpc() { - return rpc; - } - - - public void setRpc(String rpc) { - this.rpc = rpc; - } - - - - - public String getMode() { - return mode; - } - - - public void setMode(String mode) { - this.mode = mode; - } - - - public String getVersion() { - return version; - } - - - public void setVersion(String version) { - this.version = version; - } - - - public void setRootNode(SvcLogicNode rootNode) - { - this.rootNode = rootNode; - } - - public SvcLogicNode getRootNode() - { - return(rootNode); - } - - public Serializable getAttribute(String name) - { - if (attributes.containsKey(name)) - { - return(attributes.get(name)); - } - else - { - return(null); - } - - } - - public void setAttribute(String name, Serializable value) throws DuplicateValueException - { - if (attributes.containsKey(name)) - { - throw new DuplicateValueException("Duplicate attribute "+name); - } - - attributes.put(name, value); - } - - public SvcLogicNode getNamedNode(String nodeName) - { - if (namedNodes.containsKey(nodeName)) - { - return(namedNodes.get(nodeName)); - } - else - { - return(null); - } - } - - public void setNamedNode(String nodeName, SvcLogicNode node) throws DuplicateValueException - { - if (namedNodes.containsKey(nodeName)) - { - throw new DuplicateValueException("Duplicate node name "+nodeName); - } - - namedNodes.put(nodeName, node); - } - - - - public void printAsGv(PrintStream pstr) - { - pstr.println("digraph g {"); - pstr.println("START [label=\"START\\n"+module+":"+rpc+"\"];"); - - if (rootNode != null) - { - pstr.println("START -> node"+rootNode.getNodeId()+";"); - rootNode.setVisited(false, true); - rootNode.printAsGv(pstr); - } - pstr.println("}"); - } - - public void printAsXml(PrintStream pstr) - { - pstr.println(""); - pstr.println(" "); - if (rootNode != null) - { - rootNode.setVisited(false, true); - rootNode.printAsXml(pstr, 2); - } - pstr.println(" "); - pstr.println(""); - } - - @Override - public String toString() { - return "SvcLogicGraph [module=" + module + ", rpc=" + rpc + ", mode=" + mode + ", version=" + version + "]"; - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJavaPlugin.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJavaPlugin.java deleted file mode 100644 index ac14cacc1..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJavaPlugin.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.Map; - -public interface SvcLogicJavaPlugin { - - /** - * A marker interface, used to indicate that a class exposes methods that can be - * called from an node. Such methods must have the signature: - * void methodName(Map, SvcLogicContext) - */ - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJdbcStore.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJdbcStore.java deleted file mode 100644 index b9e7f80ec..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicJdbcStore.java +++ /dev/null @@ -1,895 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class SvcLogicJdbcStore implements SvcLogicStore { - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicJdbcStore.class); - - private String dbUrl = null; - private String dbName = null; - private String dbUser = null; - private String dbPasswd = null; - private String dbDriver = null; - - private Connection dbConn; - private PreparedStatement hasActiveGraphStmt = null; - private PreparedStatement hasVersionGraphStmt = null; - private PreparedStatement fetchActiveGraphStmt = null; - private PreparedStatement fetchVersionGraphStmt = null; - private PreparedStatement storeGraphStmt = null; - private PreparedStatement deleteGraphStmt = null; - - private PreparedStatement deactivateStmt = null; - private PreparedStatement activateStmt = null; - - private PreparedStatement registerNodeStmt = null; - private PreparedStatement unregisterNodeStmt = null; - private PreparedStatement validateNodeStmt = null; - - private void getConnection() throws ConfigurationException - { - - Properties jdbcProps = new Properties(); - - jdbcProps.setProperty("user", dbUser); - jdbcProps.setProperty("password", dbPasswd); - - try { - Driver dvr = new com.mysql.jdbc.Driver(); - if (dvr.acceptsURL(dbUrl)) - { - LOG.debug("Driver com.mysql.jdbc.Driver accepts "+dbUrl); - } - else - { - LOG.warn("Driver com.mysql.jdbc.Driver does not accept "+dbUrl); - } - } catch (SQLException e1) { - LOG.error("Caught exception trying to load com.mysql.jdbc.Driver", e1); - - - } - - - try - { - this.dbConn = DriverManager.getConnection(dbUrl, jdbcProps); - } - catch (Exception e) - { - throw new ConfigurationException("failed to get database connection ["+dbUrl+"]", e); - } - - } - - private void createTable() throws ConfigurationException - { - - - DatabaseMetaData dbm = null; - - - try { - dbm = dbConn.getMetaData(); - } catch (SQLException e) { - - throw new ConfigurationException("could not get databse metadata", e); - } - - // See if table SVC_LOGIC exists. If not, create it. - try - { - - - ResultSet tables = dbm.getTables(null, null, "SVC_LOGIC", null); - if (tables.next()) { - // Table exists - } - else { - - String crTableCmd = "CREATE TABLE "+dbName+".SVC_LOGIC (" - + "module varchar(80) NOT NULL," - + "rpc varchar(80) NOT NULL," - + "version varchar(40) NOT NULL," - + "mode varchar(5) NOT NULL," - + "active varchar(1) NOT NULL," - + "graph BLOB," - + "CONSTRAINT P_SVC_LOGIC PRIMARY KEY(module, rpc, version, mode))"; - - Statement stmt = null; - ConfigurationException myExc = null; - try - { - stmt = dbConn.createStatement(); - stmt.executeUpdate(crTableCmd); - } - catch (SQLException e1) - { - myExc = new ConfigurationException("cannot create SVC_LOGIC table", e1); - } - finally - { - if (stmt != null) - { - stmt.close(); - } - } - - if (myExc != null) - { - throw myExc; - } - } - } - catch (Exception e) - { - throw new ConfigurationException("could not create SVC_LOGIC table", e); - } - - // See if NODE_TYPES table exists and, if not, create it - - try - { - - - ResultSet tables = dbm.getTables(null, null, "NODE_TYPES", null); - if (tables.next()) { - // Table exists - } - else { - - String crTableCmd = "CREATE TABLE "+dbName+".NODE_TYPES (" - + "nodetype varchar(80) NOT NULL," - + "CONSTRAINT P_NODE_TYPES PRIMARY KEY(nodetype))"; - - Statement stmt = null; - ConfigurationException myExc = null; - try - { - stmt = dbConn.createStatement(); - stmt.executeUpdate(crTableCmd); - } - catch (SQLException e1) - { - myExc = new ConfigurationException("cannot create SVC_LOGIC table", e1); - } - finally - { - if (stmt != null) - { - stmt.close(); - } - } - - if (myExc != null) - { - throw myExc; - } - } - } - catch (Exception e) - { - throw new ConfigurationException("could not create SVC_LOGIC table", e); - } - } - - private void prepStatements() throws ConfigurationException - { - - // Prepare statements - String hasVersionGraphSql = "SELECT count(*) FROM "+dbName+".SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; - - try - { - hasVersionGraphStmt = dbConn.prepareStatement(hasVersionGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+hasVersionGraphSql, e); - - } - - String hasActiveGraphSql = "SELECT count(*) FROM "+dbName+".SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; - - try - { - hasActiveGraphStmt = dbConn.prepareStatement(hasActiveGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+hasVersionGraphSql, e); - - } - - String fetchVersionGraphSql = "SELECT graph FROM "+dbName+".SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; - - try - { - fetchVersionGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+fetchVersionGraphSql, e); - - } - - String fetchActiveGraphSql = "SELECT graph FROM "+dbName+".SVC_LOGIC" - + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'"; - - try - { - fetchActiveGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+fetchVersionGraphSql, e); - - } - - String storeGraphSql = "INSERT INTO "+dbName+".SVC_LOGIC (module, rpc, version, mode, active, graph)" - + " VALUES(?, ?, ?, ?, ?, ?)"; - - try - { - storeGraphStmt = dbConn.prepareStatement(storeGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+storeGraphSql, e); - } - - String deleteGraphSql = "DELETE FROM "+dbName+".SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; - - try - { - deleteGraphStmt = dbConn.prepareStatement(deleteGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+deleteGraphSql, e); - } - - String deactivateSql = "UPDATE "+dbName+".SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; - - try - { - deactivateStmt = dbConn.prepareStatement(deactivateSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+deactivateSql, e); - } - - String activateSql = "UPDATE "+dbName+".SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; - - try - { - activateStmt = dbConn.prepareStatement(activateSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+activateSql, e); - } - - String registerNodeSql = "INSERT INTO "+dbName+".NODE_TYPES (nodetype) VALUES(?)"; - try - { - registerNodeStmt = dbConn.prepareStatement(registerNodeSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+registerNodeSql, e); - } - - String unregisterNodeSql = "DELETE FROM "+dbName+".NODE_TYPES WHERE nodetype = ?"; - try - { - unregisterNodeStmt = dbConn.prepareStatement(unregisterNodeSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+unregisterNodeSql, e); - } - - String validateNodeSql = "SELECT count(*) FROM "+dbName+".NODE_TYPES WHERE nodetype = ?"; - try - { - validateNodeStmt = dbConn.prepareStatement(validateNodeSql); - } - catch (Exception e) - { - throw new ConfigurationException("could not prepare statement "+validateNodeSql, e); - } - } - - private void initDbResources() throws ConfigurationException - { - if ((dbDriver != null) && (dbDriver.length() > 0)) - { - - try - { - Class.forName(dbDriver); - } - catch (Exception e) - { - throw new ConfigurationException("could not load driver class "+dbDriver, e); - } - } - getConnection(); - createTable(); - prepStatements(); - } - - - public void init(Properties props) throws ConfigurationException { - - - dbUrl = props.getProperty("org.openecomp.sdnc.sli.jdbc.url"); - if ((dbUrl == null) || (dbUrl.length() == 0)) - { - throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.url unset"); - } - - dbName = props.getProperty("org.openecomp.sdnc.sli.jdbc.database"); - if ((dbName == null) || (dbName.length() == 0)) - { - throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.database unset"); - } - - dbUser = props.getProperty("org.openecomp.sdnc.sli.jdbc.user"); - if ((dbUser == null) || (dbUser.length() == 0)) - { - throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.user unset"); - } - - - dbPasswd = props.getProperty("org.openecomp.sdnc.sli.jdbc.password"); - if ((dbPasswd == null) || (dbPasswd.length() == 0)) - { - throw new ConfigurationException("property org.openecomp.sdnc.sli.jdbc.password unset"); - } - - dbDriver = props.getProperty("org.openecomp.sdnc.sli.jdbc.driver"); - - - initDbResources(); - - } - - private boolean isDbConnValid() - { - - boolean isValid = false; - - try - { - if (dbConn != null) - { - isValid = dbConn.isValid(1); - } - } - catch (SQLException e) - {} - - return(isValid); - } -public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { - - - - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - - - boolean retval = false; - ResultSet results = null; - - PreparedStatement hasGraphStmt = null; - if (version == null) - { - hasGraphStmt = hasActiveGraphStmt; - } - else - { - hasGraphStmt = hasVersionGraphStmt; - } - - - - try - { - hasGraphStmt.setString(1, module); - hasGraphStmt.setString(2, rpc); - hasGraphStmt.setString(3, mode); - - - if (version != null) - { - hasGraphStmt.setString(4, version); - } - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - results = hasGraphStmt.executeQuery(); - dbConn.commit(); - dbConn.setAutoCommit(oldAutoCommit); - - if (results.next()) - { - int cnt = results.getInt(1); - - if (cnt > 0) - { - retval = true; - } - - } - } - catch (Exception e) - { - throw new ConfigurationException("SQL query failed", e); - } - finally - { - if (results != null) - { - try - { - - results.close(); - } - catch (SQLException x) - {} - } - - } - - - return(retval); - - - } - - public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException { - - - - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - - - SvcLogicGraph retval = null; - ResultSet results = null; - - PreparedStatement fetchGraphStmt = null; - if (version == null) - { - fetchGraphStmt = fetchActiveGraphStmt; - } - else - { - fetchGraphStmt = fetchVersionGraphStmt; - } - try - { - fetchGraphStmt.setString(1, module); - fetchGraphStmt.setString(2, rpc); - fetchGraphStmt.setString(3, mode); - - - if (version != null) - { - fetchGraphStmt.setString(4, version); - } - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - results = fetchGraphStmt.executeQuery(); - dbConn.commit(); - dbConn.setAutoCommit(oldAutoCommit); - - if (results.next()) - { - Blob graphBlob = results.getBlob("graph"); - - ObjectInputStream gStream = new ObjectInputStream(graphBlob.getBinaryStream()); - - Object graphObj = gStream.readObject(); - gStream.close(); - - if (graphObj instanceof SvcLogicGraph) - { - retval = (SvcLogicGraph) graphObj; - } - else - { - throw new ConfigurationException("invalid type for graph ("+graphObj.getClass().getName()); - - } - - } - else - { - return(null); - } - } - catch (Exception e) - { - throw new ConfigurationException("SQL query failed", e); - } - finally - { - if (results != null) - { - try - { - results.close(); - } - catch (SQLException x) - {} - } - - } - - - return(retval); - - - } - - public void store(SvcLogicGraph graph) throws SvcLogicException { - - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - if (graph == null) - { - throw new SvcLogicException("graph cannot be null"); - } - - byte[] graphBytes = null; - - ByteArrayOutputStream byteStr = null; - ObjectOutputStream goutStr = null; - - try - { - byteStr = new ByteArrayOutputStream(); - goutStr = new ObjectOutputStream(byteStr); - goutStr.writeObject(graph); - - graphBytes = byteStr.toByteArray(); - - } - catch (Exception e) - { - throw new SvcLogicException("could not serialize graph", e); - } - finally - { - - if (goutStr != null) - { - try { - goutStr.close(); - } catch (IOException e) { - - } - } - - if (byteStr != null) - { - try { - byteStr.close(); - } catch (IOException e) { - - } - } - } - - - // If object already stored in database, delete it - if (hasGraph(graph.getModule(), graph.getRpc(), graph.getVersion(), graph.getMode())) - { - delete(graph.getModule(), graph.getRpc(), graph.getVersion(), graph.getMode()); - } - - try - { - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - storeGraphStmt.setString(1, graph.getModule()); - storeGraphStmt.setString(2, graph.getRpc()); - storeGraphStmt.setString(3, graph.getVersion()); - storeGraphStmt.setString(4, graph.getMode()); - storeGraphStmt.setString(5, "N"); - storeGraphStmt.setBlob(6, new ByteArrayInputStream(graphBytes)); - - storeGraphStmt.executeUpdate(); - dbConn.commit(); - - dbConn.setAutoCommit(oldAutoCommit); - } - catch (Exception e) - { - throw new SvcLogicException("Could not write object to database", e); - } - } - - public void delete(String module, String rpc, String version, String mode) throws SvcLogicException - { - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - try - { - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - deleteGraphStmt.setString(1, module); - deleteGraphStmt.setString(2, rpc); - deleteGraphStmt.setString(3, version); - deleteGraphStmt.setString(4, mode); - - - deleteGraphStmt.executeUpdate(); - dbConn.commit(); - dbConn.setAutoCommit(oldAutoCommit); - } - catch (Exception e) - { - throw new SvcLogicException("Could not delete object from database", e); - } - } - - public void activate(SvcLogicGraph graph) throws SvcLogicException - { - try - { - boolean oldAutoCommit = dbConn.getAutoCommit(); - - dbConn.setAutoCommit(false); - - // Deactivate any current active version - deactivateStmt.setString(1, graph.getModule()); - deactivateStmt.setString(2, graph.getRpc()); - deactivateStmt.setString(3, graph.getMode()); - deactivateStmt.executeUpdate(); - - // Activate this version - activateStmt.setString(1, graph.getModule()); - activateStmt.setString(2, graph.getRpc()); - activateStmt.setString(3, graph.getVersion()); - activateStmt.setString(4, graph.getMode()); - activateStmt.executeUpdate(); - - dbConn.commit(); - - dbConn.setAutoCommit(oldAutoCommit); - - } - catch (Exception e) - { - throw new SvcLogicException("Could not activate graph", e); - } - } - - @Override - public void registerNodeType(String nodeType) throws SvcLogicException { - - if (isValidNodeType(nodeType)) - { - return; - } - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - try - { - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - registerNodeStmt.setString(1, nodeType); - registerNodeStmt.executeUpdate(); - dbConn.commit(); - dbConn.setAutoCommit(oldAutoCommit); - } - catch (Exception e) - { - throw new SvcLogicException("Could not add node type to database", e); - } - - } - - @Override - public void unregisterNodeType(String nodeType) throws SvcLogicException { - - if (!isValidNodeType(nodeType)) - { - return; - } - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - try - { - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - unregisterNodeStmt.setString(1, nodeType); - unregisterNodeStmt.executeUpdate(); - dbConn.commit(); - dbConn.setAutoCommit(oldAutoCommit); - } - catch (Exception e) - { - throw new SvcLogicException("Could not delete node type from database", e); - } - - } - - @Override - public boolean isValidNodeType(String nodeType) throws SvcLogicException { - - boolean isValid = false; - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException("no jdbc connection"); - } - } - - ResultSet results = null; - try - { - validateNodeStmt.setString(1, nodeType); - - boolean oldAutoCommit = dbConn.getAutoCommit(); - dbConn.setAutoCommit(false); - results = validateNodeStmt.executeQuery(); - dbConn.commit(); - dbConn.setAutoCommit(oldAutoCommit); - - if (results != null) - { - if (results.next()) - { - int cnt = results.getInt(1); - - if (cnt > 0) - { - isValid = true; - } - } - } - - } - catch (Exception e) - { - throw new SvcLogicException("Cannot select node type from database", e); - } - finally - { - if (results != null) - { - try - { - results.close(); - } - catch (SQLException x) - {} - } - - } - - return(isValid); - } - - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicNode.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicNode.java deleted file mode 100644 index 6828e9ad1..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicNode.java +++ /dev/null @@ -1,456 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.openecomp.sdnc.sli; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.commons.lang3.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.Locator; - - -public class SvcLogicNode implements Serializable { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicExprListener.class); - - private static final long serialVersionUID = 2L; - - private String nodeName; - private int nodeId; - private String nodeType; - private boolean visited; - private SvcLogicGraph graph; - - - private HashMap attributes; - private HashMap outcomes; - private HashMap parameters; - - public SvcLogicNode(int nodeId, String nodeType, SvcLogicGraph graph) - { - this.nodeId = nodeId; - nodeName = ""; - this.nodeType = nodeType; - this.graph = graph; - attributes = new HashMap (); - parameters = new HashMap (); - outcomes = null; - - } - - public SvcLogicNode(int nodeId, String nodeType, String nodeName, SvcLogicGraph graph) throws DuplicateValueException - { - this.nodeId = nodeId; - this.nodeName = nodeName; - this.nodeType = nodeType; - this.graph = graph; - attributes = new HashMap (); - parameters = new HashMap (); - outcomes = null; - graph.setNamedNode(nodeName, this); - } - - - public int getNodeId() - { - return nodeId; - } - - public String getNodeName() - { - return(nodeName); - } - - public String getNodeType() - { - return(nodeType); - } - - public SvcLogicGraph getGraph() - { - return(graph); - } - - public int getNumOutcomes() - { - if (outcomes == null) - { - return(0); - } - else - { - return(outcomes.size()); - } - } - - public SvcLogicExpression getAttribute(String name) - { - if (attributes.containsKey(name)) - { - return(attributes.get(name)); - } - else - { - return(null); - } - - } - - public void setAttribute(String name, String value) throws SvcLogicException - { - setAttribute(name, new SvcLogicAtom("STRING", value)); - } - - public void setAttribute(String name, SvcLogicExpression value) throws SvcLogicException - { - if (attributes.containsKey(name)) - { - throw new DuplicateValueException("Duplicate attribute "+name); - } - - attributes.put(name, value); - } - - - public void mapParameter(String name, String value) throws SvcLogicException - { - - if (parameters.containsKey(name)) - { - throw new DuplicateValueException("Duplicate parameter "+name); - } - try - { - SvcLogicExpression parmValue; - if ((value == null) || (value.length() == 0)) - { - parmValue = new SvcLogicAtom("STRING", ""); - } - else if (value.trim().startsWith("`")) - { - int lastParen = value.lastIndexOf("`"); - String evalExpr = value.trim().substring(1, lastParen); - parmValue = SvcLogicExpressionFactory.parse(evalExpr); - - } - else - { - if (Character.isDigit(value.charAt(0))) - { - parmValue = new SvcLogicAtom("NUMBER", value); - } - else - { - parmValue = new SvcLogicAtom("STRING", value); - } - } - LOG.debug("Setting parameter "+name+" = "+value+" = "+parmValue.asParsedExpr()); - parameters.put(name, parmValue); - } - catch (IOException e) { - - LOG.error("Invalid parameter value expression ("+value+")"); - throw new SvcLogicException(e.getMessage()); - } - } - - public SvcLogicExpression getParameter(String name) - { - if (parameters.containsKey(name)) - { - return(parameters.get(name)); - } - else - { - return(null); - } - } - - public boolean isVisited() { - return visited; - } - - public void setVisited(boolean visited, boolean recursive) { - this.visited = visited; - - if (recursive) - { - Set> outcomeSet = getOutcomeSet(); - - if (outcomeSet == null) - { - return; - } - - for (Iterator> iter = outcomeSet.iterator(); iter.hasNext();) - { - Map.Entry curOutcome = iter.next(); - SvcLogicNode outNode = curOutcome.getValue(); - outNode.setVisited(visited, recursive); - } - } - } - - public void addOutcome(String outcomeValue, SvcLogicNode node) throws SvcLogicException - { - if (outcomes == null) - { - outcomes = new HashMap(); - } - - if (outcomeValue.length() == 0) { - outcomeValue = "\"\""; - } - if (outcomes.containsKey(outcomeValue)) - { - throw new DuplicateValueException("Duplicate outcome value "+outcomeValue); - } - - outcomes.put(outcomeValue, node); - } - - public Set> getOutcomeSet() - { - if (outcomes == null) - { - return null; - } - - return(outcomes.entrySet()); - - } - - public Set> getParameterSet() - { - if (parameters == null) - { - return null; - } - - return(parameters.entrySet()); - - } - - public void printAsGv(PrintStream pstr) - { - - if (visited) - { - return; - } - else - { - visited = true; - } - - StringBuffer sbuff = new StringBuffer(); - - sbuff.append("node"); - sbuff.append(nodeId); - sbuff.append(" [ shape=none, margin=0, label=<"); - sbuff.append(""); - - if (nodeName.length() > 0) - { - sbuff.append(""); - } - - Set> attrSet = attributes.entrySet(); - for (Iterator> iter = attrSet.iterator() ; iter.hasNext();) - { - Map.Entry curAttr = iter.next(); - sbuff.append(""); - } - sbuff.append("
"); - sbuff.append(nodeId); - sbuff.append(" : "); - sbuff.append(nodeType); - sbuff.append("
AttributeValue
name"); - sbuff.append(nodeName); - sbuff.append("
"); - sbuff.append(curAttr.getKey()); - sbuff.append(""); - sbuff.append(StringEscapeUtils.escapeHtml3(curAttr.getValue().toString())); - sbuff.append("
>];"); - - pstr.println(sbuff.toString()); - - - if (outcomes != null) - { - TreeMap sortedOutcomes = new TreeMap(outcomes); - Set> outcomeSet = sortedOutcomes.entrySet(); - - for (Iterator> iter = outcomeSet.iterator(); iter.hasNext();) - { - Map.Entry curOutcome = iter.next(); - String outValue = curOutcome.getKey(); - SvcLogicNode outNode = curOutcome.getValue(); - pstr.println("node"+nodeId+" -> node"+outNode.getNodeId()+" [label=\""+outValue+"\"];"); - outNode.printAsGv(pstr); - } - } - } - - public void printAsXml(PrintStream pstr, int indentLvl) - { - if (visited) - { - return; - } - // Print node tag - for (int i = 0 ; i < indentLvl ; i++) - { - pstr.print(" "); - } - pstr.print("<"); - pstr.print(this.getNodeType()); - - Set> attrSet = attributes.entrySet(); - for (Iterator> iter = attrSet.iterator() ; iter.hasNext();) - { - Map.Entry curAttr = iter.next(); - pstr.print(" "); - pstr.print(curAttr.getKey()); - pstr.print("='`"); - pstr.print(curAttr.getValue()); - pstr.print("'`"); - } - - if (((parameters == null) || (parameters.isEmpty())) && - ((outcomes == null) || outcomes.isEmpty())) - { - pstr.print("/>\n"); - pstr.flush(); - return; - } - else - { - pstr.print(">\n"); - } - - // Print parameters (if any) - if (parameters != null) - { - Set> paramSet = parameters.entrySet(); - for (Iterator> iter = paramSet.iterator() ; iter.hasNext();) - { - for (int i = 0 ; i < indentLvl+1 ; i++) - { - pstr.print(" "); - } - pstr.print(" curAttr = iter.next(); - pstr.print(" name='"); - pstr.print(curAttr.getKey()); - pstr.print("' value='`"); - pstr.print(curAttr.getValue().toString()); - pstr.print("`'/>\n"); - } - } - - // Print outcomes (if any) - if (outcomes != null) - { - Set> outcomeSet = outcomes.entrySet(); - for (Iterator> iter = outcomeSet.iterator() ; iter.hasNext();) - { - for (int i = 0 ; i < indentLvl+1 ; i++) - { - pstr.print(" "); - } - pstr.print(" curAttr = iter.next(); - pstr.print(" value='"); - pstr.print(curAttr.getKey()); - pstr.print("'>\n"); - SvcLogicNode outNode = curAttr.getValue(); - outNode.printAsXml(pstr, indentLvl+2); - for (int i = 0 ; i < indentLvl+1 ; i++) - { - pstr.print(" "); - } - pstr.print("\n"); - } - } - - // Print node end tag - for (int i = 0 ; i < indentLvl ; i++) - { - pstr.print(" "); - } - pstr.print("\n"); - pstr.flush(); - - } - - - public SvcLogicNode getOutcomeValue(String value) - { - - if (value.length() == 0) { - value = "\"\""; - } - if (outcomes == null) - { - return(null); - } - - if (outcomes.containsKey(value)) - { - return(outcomes.get(value)); - } - else - { - StringBuffer keyBuffer = new StringBuffer(); - keyBuffer.append("{"); - for (String key : outcomes.keySet()) { - keyBuffer.append(" ("+key+")"); - } - keyBuffer.append("}"); - LOG.info("Outcome (" + value + ") not found, keys are " + keyBuffer.toString()); - - if (outcomes.containsKey("Other")) - { - return(outcomes.get("Other")); - } - else - { - return(null); - } - } - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParser.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParser.java deleted file mode 100644 index 398c28de7..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParser.java +++ /dev/null @@ -1,598 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.File; -import java.io.InputStream; -import java.net.URL; -import java.util.LinkedList; - -import javax.xml.XMLConstants; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.Attributes; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * @author dt5972 - * - */ -public class SvcLogicParser { - - SvcLogicStore store = null; - static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; - static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; - static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; - static final String JAXP_DYNAMIC_VALIDATION = "http://apache.org/xml/features/validation/dynamic"; - static final String JAXP_SCHEMA_VALIDATION = "http://apache.org/xml/features/validation/schema"; - - private static final String LOAD_MESSAGE = "Getting SvcLogicGraph from database - "; - private static final String LOAD_ERROR_MESSAGE = "SvcLogicGraph not found - "; - private static final String ACTIVATION_ERROR_MESSAGE = "Could not activate SvcLogicGraph - "; - private static final String PRINT_ERROR_MESSAGE = "Could not print SvcLogicGraph - "; - private static final String SVC_LOGIC_STORE_ERROR = "Could not get service logic store"; - - private static final Logger LOGGER = LoggerFactory.getLogger(SvcLogicParser.class); - private static final String SLI_VALIDATING_PARSER = "org.openecomp.sdnc.sli.parser.validate"; - private static final String SVCLOGIC_XSD = "/svclogic.xsd"; - - private class SvcLogicHandler extends DefaultHandler { - private Locator locator = null; - private String module = null; - private String version = null; - private LinkedList graphs = null; - private SvcLogicGraph curGraph = null; - private SvcLogicNode curNode = null; - private LinkedList nodeStack = null; - private int curNodeId = 0; - private String outcomeValue = null; - private LinkedList outcomeStack = null; - private SvcLogicStore svcLogicStore = null; - - public SvcLogicHandler(LinkedList graphs, SvcLogicStore store) { - this.graphs = graphs; - this.curNode = null; - this.nodeStack = new LinkedList<>(); - this.outcomeStack = new LinkedList<>(); - this.curNodeId = 1; - this.outcomeValue = null; - this.svcLogicStore = store; - - } - - @Override - public void setDocumentLocator(Locator locator) { - this.locator = locator; - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - - // Handle service-logic (graph) tag - if ("service-logic".equalsIgnoreCase(qName)) { - - module = attributes.getValue("module"); - if (module == null || module.length() == 0) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'module' attribute from service-logic tag"); - } - - version = attributes.getValue("version"); - if (version == null || version.length() == 0) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'version' attribute from service-logic tag"); - } - - return; - } - - if ("method".equalsIgnoreCase(qName)) { - if (curGraph != null) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot nest module tags"); - } - curGraph = new SvcLogicGraph(); - curGraph.setModule(module); - curGraph.setVersion(version); - this.curNodeId = 1; - - String attrValue = attributes.getValue("rpc"); - if (attrValue == null || attrValue.length() == 0) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'rpc' attribute for method tag"); - } - curGraph.setRpc(attrValue); - - attrValue = attributes.getValue("mode"); - if (attrValue == null || attrValue.length() == 0) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Missing 'mode' attribute for method tag"); - } - curGraph.setMode(attrValue); - - return; - - } - - // Handle outcome (edge) tag - if ("outcome".equalsIgnoreCase(qName)) { - String refValue = attributes.getValue("ref"); - - if (refValue != null) { - SvcLogicNode refNode = curGraph.getNamedNode(refValue); - - if (refNode != null) { - try { - curNode.addOutcome(attributes.getValue("value"), refNode); - } catch (SvcLogicException e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot add outcome", e); - } - } else { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "ref to unknown node " + refValue); - } - return; - } - - if (outcomeValue != null) { - outcomeStack.push(outcomeValue); - } - outcomeValue = attributes.getValue("value"); - - return; - } - - // Handle parameter tag - if ("parameter".equalsIgnoreCase(qName)) { - String parmName = attributes.getValue("name"); - String parmValue = attributes.getValue("value"); - - if (parmName != null && parmName.length() > 0 && parmValue != null) { - try { - - curNode.mapParameter(parmName, parmValue); - } catch (Exception e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + " cannot set parameter " + parmName + " to " + parmValue + " [" + e.getMessage() + "]"); - } - } - - return; - } - - // Handle node tags - - String nodeName = attributes.getValue("name"); - SvcLogicNode thisNode = null; - - try { - if (!svcLogicStore.isValidNodeType(qName)) { - throw new SAXNotRecognizedException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Unknown tag " + qName); - } - } catch (Exception e) { - throw new SAXNotRecognizedException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot validate node type " + qName); - } - - try { - if (nodeName != null && nodeName.length() > 0) { - thisNode = new SvcLogicNode(curNodeId++, qName, nodeName, curGraph); - } else { - thisNode = new SvcLogicNode(curNodeId++, qName, curGraph); - } - - if (curGraph.getRootNode() == null) { - curGraph.setRootNode(thisNode); - } - } catch (SvcLogicException e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + e.getMessage()); - - } - - int numAttributes = attributes.getLength(); - - for (int i = 0; i < numAttributes; i++) { - String attrName = attributes.getQName(i); - if (!"name".equalsIgnoreCase(attrName)) { - try { - - String attrValueStr = attributes.getValue(i); - SvcLogicExpression attrValue = null; - if (attrValueStr.trim().startsWith("`")) { - int lastParen = attrValueStr.lastIndexOf("`"); - String evalExpr = attrValueStr.trim().substring(1, lastParen); - attrValue = SvcLogicExpressionFactory.parse(evalExpr); - - } else { - if (Character.isDigit(attrValueStr.charAt(0))) { - attrValue = new SvcLogicAtom("NUMBER", attrValueStr); - } else { - attrValue = new SvcLogicAtom("STRING", attrValueStr); - } - } - thisNode.setAttribute(attrName, attrValue); - } catch (Exception e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + "Cannot set attribute " + attrName, e); - } - } - } - - if (curNode != null) { - try { - if ("block".equalsIgnoreCase(curNode.getNodeType()) || "for".equalsIgnoreCase(curNode.getNodeType()) || "while".equalsIgnoreCase(curNode.getNodeType())) { - curNode.addOutcome("" + (curNode.getNumOutcomes() + 1), thisNode); - } else { - if (outcomeValue == null) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + curNode.getNodeType() + " node expects outcome, instead found " + thisNode.getNodeType()); - } - curNode.addOutcome(outcomeValue, thisNode); - } - } catch (SvcLogicException e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + e.getMessage()); - } - nodeStack.push(curNode); - } - curNode = thisNode; - - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - - // Handle close of service-logic tag - if ("service-logic".equalsIgnoreCase(qName)) { - // Nothing more to do - return; - } - - // Handle close of method tag - if ("method".equalsIgnoreCase(qName)) { - graphs.add(curGraph); - curGraph = null; - return; - } - - // Handle close of outcome tag - if ("outcome".equalsIgnoreCase(qName)) { - // Finished this outcome - pop the outcome stack - if (outcomeStack.isEmpty()) { - outcomeValue = null; - } else { - outcomeValue = outcomeStack.pop(); - } - return; - } - - // Handle close of parameter tag - do nothing - if ("parameter".equalsIgnoreCase(qName)) { - return; - } - - // Handle close of a node tag - if (nodeStack.isEmpty()) { - curNode = null; - } else { - curNode = nodeStack.pop(); - } - } - - @Override - public void error(SAXParseException arg0) throws SAXException { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + arg0.getMessage()); - } - - } - - public SvcLogicParser(SvcLogicStore store) { - this.store = store; - } - - public SvcLogicParser(String propFile) { - - try { - this.store = SvcLogicStoreFactory.getSvcLogicStore(propFile); - } catch (Exception e) { - LOGGER.error(SVC_LOGIC_STORE_ERROR, e); - - } - - } - - public SvcLogicParser(InputStream propStr) { - - try { - this.store = SvcLogicStoreFactory.getSvcLogicStore(propStr); - } catch (Exception e) { - LOGGER.error(SVC_LOGIC_STORE_ERROR, e); - - } - - } - - public LinkedList parse(String fileName) throws SvcLogicException { - LinkedList graphs = null; - - URL xsdUrl = null; - Schema schema = null; - String validateSchema = System.getProperty(SLI_VALIDATING_PARSER, "true"); - - if (validateSchema != null || validateSchema.equalsIgnoreCase("true")) { - xsdUrl = getClass().getResource(SVCLOGIC_XSD); - - } - - if (xsdUrl != null) { - try { - SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - schema = schemaFactory.newSchema(xsdUrl); - } catch (Exception e) { - LOGGER.warn("Could not validate using schema " + xsdUrl.getPath(), e); - } - } else { - LOGGER.warn("Could not find resource " + SVCLOGIC_XSD); - } - - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - - if (schema != null) { - factory.setNamespaceAware(true); - factory.setSchema(schema); - } - SAXParser saxParser = factory.newSAXParser(); - - if (saxParser.isValidating()) { - LOGGER.info("Validating against schema " + xsdUrl.getPath()); - } - graphs = new LinkedList<>(); - - saxParser.parse(fileName, new SvcLogicHandler(graphs, store)); - - } catch (Exception e) { - String msg = e.getMessage(); - if (msg != null) { - LOGGER.error(msg); - throw new SvcLogicException("Compiler error: " + fileName + " @ " + msg); - } else { - LOGGER.info("Caught exception parsing " + fileName, e); - throw new SvcLogicException("Compiler error: " + fileName, e); - } - } - - return graphs; - } - - public static void main(String argv[]) { - - if (argv.length == 0) { - SvcLogicParser.usage(); - } - - if ("load".equalsIgnoreCase(argv[0])) { - if (argv.length == 3) { - String xmlfile = argv[1]; - String propfile = argv[2]; - - SvcLogicStore store = SvcLogicParser.getStore(propfile); - try { - SvcLogicParser.load(xmlfile, store); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - } - } else { - SvcLogicParser.usage(); - } - } else if ("print".equalsIgnoreCase(argv[0])) { - String version = null; - String propfile = null; - - switch (argv.length) { - case 6: - version = argv[4]; - propfile = argv[5]; - case 5: - if (propfile == null) { - propfile = argv[4]; - } - SvcLogicStore store = SvcLogicParser.getStore(propfile); - SvcLogicParser.print(argv[1], argv[2], argv[3], version, store); - break; - default: - SvcLogicParser.usage(); - } - } else if ("get-source".equalsIgnoreCase(argv[0])) { - - switch (argv.length) { - case 6: - SvcLogicStore store = SvcLogicParser.getStore(argv[5]); - SvcLogicParser.getSource(argv[1], argv[2], argv[3], argv[4], store); - break; - default: - SvcLogicParser.usage(); - } - } else if ("activate".equalsIgnoreCase(argv[0])) { - if (argv.length == 6) { - SvcLogicStore store = SvcLogicParser.getStore(argv[5]); - SvcLogicParser.activate(argv[1], argv[2], argv[3], argv[4], store); - } else { - SvcLogicParser.usage(); - } - } else if ("validate".equalsIgnoreCase(argv[0])) { - if (argv.length == 3) { - String xmlfile = argv[1]; - String propfile = argv[2]; - - System.setProperty(SLI_VALIDATING_PARSER, "true"); - SvcLogicStore store = SvcLogicParser.getStore(propfile); - try { - SvcLogicParser.validate(xmlfile, store); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - } - } else { - SvcLogicParser.usage(); - } - } - - System.exit(0); - } - - private static SvcLogicStore getStore(String propfile) { - - SvcLogicStore store = null; - - try { - store = SvcLogicStoreFactory.getSvcLogicStore(propfile); - } catch (Exception e) { - LOGGER.error(SVC_LOGIC_STORE_ERROR, e); - System.exit(1); - } - - return store; - - } - - public static void load(String xmlfile, SvcLogicStore store) throws SvcLogicException { - File xmlFile = new File(xmlfile); - if (!xmlFile.canRead()) { - throw new ConfigurationException("Cannot read xml file (" + xmlfile + ")"); - } - - SvcLogicParser parser = new SvcLogicParser(store); - LinkedList graphs = null; - try { - graphs = parser.parse(xmlfile); - } catch (Exception e) { - throw new SvcLogicException(e.getMessage(), e); - } - - if (graphs == null) { - throw new SvcLogicException("Could not parse " + xmlfile); - } - - for (SvcLogicGraph graph : graphs) { - - String module = graph.getModule(); - String rpc = graph.getRpc(); - String version = graph.getVersion(); - String mode = graph.getMode(); - try { - LOGGER.info("Saving SvcLogicGraph to database (module:" + module + ",rpc:" + rpc + ",version:" + version + ",mode:" + mode + ")"); - store.store(graph); - } catch (Exception e) { - throw new SvcLogicException(e.getMessage(), e); - } - - } - - } - - public static void validate(String xmlfile, SvcLogicStore store) throws SvcLogicException { - File xmlFile = new File(xmlfile); - if (!xmlFile.canRead()) { - throw new ConfigurationException("Cannot read xml file (" + xmlfile + ")"); - } - - SvcLogicParser parser = new SvcLogicParser(store); - LinkedList graphs = null; - try { - LOGGER.info("Validating " + xmlfile); - graphs = parser.parse(xmlfile); - } catch (Exception e) { - throw new SvcLogicException(e.getMessage(), e); - } - - if (graphs == null) { - throw new SvcLogicException("Could not parse " + xmlfile); - } else { - LOGGER.info("Compilation successful for " + xmlfile); - } - - } - - private static void print(String module, String rpc, String mode, String version, SvcLogicStore store) { - String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; - - try { - LOGGER.info(LOAD_MESSAGE + details); - - SvcLogicGraph graph = store.fetch(module, rpc, version, mode); - if (graph == null) { - LOGGER.error(LOAD_ERROR_MESSAGE + details); - System.exit(1); - } - graph.printAsGv(System.out); - } catch (Exception e) { - LOGGER.error(PRINT_ERROR_MESSAGE + details, e); - System.exit(1); - } - - } - - private static void getSource(String module, String rpc, String mode, String version, SvcLogicStore store) { - String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; - - try { - LOGGER.info(LOAD_MESSAGE + details); - - SvcLogicGraph graph = store.fetch(module, rpc, version, mode); - if (graph == null) { - LOGGER.error(LOAD_ERROR_MESSAGE + details); - System.exit(1); - } - graph.printAsXml(System.out); - } catch (Exception e) { - LOGGER.error(PRINT_ERROR_MESSAGE + details, e); - System.exit(1); - } - - } - - private static void activate(String module, String rpc, String version, String mode, SvcLogicStore store) { - String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; - - try { - LOGGER.info(LOAD_MESSAGE + details); - - SvcLogicGraph graph = store.fetch(module, rpc, version, mode); - if (graph == null) { - LOGGER.error(LOAD_ERROR_MESSAGE + details); - System.exit(1); - } - store.activate(graph); - } catch (Exception e) { - LOGGER.error(ACTIVATION_ERROR_MESSAGE + details, e); - System.exit(1); - } - - } - - private static void usage() { - System.err.println("Usage: SvcLogicParser load "); - System.err.println(" OR SvcLogicParser print [] "); - System.err.println(" OR SvcLogicParser get-source "); - System.err.println(" OR SvcLogicParser activate "); - System.exit(1); - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParserException.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParserException.java deleted file mode 100644 index ac9c515e9..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicParserException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.IOException; - -public class SvcLogicParserException extends IOException { - - public SvcLogicParserException() { - super(); - } - - public SvcLogicParserException(String msg) { - super(msg); - } - - public SvcLogicParserException(Throwable t) { - super(t); - } - - public SvcLogicParserException(String msg, Throwable t) { - super(msg, t); - } -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicRecorder.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicRecorder.java deleted file mode 100644 index 8a23adf1a..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicRecorder.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.Map; - -public interface SvcLogicRecorder { - - void record(Map parmMap) throws SvcLogicException; - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicResource.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicResource.java deleted file mode 100644 index 5fc00f87b..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicResource.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.sql.SQLException; -import java.util.Map; - -public interface SvcLogicResource { - - public enum QueryStatus { - SUCCESS, - NOT_FOUND, - FAILURE - } - - public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus reserve(String resource, String select, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map parms, String prefix, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) throws SvcLogicException; - - public QueryStatus update(String resource, String key, Map parms, String prefix, SvcLogicContext ctx) throws SvcLogicException; - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStore.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStore.java deleted file mode 100644 index 6959c86a8..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStore.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.util.Properties; - -public interface SvcLogicStore { - - public void init(Properties props) throws SvcLogicException; - public void registerNodeType(String nodeType) throws SvcLogicException; - public void unregisterNodeType(String nodeType) throws SvcLogicException; - public boolean isValidNodeType(String nodeType) throws SvcLogicException; - public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException; - public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException; - public void store(SvcLogicGraph graph) throws SvcLogicException; - public void delete(String module, String rpc, String version, String mode) throws SvcLogicException; - public void activate(SvcLogicGraph graph) throws SvcLogicException; -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStoreFactory.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStoreFactory.java deleted file mode 100644 index 8b6618bef..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicStoreFactory.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SvcLogicStoreFactory { - - private static final Logger LOG = LoggerFactory.getLogger(SvcLogicStoreFactory.class); - - public static SvcLogicStore getSvcLogicStore(String propfile) - throws SvcLogicException { - File propFile = new File(propfile); - if (!propFile.canRead()) { - throw new ConfigurationException("Cannot read property file " - + propfile); - - } - - try { - return (getSvcLogicStore(new FileInputStream(propFile))); - } catch (Exception e) { - throw new ConfigurationException( - "Could load service store from properties file " + propfile, - e); - } - - } - - public static SvcLogicStore getSvcLogicStore(InputStream inStr) throws SvcLogicException - { - Properties props = new Properties(); - - try { - props.load(inStr); - } catch (Exception e) { - throw new ConfigurationException("Could not get load properties from input stream", e); - } - - return(getSvcLogicStore(props)); - } - - public static SvcLogicStore getSvcLogicStore(Properties props) - throws SvcLogicException { - String storeType = props.getProperty("org.openecomp.sdnc.sli.dbtype"); - if ((storeType == null) || (storeType.length() == 0)) { - throw new ConfigurationException( - "property org.openecomp.sdnc.sli.dbtype unset"); - - } - - SvcLogicStore retval = null; - LOG.debug(String.format("Using org.openecomp.sdnc.sli.dbtype=%s", storeType)); - - if ("jdbc".equalsIgnoreCase(storeType)) { - retval = new SvcLogicJdbcStore(); - - } else if ("dblib".equalsIgnoreCase(storeType)) { - retval = new SvcLogicDblibStore(); - } else { - throw new ConfigurationException("unsupported dbtype (" + storeType - + ")"); - - } - - - retval.init(props); - return (retval); - } - -} diff --git a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicVariableTerm.java b/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicVariableTerm.java deleted file mode 100644 index 9ddc3c0b8..000000000 --- a/sli/common/src/main/java/org/openecomp/sdnc/sli/SvcLogicVariableTerm.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -public class SvcLogicVariableTerm extends SvcLogicExpression { - - private String name = null; - - public String getName() { - return name; - } - - - public SvcLogicVariableTerm(String identifier) - { - this.name = identifier; - } - - public SvcLogicExpression getSubscript() - { - if (numOperands() > 0) - { - return(getOperands().get(0)); - } - else - { - return(null); - } - } - - - public String toString() - { - String retval = ""; - - if (numOperands() > 0) - { - retval = name + "[" + getSubscript().toString() + "]"; - } - else - { - retval = name; - } - return(retval); - } - - @Override - public String asParsedExpr() { - if (numOperands() == 0) { - return("(variable-term "+name+")"); - } - else - { - return("(variable-term "+name+" "+getSubscript().asParsedExpr()+")"); - } - } - -} diff --git a/sli/common/src/main/resources/crAseNetwork.sql b/sli/common/src/main/resources/crAseNetwork.sql index 412311761..d95891ae1 100644 --- a/sli/common/src/main/resources/crAseNetwork.sql +++ b/sli/common/src/main/resources/crAseNetwork.sql @@ -1,9 +1,8 @@ --- -- ============LICENSE_START======================================================= --- openECOMP : SDN-C +-- ONAP : CCSDK -- ================================================================================ --- Copyright (C) 2017 AT&T Intellectual Property. All rights --- reserved. +-- Copyright (C) 2017 ONAP -- ================================================================================ -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java new file mode 100644 index 000000000..123083a74 --- /dev/null +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Enumeration; +import java.util.Properties; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +import junit.framework.TestCase; + +public class SvcLogicContextTest extends TestCase { + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicContext.class); + + public void testMerge() { + + try { + InputStream testStr = getClass().getResourceAsStream("/mergetest.xml"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + Document theDocument = db.parse(testStr); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.mergeDocument("test-merge", theDocument); + Properties props = ctx.toProperties(); + LOG.info("SvcLogicContext contains the following : "); + for (Enumeration e = props.propertyNames(); e.hasMoreElements() ; ) { + String propName = (String) e.nextElement(); + LOG.info(propName+" = "+props.getProperty(propName)); + + } + } catch (Exception e) { + LOG.error("Caught exception trying to merge", e); + fail("Caught exception trying to merge"); + } + + } + +} diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java new file mode 100644 index 000000000..543bb1be3 --- /dev/null +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; + +import org.onap.ccsdk.sli.core.sli.SvcLogicExprListener; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpressionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import junit.framework.TestCase; + +public class SvcLogicExpressionParserTest extends TestCase { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicExprListener.class); + + public void testParse() { + try + { + InputStream testStr = getClass().getResourceAsStream("/expression.tests"); + BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); + + String testExpr = null; + while ((testExpr = testsReader.readLine()) != null) { + + SvcLogicExpression parsedExpr = SvcLogicExpressionFactory.parse(testExpr); + if (parsedExpr == null) + { + fail("parse("+testExpr+") returned null"); + } + else + { + LOG.info("test expression = ["+testExpr+"] ; parsed expression = ["+parsedExpr.asParsedExpr()+"]"); + + } + } + } + catch (Exception e) + { + e.printStackTrace(); + fail("Caught exception processing test cases"); + } + } + +} diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserTest.java new file mode 100644 index 000000000..2da8dd4f8 --- /dev/null +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicParserTest.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.LinkedList; + +import org.onap.ccsdk.sli.core.sli.SvcLogicParser; +import org.onap.ccsdk.sli.core.sli.SvcLogicParserException; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; + +import junit.framework.TestCase; + +/** + * @author dt5972 + * + */ +public class SvcLogicParserTest extends TestCase { + + /** + * Test method for {@link org.onap.ccsdk.sli.core.sli.SvcLogicParser#parse(java.lang.String)}. + */ + + + public void testParse() { + + + try + { + + URL propUrl = getClass().getResource("/svclogic.properties"); + + InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); + + SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(propStr); + + assertNotNull(store); + + store.registerNodeType("switch"); + store.registerNodeType("block"); + store.registerNodeType("get-resource"); + store.registerNodeType("reserve"); + store.registerNodeType("is-available"); + store.registerNodeType("exists"); + store.registerNodeType("configure"); + store.registerNodeType("return"); + store.registerNodeType("record"); + store.registerNodeType("allocate"); + store.registerNodeType("release"); + store.registerNodeType("for"); + store.registerNodeType("set"); + + + InputStream testStr = getClass().getResourceAsStream("/parser-good.tests"); + BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); + String testCaseFile = null; + while ((testCaseFile = testsReader.readLine()) != null) { + + testCaseFile = testCaseFile.trim(); + + if (testCaseFile.length() > 0) + { + if (!testCaseFile.startsWith("/")) + { + testCaseFile = "/"+testCaseFile; + } + URL testCaseUrl = getClass().getResource(testCaseFile); + if (testCaseUrl == null) + { + fail("Could not resolve test case file "+testCaseFile); + } + + try { + SvcLogicParser.validate(testCaseUrl.getPath(), store); + } catch (Exception e) { + fail("Validation failure ["+e.getMessage()+"]"); + + } + + + + + + } + } + + testStr = getClass().getResourceAsStream("/parser-bad.tests"); + testsReader = new BufferedReader(new InputStreamReader(testStr)); + testCaseFile = null; + while ((testCaseFile = testsReader.readLine()) != null) { + + testCaseFile = testCaseFile.trim(); + + if (testCaseFile.length() > 0) + { + if (!testCaseFile.startsWith("/")) + { + testCaseFile = "/"+testCaseFile; + } + URL testCaseUrl = getClass().getResource(testCaseFile); + if (testCaseUrl == null) + { + fail("Could not resolve test case file "+testCaseFile); + } + + boolean valid = true; + try { + SvcLogicParser.load(testCaseUrl.getPath(), store); + } catch (Exception e) { + System.out.println(e.getMessage()); + valid = false; + } + + if (valid) { + fail("Expected compiler error on "+testCaseFile+", but got success"); + } + + + } + } + } + catch (SvcLogicParserException e) + { + fail("Parser error : "+e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Caught exception processing test cases"); + } + + + } + + + +} diff --git a/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicContextTest.java b/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicContextTest.java deleted file mode 100644 index 6e6656e89..000000000 --- a/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicContextTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Enumeration; -import java.util.Properties; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -import junit.framework.TestCase; - -public class SvcLogicContextTest extends TestCase { - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicContext.class); - - public void testMerge() { - - try { - InputStream testStr = getClass().getResourceAsStream("/mergetest.xml"); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - - Document theDocument = db.parse(testStr); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.mergeDocument("test-merge", theDocument); - Properties props = ctx.toProperties(); - LOG.info("SvcLogicContext contains the following : "); - for (Enumeration e = props.propertyNames(); e.hasMoreElements() ; ) { - String propName = (String) e.nextElement(); - LOG.info(propName+" = "+props.getProperty(propName)); - - } - } catch (Exception e) { - LOG.error("Caught exception trying to merge", e); - fail("Caught exception trying to merge"); - } - - } - -} diff --git a/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicExpressionParserTest.java b/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicExpressionParserTest.java deleted file mode 100644 index d6503b60c..000000000 --- a/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicExpressionParserTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; - -import org.openecomp.sdnc.sli.SvcLogicExprListener; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicExpressionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestCase; - -public class SvcLogicExpressionParserTest extends TestCase { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicExprListener.class); - - public void testParse() { - try - { - InputStream testStr = getClass().getResourceAsStream("/expression.tests"); - BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); - - String testExpr = null; - while ((testExpr = testsReader.readLine()) != null) { - - SvcLogicExpression parsedExpr = SvcLogicExpressionFactory.parse(testExpr); - if (parsedExpr == null) - { - fail("parse("+testExpr+") returned null"); - } - else - { - LOG.info("test expression = ["+testExpr+"] ; parsed expression = ["+parsedExpr.asParsedExpr()+"]"); - - } - } - } - catch (Exception e) - { - e.printStackTrace(); - fail("Caught exception processing test cases"); - } - } - -} diff --git a/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicParserTest.java b/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicParserTest.java deleted file mode 100644 index e8ff2feeb..000000000 --- a/sli/common/src/test/java/org/openecomp/sdnc/sli/SvcLogicParserTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.openecomp.sdnc.sli; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.LinkedList; - -import org.openecomp.sdnc.sli.SvcLogicParser; -import org.openecomp.sdnc.sli.SvcLogicParserException; -import org.openecomp.sdnc.sli.SvcLogicStore; -import org.openecomp.sdnc.sli.SvcLogicStoreFactory; - -import junit.framework.TestCase; - -/** - * @author dt5972 - * - */ -public class SvcLogicParserTest extends TestCase { - - /** - * Test method for {@link org.openecomp.sdnc.sli.SvcLogicParser#parse(java.lang.String)}. - */ - - - public void testParse() { - - - try - { - - URL propUrl = getClass().getResource("/svclogic.properties"); - - InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); - - SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(propStr); - - assertNotNull(store); - - store.registerNodeType("switch"); - store.registerNodeType("block"); - store.registerNodeType("get-resource"); - store.registerNodeType("reserve"); - store.registerNodeType("is-available"); - store.registerNodeType("exists"); - store.registerNodeType("configure"); - store.registerNodeType("return"); - store.registerNodeType("record"); - store.registerNodeType("allocate"); - store.registerNodeType("release"); - store.registerNodeType("for"); - store.registerNodeType("set"); - - - InputStream testStr = getClass().getResourceAsStream("/parser-good.tests"); - BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); - String testCaseFile = null; - while ((testCaseFile = testsReader.readLine()) != null) { - - testCaseFile = testCaseFile.trim(); - - if (testCaseFile.length() > 0) - { - if (!testCaseFile.startsWith("/")) - { - testCaseFile = "/"+testCaseFile; - } - URL testCaseUrl = getClass().getResource(testCaseFile); - if (testCaseUrl == null) - { - fail("Could not resolve test case file "+testCaseFile); - } - - try { - SvcLogicParser.validate(testCaseUrl.getPath(), store); - } catch (Exception e) { - fail("Validation failure ["+e.getMessage()+"]"); - - } - - - - - - } - } - - testStr = getClass().getResourceAsStream("/parser-bad.tests"); - testsReader = new BufferedReader(new InputStreamReader(testStr)); - testCaseFile = null; - while ((testCaseFile = testsReader.readLine()) != null) { - - testCaseFile = testCaseFile.trim(); - - if (testCaseFile.length() > 0) - { - if (!testCaseFile.startsWith("/")) - { - testCaseFile = "/"+testCaseFile; - } - URL testCaseUrl = getClass().getResource(testCaseFile); - if (testCaseUrl == null) - { - fail("Could not resolve test case file "+testCaseFile); - } - - boolean valid = true; - try { - SvcLogicParser.load(testCaseUrl.getPath(), store); - } catch (Exception e) { - System.out.println(e.getMessage()); - valid = false; - } - - if (valid) { - fail("Expected compiler error on "+testCaseFile+", but got success"); - } - - - } - } - } - catch (SvcLogicParserException e) - { - fail("Parser error : "+e.getMessage()); - } - catch (Exception e) - { - e.printStackTrace(); - fail("Caught exception processing test cases"); - } - - - } - - - -} diff --git a/sli/common/src/test/resources/EvcActivateSvcLogic_v100.xml b/sli/common/src/test/resources/EvcActivateSvcLogic_v100.xml index 097078a8a..308bda1e9 100644 --- a/sli/common/src/test/resources/EvcActivateSvcLogic_v100.xml +++ b/sli/common/src/test/resources/EvcActivateSvcLogic_v100.xml @@ -1,10 +1,9 @@ - org.openecomp.sdnc.sli;version="${project.version}",* + org.onap.ccsdk.sli.core.sli;version="${project.version}",* diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BlockNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BlockNodeExecutor.java new file mode 100644 index 000000000..7132950f3 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BlockNodeExecutor.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BlockNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(BlockNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) + throws SvcLogicException { + + SvcLogicExpression atomicExpr = node.getAttribute("atomic"); + String atomicStr = SvcLogicExpressionResolver.evaluate(atomicExpr, node, ctx); + boolean isAtomic = "true".equalsIgnoreCase(atomicStr); + + // Initialize status to success so that at least one outcome will execute + ctx.setStatus("success"); + + int numOutcomes = node.getNumOutcomes(); + + for (int i = 0; i < numOutcomes; i++) { + if ("failure".equals(ctx.getStatus()) && isAtomic) { + LOG.info("Block - stopped executing nodes due to failure status"); + return(null); + } + + SvcLogicNode nextNode = node.getOutcomeValue("" + (i + 1)); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("Block - executing outcome " + (i + 1)); + } + while (nextNode != null) + { + nextNode = svc.executeNode(nextNode, ctx); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("Block - done: no outcome " + (i + 1)); + } + } + } + + return (null); + } + + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BreakNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BreakNodeExecutor.java new file mode 100644 index 000000000..ec0a5daa0 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/BreakNodeExecutor.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.BreakNodeException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BreakNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory.getLogger(BreakNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { + String message = "BreakNodeExecutor encountered break with nodeId " + node.getNodeId(); + LOG.debug(message); + throw new BreakNodeException(message); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java new file mode 100644 index 000000000..9498d6768 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CallNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(CallNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) + throws SvcLogicException { + + String outValue = "not-found"; + + SvcLogicGraph myGraph = node.getGraph(); + + if (myGraph == null) + { + LOG.debug("execute: getGraph returned null"); + } + else + { + LOG.debug("execute: got SvcLogicGraph"); + } + + SvcLogicExpression moduleExpr = null; + + String module = null; + + moduleExpr = node.getAttribute("module"); + if (moduleExpr != null) + { + module = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); + } + + if ((module == null) || (module.length() == 0)) + { + if (myGraph != null) + { + module = myGraph.getModule(); + LOG.debug("myGraph.getModule() returned "+module); + } + } + + SvcLogicExpression rpcExpr = null; + String rpc = null; + rpcExpr = node.getAttribute("rpc"); + if (rpcExpr != null) + { + rpc = SvcLogicExpressionResolver.evaluate(rpcExpr, node, ctx); + } + + if ((rpc == null) || (rpc.length() == 0)) + { + if (myGraph != null) + { + rpc = myGraph.getRpc(); + LOG.debug("myGraph.getRpc() returned "+rpc); + } + } + + String mode = null; + + moduleExpr = node.getAttribute("mode"); + if (moduleExpr != null) + { + mode = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); + } + + if ((mode == null) || (mode.length() == 0)) + { + if (myGraph != null) + { + mode = myGraph.getMode(); + + LOG.debug("myGraph.getMode() returned "+mode); + } + } + + String version = null; + + moduleExpr = node.getAttribute("version"); + if (moduleExpr != null) + { + version = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); + } + + String parentGraph = ctx.getAttribute("currentGraph"); + ctx.setAttribute("parentGraph", parentGraph); + + SvcLogicStore store = getStore(); + + if (store != null) { + SvcLogicGraph calledGraph = store.fetch(module, rpc, version, mode); + LOG.debug("Parent " + parentGraph + " is calling child " + calledGraph.toString()); + ctx.setAttribute("currentGraph", calledGraph.toString()); + if (calledGraph != null) { + svc.execute(calledGraph, ctx); + + outValue = ctx.getStatus(); + } else { + LOG.error("Could not find service logic for [" + module + "," + rpc + "," + version + "," + mode + "]"); + } + } + else + { + LOG.debug("Could not get SvcLogicStore reference"); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + ctx.setAttribute("currentGraph", parentGraph); + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no " + outValue + " or Other branch found"); + } + } + ctx.setAttribute("currentGraph", parentGraph); + ctx.setAttribute("parentGraph", null); + + return (nextNode); + + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ConfigureNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ConfigureNodeExecutor.java new file mode 100644 index 000000000..21b63d4fa --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ConfigureNodeExecutor.java @@ -0,0 +1,247 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ConfigureNodeExecutor extends SvcLogicNodeExecutor { + private static final Logger LOG = LoggerFactory + .getLogger(ConfigureNodeExecutor.class); + + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String adaptorName = SvcLogicExpressionResolver.evaluate( + node.getAttribute("adaptor"), node, ctx); + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("configure node encountered - looking for adaptor " + + adaptorName); + } + + SvcLogicAdaptor adaptor = getAdaptor(adaptorName); + + if (adaptor != null) { + String activate = SvcLogicExpressionResolver.evaluate( + node.getAttribute("activate"), node, ctx); + String key = SvcLogicExpressionResolver.evaluate( + node.getAttribute("key"), node, ctx); + + Map parmMap = new HashMap(); + + Set> parmSet = node + .getParameterSet(); + boolean hasParms = false; + + for (Iterator> iter = parmSet + .iterator(); iter.hasNext();) { + hasParms = true; + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + SvcLogicExpression curExpr = curEnt.getValue(); + String curExprValue = SvcLogicExpressionResolver.evaluate(curExpr, node, ctx); + + LOG.debug("Parameter "+curName+" = "+curExpr.asParsedExpr()+" resolves to "+curExprValue); + + parmMap.put(curName,curExprValue); + } + + if (hasParms) { + SvcLogicAdaptor.ConfigStatus confStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + + try { + confStatus = adaptor.configure(key, parmMap, ctx); + } catch (Exception e) { + LOG.warn("Caught exception from "+adaptorName+".configure", e); + confStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + } + + switch (confStatus) { + case SUCCESS: + outValue = "success"; + if ((activate != null) && (activate.length() > 0)) { + if ("true".equalsIgnoreCase(activate)) { + SvcLogicAdaptor.ConfigStatus activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + + try { + activateStatus = adaptor.activate(key, ctx); + } catch (Exception e) { + + LOG.warn("Caught exception from "+adaptorName+".activate", e); + activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + } + switch (activateStatus) { + case SUCCESS: + break; + case ALREADY_ACTIVE: + outValue = "already-active"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case NOT_READY: + outValue = "not-ready"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } else if ("false".equalsIgnoreCase(activate)) { + SvcLogicAdaptor.ConfigStatus deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + + try { + deactivateStatus = adaptor.deactivate(key, ctx); + } catch (Exception e) { + + LOG.warn("Caught exception from "+adaptorName+".deactivate", e); + deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + } + switch (deactivateStatus) { + case SUCCESS: + break; + case ALREADY_ACTIVE: + outValue = "already-active"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case NOT_READY: + outValue = "not-ready"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } + } + break; + case ALREADY_ACTIVE: + outValue = "already-active"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case NOT_READY: + outValue = "not-ready"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } else { + if ((activate != null) && (activate.length() > 0)) { + if ("true".equalsIgnoreCase(activate)) { + SvcLogicAdaptor.ConfigStatus activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + try { + activateStatus = adaptor.activate(key, ctx); + } catch (Exception e) { + LOG.warn("Caught exception from "+adaptorName+".activate", e); + activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + } + switch (activateStatus) { + case SUCCESS: + outValue = "success"; + break; + case ALREADY_ACTIVE: + outValue = "already-active"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case NOT_READY: + outValue = "not-ready"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } else if ("false".equalsIgnoreCase(activate)) { + SvcLogicAdaptor.ConfigStatus deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + + try { + deactivateStatus = adaptor.deactivate(key, ctx); + } catch (Exception e) { + LOG.warn("Caught exception from "+adaptorName+".deactivate", e); + deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; + } + switch (deactivateStatus) { + case SUCCESS: + outValue = "success"; + break; + case ALREADY_ACTIVE: + outValue = "already-active"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case NOT_READY: + outValue = "not-ready"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } + } else { + LOG.warn("Nothing to configure - no parameters passed, and activate attribute is not set"); + outValue = "success"; + } + } + } else { + if (LOG.isWarnEnabled()) { + LOG.warn("Adaptor for " + adaptorName + " not found"); + } + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no " + outValue + " or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/DeleteNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/DeleteNodeExecutor.java new file mode 100644 index 000000000..caba0943f --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/DeleteNodeExecutor.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DeleteNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(DeleteNodeExecutor.class); + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("delete node encountered - looking for resource class " + + plugin); + } + + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + if (resourcePlugin != null) { + + try { + + switch (resourcePlugin.delete(resourceType, key, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutor.java new file mode 100644 index 000000000..19868ed75 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutor.java @@ -0,0 +1,160 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExecuteNodeExecutor extends SvcLogicNodeExecutor { + private static final Logger LOG = LoggerFactory + .getLogger(ExecuteNodeExecutor.class); + + private static final String pluginErrorMessage = "Could not execute plugin. SvcLogic status will be set to failure."; + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String pluginName = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("execute node encountered - looking for plugin " + + pluginName); + } + + SvcLogicJavaPlugin plugin = getSvcLogicJavaPlugin(pluginName); + + if (plugin == null) { + outValue = "not-found"; + } else { + + String methodName = evaluate(node.getAttribute("method"), node, ctx); + + Class pluginClass = plugin.getClass(); + + Method pluginMethod = null; + + try { + pluginMethod = pluginClass.getMethod(methodName, Map.class, SvcLogicContext.class); + } catch (NoSuchMethodException e) { + LOG.error(pluginErrorMessage, e); + } + + if (pluginMethod == null) { + outValue = "unsupported-method"; + } else { + try { + + Map parmMap = new HashMap(); + + Set> parmSet = node + .getParameterSet(); + + for (Iterator> iter = parmSet + .iterator(); iter.hasNext();) { + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + SvcLogicExpression curExpr = curEnt.getValue(); + String curExprValue = SvcLogicExpressionResolver.evaluate(curExpr, node, ctx); + + LOG.debug("Parameter "+curName+" = "+curExpr.asParsedExpr()+" resolves to "+curExprValue); + + parmMap.put(curName,curExprValue); + } + + Object o = pluginMethod.invoke(plugin, parmMap, ctx); + String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); + + outValue = mapOutcome(o, emitsOutcome); + + } catch (InvocationTargetException e) { + if(e.getCause() != null){ + LOG.error(pluginErrorMessage, e.getCause()); + }else{ + LOG.error(pluginErrorMessage, e); + } + outValue = "failure"; + ctx.setStatus("failure"); + } catch (IllegalAccessException e) { + LOG.error(pluginErrorMessage, e); + outValue = "failure"; + ctx.setStatus("failure"); + } catch (IllegalArgumentException e) { + LOG.error(pluginErrorMessage, e); + outValue = "failure"; + ctx.setStatus("failure"); + } + } + + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no " + outValue + " or Other branch found"); + } + } + return (nextNode); + } + + protected String evaluate(SvcLogicExpression expr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { + return SvcLogicExpressionResolver.evaluate(node.getAttribute("method"), node, ctx); + } + + public String mapOutcome(Object o, String emitsOutcome) { + if (emitsOutcome != null) { + Boolean nodeEmitsOutcome = Boolean.valueOf(emitsOutcome); + if (nodeEmitsOutcome) { + return (String) o; + } else { + return "success"; + } + + } else { + return "success"; + } + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExistsNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExistsNodeExecutor.java new file mode 100644 index 000000000..1798d50a9 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ExistsNodeExecutor.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExistsNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(ExistsNodeExecutor.class); + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + String pfx = SvcLogicExpressionResolver.evaluate( + node.getAttribute("pfx"), node, ctx); + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("exists node encountered - looking for resource class " + + plugin); + } + + + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + + if (resourcePlugin != null) { + + try { + + switch (resourcePlugin.exists(resourceType, key, pfx, ctx)) { + case SUCCESS: + outValue = "true"; + break; + case NOT_FOUND: + outValue = "false"; + break; + case FAILURE: + default: + outValue = "false"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java new file mode 100644 index 000000000..a9ee00768 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.BreakNodeException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ForNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(ForNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + SvcLogicExpression atomicExpr = node.getAttribute("atomic"); + String atomicStr = SvcLogicExpressionResolver.evaluate(atomicExpr, node, ctx); + boolean isAtomic = !("false".equalsIgnoreCase(atomicStr)); + + int numOutcomes = node.getNumOutcomes(); + String idxVar = SvcLogicExpressionResolver.evaluate( + node.getAttribute("index"), node, ctx); + String startVal = SvcLogicExpressionResolver.evaluate( + node.getAttribute("start"), node, ctx); + String endVal = SvcLogicExpressionResolver.evaluate( + node.getAttribute("end"), node, ctx); + + LOG.debug("Executing "+ (isAtomic ? "atomic" : "non-atomic") + " for loop - for (int " + idxVar + " = " + startVal + + "; " + idxVar + " < " + endVal + "; " + idxVar + "++)"); + + int startIdx = 0; + int endIdx = 0; + + try { + startIdx = Integer.parseInt(startVal); + endIdx = Integer.parseInt(endVal); + } catch (NumberFormatException e) { + SvcLogicExpression silentFailureExpr = node.getAttribute("silentFailure"); + String silentFailure = SvcLogicExpressionResolver.evaluate(silentFailureExpr, node, ctx); + boolean isSilentFailure = Boolean.parseBoolean(silentFailure); + String message = "Invalid index values [" + startVal + "," + endVal + "]"; + if(!isSilentFailure){ + throw new SvcLogicException(message); + }else{ + LOG.debug(message + ". Not exiting because silentFailure was set to true."); + return(null); + } + } + + try { + for (int ctr = startIdx; ctr < endIdx; ctr++) { + + ctx.setAttribute(idxVar, "" + ctr); + + for (int i = 0; i < numOutcomes; i++) { + + if ("failure".equals(ctx.getStatus()) && isAtomic) { + LOG.info("For - stopped executing nodes due to failure status"); + return(null); + } + + SvcLogicNode nextNode = node.getOutcomeValue("" + (i + 1)); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("For - executing outcome " + (i + 1)); + } + SvcLogicNode innerNextNode = nextNode; + while (innerNextNode != null) { + innerNextNode = svc.executeNode(innerNextNode, ctx); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("For - done: no outcome " + (i + 1)); + } + } + } + } + } catch (BreakNodeException br) { + LOG.debug("ForNodeExecutor caught break"); + } + return (null); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/GetResourceNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/GetResourceNodeExecutor.java new file mode 100644 index 000000000..7ecc76c51 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/GetResourceNodeExecutor.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GetResourceNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(GetResourceNodeExecutor.class); + + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + String pfx = SvcLogicExpressionResolver.evaluate( + node.getAttribute("pfx"), node, ctx); + + String localOnlyStr = SvcLogicExpressionResolver.evaluate( + node.getAttribute("local-only"), node, ctx); + + // Note: for get-resource, only refresh from A&AI if the DG explicitly set + // local-only to false. Otherwise, just read from local database. + boolean localOnly = true; + + if ("false".equalsIgnoreCase(localOnlyStr)) { + localOnly = false; + } + + SvcLogicExpression selectExpr = node.getAttribute("select"); + String select = null; + + if (selectExpr != null) { + select = SvcLogicExpressionResolver.evaluateAsKey(selectExpr, node, + ctx); + } + + SvcLogicExpression orderByExpr = node.getAttribute("order-by"); + String orderBy = null; + + if (orderByExpr != null) { + orderBy = SvcLogicExpressionResolver.evaluateAsKey(orderByExpr, node, + ctx); + } + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug(node.getNodeType() + + " node encountered - looking for resource class " + + plugin); + } + + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + + if (resourcePlugin != null) { + + try { + switch (resourcePlugin.query(resourceType, localOnly, select, key, + pfx, orderBy, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/IsAvailableNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/IsAvailableNodeExecutor.java new file mode 100644 index 000000000..7bc15d8a2 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/IsAvailableNodeExecutor.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IsAvailableNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(IsAvailableNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + String pfx = SvcLogicExpressionResolver.evaluate( + node.getAttribute("pfx"), node, ctx); + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("is-available node encountered - looking for resource class " + + plugin); + } + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + + + if (resourcePlugin != null) { + try { + switch (resourcePlugin.isAvailable(resourceType, key, pfx, ctx)) { + case SUCCESS: + outValue = "true"; + break; + case NOT_FOUND: + outValue = "false"; + break; + case FAILURE: + default: + outValue = "false"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java new file mode 100644 index 000000000..a35c05243 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java @@ -0,0 +1,1185 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefixBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address; +import org.opendaylight.yangtools.yang.binding.Identifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MdsalHelper { + + private static final Logger LOG = LoggerFactory.getLogger(MdsalHelper.class); + private static Properties yangMappingProperties = new Properties(); + + @Deprecated + public static void setProperties(Properties input) { + setYangMappingProperties(input); + } + + public static void setYangMappingProperties(Properties properties) { + for (Object propNameObj : properties.keySet()) { + String propName = (String) propNameObj; + MdsalHelper.yangMappingProperties.setProperty(propName, properties.getProperty(propName)); + } + } + + public static void loadProperties(String propertiesFile) { + File file = new File(propertiesFile); + Properties properties = new Properties(); + InputStream input = null; + if (file.isFile() && file.canRead()) { + try { + input = new FileInputStream(file); + properties.load(input); + MdsalHelper.setYangMappingProperties(properties); + LOG.info("Loaded properties from " + propertiesFile); + } catch (Exception e) { + LOG.error("Failed to load properties " + propertiesFile + "\n", e); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + LOG.error("Failed to close properties file " + propertiesFile + "\n", e); + } + } + } + }else{ + LOG.error("Failed to load the properties file " + propertiesFile + "\n"); + LOG.error("Either isFile or canRead returned false for " + propertiesFile + "\n"); + } + } + + public static Properties toProperties(Properties props, Object fromObj) { + Class fromClass = null; + + if (fromObj != null) { + fromClass = fromObj.getClass(); + } + return (toProperties(props, "", fromObj, fromClass)); + } + + public static Properties toProperties(Properties props, String pfx, Object fromObj) { + Class fromClass = null; + + if (fromObj != null) { + fromClass = fromObj.getClass(); + } + + return (toProperties(props, pfx, fromObj, fromClass)); + } + + public static Properties toProperties(Properties props, String pfx, Object fromObj, Class fromClass) { + + if (fromObj == null) { + return (props); + } + + String simpleName = fromClass.getSimpleName(); + + LOG.trace("Extracting properties from " + fromClass.getName() + " class"); + if (fromObj instanceof List) { + + // Class is a List. List should contain yang-generated classes. + LOG.trace(fromClass.getName() + " is a List"); + + List fromList = (List) fromObj; + + for (int i = 0; i < fromList.size(); i++) { + toProperties(props, pfx + "[" + i + "]", fromList.get(i), fromClass); + } + props.setProperty(pfx + "_length", "" + fromList.size()); + + } else if (isYangGenerated(fromClass)) { + // Class is yang generated. + LOG.trace(fromClass.getName() + " is a Yang-generated class"); + + String propNamePfx = null; + + // If called from a list (so prefix ends in ']'), don't + // add class name again + if (pfx.endsWith("]")) { + propNamePfx = pfx; + } else { + if ((pfx != null) && (pfx.length() > 0)) { + propNamePfx = pfx; + } else { + propNamePfx = toLowerHyphen(fromClass.getSimpleName()); + } + + if (propNamePfx.endsWith("-builder")) { + propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-builder".length()); + } + + if (propNamePfx.endsWith("-impl")) { + propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-impl".length()); + } + } + + // Iterate through getter methods to figure out values we need to + // save from + + int numGetters = 0; + String lastGetterName = null; + String propVal = null; + + for (Method m : fromClass.getMethods()) { + if (isGetter(m)) { + + numGetters++; + lastGetterName = m.getName(); + + Class returnType = m.getReturnType(); + String fieldName; + if (m.getName().startsWith("get")) { + fieldName = toLowerHyphen(m.getName().substring(3)); + } else { + + fieldName = toLowerHyphen(m.getName().substring(2)); + } + + fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); + + // Is the return type a yang generated class? + if (isYangGenerated(returnType)) { + // Is it an enum? + if (returnType.isEnum()) { + // Return type is a typedef. Save its value. + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + + Object retValue = m.invoke(fromObj); + + if (!isAccessible) { + m.setAccessible(isAccessible); + } + if (retValue != null) { + String propName = propNamePfx + "." + fieldName; + propVal = retValue.toString(); + props.setProperty(propName, mapEnumeratedValue(fieldName, propVal)); + } + } catch (Exception e) { + LOG.error("Caught exception trying to convert Yang-generated enum returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } else if (isIpv4Address(returnType)) { + // Save its value + try { + String propName = propNamePfx + "." + fieldName; + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + Ipv4Address retValue = (Ipv4Address) m.invoke(fromObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + + if (retValue != null) { + propVal = retValue.getValue().toString(); + LOG.debug("Setting property " + propName + " to " + propVal); + props.setProperty(propName, propVal); + + } + } catch (Exception e) { + LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } else if (isIpv6Address(returnType)) { + // Save its value + try { + String propName = propNamePfx + "." + fieldName; + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + Ipv6Address retValue = (Ipv6Address) m.invoke(fromObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + + if (retValue != null) { + propVal = retValue.getValue().toString(); + LOG.debug("Setting property " + propName + " to " + propVal); + props.setProperty(propName, propVal); + + } + } catch (Exception e) { + LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } else if (isIpAddress(returnType)) { + // Save its value + try { + String propName = propNamePfx + "." + fieldName; + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + IpAddress retValue = (IpAddress) m.invoke(fromObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + + if (retValue != null) { + propVal = new String(retValue.getValue()); + LOG.debug("Setting property " + propName + " to " + propVal); + props.setProperty(propName, propVal); + + } + } catch (Exception e) { + LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } else if (isIpPrefix(returnType)) { + // Save its value + try { + String propName = propNamePfx + "." + fieldName; + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + IpPrefix retValue = (IpPrefix) m.invoke(fromObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + + if (retValue != null) { + propVal = new String(retValue.getValue()); + LOG.debug("Setting property " + propName + " to " + propVal); + props.setProperty(propName, propVal); + + } + } catch (Exception e) { + LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } else { + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + Object retValue = m.invoke(fromObj); + + if (retValue instanceof byte[]) { + LOG.trace(m.getName() + " returns a byte[]"); + retValue = new String((byte[]) retValue, "UTF-8"); + LOG.trace("Converted byte array " + propNamePfx + "." + fieldName + "to string " + retValue); + } + if (!isAccessible) { + m.setAccessible(isAccessible); + } + if (retValue != null) { + toProperties(props, propNamePfx + "." + fieldName, retValue, returnType); + } + } catch (Exception e) { + + if (m.getName().equals("getKey")) { + LOG.trace("Caught " + e.getClass().getName() + " exception trying to convert results from getKey() - ignoring"); + } else { + LOG.error("Caught exception trying to convert Yang-generated class returned by" + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } + } + } else if (returnType.equals(Class.class)) { + + LOG.trace(m.getName() + " returns a Class object - not interested"); + + } else if (List.class.isAssignableFrom(returnType)) { + + // This getter method returns a list. + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + Object retList = m.invoke(fromObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + // Figure out what type of elements are stored in + // this array. + Type paramType = m.getGenericReturnType(); + Type elementType = ((ParameterizedType) paramType).getActualTypeArguments()[0]; + toProperties(props, propNamePfx + "." + fieldName, retList, (Class) elementType); + } catch (Exception e) { + LOG.error("Caught exception trying to convert List returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + + } else { + + // Method returns something that is not a List and not + // yang-generated. + // Save its value + try { + String propName = propNamePfx + "." + fieldName; + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + Object propValObj = m.invoke(fromObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + + if (propValObj != null) { + if (propValObj instanceof byte[]) { + LOG.trace(m.getName() + " returns a byte[]"); + propVal = new String((byte[]) propValObj, "UTF-8"); + LOG.trace("Converted byte array " + propNamePfx + "." + fieldName + "to string " + propVal); + + } else { + propVal = propValObj.toString(); + } + LOG.debug("Setting property " + propName + " to " + propVal); + props.setProperty(propName, propVal); + + } + } catch (Exception e) { + if (m.getName().equals("getKey")) { + LOG.trace("Caught " + e.getClass().getName() + " exception trying to convert results from getKey() - ignoring"); + } else { + LOG.error("Caught exception trying to convert value returned by" + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } + } + + } + } + + // End of method loop. If there was only one getter, named + // "getValue", then + // set value identified by "prefix" to that one value. + if ((numGetters == 1) && ("getValue".equals(lastGetterName))) { + LOG.trace("getValueFIX : " + propNamePfx + " only has getValue() getter - setting " + propNamePfx + " = " + propVal); + props.setProperty(propNamePfx, propVal); + } else { + LOG.trace("getValueFIX : " + propNamePfx + " has " + numGetters + " getter(s), last one found was " + lastGetterName); + + } + + } else { + // Class is not yang generated and not a list + // It must be an element of a leaf list - set "prefix" to value + String fromVal = null; + if (fromObj instanceof byte[]) { + try { + fromVal = new String((byte[]) fromObj, "UTF-8"); + LOG.trace("Converted byte array " + pfx + "to string " + fromVal); + } catch (Exception e) { + LOG.warn("Caught exception trying to convert " + pfx + " from byte[] to String", e); + fromVal = fromObj.toString(); + } + + } else { + fromVal = fromObj.toString(); + } + LOG.debug("Setting property " + pfx + " to " + fromVal); + props.setProperty(pfx, fromVal); + } + + return (props); + } + + public static Object toBuilder(Properties props, Object toObj) { + + return (toBuilder(props, "", toObj)); + } + + public static List toList(Properties props, String pfx, List toObj, Class elemType) { + + int maxIdx = -1; + boolean foundValue = false; + + LOG.trace("Saving properties to List<" + elemType.getName() + "> from " + pfx); + + if (props.contains(pfx + "_length")) { + try { + int listLength = Integer.parseInt(props.getProperty(pfx + "_length")); + + if (listLength > 0) { + maxIdx = listLength - 1; + } + } catch (Exception e) { + // Ignore exception + } + } + + if (maxIdx == -1) { + // Figure out array size + for (Object pNameObj : props.keySet()) { + String key = (String) pNameObj; + + if (key.startsWith(pfx + "[")) { + String idxStr = key.substring(pfx.length() + 1); + int endloc = idxStr.indexOf("]"); + if (endloc != -1) { + idxStr = idxStr.substring(0, endloc); + } + + try { + int curIdx = Integer.parseInt(idxStr); + if (curIdx > maxIdx) { + maxIdx = curIdx; + } + } catch (Exception e) { + LOG.error("Illegal subscript in property " + key); + } + + } + } + } + + LOG.trace(pfx + " has max index of " + maxIdx); + for (int i = 0; i <= maxIdx; i++) { + + String curBase = pfx + "[" + i + "]"; + + if (isYangGenerated(elemType)) { + String builderName = elemType.getName() + "Builder"; + try { + Class builderClass = Class.forName(builderName); + Object builderObj = builderClass.newInstance(); + Method buildMethod = builderClass.getMethod("build"); + builderObj = toBuilder(props, curBase, builderObj, true); + if (builderObj != null) { + LOG.trace("Calling " + builderObj.getClass().getName() + "." + buildMethod.getName() + "()"); + Object builtObj = buildMethod.invoke(builderObj); + toObj.add(builtObj); + foundValue = true; + } + + } catch (ClassNotFoundException e) { + LOG.warn("Could not find builder class " + builderName, e); + } catch (Exception e) { + LOG.error("Caught exception trying to populate list from " + pfx); + } + } else { + // Must be a leaf list + String curValue = props.getProperty(curBase, ""); + + toObj.add(curValue); + + if ((curValue != null) && (curValue.length() > 0)) { + foundValue = true; + } + } + + } + + if (foundValue) { + return (toObj); + } else { + return (null); + } + + } + + public static Object toBuilder(Properties props, String pfx, Object toObj) { + return (toBuilder(props, pfx, toObj, false)); + } + + public static Object toBuilder(Properties props, String pfx, Object toObj, boolean preservePfx) { + Class toClass = toObj.getClass(); + boolean foundValue = false; + + LOG.trace("Saving properties to " + toClass.getName() + " class from " + pfx); + + Ipv4Address addr; + + if (isYangGenerated(toClass)) { + // Class is yang generated. + LOG.trace(toClass.getName() + " is a Yang-generated class"); + + String propNamePfx = null; + if (preservePfx) { + propNamePfx = pfx; + } else { + + if ((pfx != null) && (pfx.length() > 0)) { + propNamePfx = pfx + "." + toLowerHyphen(toClass.getSimpleName()); + } else { + propNamePfx = toLowerHyphen(toClass.getSimpleName()); + } + + if (propNamePfx.endsWith("-builder")) { + propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-builder".length()); + } + + if (propNamePfx.endsWith("-impl")) { + propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-impl".length()); + } + } + + if (toObj instanceof Identifier) { + LOG.trace(toClass.getName() + " is a Key - skipping"); + return (toObj); + } + + // Iterate through getter methods to figure out values we need to + // set + + for (Method m : toClass.getMethods()) { + if (isSetter(m)) { + Class paramTypes[] = m.getParameterTypes(); + Class paramClass = paramTypes[0]; + + String fieldName = toLowerHyphen(m.getName().substring(3)); + fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); + + String propName = propNamePfx + "." + fieldName; + + String paramValue = props.getProperty(propName); + if (paramValue == null) { + LOG.trace(propName + " is unset"); + } else { + LOG.trace(propName + " = " + paramValue); + } + + // Is the return type a yang generated class? + if (isYangGenerated(paramClass)) { + // Is it an enum? + if (paramClass.isEnum()) { + + LOG.trace(m.getName() + " expects an Enum"); + // Param type is a typedef. + if ((paramValue != null) && (paramValue.length() > 0)) { + Object paramObj = null; + + try { + paramObj = Enum.valueOf(paramClass, toJavaEnum(paramValue)); + } catch (Exception e) { + LOG.error("Caught exception trying to convert field " + propName + " to enum " + paramClass.getName(), e); + } + + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); + m.invoke(toObj, paramObj); + + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e) { + LOG.error("Caught exception trying to create Yang-generated enum expected by" + toClass.getName() + "." + m.getName() + "() from Properties entry", e); + } + } + } else { + + String simpleName = paramClass.getSimpleName(); + + if ("Ipv4Address".equals(simpleName) || "Ipv6Address".equals(simpleName) || "IpAddress".equals(simpleName)) { + + if ((paramValue != null) && (paramValue.length() > 0)) { + try { + IpAddress ipAddr = IpAddressBuilder.getDefaultInstance(paramValue); + + if ("Ipv4Address".equals(simpleName)) { + m.invoke(toObj, ipAddr.getIpv4Address()); + } else if ("Ipv6Address".equals(simpleName)) { + m.invoke(toObj, ipAddr.getIpv6Address()); + + } else { + m.invoke(toObj, ipAddr); + } + foundValue = true; + } catch (Exception e) { + LOG.error("Caught exception calling " + toClass.getName() + "." + m.getName() + "(" + paramValue + ")", e); + + } + } else { + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); + m.invoke(toObj, paramValue); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e) { + LOG.error("Caught exception trying to call " + toClass.getName() + "." + m.getName() + "() with Properties entry", e); + } + } + } else if ("IpPrefix".equals(simpleName)) { + if ((paramValue != null) && (paramValue.length() > 0)) { + try { + IpPrefix ipPrefix = IpPrefixBuilder.getDefaultInstance(paramValue); + m.invoke(toObj, ipPrefix); + foundValue = true; + } catch (Exception e) { + LOG.error("Caught exception calling " + toClass.getName() + "." + m.getName() + "(" + paramValue + ")", e); + } + } + } else { + // setter expects a yang-generated class. Need + // to + // create a builder to set it. + + String builderName = paramClass.getName() + "Builder"; + Class builderClass = null; + Object builderObj = null; + Object paramObj = null; + + Object constObj = null; + + LOG.trace(m.getName() + " expects a yang-generated class - looking for builder " + builderName); + try { + builderClass = Class.forName(builderName); + builderObj = builderClass.newInstance(); + paramObj = toBuilder(props, propNamePfx, builderObj); + } catch (ClassNotFoundException e) { + + if (paramValue == null) { + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(null)"); + m.invoke(toObj, new Object[] { null }); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e1) { + LOG.error("Caught exception trying to cally" + toClass.getName() + "." + m.getName() + "() with Properties entry", e1); + } + } else { + try { + // See if I can find a constructor I + // can + // use + Constructor[] constructors = paramClass.getConstructors(); + // Is there a String constructor? + for (Constructor c : constructors) { + Class[] cParms = c.getParameterTypes(); + if ((cParms != null) && (cParms.length == 1)) { + if (String.class.isAssignableFrom(cParms[0])) { + constObj = c.newInstance(paramValue); + } + } + } + + if (constObj == null) { + // Is there a Long constructor? + for (Constructor c : constructors) { + Class[] cParms = c.getParameterTypes(); + if ((cParms != null) && (cParms.length == 1)) { + if (Long.class.isAssignableFrom(cParms[0])) { + constObj = c.newInstance(Long.parseLong(paramValue)); + } + } + } + + } + + if (constObj == null) { + + // Last chance - see if + // parameter class has a static + // method + // getDefaultInstance(String) + try { + Method gm = paramClass.getMethod("getDefaultInstance", String.class); + + int gmodifier = gm.getModifiers(); + if (Modifier.isStatic(gmodifier)) { + // Invoke static + // getDefaultInstance(String) + paramObj = gm.invoke(null, paramValue); + } + + } catch (Exception gme) { + // Ignore exceptions + } + } + + } catch (Exception e1) { + LOG.warn("Could not find a suitable constructor for " + paramClass.getName(), e1); + } + + if (constObj == null) { + LOG.warn("Could not find builder class " + builderName + " and could not find a String or Long constructor or static getDefaultInstance(String) - trying just to set passing paramValue"); + + } + } + } catch (Exception e) { + LOG.error("Caught exception trying to create builder " + builderName, e); + } + + if (paramObj != null) { + + try { + + Method buildMethod = builderClass.getMethod("build"); + LOG.trace("Calling " + paramObj.getClass().getName() + "." + buildMethod.getName() + "()"); + Object builtObj = buildMethod.invoke(paramObj); + + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "()"); + m.invoke(toObj, builtObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e) { + LOG.error("Caught exception trying to set Yang-generated class expected by" + toClass.getName() + "." + m.getName() + "() from Properties entry", e); + } + } else { + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + + if (constObj != null) { + + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + constObj.toString() + ")"); + m.invoke(toObj, constObj); + } else { + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); + m.invoke(toObj, paramValue); + + } + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e) { + LOG.error("Caught exception trying to convert value returned by" + toClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } + } + } + } else { + + // Setter's argument is not a yang-generated class. See + // if it is a List. + + if (List.class.isAssignableFrom(paramClass)) { + + LOG.trace("Parameter class " + paramClass.getName() + " is a List"); + + // Figure out what type of args are in List and pass + // that to toList(). + + Type paramType = m.getGenericParameterTypes()[0]; + Type elementType = ((ParameterizedType) paramType).getActualTypeArguments()[0]; + Object paramObj = new LinkedList(); + try { + paramObj = toList(props, propName, (List) paramObj, (Class) elementType); + } catch (Exception e) { + LOG.error("Caught exception trying to create list expected as argument to " + toClass.getName() + "." + m.getName()); + } + + if (paramObj != null) { + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); + m.invoke(toObj, paramObj); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e) { + LOG.error("Caught exception trying to convert List returned by" + toClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } + } else { + + // Setter expects something that is not a List and + // not yang-generated. Just pass the parameter value + + LOG.trace("Parameter class " + paramClass.getName() + " is not a yang-generated class or a List"); + + if ((paramValue != null) && (paramValue.length() > 0)) { + + Object constObj = null; + + try { + // See if I can find a constructor I can use + Constructor[] constructors = paramClass.getConstructors(); + // Is there a String constructor? + for (Constructor c : constructors) { + Class[] cParms = c.getParameterTypes(); + if ((cParms != null) && (cParms.length == 1)) { + if (String.class.isAssignableFrom(cParms[0])) { + constObj = c.newInstance(paramValue); + } + } + } + + if (constObj == null) { + // Is there a Long constructor? + for (Constructor c : constructors) { + Class[] cParms = c.getParameterTypes(); + if ((cParms != null) && (cParms.length == 1)) { + if (Long.class.isAssignableFrom(cParms[0])) { + constObj = c.newInstance(Long.parseLong(paramValue)); + } + } + } + + } + + if (constObj != null) { + try { + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + constObj + ")"); + m.invoke(toObj, constObj); + foundValue = true; + } catch (Exception e2) { + LOG.error("Caught exception trying to call " + m.getName(), e2); + } + } else { + try { + boolean isAccessible = m.isAccessible(); + if (!isAccessible) { + m.setAccessible(true); + } + LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); + m.invoke(toObj, paramValue); + if (!isAccessible) { + m.setAccessible(isAccessible); + } + foundValue = true; + + } catch (Exception e) { + LOG.error("Caught exception trying to convert value returned by" + toClass.getName() + "." + m.getName() + "() to Properties entry", e); + } + } + } catch (Exception e1) { + LOG.warn("Could not find a suitable constructor for " + paramClass.getName(), e1); + } + + } + } + } + } // End of section handling "setter" method + } // End of loop through Methods + } // End of section handling yang-generated class + + if (foundValue) { + return (toObj); + } else { + return (null); + } + } + + public static void printPropertyList(PrintStream pstr, String pfx, Class toClass) { + boolean foundValue = false; + + LOG.trace("Analyzing " + toClass.getName() + " class : pfx " + pfx); + + if (isYangGenerated(toClass) && (!Identifier.class.isAssignableFrom(toClass))) { + // Class is yang generated. + LOG.trace(toClass.getName() + " is a Yang-generated class"); + + if (toClass.getName().endsWith("Key")) { + if (Identifier.class.isAssignableFrom(toClass)) { + LOG.trace(Identifier.class.getName() + " is assignable from " + toClass.getName()); + } else { + + LOG.trace(Identifier.class.getName() + " is NOT assignable from " + toClass.getName()); + } + } + + String propNamePfx = null; + if (pfx.endsWith("]")) { + propNamePfx = pfx; + } else { + + if ((pfx != null) && (pfx.length() > 0)) { + propNamePfx = pfx + "." + toLowerHyphen(toClass.getSimpleName()); + } else { + propNamePfx = toLowerHyphen(toClass.getSimpleName()); + } + + if (propNamePfx.endsWith("-builder")) { + propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-builder".length()); + } + + if (propNamePfx.endsWith("-impl")) { + propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-impl".length()); + } + } + + // Iterate through getter methods to figure out values we need to + // set + + for (Method m : toClass.getMethods()) { + LOG.trace("Is " + m.getName() + " method a getter?"); + if (isGetter(m)) { + LOG.trace(m.getName() + " is a getter"); + Class returnClass = m.getReturnType(); + + String fieldName = toLowerHyphen(m.getName().substring(3)); + fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); + + String propName = propNamePfx + "." + fieldName; + + // Is the return type a yang generated class? + if (isYangGenerated(returnClass)) { + // Is it an enum? + if (returnClass.isEnum()) { + + LOG.trace(m.getName() + " is an Enum"); + pstr.print("\n\n * " + propName); + + } else { + + String simpleName = returnClass.getSimpleName(); + + if ("Ipv4Address".equals(simpleName) || "Ipv6Address".equals(simpleName) || "IpAddress".equals(simpleName) || "IpPrefix".equals(simpleName)) { + LOG.trace(m.getName() + " is an " + simpleName); + pstr.print("\n\n * " + propName); + } else { + printPropertyList(pstr, propNamePfx, returnClass); + } + + } + } else { + + // Setter's argument is not a yang-generated class. See + // if it is a List. + + if (List.class.isAssignableFrom(returnClass)) { + + LOG.trace("Parameter class " + returnClass.getName() + " is a List"); + + // Figure out what type of args are in List and pass + // that to toList(). + + Type returnType = m.getGenericReturnType(); + Type elementType = ((ParameterizedType) returnType).getActualTypeArguments()[0]; + Class elementClass = (Class) elementType; + LOG.trace("Calling printPropertyList on list type (" + elementClass.getName() + "), pfx is (" + pfx + "), toClass is (" + toClass.getName() + ")"); + printPropertyList(pstr, propNamePfx + "." + toLowerHyphen(elementClass.getSimpleName()) + "[]", elementClass); + + } else if (!returnClass.equals(Class.class)) { + + // Setter expects something that is not a List and + // not yang-generated. Just pass the parameter value + + LOG.trace("Parameter class " + returnClass.getName() + " is not a yang-generated class or a List"); + + pstr.print("\n\n * " + propName); + + } + } + } // End of section handling "setter" method + } // End of loop through Methods + } // End of section handling yang-generated class + + } + + public static boolean isYangGenerated(Class c) { + if (c == null) { + return (false); + } else { + return (c.getName().startsWith("org.opendaylight.yang.gen.")); + } + } + + public static boolean isIpPrefix(Class c) { + + if (c == null) { + return (false); + } + String simpleName = c.getSimpleName(); + return ("IpPrefix".equals(simpleName)); + } + + public static boolean isIpv4Address(Class c) { + + if (c == null) { + return (false); + } + String simpleName = c.getSimpleName(); + return ("Ipv4Address".equals(simpleName)); + } + + public static boolean isIpv6Address(Class c) { + + if (c == null) { + return (false); + } + String simpleName = c.getSimpleName(); + return ("Ipv6Address".equals(simpleName)); + } + + public static boolean isIpAddress(Class c) { + + if (c == null) { + return (false); + } + String simpleName = c.getSimpleName(); + return ("IpAddress".equals(simpleName)); + } + + public static String toLowerHyphen(String inStr) { + if (inStr == null) { + return (null); + } + + String str = inStr.substring(0, 1).toLowerCase(); + if (inStr.length() > 1) { + str = str + inStr.substring(1); + } + + String regex = "(([a-z0-9])([A-Z]))"; + String replacement = "$2-$3"; + + String retval = str.replaceAll(regex, replacement).toLowerCase(); + + LOG.trace("Converting " + inStr + " => " + str + " => " + retval); + return (retval); + } + + //This is called when mapping the yang value back to a valid java enumeration + public static String toJavaEnum(String inStr) { + if (inStr == null) { + return (null); + } else if (inStr.length() == 0) { + return (inStr); + } + + //This will strip out all periods, which cannot be in a java enum + inStr = inStr.replaceAll("\\.", ""); + + String[] terms = inStr.split("-"); + StringBuffer sbuff = new StringBuffer(); + + //appends an _ if the string starts with a digit to make it a valid java enum + if (Character.isDigit(inStr.charAt(0))) { + sbuff.append('_'); + } + //If the string contains hyphens it will convert the string to upperCamelCase without hyphens + for (String term : terms) { + sbuff.append(term.substring(0, 1).toUpperCase()); + if (term.length() > 1) { + sbuff.append(term.substring(1)); + } + } + return (sbuff.toString()); + + } + + public static boolean isGetter(Method m) { + if (m == null) { + return (false); + } + + if (Modifier.isPublic(m.getModifiers()) && (m.getParameterTypes().length == 0)) { + if (m.getName().matches("^get[A-Z].*") && !m.getReturnType().equals(void.class)) { + if (!"getClass".equals(m.getName())) { + return (true); + } + } + + if (m.getName().matches("^get[A-Z].*") && m.getReturnType().equals(boolean.class)) { + return (true); + } + + if (m.getName().matches("^is[A-Z].*") && m.getReturnType().equals(Boolean.class)) { + return (true); + } + } + + return (false); + } + + public static boolean isSetter(Method m) { + if (m == null) { + return (false); + } + + if (Modifier.isPublic(m.getModifiers()) && (m.getParameterTypes().length == 1)) { + if (m.getName().matches("^set[A-Z].*")) { + Class[] paramTypes = m.getParameterTypes(); + if (paramTypes[0].isAssignableFrom(Identifier.class) || Identifier.class.isAssignableFrom(paramTypes[0])) { + return (false); + } else { + return (true); + } + } + + } + + return (false); + } + + public static String getFullPropertiesPath(String propertiesFileName) { + return "/opt/bvc/controller/configuration/" + propertiesFileName; + } + + //This is called when mapping a valid java enumeration back to the yang model value + public static String mapEnumeratedValue(String propertyName, String propertyValue) { + LOG.info("mapEnumeratedValue called with propertyName=" + propertyName + " and value=" + propertyValue); + String mappingKey = "yang." + propertyName + "." + propertyValue; + if (yangMappingProperties.containsKey(mappingKey)) { + return (yangMappingProperties.getProperty(mappingKey)); + } else { + LOG.info("yangMappingProperties did not contain the key " + mappingKey + " returning the original value."); + return propertyValue; + } + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/NotifyNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/NotifyNodeExecutor.java new file mode 100644 index 000000000..9f50547bd --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/NotifyNodeExecutor.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NotifyNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(NotifyNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String action = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("action"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("release node encountered - looking for resource class " + + plugin); + } + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + if (resourcePlugin != null) { + + try { + + switch (resourcePlugin.notify(resourceType, action, key, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/RecordNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/RecordNodeExecutor.java new file mode 100644 index 000000000..3c8c4c06d --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/RecordNodeExecutor.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicRecorder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RecordNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(RecordNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String outValue = "failure"; + + if (LOG.isTraceEnabled()) { + LOG.trace(node.getNodeType() + + " node encountered - looking for recorder class " + + plugin); + } + + Map parmMap = new HashMap(); + + Set> parmSet = node + .getParameterSet(); + boolean hasParms = false; + + for (Iterator> iter = parmSet + .iterator(); iter.hasNext();) { + hasParms = true; + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + SvcLogicExpression curExpr = curEnt.getValue(); + String curExprValue = SvcLogicExpressionResolver.evaluate(curExpr, + node, ctx); + + if (LOG.isTraceEnabled()) { + LOG.trace("executeRecordNode : parameter " + curName + " = " + + curExpr + " => " + curExprValue); + } + parmMap.put(curName, curExprValue); + } + + + SvcLogicRecorder recorder = getSvcLogicRecorder(plugin); + + if (recorder != null) { + + try { + recorder.record(parmMap); + } catch (SvcLogicException e) { + LOG.error("Caught exception from recorder plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicRecorder object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isTraceEnabled()) { + LOG.trace("no failure or Other branch found"); + } + } + return (nextNode); + } + + + + + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReleaseNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReleaseNodeExecutor.java new file mode 100644 index 000000000..4fee9aa8c --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReleaseNodeExecutor.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReleaseNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(ReleaseNodeExecutor.class); + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("release node encountered - looking for resource class " + + plugin); + } + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + if (resourcePlugin != null) { + + try { + + switch (resourcePlugin.release(resourceType, key, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReserveNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReserveNodeExecutor.java new file mode 100644 index 000000000..6d8035e2a --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReserveNodeExecutor.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReserveNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(ReserveNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + String pfx = SvcLogicExpressionResolver.evaluate(node.getAttribute("pfx"),node,ctx); + + + SvcLogicExpression selectExpr = node.getAttribute("select"); + String select = null; + + if (selectExpr != null) + { + select = SvcLogicExpressionResolver.evaluateAsKey(selectExpr, node, ctx); + } + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("reserve node encountered - looking for resource class " + + plugin); + } + + + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + + if (resourcePlugin != null) { + + try { + switch (resourcePlugin.reserve(resourceType, select, key, pfx, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReturnNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReturnNodeExecutor.java new file mode 100644 index 000000000..b1a2b9020 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ReturnNodeExecutor.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReturnNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(ReturnNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String status = SvcLogicExpressionResolver.evaluate( + node.getAttribute("status"), node, ctx); + + if (status != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("Returning status " + status); + } + ctx.setStatus(status); + } else { + if (LOG.isWarnEnabled()) { + LOG.warn("Return node has no status attribute set"); + } + } + + Set> parameterSet = node + .getParameterSet(); + + for (Iterator> iter = parameterSet + .iterator(); iter.hasNext();) { + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + String curValue = SvcLogicExpressionResolver.evaluate( + curEnt.getValue(), node, ctx); + + if (LOG.isDebugEnabled()) { + LOG.debug("Setting context attribute " + curName + " to " + + curValue); + } + ctx.setAttribute(curName, curValue); + } + return null; + } + + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SaveNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SaveNodeExecutor.java new file mode 100644 index 000000000..0dd555250 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SaveNodeExecutor.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SaveNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(SaveNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + String forceStr = SvcLogicExpressionResolver.evaluate( + node.getAttribute("force"), node, ctx); + String localOnlyStr = SvcLogicExpressionResolver.evaluate( + node.getAttribute("local-only"), node, ctx); + String pfx = SvcLogicExpressionResolver.evaluate( + node.getAttribute("pfx"), node, ctx); + + boolean force = "true".equalsIgnoreCase(forceStr); + boolean localOnly = "true".equalsIgnoreCase(localOnlyStr); + + Map parmMap = new HashMap(); + + Set> parmSet = node + .getParameterSet(); + boolean hasParms = false; + + for (Iterator> iter = parmSet + .iterator(); iter.hasNext();) { + hasParms = true; + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + SvcLogicExpression curExpr = curEnt.getValue(); + if (curExpr != null) { + String curExprValue = SvcLogicExpressionResolver.evaluate( + curExpr, node, ctx); + + LOG.debug("Parameter " + curName + " = " + + curExpr.asParsedExpr() + " resolves to " + + curExprValue); + + parmMap.put(curName, curExprValue); + } + } + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("save node encountered - looking for resource class " + + plugin); + } + + + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + + if (resourcePlugin != null) { + + try { + switch (resourcePlugin.save(resourceType, force, localOnly, key, + parmMap, pfx, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SetNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SetNodeExecutor.java new file mode 100644 index 000000000..18ca3d0d2 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SetNodeExecutor.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpressionFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SetNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(SetNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String ifunsetStr = SvcLogicExpressionResolver.evaluate( + node.getAttribute("only-if-unset"), node, ctx); + + boolean ifunset = "true".equalsIgnoreCase(ifunsetStr); + + Set> parameterSet = node + .getParameterSet(); + + for (Iterator> iter = parameterSet + .iterator(); iter.hasNext();) { + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + String lhsVarName = curName; + + // Resolve LHS of assignment (could contain index variables) + try { + SvcLogicExpression lhsExpr = SvcLogicExpressionFactory.parse(curName); + lhsVarName = SvcLogicExpressionResolver.resolveVariableName(lhsExpr, node, ctx); + } catch (Exception e) { + LOG.warn("Caught exception trying to resolve variable name ("+curName+")", e); + } + + + boolean setValue = true; + + if (curName.endsWith(".")) { + + // Copy subtree - value should be a variable name + SvcLogicExpression curValue = curEnt.getValue(); + + if (curValue != null) { + String rhsRoot = curValue.toString(); + + if ((rhsRoot != null) && (rhsRoot.length() > 0)) { + if (rhsRoot.endsWith(".")) { + rhsRoot = rhsRoot + .substring(0, rhsRoot.length() - 1); + } + + + // SDNGC-2321 : rhsRoot is variable name, possibly with subscript(s) to be resolved + try { + SvcLogicExpression rhsExpr = SvcLogicExpressionFactory.parse(rhsRoot); + rhsRoot = SvcLogicExpressionResolver.resolveVariableName(rhsExpr, node, ctx); + } catch (Exception e) { + LOG.warn("Caught exception trying to resolve variable name ("+rhsRoot+")", e); + } + + // See if the parameters are reversed (copying service-data to input) .. this + // was done as a workaround to earlier issue + if (curName.endsWith("-input.") && rhsRoot.startsWith("service-data")) { + LOG.warn("Arguments appear to be reversed .. will copy input to service-data instead"); + lhsVarName = rhsRoot + "."; + rhsRoot = curName.substring(0, curName.length()-1); + } + + rhsRoot = rhsRoot + "."; + String lhsPrefix = lhsVarName; + + if (lhsPrefix.endsWith(".")) { + lhsPrefix = lhsPrefix.substring(0, + lhsPrefix.length()-1); + } + int lhsPfxLength = lhsPrefix.length(); + HashMap parmsToAdd = new HashMap(); + + for (String sourceVarName : ctx.getAttributeKeySet()) { + + if (sourceVarName.startsWith(rhsRoot)) { + + String targetVar = lhsPrefix + + "." + + sourceVarName + .substring(rhsRoot.length()); + + LOG.debug("Copying " + sourceVarName + + " value to " + targetVar); + + parmsToAdd.put(targetVar, + ctx.getAttribute(sourceVarName)); + } + } + + for (String newParmName : parmsToAdd.keySet()) { + ctx.setAttribute(newParmName, parmsToAdd.get(newParmName)); + } + + } else { + // If RHS is empty, unset attributes in LHS + String lhsPrefix = lhsVarName.substring(0, + lhsVarName.length() - 1); + int lhsPfxLength = lhsPrefix.length(); + + LinkedList parmsToRemove = new LinkedList (); + + for (String curCtxVarname : ctx.getAttributeKeySet()) { + + if (curCtxVarname.startsWith(lhsPrefix)) { + LOG.debug("Unsetting " + curCtxVarname); + parmsToRemove.add(curCtxVarname); + } + } + + for (String parmName : parmsToRemove) { + ctx.setAttribute(parmName, null); + } + + } + } + + } else { + + if (ifunset) { + String ctxValue = ctx.getAttribute(lhsVarName); + + if ((ctxValue != null) && (ctxValue.length() > 0)) { + setValue = false; + LOG.debug("Attribute " + + lhsVarName + + " already set and only-if-unset is true, so not overriding"); + } + } + + if (setValue) { + String curValue = SvcLogicExpressionResolver.evaluate( + curEnt.getValue(), node, ctx); + + if (LOG.isDebugEnabled()) { + LOG.trace("Parameter value " + + curEnt.getValue().asParsedExpr() + + " resolves to " + curValue); + LOG.debug("Setting context attribute " + lhsVarName + + " to " + curValue); + } + ctx.setAttribute(lhsVarName, curValue); + } + } + } + + return null; + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java new file mode 100644 index 000000000..3bc8f0922 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.LinkedList; +import java.util.Map; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.ConfigurationException; +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; +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; + +import com.mysql.jdbc.Driver; + +public class SvcLogicActivator implements BundleActivator { + + private static final String SVCLOGIC_PROP_VAR = "SDNC_SLI_PROPERTIES"; + private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; + + private static final Map BUILTIN_NODES = new HashMap() { + { + put("block", new BlockNodeExecutor()); + put("call", new CallNodeExecutor()); + put("configure", new ConfigureNodeExecutor()); + put("delete", new DeleteNodeExecutor()); + put("execute", new ExecuteNodeExecutor()); + put("exists", new ExistsNodeExecutor()); + put("for", new ForNodeExecutor()); + put("get-resource", new GetResourceNodeExecutor()); + put("is-available", new IsAvailableNodeExecutor()); + put("notify", new NotifyNodeExecutor()); + put("record", new RecordNodeExecutor()); + put("release", new ReleaseNodeExecutor()); + put("reserve", new ReserveNodeExecutor()); + put("return", new ReturnNodeExecutor()); + put("save", new SaveNodeExecutor()); + put("set", new SetNodeExecutor()); + put("switch", new SwitchNodeExecutor()); + put("update", new UpdateNodeExecutor()); + put("break", new BreakNodeExecutor()); + + } + }; + + private static LinkedList registrations = new LinkedList(); + + private static HashMap adaptorMap = null; + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicActivator.class); + + private static Properties props = null; + + private static BundleContext bundleCtx = null; + + private static SvcLogicService svcLogicServiceImpl = null; + + @Override + public void start(BundleContext ctx) throws Exception { + + LOG.info("Activating SLI"); + + bundleCtx = ctx; + + // Read properties + props = new Properties(); + String propPath = System.getenv(SVCLOGIC_PROP_VAR); + + if (propPath == null) { + String propDir = System.getenv(SDNC_CONFIG_DIR); + if (propDir == null) { + + propDir = "/opt/sdnc/data/properties"; + } + propPath = propDir + "/svclogic.properties"; + LOG.warn("Environment variable "+SVCLOGIC_PROP_VAR+" unset - defaulting to "+propPath); + } + + File propFile = new File(propPath); + + if (!propFile.exists()) { + + throw new ConfigurationException( + "Missing configuration properties file : " + + propFile); + } + try { + + props.load(new FileInputStream(propFile)); + } catch (Exception e) { + throw new ConfigurationException( + "Could not load properties file " + propPath, e); + + } + + + if (registrations == null) { + + registrations = new LinkedList(); + } + + // Advertise SvcLogicService + svcLogicServiceImpl = new SvcLogicServiceImpl(); + + LOG.info("SLI: Registering service " + SvcLogicService.NAME + + " in bundle " + ctx.getBundle().getSymbolicName()); + ServiceRegistration reg = ctx.registerService(SvcLogicService.NAME, + svcLogicServiceImpl, null); + registrations.add(reg); + + // Initialize SvcLogicStore + try { + SvcLogicStore store = getStore(); + registerNodeTypes(store); + } catch (ConfigurationException e) { + LOG.warn("Could not initialize SvcLogicScore", e); + } + + LOG.info("SLI - done registering services"); + } + + @Override + public void stop(BundleContext ctx) throws Exception { + + if (registrations != null) { + for (ServiceRegistration reg : registrations) { + ServiceReference regRef = reg.getReference(); + /* Don't bother to remove node types from table + String nodeType = (String) regRef.getProperty("nodeType"); + if (nodeType != null) { + LOG.info("SLI - unregistering node type " + nodeType); + store.unregisterNodeType(nodeType); + } + */ + reg.unregister(); + } + registrations = null; + } + } + + public static SvcLogicStore getStore() throws SvcLogicException { + // Create and initialize SvcLogicStore object - used to access + // saved service logic. + + SvcLogicStore store = null; + + try { + Driver dvr = new Driver(); + store = SvcLogicStoreFactory.getSvcLogicStore(props); + } catch (Exception e) { + throw new ConfigurationException( + "Could not get service logic store", e); + + } + + try { + store.init(props); + } catch (Exception e) { + throw new ConfigurationException( + "Could not get service logic store", e); + } + + return(store); + } + + private static void registerNodeTypes(SvcLogicStore store) throws SvcLogicException { + + if (store == null) { + return; + } + // Advertise built-in node executors + LOG.info("SLI : Registering built-in node executors"); + Hashtable propTable = new Hashtable(); + + for (String nodeType : BUILTIN_NODES.keySet()) { + LOG.info("SLI - registering node type " + nodeType); + propTable.clear(); + propTable.put("nodeType", nodeType); + + ServiceRegistration reg = bundleCtx.registerService(SvcLogicNodeExecutor.class.getName(), + BUILTIN_NODES.get(nodeType), propTable); + registrations.add(reg); + + store.registerNodeType(nodeType); + + LOG.info("SLI - registering node executor"); + + ((SvcLogicServiceImpl)svcLogicServiceImpl).registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); + + } + + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicAdaptorFactory.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicAdaptorFactory.java new file mode 100644 index 000000000..1bc8e0f8d --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicAdaptorFactory.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; + +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SvcLogicAdaptorFactory { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicAdaptorFactory.class); + + private static HashMap adaptorMap = new HashMap(); + + public static void registerAdaptor(SvcLogicAdaptor adaptor) { + String name = adaptor.getClass().getName(); + LOG.info("Registering adaptor " + name); + adaptorMap.put(name, adaptor); + + } + + public static void unregisterAdaptor(String name) { + if (adaptorMap.containsKey(name)) { + LOG.info("Unregistering " + name); + adaptorMap.remove(name); + } + } + + public static SvcLogicAdaptor getInstance(String name) { + if (adaptorMap.containsKey(name)) { + return (adaptorMap.get(name)); + } else { + BundleContext bctx = null; + try + { + bctx = FrameworkUtil.getBundle(SvcLogicAdaptorFactory.class) + .getBundleContext(); + } + catch (Exception e) + { + LOG.debug("Caught exception trying to locate device adaptor "+name, e); + return(null); + } + + ServiceReference sref = bctx.getServiceReference(name); + + if (sref != null) { + SvcLogicAdaptor adaptor = (SvcLogicAdaptor) bctx + .getService(sref); + + if (adaptor != null) { + registerAdaptor(adaptor); + + return (adaptor); + } + return (null); + } + } + return(null); + } +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolver.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolver.java new file mode 100644 index 000000000..01851cc62 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolver.java @@ -0,0 +1,604 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicAtom; +import org.onap.ccsdk.sli.core.sli.SvcLogicBinaryExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicFunctionCall; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicVariableTerm; +import org.onap.ccsdk.sli.core.sli.SvcLogicAtom.AtomType; +import org.onap.ccsdk.sli.core.sli.SvcLogicBinaryExpression.OperatorType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SvcLogicExpressionResolver { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicExpressionResolver.class); + + public static String evaluate(SvcLogicExpression expr, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + if (expr == null) { + return (null); + } + + + + if (expr instanceof SvcLogicAtom) { + SvcLogicAtom atom = (SvcLogicAtom) expr; + + AtomType atomType = atom.getAtomType(); + switch (atomType) { + case NUMBER: + case STRING: + return (atom.toString()); + case CONTEXT_VAR: + case IDENTIFIER: + + String varName = resolveVariableName(atom, node, ctx); + + if (atomType == AtomType.CONTEXT_VAR) + { + LOG.trace("Evaluating context variable $"+varName); + + String varValue = ctx.getAttribute(varName); + + if (varValue == null) { + LOG.trace("Context variable $"+varName+" unset - treating as empty string"); + varValue = ""; + } + + return (varValue); + } + SvcLogicExpression parm = node.getParameter(varName); + if (parm != null) { + LOG.trace("Evaluating value of parameter "+varName+": "+parm.asParsedExpr()); + + return (evaluate(parm, node, ctx)); + } + else + { + return(varName); + } + default: + return(null); + } + + } else if (expr instanceof SvcLogicBinaryExpression) { + SvcLogicBinaryExpression binExpr = (SvcLogicBinaryExpression) expr; + List operators = binExpr.getOperators(); + if (operators.isEmpty()) + { + List operands = binExpr.getOperands(); + if (operands.size() == 1) + { + LOG.trace("SvcLogicBinaryExpression as no operator and one operand - evaluating its operand"); + return(evaluate(operands.get(0), node, ctx)); + } + else + { + if (operands.isEmpty()) + { + LOG.error("SvcLogicBinaryExpression has no operators and no operands - evaluating value as null"); + } + else + { + LOG.error("SvcLogicBinaryExpression has no operators and "+operands.size()+" operands - evaluating value as null"); + } + return(null); + } + } + switch (operators.get(0)) { + case addOp: + case subOp: + case multOp: + case divOp: + return(evalArithExpression(binExpr, node, ctx)); + case equalOp: + case neOp: + case ltOp: + case leOp: + case gtOp: + case geOp: + return (evalCompareExpression(binExpr, node, ctx)); + case andOp: + case orOp: + return(evalLogicExpression(binExpr, node, ctx)); + + default: + return(null); + } + } + else if (expr instanceof SvcLogicFunctionCall) + { + return(evalFunctionCall((SvcLogicFunctionCall)expr, node, ctx)); + } + else + { + throw new SvcLogicException("Unrecognized expression type ["+expr+"]"); + } + } + + private static String evalArithExpression(SvcLogicBinaryExpression binExpr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { + List operands = binExpr.getOperands(); + List operators = binExpr.getOperators(); + if (operands.size() != (operators.size()+1)) + { + throw new SvcLogicException("Invalid expression ("+binExpr+")"); + } + String retval = evaluate(operands.get(0), node, ctx); + String retsval = retval; + long retlval = 0; + boolean valueIsLong = false; + + int i = 1; + try + { + + if ((retval.length() > 0) && StringUtils.isNumeric(retval)) + { + retlval = Long.parseLong(retval); + valueIsLong = true; + } + for (OperatorType operator: operators) + { + String curOperandValue = evaluate(operands.get(i++), node, ctx); + switch(operator) { + case addOp: + retsval = retsval + curOperandValue; + if (valueIsLong) + { + if ((curOperandValue.length() > 0) && StringUtils.isNumeric(curOperandValue) ) + { + retlval = retlval + Long.parseLong(curOperandValue); + } + else + { + valueIsLong = false; + } + } + break; + case subOp: + retlval = retlval - Long.parseLong(curOperandValue); + break; + case multOp: + retlval = retlval * Long.parseLong(curOperandValue); + break; + case divOp: + retlval = retlval / Long.parseLong(curOperandValue); + break; + } + + } + } + catch (NumberFormatException e1) + { + throw new SvcLogicException("Illegal value in arithmetic expression", e1); + } + + if (valueIsLong) + { + return("" + retlval); + } + else + { + return(retsval); + } + + } + + + + private static String evalCompareExpression(SvcLogicBinaryExpression expr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException + { + + List operators = expr.getOperators(); + List operands = expr.getOperands(); + + if ((operators.size() != 1) || (operands.size() != 2)) + { + throw new SvcLogicException ("Invalid comparison expression : "+expr); + } + + OperatorType operator = operators.get(0); + String op1Value = evaluate(operands.get(0), node, ctx); + String op2Value = evaluate(operands.get(1), node, ctx); + + if ((StringUtils.isNotEmpty(op1Value) && StringUtils.isNumeric(op1Value) && StringUtils.isNotEmpty(op2Value) && StringUtils.isNumeric(op2Value))) + { + try + { + double op1dbl = Double.parseDouble(op1Value); + double op2dbl = Double.parseDouble(op2Value); + + switch(operator) + { + case equalOp: + return(Boolean.toString(op1dbl == op2dbl)); + case neOp: + return(Boolean.toString(op1dbl != op2dbl)); + case ltOp: + return(Boolean.toString(op1dbl < op2dbl)); + case leOp: + return(Boolean.toString(op1dbl <= op2dbl)); + case gtOp: + return(Boolean.toString(op1dbl > op2dbl)); + case geOp: + return(Boolean.toString(op1dbl >= op2dbl)); + default: + return(null); + } + } + catch (NumberFormatException e) + { + throw new SvcLogicException("Caught exception trying to compare numeric values", e); + } + } + else + { + + int compResult = 0; + + if (op1Value == null) { + compResult = -1; + } else if (op2Value == null ) { + compResult = 1; + } else { + compResult = op1Value.compareToIgnoreCase(op2Value); + } + + switch(operator) + { + case equalOp: + return(Boolean.toString(compResult == 0)); + case neOp: + return(Boolean.toString(compResult != 0)); + case ltOp: + return(Boolean.toString(compResult < 0)); + case leOp: + return(Boolean.toString(compResult <= 0)); + case gtOp: + return(Boolean.toString(compResult > 0)); + case geOp: + return(Boolean.toString(compResult >= 0)); + default: + return(null); + } + } + + } + + private static String evalLogicExpression(SvcLogicBinaryExpression expr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException + { + boolean retval; + + List operands = expr.getOperands(); + List operators = expr.getOperators(); + + if (operands.size() != (operators.size()+1)) + { + throw new SvcLogicException("Invalid expression ("+expr+")"); + } + + try + { + retval = Boolean.parseBoolean(evaluate(operands.get(0), node, ctx)); + int i = 1; + for (OperatorType operator : operators) + { + if (operator == OperatorType.andOp) + { + retval = retval && Boolean.parseBoolean(evaluate(operands.get(i++), node, ctx)); + } + else + { + + retval = retval || Boolean.parseBoolean(evaluate(operands.get(i++), node, ctx)); + } + + } + } + catch (Exception e) + { + throw new SvcLogicException("Invalid expression ("+expr+")"); + } + + + return(Boolean.toString(retval)); + } + + private static String evalFunctionCall(SvcLogicFunctionCall func, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException + { + String funcName = func.getFunctionName(); + List operands = func.getOperands(); + + if ("length".equalsIgnoreCase(funcName)) + { + + if (operands.size() == 1) + { + String opValue = evaluate(operands.get(0), node, ctx); + return(""+opValue.length()); + } + else + { + throw new SvcLogicException("Invalid call to length() function"); + } + } + else if ("substr".equalsIgnoreCase(funcName)) + { + if (operands.size() == 3) + { + String op1Value = evaluate(operands.get(0), node, ctx); + String op2Value = evaluate(operands.get(1), node, ctx); + String op3Value = evaluate(operands.get(2), node, ctx); + + if (!StringUtils.isNumeric(op2Value) || !StringUtils.isNumeric(op3Value)) + { + throw new SvcLogicException("Invalid arguments to substr() function"); + } + + try + { + return(op1Value.substring(Integer.parseInt(op2Value), Integer.parseInt(op3Value))); + } + catch (Exception e) + { + throw new SvcLogicException("Caught exception trying to take substring", e); + } + } + else + { + + throw new SvcLogicException("Invalid call to substr() function"); + } + + } + else if ("toUpperCase".equalsIgnoreCase(funcName)) + { + if (operands.size() == 1) + { + String opValue = evaluate(operands.get(0), node, ctx); + if (opValue != null) { + return(opValue.toUpperCase()); + } else { + return(""); + } + } + else + { + throw new SvcLogicException("Invalid call to toUpperCase() function"); + } + } + else if ("toLowerCase".equalsIgnoreCase(funcName)) + { + if (operands.size() == 1) + { + String opValue = evaluate(operands.get(0), node, ctx); + if (opValue != null) { + return(opValue.toLowerCase()); + } else { + return(""); + } + } + else + { + throw new SvcLogicException("Invalid call to toLowerCase() function"); + } + } + else if ("convertBase".equalsIgnoreCase(funcName)) { + int fromBase = 10; + int toBase = 10; + String srcString = ""; + + if (operands.size() == 2) + { + fromBase = 10; + srcString = evaluate(operands.get(0), node, ctx); + toBase = Integer.parseInt(evaluate(operands.get(1), node, ctx)); + } else if (operands.size() == 3) { + + srcString = evaluate(operands.get(0), node, ctx); + fromBase = Integer.parseInt(evaluate(operands.get(1), node, ctx)); + toBase = Integer.parseInt(evaluate(operands.get(2), node, ctx)); + } else { + throw new SvcLogicException("Invalid call to convertBase() function"); + } + + long srcValue = Long.parseLong(srcString, fromBase); + return(Long.toString(srcValue, toBase)); + } + else + { + throw new SvcLogicException("Unrecognized function ("+funcName+")"); + } + + } + + public static String evaluateAsKey(SvcLogicExpression expr, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + if (expr == null) { + return (null); + } + + + + if (expr instanceof SvcLogicAtom) { + SvcLogicAtom atom = (SvcLogicAtom) expr; + + AtomType atomType = atom.getAtomType(); + StringBuffer varNameBuff = new StringBuffer(); + switch (atomType) { + case NUMBER: + return (atom.toString()); + case STRING: + return("'"+atom.toString()+"'"); + case CONTEXT_VAR: + case IDENTIFIER: + boolean needDot = false; + for (SvcLogicExpression term : atom.getOperands()) + { + if (needDot) + { + varNameBuff.append("."); + } + if (term instanceof SvcLogicVariableTerm) + { + SvcLogicVariableTerm vterm = (SvcLogicVariableTerm) term; + varNameBuff.append(vterm.getName()); + if (vterm.numOperands() > 0) + { + varNameBuff.append("["); + varNameBuff.append(evaluate(vterm.getSubscript(), node, ctx)); + varNameBuff.append("]"); + + } + } + else + { + varNameBuff.append(term.toString()); + } + needDot = true; + } + + String varName = varNameBuff.toString(); + LOG.debug("Evaluating context variable $"+varName); + String ctxValue = ctx.getAttribute(varName); + if (ctxValue == null) + { + return(null); + } + if (StringUtils.isNumeric(ctxValue)) + { + return(ctxValue); + } + else + { + return("'"+ctxValue+"'"); + } + + default: + return(null); + } + + } else if (expr instanceof SvcLogicBinaryExpression) { + SvcLogicBinaryExpression binExpr = (SvcLogicBinaryExpression) expr; + List operators = binExpr.getOperators(); + List operands = binExpr.getOperands(); + if (operators.isEmpty()) + { + if (operands.size() == 1) + { + LOG.debug("SvcLogicBinaryExpression as no operator and one operand - evaluating its operand"); + return(evaluateAsKey(operands.get(0), node, ctx)); + } + else + { + if (operands.isEmpty()) + { + LOG.error("SvcLogicBinaryExpression has no operators and no operands - evaluating value as null"); + } + else + { + LOG.error("SvcLogicBinaryExpression has no operators and "+operands.size()+" operands - evaluating value as null"); + } + return(null); + } + } + StringBuffer sbuff = new StringBuffer(); + sbuff.append(evaluateAsKey(operands.get(0), node, ctx)); + int i = 1; + for (OperatorType operator : operators) + { + sbuff.append(" "); + sbuff.append(operator.toString()); + sbuff.append(" "); + sbuff.append(evaluateAsKey(operands.get(i++), node,ctx)); + } + return(sbuff.toString()); + } + else if (expr instanceof SvcLogicFunctionCall) + { + StringBuffer sbuff = new StringBuffer(); + SvcLogicFunctionCall funcCall = (SvcLogicFunctionCall) expr; + sbuff.append(funcCall.getFunctionName()); + sbuff.append("("); + boolean needComma = false; + for (SvcLogicExpression operand : funcCall.getOperands()) + { + if (needComma) + { + sbuff.append(","); + } + else + { + needComma = true; + } + sbuff.append(evaluateAsKey(operand, node, ctx)); + } + sbuff.append(")"); + return(sbuff.toString()); + } + else + { + throw new SvcLogicException("Unrecognized expression type ["+expr+"]"); + } + } + + public static String resolveVariableName(SvcLogicExpression atom, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException + { + StringBuffer varNameBuff = new StringBuffer(); + + boolean needDot = false; + for (SvcLogicExpression term : atom.getOperands()) + { + if (needDot) + { + varNameBuff.append("."); + } + if (term instanceof SvcLogicVariableTerm) + { + SvcLogicVariableTerm vterm = (SvcLogicVariableTerm) term; + varNameBuff.append(vterm.getName()); + if (vterm.numOperands() > 0) + { + varNameBuff.append("["); + varNameBuff.append(evaluate(vterm.getSubscript(), node, ctx)); + varNameBuff.append("]"); + } + } + else + { + varNameBuff.append(term.toString()); + } + needDot = true; + } + return(varNameBuff.toString()); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java new file mode 100644 index 000000000..8d72f7a8b --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicRecorder; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class SvcLogicNodeExecutor { + + public abstract SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException; + + private static final Logger LOG = LoggerFactory.getLogger(SvcLogicNodeExecutor.class); + + protected String evaluateNodeTest(SvcLogicNode node, SvcLogicContext ctx) + throws SvcLogicException { + if (node == null) { + return null; + } + + return (SvcLogicExpressionResolver.evaluate(node.getAttribute("test"), + node, ctx)); + + } + + protected SvcLogicStore getStore() throws SvcLogicException { + return SvcLogicActivator.getStore(); + } + + protected SvcLogicAdaptor getAdaptor(String adaptorName) { + return SvcLogicAdaptorFactory.getInstance(adaptorName); + } + + protected SvcLogicResource getSvcLogicResource(String plugin) { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) + .getBundleContext(); + + ServiceReference sref = bctx.getServiceReference(plugin); + if (sref != null) { + SvcLogicResource resourcePlugin = (SvcLogicResource) bctx + .getService(sref); + return resourcePlugin; + } + else { + LOG.warn("Could not find service reference object for plugin " + plugin); + return null; + } + } + + protected SvcLogicRecorder getSvcLogicRecorder(String plugin) { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) + .getBundleContext(); + + ServiceReference sref = bctx.getServiceReference(plugin); + if (sref != null) { + SvcLogicRecorder resourcePlugin = (SvcLogicRecorder) bctx + .getService(sref); + return resourcePlugin; + } + else { + return null; + } + } + + protected SvcLogicJavaPlugin getSvcLogicJavaPlugin(String pluginName){ + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) + .getBundleContext(); + + ServiceReference sref = bctx.getServiceReference(pluginName); + + if (sref == null) { + LOG.warn("Could not find service reference object for plugin " + pluginName); + return null; + } else { + SvcLogicJavaPlugin plugin = (SvcLogicJavaPlugin) bctx + .getService(sref); + return plugin; + } + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java new file mode 100644 index 000000000..cfba5866e --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; + +public interface SvcLogicService { + + public static final String NAME = "org.openecomp.sdnc.sli.provider.SvcLogicService"; + + // public SvcLogicContext execute(SvcLogicGraph graph, SvcLogicContext ctx) throws SvcLogicException; + /** + * Check for existence of a directed graph + * @param module - module name + * @param rpc - rpc name + * @param version - version. If null, looks for active version + * @param mode - mode (sync/async) + * @return true if directed graph found, false otherwise + * @throws SvcLogicException + */ + public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException; + + /** + * Execute a directed graph + * + * @param module - module name + * @param rpc - rpc name + * @param version - version. If null, use active version + * @param mode - mode (sync/async) + * @param parms - parameters, used to set SvcLogicContext attributes + * @return final values of attributes from SvcLogicContext, as Properties + * @throws SvcLogicException + * + * + * @deprecated use execute(String module, String rpc, String version, String mode, DOMDataBroker dataBroker) instead + */ + @Deprecated + public Properties execute(String module, String rpc, String version, String mode, Properties parms) throws SvcLogicException; + + /** + * Execute a directed graph + * + * @param module - module name + * @param rpc - rpc name + * @param version - version. If null, use active version + * @param mode - mode (sync/async) + * @param parms - parameters, used to set SvcLogicContext attributes + * @param domDataBroker - DOMDataBroker object + * @return final values of attributes from SvcLogicContext, as Properties + * @throws SvcLogicException + */ + public Properties execute(String module, String rpc, String version, String mode, Properties parms, DOMDataBroker domDataBroker) throws SvcLogicException; + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java new file mode 100644 index 000000000..c0ee4c2c1 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java @@ -0,0 +1,272 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.MetricLogger; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceEvent; +import org.osgi.framework.ServiceListener; +import org.osgi.framework.ServiceReference; +import org.osgi.util.tracker.ServiceTracker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +public class SvcLogicServiceImpl implements SvcLogicService { + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicServiceImpl.class); + + private HashMap nodeExecutors = null; + + private BundleContext bctx = null; + + private void registerExecutors() { + + LOG.info("Entered register executors"); + if (bctx == null) { + bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + } + + if (nodeExecutors == null) { + nodeExecutors = new HashMap(); + } + + LOG.info("Opening service tracker"); + ServiceTracker tracker = new ServiceTracker(bctx, + SvcLogicNodeExecutor.class.getName(), null); + + tracker.open(); + + ServiceListener listener = new ServiceListener() { + + public void serviceChanged(ServiceEvent ev) { + ServiceReference sr = ev.getServiceReference(); + switch (ev.getType()) { + case ServiceEvent.REGISTERED: { + registerExecutor(sr); + } + break; + case ServiceEvent.UNREGISTERING: { + unregisterExecutor(sr); + } + break; + } + } + }; + + LOG.info("Adding service listener"); + String filter = "(objectclass=" + SvcLogicNodeExecutor.class.getName() + + ")"; + try { + bctx.addServiceListener(listener, filter); + ServiceReference[] srl = bctx.getServiceReferences( + SvcLogicNodeExecutor.class.getName(), null); + for (int i = 0; srl != null && i < srl.length; i++) { + listener.serviceChanged(new ServiceEvent( + ServiceEvent.REGISTERED, srl[i])); + } + } catch (InvalidSyntaxException e) { + e.printStackTrace(); + } + LOG.info("Done registerExecutors"); + } + + public void registerExecutor(ServiceReference sr) { + + String nodeName = (String) sr.getProperty("nodeType"); + if (nodeName != null) { + + SvcLogicNodeExecutor executor = null; + + try { + executor = (SvcLogicNodeExecutor) bctx.getService(sr); + } catch (Exception e) { + LOG.error("Cannot get service executor for " + nodeName); + return; + } + + registerExecutor(nodeName, executor); + + } + } + + public void registerExecutor(String nodeName, SvcLogicNodeExecutor executor) + { + if (nodeExecutors == null) { + nodeExecutors = new HashMap(); + } + LOG.info("SLI - registering executor for node type "+nodeName); + nodeExecutors.put(nodeName, executor); + } + + public void unregisterExecutor(ServiceReference sr) { + String nodeName = (String) sr.getProperty("nodeType"); + + if (nodeName != null) { + + unregisterExecutor(nodeName); + + } + + } + + public void unregisterExecutor(String nodeName) + { + + LOG.info("SLI - unregistering executor for node type "+nodeName); + nodeExecutors.remove(nodeName); + } + + + + + public SvcLogicContext execute(SvcLogicGraph graph, SvcLogicContext ctx) + throws SvcLogicException { + + if (nodeExecutors == null) { + registerExecutors(); + } + + // Set service name in MDC to reference current working directed graph + MDC.put(MetricLogger.SERVICE_NAME, graph.getModule()+":"+graph.getRpc()+"/v"+graph.getVersion()); + + SvcLogicNode curNode = graph.getRootNode(); + LOG.info("About to execute graph " + graph.toString()); + + + + while (curNode != null) { + LOG.info("About to execute node # "+curNode.getNodeId()+" ("+curNode.getNodeType()+")"); + + SvcLogicNode nextNode = executeNode(curNode, ctx); + curNode = nextNode; + } + + return (ctx); + } + + + public SvcLogicNode executeNode(SvcLogicNode node, SvcLogicContext ctx) + throws SvcLogicException { + if (node == null) { + return (null); + } + + if (LOG.isDebugEnabled()) { + LOG.debug("Executing node " + node.getNodeId()); + } + + SvcLogicNodeExecutor executor = nodeExecutors.get(node.getNodeType()); + + if (executor != null) { + LOG.debug("Executing node executor for node type "+node.getNodeType()+" - "+executor.getClass().getName()); + return (executor.execute(this, node, ctx)); + } else { + if (LOG.isDebugEnabled()) { + LOG.debug(node.getNodeType() + " node not implemented"); + } + SvcLogicNode nextNode = node.getOutcomeValue("failure"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute failure branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no failure or Other branch found"); + } + } + return (nextNode); + } + + } + + @Override + public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException + { + SvcLogicStore store = SvcLogicActivator.getStore(); + + return (store.hasGraph(module, rpc, version, mode)); + } + + @Override + public Properties execute(String module, String rpc, String version, String mode, Properties props) + throws SvcLogicException { + return(execute(module, rpc, version, mode, props, null)); + } + + + @Override + public Properties execute(String module, String rpc, String version, String mode, + Properties props, DOMDataBroker domDataBroker) throws SvcLogicException { + + + // See if there is a service logic defined + // + SvcLogicStore store = SvcLogicActivator.getStore(); + + LOG.info("Fetching service logic from data store"); + SvcLogicGraph graph = store.fetch(module, rpc, version, mode); + + + + if (graph == null) + { + Properties retProps = new Properties(); + retProps.setProperty("error-code", "401"); + retProps.setProperty("error-message", "No service logic found for ["+module+","+rpc+","+version+","+mode+"]"); + return(retProps); + + } + + SvcLogicContext ctx = new SvcLogicContext(props); + ctx.setAttribute("currentGraph", graph.toString()); + ctx.setAttribute("X-ECOMP-RequestID", MDC.get("X-ECOMP-RequestID")); + ctx.setDomDataBroker(domDataBroker); + + execute(graph, ctx); + + return(ctx.toProperties()); + } + + + + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SwitchNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SwitchNodeExecutor.java new file mode 100644 index 000000000..ac0c428b3 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SwitchNodeExecutor.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SwitchNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(SwitchNodeExecutor.class); + + @Override + + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + + String testResult = evaluateNodeTest(node, ctx); + + if (LOG.isDebugEnabled()) { + LOG.debug("Executing switch node"); + + + LOG.debug("test expression (" + node.getAttribute("test") + + ") evaluates to " + testResult); + } + + SvcLogicNode nextNode = node.getOutcomeValue(testResult); + + if (LOG.isDebugEnabled()) { + if (nextNode != null) { + LOG.debug("Next node to execute is node " + nextNode.getNodeId()); + } else { + LOG.debug("No next node found"); + } + } + return (nextNode); + + } +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/UpdateNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/UpdateNodeExecutor.java new file mode 100644 index 000000000..48510e60f --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/UpdateNodeExecutor.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UpdateNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory + .getLogger(UpdateNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + + String plugin = SvcLogicExpressionResolver.evaluate( + node.getAttribute("plugin"), node, ctx); + String resourceType = SvcLogicExpressionResolver.evaluate( + node.getAttribute("resource"), node, ctx); + String key = SvcLogicExpressionResolver.evaluateAsKey( + node.getAttribute("key"), node, ctx); + String pfx = SvcLogicExpressionResolver.evaluate( + node.getAttribute("pfx"), node, ctx); + + + Map parmMap = new HashMap(); + + Set> parmSet = node + .getParameterSet(); + boolean hasParms = false; + + for (Iterator> iter = parmSet + .iterator(); iter.hasNext();) { + hasParms = true; + Map.Entry curEnt = iter.next(); + String curName = curEnt.getKey(); + SvcLogicExpression curExpr = curEnt.getValue(); + if (curExpr != null) { + String curExprValue = SvcLogicExpressionResolver.evaluate( + curExpr, node, ctx); + + LOG.debug("Parameter " + curName + " = " + + curExpr.asParsedExpr() + " resolves to " + + curExprValue); + + parmMap.put(curName, curExprValue); + } + } + + String outValue = "failure"; + + if (LOG.isDebugEnabled()) { + LOG.debug("save node encountered - looking for resource class " + + plugin); + } + + + SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); + + + if (resourcePlugin != null) { + + try { + switch (resourcePlugin.update(resourceType, key, + parmMap, pfx, ctx)) { + case SUCCESS: + outValue = "success"; + break; + case NOT_FOUND: + outValue = "not-found"; + break; + case FAILURE: + default: + outValue = "failure"; + } + } catch (SvcLogicException e) { + LOG.error("Caught exception from resource plugin", e); + outValue = "failure"; + } + } else { + LOG.warn("Could not find SvcLogicResource object for plugin " + + plugin); + } + + SvcLogicNode nextNode = node.getOutcomeValue(outValue); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute " + outValue + " branch"); + } + return (nextNode); + } + + nextNode = node.getOutcomeValue("Other"); + if (nextNode != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("about to execute Other branch"); + } + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("no "+outValue+" or Other branch found"); + } + } + return (nextNode); + } + +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/WhileNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/WhileNodeExecutor.java new file mode 100644 index 000000000..bc3cc773b --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/WhileNodeExecutor.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.BreakNodeException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WhileNodeExecutor extends SvcLogicNodeExecutor { + + private static final Logger LOG = LoggerFactory.getLogger(WhileNodeExecutor.class); + + @Override + public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { + + String testResult = evaluateNodeTest(node, ctx); + SvcLogicExpression silentFailureExpr = node.getAttribute("do"); + String doWhile = SvcLogicExpressionResolver.evaluate(silentFailureExpr, node, ctx); + if ("true".equals(doWhile)) { + LOG.debug("While loop will execute once regardless of expression because do is set to true"); + } + + try { + while ("true".equals(testResult) || "true".equals(doWhile)) { + if (!"true".equals(doWhile)) { + LOG.debug("Test expression (" + node.getAttribute("test") + ") evaluates to true, executing loop."); + } + int numOutcomes = node.getNumOutcomes() + 1; + for (int i = 0; i < numOutcomes; i++) { + SvcLogicNode nextNode = node.getOutcomeValue("" + (i + 1)); + if (nextNode != null) { + while (nextNode != null) { + nextNode = svc.executeNode(nextNode, ctx); + } + } else { + if ("true".equals(doWhile)) { + LOG.debug("Do executed, will only execute again if test expression is true."); + doWhile = "false"; + } + testResult = evaluateNodeTest(node, ctx); + LOG.debug("test expression (" + node.getAttribute("test") + ") evaluates to " + testResult); + } + } + } + LOG.debug("testResult was " + testResult + " which is not equal to true, exiting while loop."); + } catch (BreakNodeException e) { + LOG.debug("WhileNodeExecutor caught break"); + } + return (null); + } + +} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BlockNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BlockNodeExecutor.java deleted file mode 100644 index f83154d9e..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BlockNodeExecutor.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BlockNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(BlockNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) - throws SvcLogicException { - - SvcLogicExpression atomicExpr = node.getAttribute("atomic"); - String atomicStr = SvcLogicExpressionResolver.evaluate(atomicExpr, node, ctx); - boolean isAtomic = "true".equalsIgnoreCase(atomicStr); - - // Initialize status to success so that at least one outcome will execute - ctx.setStatus("success"); - - int numOutcomes = node.getNumOutcomes(); - - for (int i = 0; i < numOutcomes; i++) { - if ("failure".equals(ctx.getStatus()) && isAtomic) { - LOG.info("Block - stopped executing nodes due to failure status"); - return(null); - } - - SvcLogicNode nextNode = node.getOutcomeValue("" + (i + 1)); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Block - executing outcome " + (i + 1)); - } - while (nextNode != null) - { - nextNode = svc.executeNode(nextNode, ctx); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Block - done: no outcome " + (i + 1)); - } - } - } - - return (null); - } - - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BreakNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BreakNodeExecutor.java deleted file mode 100644 index 0f8719c8a..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/BreakNodeExecutor.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.BreakNodeException; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BreakNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory.getLogger(BreakNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { - String message = "BreakNodeExecutor encountered break with nodeId " + node.getNodeId(); - LOG.debug(message); - throw new BreakNodeException(message); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/CallNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/CallNodeExecutor.java deleted file mode 100644 index 7b79c19f6..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/CallNodeExecutor.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicGraph; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CallNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(CallNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) - throws SvcLogicException { - - String outValue = "not-found"; - - SvcLogicGraph myGraph = node.getGraph(); - - if (myGraph == null) - { - LOG.debug("execute: getGraph returned null"); - } - else - { - LOG.debug("execute: got SvcLogicGraph"); - } - - SvcLogicExpression moduleExpr = null; - - String module = null; - - moduleExpr = node.getAttribute("module"); - if (moduleExpr != null) - { - module = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); - } - - if ((module == null) || (module.length() == 0)) - { - if (myGraph != null) - { - module = myGraph.getModule(); - LOG.debug("myGraph.getModule() returned "+module); - } - } - - SvcLogicExpression rpcExpr = null; - String rpc = null; - rpcExpr = node.getAttribute("rpc"); - if (rpcExpr != null) - { - rpc = SvcLogicExpressionResolver.evaluate(rpcExpr, node, ctx); - } - - if ((rpc == null) || (rpc.length() == 0)) - { - if (myGraph != null) - { - rpc = myGraph.getRpc(); - LOG.debug("myGraph.getRpc() returned "+rpc); - } - } - - String mode = null; - - moduleExpr = node.getAttribute("mode"); - if (moduleExpr != null) - { - mode = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); - } - - if ((mode == null) || (mode.length() == 0)) - { - if (myGraph != null) - { - mode = myGraph.getMode(); - - LOG.debug("myGraph.getMode() returned "+mode); - } - } - - String version = null; - - moduleExpr = node.getAttribute("version"); - if (moduleExpr != null) - { - version = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); - } - - String parentGraph = ctx.getAttribute("currentGraph"); - ctx.setAttribute("parentGraph", parentGraph); - - SvcLogicStore store = getStore(); - - if (store != null) { - SvcLogicGraph calledGraph = store.fetch(module, rpc, version, mode); - LOG.debug("Parent " + parentGraph + " is calling child " + calledGraph.toString()); - ctx.setAttribute("currentGraph", calledGraph.toString()); - if (calledGraph != null) { - svc.execute(calledGraph, ctx); - - outValue = ctx.getStatus(); - } else { - LOG.error("Could not find service logic for [" + module + "," + rpc + "," + version + "," + mode + "]"); - } - } - else - { - LOG.debug("Could not get SvcLogicStore reference"); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - ctx.setAttribute("currentGraph", parentGraph); - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no " + outValue + " or Other branch found"); - } - } - ctx.setAttribute("currentGraph", parentGraph); - ctx.setAttribute("parentGraph", null); - - return (nextNode); - - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ConfigureNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ConfigureNodeExecutor.java deleted file mode 100644 index a3f2874fb..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ConfigureNodeExecutor.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicAdaptor; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConfigureNodeExecutor extends SvcLogicNodeExecutor { - private static final Logger LOG = LoggerFactory - .getLogger(ConfigureNodeExecutor.class); - - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String adaptorName = SvcLogicExpressionResolver.evaluate( - node.getAttribute("adaptor"), node, ctx); - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("configure node encountered - looking for adaptor " - + adaptorName); - } - - SvcLogicAdaptor adaptor = getAdaptor(adaptorName); - - if (adaptor != null) { - String activate = SvcLogicExpressionResolver.evaluate( - node.getAttribute("activate"), node, ctx); - String key = SvcLogicExpressionResolver.evaluate( - node.getAttribute("key"), node, ctx); - - Map parmMap = new HashMap(); - - Set> parmSet = node - .getParameterSet(); - boolean hasParms = false; - - for (Iterator> iter = parmSet - .iterator(); iter.hasNext();) { - hasParms = true; - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - SvcLogicExpression curExpr = curEnt.getValue(); - String curExprValue = SvcLogicExpressionResolver.evaluate(curExpr, node, ctx); - - LOG.debug("Parameter "+curName+" = "+curExpr.asParsedExpr()+" resolves to "+curExprValue); - - parmMap.put(curName,curExprValue); - } - - if (hasParms) { - SvcLogicAdaptor.ConfigStatus confStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - - try { - confStatus = adaptor.configure(key, parmMap, ctx); - } catch (Exception e) { - LOG.warn("Caught exception from "+adaptorName+".configure", e); - confStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - } - - switch (confStatus) { - case SUCCESS: - outValue = "success"; - if ((activate != null) && (activate.length() > 0)) { - if ("true".equalsIgnoreCase(activate)) { - SvcLogicAdaptor.ConfigStatus activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - - try { - activateStatus = adaptor.activate(key, ctx); - } catch (Exception e) { - - LOG.warn("Caught exception from "+adaptorName+".activate", e); - activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - } - switch (activateStatus) { - case SUCCESS: - break; - case ALREADY_ACTIVE: - outValue = "already-active"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case NOT_READY: - outValue = "not-ready"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } else if ("false".equalsIgnoreCase(activate)) { - SvcLogicAdaptor.ConfigStatus deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - - try { - deactivateStatus = adaptor.deactivate(key, ctx); - } catch (Exception e) { - - LOG.warn("Caught exception from "+adaptorName+".deactivate", e); - deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - } - switch (deactivateStatus) { - case SUCCESS: - break; - case ALREADY_ACTIVE: - outValue = "already-active"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case NOT_READY: - outValue = "not-ready"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } - } - break; - case ALREADY_ACTIVE: - outValue = "already-active"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case NOT_READY: - outValue = "not-ready"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } else { - if ((activate != null) && (activate.length() > 0)) { - if ("true".equalsIgnoreCase(activate)) { - SvcLogicAdaptor.ConfigStatus activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - try { - activateStatus = adaptor.activate(key, ctx); - } catch (Exception e) { - LOG.warn("Caught exception from "+adaptorName+".activate", e); - activateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - } - switch (activateStatus) { - case SUCCESS: - outValue = "success"; - break; - case ALREADY_ACTIVE: - outValue = "already-active"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case NOT_READY: - outValue = "not-ready"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } else if ("false".equalsIgnoreCase(activate)) { - SvcLogicAdaptor.ConfigStatus deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - - try { - deactivateStatus = adaptor.deactivate(key, ctx); - } catch (Exception e) { - LOG.warn("Caught exception from "+adaptorName+".deactivate", e); - deactivateStatus = SvcLogicAdaptor.ConfigStatus.FAILURE; - } - switch (deactivateStatus) { - case SUCCESS: - outValue = "success"; - break; - case ALREADY_ACTIVE: - outValue = "already-active"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case NOT_READY: - outValue = "not-ready"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } - } else { - LOG.warn("Nothing to configure - no parameters passed, and activate attribute is not set"); - outValue = "success"; - } - } - } else { - if (LOG.isWarnEnabled()) { - LOG.warn("Adaptor for " + adaptorName + " not found"); - } - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no " + outValue + " or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/DeleteNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/DeleteNodeExecutor.java deleted file mode 100644 index 081cbcfa1..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/DeleteNodeExecutor.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DeleteNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(DeleteNodeExecutor.class); - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("delete node encountered - looking for resource class " - + plugin); - } - - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - if (resourcePlugin != null) { - - try { - - switch (resourcePlugin.delete(resourceType, key, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutor.java deleted file mode 100644 index 7ae4d0db9..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutor.java +++ /dev/null @@ -1,161 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ExecuteNodeExecutor extends SvcLogicNodeExecutor { - private static final Logger LOG = LoggerFactory - .getLogger(ExecuteNodeExecutor.class); - - private static final String pluginErrorMessage = "Could not execute plugin. SvcLogic status will be set to failure."; - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String pluginName = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("execute node encountered - looking for plugin " - + pluginName); - } - - SvcLogicJavaPlugin plugin = getSvcLogicJavaPlugin(pluginName); - - if (plugin == null) { - outValue = "not-found"; - } else { - - String methodName = evaluate(node.getAttribute("method"), node, ctx); - - Class pluginClass = plugin.getClass(); - - Method pluginMethod = null; - - try { - pluginMethod = pluginClass.getMethod(methodName, Map.class, SvcLogicContext.class); - } catch (NoSuchMethodException e) { - LOG.error(pluginErrorMessage, e); - } - - if (pluginMethod == null) { - outValue = "unsupported-method"; - } else { - try { - - Map parmMap = new HashMap(); - - Set> parmSet = node - .getParameterSet(); - - for (Iterator> iter = parmSet - .iterator(); iter.hasNext();) { - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - SvcLogicExpression curExpr = curEnt.getValue(); - String curExprValue = SvcLogicExpressionResolver.evaluate(curExpr, node, ctx); - - LOG.debug("Parameter "+curName+" = "+curExpr.asParsedExpr()+" resolves to "+curExprValue); - - parmMap.put(curName,curExprValue); - } - - Object o = pluginMethod.invoke(plugin, parmMap, ctx); - String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); - - outValue = mapOutcome(o, emitsOutcome); - - } catch (InvocationTargetException e) { - if(e.getCause() != null){ - LOG.error(pluginErrorMessage, e.getCause()); - }else{ - LOG.error(pluginErrorMessage, e); - } - outValue = "failure"; - ctx.setStatus("failure"); - } catch (IllegalAccessException e) { - LOG.error(pluginErrorMessage, e); - outValue = "failure"; - ctx.setStatus("failure"); - } catch (IllegalArgumentException e) { - LOG.error(pluginErrorMessage, e); - outValue = "failure"; - ctx.setStatus("failure"); - } - } - - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no " + outValue + " or Other branch found"); - } - } - return (nextNode); - } - - protected String evaluate(SvcLogicExpression expr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { - return SvcLogicExpressionResolver.evaluate(node.getAttribute("method"), node, ctx); - } - - public String mapOutcome(Object o, String emitsOutcome) { - if (emitsOutcome != null) { - Boolean nodeEmitsOutcome = Boolean.valueOf(emitsOutcome); - if (nodeEmitsOutcome) { - return (String) o; - } else { - return "success"; - } - - } else { - return "success"; - } - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExistsNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExistsNodeExecutor.java deleted file mode 100644 index 688a86e53..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ExistsNodeExecutor.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ExistsNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(ExistsNodeExecutor.class); - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - String pfx = SvcLogicExpressionResolver.evaluate( - node.getAttribute("pfx"), node, ctx); - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("exists node encountered - looking for resource class " - + plugin); - } - - - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - - if (resourcePlugin != null) { - - try { - - switch (resourcePlugin.exists(resourceType, key, pfx, ctx)) { - case SUCCESS: - outValue = "true"; - break; - case NOT_FOUND: - outValue = "false"; - break; - case FAILURE: - default: - outValue = "false"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ForNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ForNodeExecutor.java deleted file mode 100644 index e9fdc55ef..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ForNodeExecutor.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.BreakNodeException; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ForNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(ForNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - SvcLogicExpression atomicExpr = node.getAttribute("atomic"); - String atomicStr = SvcLogicExpressionResolver.evaluate(atomicExpr, node, ctx); - boolean isAtomic = !("false".equalsIgnoreCase(atomicStr)); - - int numOutcomes = node.getNumOutcomes(); - String idxVar = SvcLogicExpressionResolver.evaluate( - node.getAttribute("index"), node, ctx); - String startVal = SvcLogicExpressionResolver.evaluate( - node.getAttribute("start"), node, ctx); - String endVal = SvcLogicExpressionResolver.evaluate( - node.getAttribute("end"), node, ctx); - - LOG.debug("Executing "+ (isAtomic ? "atomic" : "non-atomic") + " for loop - for (int " + idxVar + " = " + startVal - + "; " + idxVar + " < " + endVal + "; " + idxVar + "++)"); - - int startIdx = 0; - int endIdx = 0; - - try { - startIdx = Integer.parseInt(startVal); - endIdx = Integer.parseInt(endVal); - } catch (NumberFormatException e) { - SvcLogicExpression silentFailureExpr = node.getAttribute("silentFailure"); - String silentFailure = SvcLogicExpressionResolver.evaluate(silentFailureExpr, node, ctx); - boolean isSilentFailure = Boolean.parseBoolean(silentFailure); - String message = "Invalid index values [" + startVal + "," + endVal + "]"; - if(!isSilentFailure){ - throw new SvcLogicException(message); - }else{ - LOG.debug(message + ". Not exiting because silentFailure was set to true."); - return(null); - } - } - - try { - for (int ctr = startIdx; ctr < endIdx; ctr++) { - - ctx.setAttribute(idxVar, "" + ctr); - - for (int i = 0; i < numOutcomes; i++) { - - if ("failure".equals(ctx.getStatus()) && isAtomic) { - LOG.info("For - stopped executing nodes due to failure status"); - return(null); - } - - SvcLogicNode nextNode = node.getOutcomeValue("" + (i + 1)); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("For - executing outcome " + (i + 1)); - } - SvcLogicNode innerNextNode = nextNode; - while (innerNextNode != null) { - innerNextNode = svc.executeNode(innerNextNode, ctx); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("For - done: no outcome " + (i + 1)); - } - } - } - } - } catch (BreakNodeException br) { - LOG.debug("ForNodeExecutor caught break"); - } - return (null); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/GetResourceNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/GetResourceNodeExecutor.java deleted file mode 100644 index d431a18af..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/GetResourceNodeExecutor.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class GetResourceNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(GetResourceNodeExecutor.class); - - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - String pfx = SvcLogicExpressionResolver.evaluate( - node.getAttribute("pfx"), node, ctx); - - String localOnlyStr = SvcLogicExpressionResolver.evaluate( - node.getAttribute("local-only"), node, ctx); - - // Note: for get-resource, only refresh from A&AI if the DG explicitly set - // local-only to false. Otherwise, just read from local database. - boolean localOnly = true; - - if ("false".equalsIgnoreCase(localOnlyStr)) { - localOnly = false; - } - - SvcLogicExpression selectExpr = node.getAttribute("select"); - String select = null; - - if (selectExpr != null) { - select = SvcLogicExpressionResolver.evaluateAsKey(selectExpr, node, - ctx); - } - - SvcLogicExpression orderByExpr = node.getAttribute("order-by"); - String orderBy = null; - - if (orderByExpr != null) { - orderBy = SvcLogicExpressionResolver.evaluateAsKey(orderByExpr, node, - ctx); - } - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug(node.getNodeType() - + " node encountered - looking for resource class " - + plugin); - } - - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - - if (resourcePlugin != null) { - - try { - switch (resourcePlugin.query(resourceType, localOnly, select, key, - pfx, orderBy, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/IsAvailableNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/IsAvailableNodeExecutor.java deleted file mode 100644 index 0df73682c..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/IsAvailableNodeExecutor.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class IsAvailableNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(IsAvailableNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - String pfx = SvcLogicExpressionResolver.evaluate( - node.getAttribute("pfx"), node, ctx); - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("is-available node encountered - looking for resource class " - + plugin); - } - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - - - if (resourcePlugin != null) { - try { - switch (resourcePlugin.isAvailable(resourceType, key, pfx, ctx)) { - case SUCCESS: - outValue = "true"; - break; - case NOT_FOUND: - outValue = "false"; - break; - case FAILURE: - default: - outValue = "false"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/MdsalHelper.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/MdsalHelper.java deleted file mode 100644 index 4c5ee0686..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/MdsalHelper.java +++ /dev/null @@ -1,1186 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefixBuilder; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address; -import org.opendaylight.yangtools.yang.binding.Identifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MdsalHelper { - - private static final Logger LOG = LoggerFactory.getLogger(MdsalHelper.class); - private static Properties yangMappingProperties = new Properties(); - - @Deprecated - public static void setProperties(Properties input) { - setYangMappingProperties(input); - } - - public static void setYangMappingProperties(Properties properties) { - for (Object propNameObj : properties.keySet()) { - String propName = (String) propNameObj; - MdsalHelper.yangMappingProperties.setProperty(propName, properties.getProperty(propName)); - } - } - - public static void loadProperties(String propertiesFile) { - File file = new File(propertiesFile); - Properties properties = new Properties(); - InputStream input = null; - if (file.isFile() && file.canRead()) { - try { - input = new FileInputStream(file); - properties.load(input); - MdsalHelper.setYangMappingProperties(properties); - LOG.info("Loaded properties from " + propertiesFile); - } catch (Exception e) { - LOG.error("Failed to load properties " + propertiesFile + "\n", e); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - LOG.error("Failed to close properties file " + propertiesFile + "\n", e); - } - } - } - }else{ - LOG.error("Failed to load the properties file " + propertiesFile + "\n"); - LOG.error("Either isFile or canRead returned false for " + propertiesFile + "\n"); - } - } - - public static Properties toProperties(Properties props, Object fromObj) { - Class fromClass = null; - - if (fromObj != null) { - fromClass = fromObj.getClass(); - } - return (toProperties(props, "", fromObj, fromClass)); - } - - public static Properties toProperties(Properties props, String pfx, Object fromObj) { - Class fromClass = null; - - if (fromObj != null) { - fromClass = fromObj.getClass(); - } - - return (toProperties(props, pfx, fromObj, fromClass)); - } - - public static Properties toProperties(Properties props, String pfx, Object fromObj, Class fromClass) { - - if (fromObj == null) { - return (props); - } - - String simpleName = fromClass.getSimpleName(); - - LOG.trace("Extracting properties from " + fromClass.getName() + " class"); - if (fromObj instanceof List) { - - // Class is a List. List should contain yang-generated classes. - LOG.trace(fromClass.getName() + " is a List"); - - List fromList = (List) fromObj; - - for (int i = 0; i < fromList.size(); i++) { - toProperties(props, pfx + "[" + i + "]", fromList.get(i), fromClass); - } - props.setProperty(pfx + "_length", "" + fromList.size()); - - } else if (isYangGenerated(fromClass)) { - // Class is yang generated. - LOG.trace(fromClass.getName() + " is a Yang-generated class"); - - String propNamePfx = null; - - // If called from a list (so prefix ends in ']'), don't - // add class name again - if (pfx.endsWith("]")) { - propNamePfx = pfx; - } else { - if ((pfx != null) && (pfx.length() > 0)) { - propNamePfx = pfx; - } else { - propNamePfx = toLowerHyphen(fromClass.getSimpleName()); - } - - if (propNamePfx.endsWith("-builder")) { - propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-builder".length()); - } - - if (propNamePfx.endsWith("-impl")) { - propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-impl".length()); - } - } - - // Iterate through getter methods to figure out values we need to - // save from - - int numGetters = 0; - String lastGetterName = null; - String propVal = null; - - for (Method m : fromClass.getMethods()) { - if (isGetter(m)) { - - numGetters++; - lastGetterName = m.getName(); - - Class returnType = m.getReturnType(); - String fieldName; - if (m.getName().startsWith("get")) { - fieldName = toLowerHyphen(m.getName().substring(3)); - } else { - - fieldName = toLowerHyphen(m.getName().substring(2)); - } - - fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); - - // Is the return type a yang generated class? - if (isYangGenerated(returnType)) { - // Is it an enum? - if (returnType.isEnum()) { - // Return type is a typedef. Save its value. - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - - Object retValue = m.invoke(fromObj); - - if (!isAccessible) { - m.setAccessible(isAccessible); - } - if (retValue != null) { - String propName = propNamePfx + "." + fieldName; - propVal = retValue.toString(); - props.setProperty(propName, mapEnumeratedValue(fieldName, propVal)); - } - } catch (Exception e) { - LOG.error("Caught exception trying to convert Yang-generated enum returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } else if (isIpv4Address(returnType)) { - // Save its value - try { - String propName = propNamePfx + "." + fieldName; - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - Ipv4Address retValue = (Ipv4Address) m.invoke(fromObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - - if (retValue != null) { - propVal = retValue.getValue().toString(); - LOG.debug("Setting property " + propName + " to " + propVal); - props.setProperty(propName, propVal); - - } - } catch (Exception e) { - LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } else if (isIpv6Address(returnType)) { - // Save its value - try { - String propName = propNamePfx + "." + fieldName; - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - Ipv6Address retValue = (Ipv6Address) m.invoke(fromObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - - if (retValue != null) { - propVal = retValue.getValue().toString(); - LOG.debug("Setting property " + propName + " to " + propVal); - props.setProperty(propName, propVal); - - } - } catch (Exception e) { - LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } else if (isIpAddress(returnType)) { - // Save its value - try { - String propName = propNamePfx + "." + fieldName; - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - IpAddress retValue = (IpAddress) m.invoke(fromObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - - if (retValue != null) { - propVal = new String(retValue.getValue()); - LOG.debug("Setting property " + propName + " to " + propVal); - props.setProperty(propName, propVal); - - } - } catch (Exception e) { - LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } else if (isIpPrefix(returnType)) { - // Save its value - try { - String propName = propNamePfx + "." + fieldName; - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - IpPrefix retValue = (IpPrefix) m.invoke(fromObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - - if (retValue != null) { - propVal = new String(retValue.getValue()); - LOG.debug("Setting property " + propName + " to " + propVal); - props.setProperty(propName, propVal); - - } - } catch (Exception e) { - LOG.error("Caught exception trying to convert value returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } else { - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - Object retValue = m.invoke(fromObj); - - if (retValue instanceof byte[]) { - LOG.trace(m.getName() + " returns a byte[]"); - retValue = new String((byte[]) retValue, "UTF-8"); - LOG.trace("Converted byte array " + propNamePfx + "." + fieldName + "to string " + retValue); - } - if (!isAccessible) { - m.setAccessible(isAccessible); - } - if (retValue != null) { - toProperties(props, propNamePfx + "." + fieldName, retValue, returnType); - } - } catch (Exception e) { - - if (m.getName().equals("getKey")) { - LOG.trace("Caught " + e.getClass().getName() + " exception trying to convert results from getKey() - ignoring"); - } else { - LOG.error("Caught exception trying to convert Yang-generated class returned by" + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } - } - } else if (returnType.equals(Class.class)) { - - LOG.trace(m.getName() + " returns a Class object - not interested"); - - } else if (List.class.isAssignableFrom(returnType)) { - - // This getter method returns a list. - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - Object retList = m.invoke(fromObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - // Figure out what type of elements are stored in - // this array. - Type paramType = m.getGenericReturnType(); - Type elementType = ((ParameterizedType) paramType).getActualTypeArguments()[0]; - toProperties(props, propNamePfx + "." + fieldName, retList, (Class) elementType); - } catch (Exception e) { - LOG.error("Caught exception trying to convert List returned by " + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - - } else { - - // Method returns something that is not a List and not - // yang-generated. - // Save its value - try { - String propName = propNamePfx + "." + fieldName; - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - Object propValObj = m.invoke(fromObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - - if (propValObj != null) { - if (propValObj instanceof byte[]) { - LOG.trace(m.getName() + " returns a byte[]"); - propVal = new String((byte[]) propValObj, "UTF-8"); - LOG.trace("Converted byte array " + propNamePfx + "." + fieldName + "to string " + propVal); - - } else { - propVal = propValObj.toString(); - } - LOG.debug("Setting property " + propName + " to " + propVal); - props.setProperty(propName, propVal); - - } - } catch (Exception e) { - if (m.getName().equals("getKey")) { - LOG.trace("Caught " + e.getClass().getName() + " exception trying to convert results from getKey() - ignoring"); - } else { - LOG.error("Caught exception trying to convert value returned by" + fromClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } - } - - } - } - - // End of method loop. If there was only one getter, named - // "getValue", then - // set value identified by "prefix" to that one value. - if ((numGetters == 1) && ("getValue".equals(lastGetterName))) { - LOG.trace("getValueFIX : " + propNamePfx + " only has getValue() getter - setting " + propNamePfx + " = " + propVal); - props.setProperty(propNamePfx, propVal); - } else { - LOG.trace("getValueFIX : " + propNamePfx + " has " + numGetters + " getter(s), last one found was " + lastGetterName); - - } - - } else { - // Class is not yang generated and not a list - // It must be an element of a leaf list - set "prefix" to value - String fromVal = null; - if (fromObj instanceof byte[]) { - try { - fromVal = new String((byte[]) fromObj, "UTF-8"); - LOG.trace("Converted byte array " + pfx + "to string " + fromVal); - } catch (Exception e) { - LOG.warn("Caught exception trying to convert " + pfx + " from byte[] to String", e); - fromVal = fromObj.toString(); - } - - } else { - fromVal = fromObj.toString(); - } - LOG.debug("Setting property " + pfx + " to " + fromVal); - props.setProperty(pfx, fromVal); - } - - return (props); - } - - public static Object toBuilder(Properties props, Object toObj) { - - return (toBuilder(props, "", toObj)); - } - - public static List toList(Properties props, String pfx, List toObj, Class elemType) { - - int maxIdx = -1; - boolean foundValue = false; - - LOG.trace("Saving properties to List<" + elemType.getName() + "> from " + pfx); - - if (props.contains(pfx + "_length")) { - try { - int listLength = Integer.parseInt(props.getProperty(pfx + "_length")); - - if (listLength > 0) { - maxIdx = listLength - 1; - } - } catch (Exception e) { - // Ignore exception - } - } - - if (maxIdx == -1) { - // Figure out array size - for (Object pNameObj : props.keySet()) { - String key = (String) pNameObj; - - if (key.startsWith(pfx + "[")) { - String idxStr = key.substring(pfx.length() + 1); - int endloc = idxStr.indexOf("]"); - if (endloc != -1) { - idxStr = idxStr.substring(0, endloc); - } - - try { - int curIdx = Integer.parseInt(idxStr); - if (curIdx > maxIdx) { - maxIdx = curIdx; - } - } catch (Exception e) { - LOG.error("Illegal subscript in property " + key); - } - - } - } - } - - LOG.trace(pfx + " has max index of " + maxIdx); - for (int i = 0; i <= maxIdx; i++) { - - String curBase = pfx + "[" + i + "]"; - - if (isYangGenerated(elemType)) { - String builderName = elemType.getName() + "Builder"; - try { - Class builderClass = Class.forName(builderName); - Object builderObj = builderClass.newInstance(); - Method buildMethod = builderClass.getMethod("build"); - builderObj = toBuilder(props, curBase, builderObj, true); - if (builderObj != null) { - LOG.trace("Calling " + builderObj.getClass().getName() + "." + buildMethod.getName() + "()"); - Object builtObj = buildMethod.invoke(builderObj); - toObj.add(builtObj); - foundValue = true; - } - - } catch (ClassNotFoundException e) { - LOG.warn("Could not find builder class " + builderName, e); - } catch (Exception e) { - LOG.error("Caught exception trying to populate list from " + pfx); - } - } else { - // Must be a leaf list - String curValue = props.getProperty(curBase, ""); - - toObj.add(curValue); - - if ((curValue != null) && (curValue.length() > 0)) { - foundValue = true; - } - } - - } - - if (foundValue) { - return (toObj); - } else { - return (null); - } - - } - - public static Object toBuilder(Properties props, String pfx, Object toObj) { - return (toBuilder(props, pfx, toObj, false)); - } - - public static Object toBuilder(Properties props, String pfx, Object toObj, boolean preservePfx) { - Class toClass = toObj.getClass(); - boolean foundValue = false; - - LOG.trace("Saving properties to " + toClass.getName() + " class from " + pfx); - - Ipv4Address addr; - - if (isYangGenerated(toClass)) { - // Class is yang generated. - LOG.trace(toClass.getName() + " is a Yang-generated class"); - - String propNamePfx = null; - if (preservePfx) { - propNamePfx = pfx; - } else { - - if ((pfx != null) && (pfx.length() > 0)) { - propNamePfx = pfx + "." + toLowerHyphen(toClass.getSimpleName()); - } else { - propNamePfx = toLowerHyphen(toClass.getSimpleName()); - } - - if (propNamePfx.endsWith("-builder")) { - propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-builder".length()); - } - - if (propNamePfx.endsWith("-impl")) { - propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-impl".length()); - } - } - - if (toObj instanceof Identifier) { - LOG.trace(toClass.getName() + " is a Key - skipping"); - return (toObj); - } - - // Iterate through getter methods to figure out values we need to - // set - - for (Method m : toClass.getMethods()) { - if (isSetter(m)) { - Class paramTypes[] = m.getParameterTypes(); - Class paramClass = paramTypes[0]; - - String fieldName = toLowerHyphen(m.getName().substring(3)); - fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); - - String propName = propNamePfx + "." + fieldName; - - String paramValue = props.getProperty(propName); - if (paramValue == null) { - LOG.trace(propName + " is unset"); - } else { - LOG.trace(propName + " = " + paramValue); - } - - // Is the return type a yang generated class? - if (isYangGenerated(paramClass)) { - // Is it an enum? - if (paramClass.isEnum()) { - - LOG.trace(m.getName() + " expects an Enum"); - // Param type is a typedef. - if ((paramValue != null) && (paramValue.length() > 0)) { - Object paramObj = null; - - try { - paramObj = Enum.valueOf(paramClass, toJavaEnum(paramValue)); - } catch (Exception e) { - LOG.error("Caught exception trying to convert field " + propName + " to enum " + paramClass.getName(), e); - } - - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); - m.invoke(toObj, paramObj); - - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e) { - LOG.error("Caught exception trying to create Yang-generated enum expected by" + toClass.getName() + "." + m.getName() + "() from Properties entry", e); - } - } - } else { - - String simpleName = paramClass.getSimpleName(); - - if ("Ipv4Address".equals(simpleName) || "Ipv6Address".equals(simpleName) || "IpAddress".equals(simpleName)) { - - if ((paramValue != null) && (paramValue.length() > 0)) { - try { - IpAddress ipAddr = IpAddressBuilder.getDefaultInstance(paramValue); - - if ("Ipv4Address".equals(simpleName)) { - m.invoke(toObj, ipAddr.getIpv4Address()); - } else if ("Ipv6Address".equals(simpleName)) { - m.invoke(toObj, ipAddr.getIpv6Address()); - - } else { - m.invoke(toObj, ipAddr); - } - foundValue = true; - } catch (Exception e) { - LOG.error("Caught exception calling " + toClass.getName() + "." + m.getName() + "(" + paramValue + ")", e); - - } - } else { - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); - m.invoke(toObj, paramValue); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e) { - LOG.error("Caught exception trying to call " + toClass.getName() + "." + m.getName() + "() with Properties entry", e); - } - } - } else if ("IpPrefix".equals(simpleName)) { - if ((paramValue != null) && (paramValue.length() > 0)) { - try { - IpPrefix ipPrefix = IpPrefixBuilder.getDefaultInstance(paramValue); - m.invoke(toObj, ipPrefix); - foundValue = true; - } catch (Exception e) { - LOG.error("Caught exception calling " + toClass.getName() + "." + m.getName() + "(" + paramValue + ")", e); - } - } - } else { - // setter expects a yang-generated class. Need - // to - // create a builder to set it. - - String builderName = paramClass.getName() + "Builder"; - Class builderClass = null; - Object builderObj = null; - Object paramObj = null; - - Object constObj = null; - - LOG.trace(m.getName() + " expects a yang-generated class - looking for builder " + builderName); - try { - builderClass = Class.forName(builderName); - builderObj = builderClass.newInstance(); - paramObj = toBuilder(props, propNamePfx, builderObj); - } catch (ClassNotFoundException e) { - - if (paramValue == null) { - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(null)"); - m.invoke(toObj, new Object[] { null }); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e1) { - LOG.error("Caught exception trying to cally" + toClass.getName() + "." + m.getName() + "() with Properties entry", e1); - } - } else { - try { - // See if I can find a constructor I - // can - // use - Constructor[] constructors = paramClass.getConstructors(); - // Is there a String constructor? - for (Constructor c : constructors) { - Class[] cParms = c.getParameterTypes(); - if ((cParms != null) && (cParms.length == 1)) { - if (String.class.isAssignableFrom(cParms[0])) { - constObj = c.newInstance(paramValue); - } - } - } - - if (constObj == null) { - // Is there a Long constructor? - for (Constructor c : constructors) { - Class[] cParms = c.getParameterTypes(); - if ((cParms != null) && (cParms.length == 1)) { - if (Long.class.isAssignableFrom(cParms[0])) { - constObj = c.newInstance(Long.parseLong(paramValue)); - } - } - } - - } - - if (constObj == null) { - - // Last chance - see if - // parameter class has a static - // method - // getDefaultInstance(String) - try { - Method gm = paramClass.getMethod("getDefaultInstance", String.class); - - int gmodifier = gm.getModifiers(); - if (Modifier.isStatic(gmodifier)) { - // Invoke static - // getDefaultInstance(String) - paramObj = gm.invoke(null, paramValue); - } - - } catch (Exception gme) { - // Ignore exceptions - } - } - - } catch (Exception e1) { - LOG.warn("Could not find a suitable constructor for " + paramClass.getName(), e1); - } - - if (constObj == null) { - LOG.warn("Could not find builder class " + builderName + " and could not find a String or Long constructor or static getDefaultInstance(String) - trying just to set passing paramValue"); - - } - } - } catch (Exception e) { - LOG.error("Caught exception trying to create builder " + builderName, e); - } - - if (paramObj != null) { - - try { - - Method buildMethod = builderClass.getMethod("build"); - LOG.trace("Calling " + paramObj.getClass().getName() + "." + buildMethod.getName() + "()"); - Object builtObj = buildMethod.invoke(paramObj); - - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "()"); - m.invoke(toObj, builtObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e) { - LOG.error("Caught exception trying to set Yang-generated class expected by" + toClass.getName() + "." + m.getName() + "() from Properties entry", e); - } - } else { - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - - if (constObj != null) { - - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + constObj.toString() + ")"); - m.invoke(toObj, constObj); - } else { - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); - m.invoke(toObj, paramValue); - - } - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e) { - LOG.error("Caught exception trying to convert value returned by" + toClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } - } - } - } else { - - // Setter's argument is not a yang-generated class. See - // if it is a List. - - if (List.class.isAssignableFrom(paramClass)) { - - LOG.trace("Parameter class " + paramClass.getName() + " is a List"); - - // Figure out what type of args are in List and pass - // that to toList(). - - Type paramType = m.getGenericParameterTypes()[0]; - Type elementType = ((ParameterizedType) paramType).getActualTypeArguments()[0]; - Object paramObj = new LinkedList(); - try { - paramObj = toList(props, propName, (List) paramObj, (Class) elementType); - } catch (Exception e) { - LOG.error("Caught exception trying to create list expected as argument to " + toClass.getName() + "." + m.getName()); - } - - if (paramObj != null) { - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); - m.invoke(toObj, paramObj); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e) { - LOG.error("Caught exception trying to convert List returned by" + toClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } - } else { - - // Setter expects something that is not a List and - // not yang-generated. Just pass the parameter value - - LOG.trace("Parameter class " + paramClass.getName() + " is not a yang-generated class or a List"); - - if ((paramValue != null) && (paramValue.length() > 0)) { - - Object constObj = null; - - try { - // See if I can find a constructor I can use - Constructor[] constructors = paramClass.getConstructors(); - // Is there a String constructor? - for (Constructor c : constructors) { - Class[] cParms = c.getParameterTypes(); - if ((cParms != null) && (cParms.length == 1)) { - if (String.class.isAssignableFrom(cParms[0])) { - constObj = c.newInstance(paramValue); - } - } - } - - if (constObj == null) { - // Is there a Long constructor? - for (Constructor c : constructors) { - Class[] cParms = c.getParameterTypes(); - if ((cParms != null) && (cParms.length == 1)) { - if (Long.class.isAssignableFrom(cParms[0])) { - constObj = c.newInstance(Long.parseLong(paramValue)); - } - } - } - - } - - if (constObj != null) { - try { - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + constObj + ")"); - m.invoke(toObj, constObj); - foundValue = true; - } catch (Exception e2) { - LOG.error("Caught exception trying to call " + m.getName(), e2); - } - } else { - try { - boolean isAccessible = m.isAccessible(); - if (!isAccessible) { - m.setAccessible(true); - } - LOG.trace("Calling " + toObj.getClass().getName() + "." + m.getName() + "(" + paramValue + ")"); - m.invoke(toObj, paramValue); - if (!isAccessible) { - m.setAccessible(isAccessible); - } - foundValue = true; - - } catch (Exception e) { - LOG.error("Caught exception trying to convert value returned by" + toClass.getName() + "." + m.getName() + "() to Properties entry", e); - } - } - } catch (Exception e1) { - LOG.warn("Could not find a suitable constructor for " + paramClass.getName(), e1); - } - - } - } - } - } // End of section handling "setter" method - } // End of loop through Methods - } // End of section handling yang-generated class - - if (foundValue) { - return (toObj); - } else { - return (null); - } - } - - public static void printPropertyList(PrintStream pstr, String pfx, Class toClass) { - boolean foundValue = false; - - LOG.trace("Analyzing " + toClass.getName() + " class : pfx " + pfx); - - if (isYangGenerated(toClass) && (!Identifier.class.isAssignableFrom(toClass))) { - // Class is yang generated. - LOG.trace(toClass.getName() + " is a Yang-generated class"); - - if (toClass.getName().endsWith("Key")) { - if (Identifier.class.isAssignableFrom(toClass)) { - LOG.trace(Identifier.class.getName() + " is assignable from " + toClass.getName()); - } else { - - LOG.trace(Identifier.class.getName() + " is NOT assignable from " + toClass.getName()); - } - } - - String propNamePfx = null; - if (pfx.endsWith("]")) { - propNamePfx = pfx; - } else { - - if ((pfx != null) && (pfx.length() > 0)) { - propNamePfx = pfx + "." + toLowerHyphen(toClass.getSimpleName()); - } else { - propNamePfx = toLowerHyphen(toClass.getSimpleName()); - } - - if (propNamePfx.endsWith("-builder")) { - propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-builder".length()); - } - - if (propNamePfx.endsWith("-impl")) { - propNamePfx = propNamePfx.substring(0, propNamePfx.length() - "-impl".length()); - } - } - - // Iterate through getter methods to figure out values we need to - // set - - for (Method m : toClass.getMethods()) { - LOG.trace("Is " + m.getName() + " method a getter?"); - if (isGetter(m)) { - LOG.trace(m.getName() + " is a getter"); - Class returnClass = m.getReturnType(); - - String fieldName = toLowerHyphen(m.getName().substring(3)); - fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); - - String propName = propNamePfx + "." + fieldName; - - // Is the return type a yang generated class? - if (isYangGenerated(returnClass)) { - // Is it an enum? - if (returnClass.isEnum()) { - - LOG.trace(m.getName() + " is an Enum"); - pstr.print("\n\n * " + propName); - - } else { - - String simpleName = returnClass.getSimpleName(); - - if ("Ipv4Address".equals(simpleName) || "Ipv6Address".equals(simpleName) || "IpAddress".equals(simpleName) || "IpPrefix".equals(simpleName)) { - LOG.trace(m.getName() + " is an " + simpleName); - pstr.print("\n\n * " + propName); - } else { - printPropertyList(pstr, propNamePfx, returnClass); - } - - } - } else { - - // Setter's argument is not a yang-generated class. See - // if it is a List. - - if (List.class.isAssignableFrom(returnClass)) { - - LOG.trace("Parameter class " + returnClass.getName() + " is a List"); - - // Figure out what type of args are in List and pass - // that to toList(). - - Type returnType = m.getGenericReturnType(); - Type elementType = ((ParameterizedType) returnType).getActualTypeArguments()[0]; - Class elementClass = (Class) elementType; - LOG.trace("Calling printPropertyList on list type (" + elementClass.getName() + "), pfx is (" + pfx + "), toClass is (" + toClass.getName() + ")"); - printPropertyList(pstr, propNamePfx + "." + toLowerHyphen(elementClass.getSimpleName()) + "[]", elementClass); - - } else if (!returnClass.equals(Class.class)) { - - // Setter expects something that is not a List and - // not yang-generated. Just pass the parameter value - - LOG.trace("Parameter class " + returnClass.getName() + " is not a yang-generated class or a List"); - - pstr.print("\n\n * " + propName); - - } - } - } // End of section handling "setter" method - } // End of loop through Methods - } // End of section handling yang-generated class - - } - - public static boolean isYangGenerated(Class c) { - if (c == null) { - return (false); - } else { - return (c.getName().startsWith("org.opendaylight.yang.gen.")); - } - } - - public static boolean isIpPrefix(Class c) { - - if (c == null) { - return (false); - } - String simpleName = c.getSimpleName(); - return ("IpPrefix".equals(simpleName)); - } - - public static boolean isIpv4Address(Class c) { - - if (c == null) { - return (false); - } - String simpleName = c.getSimpleName(); - return ("Ipv4Address".equals(simpleName)); - } - - public static boolean isIpv6Address(Class c) { - - if (c == null) { - return (false); - } - String simpleName = c.getSimpleName(); - return ("Ipv6Address".equals(simpleName)); - } - - public static boolean isIpAddress(Class c) { - - if (c == null) { - return (false); - } - String simpleName = c.getSimpleName(); - return ("IpAddress".equals(simpleName)); - } - - public static String toLowerHyphen(String inStr) { - if (inStr == null) { - return (null); - } - - String str = inStr.substring(0, 1).toLowerCase(); - if (inStr.length() > 1) { - str = str + inStr.substring(1); - } - - String regex = "(([a-z0-9])([A-Z]))"; - String replacement = "$2-$3"; - - String retval = str.replaceAll(regex, replacement).toLowerCase(); - - LOG.trace("Converting " + inStr + " => " + str + " => " + retval); - return (retval); - } - - //This is called when mapping the yang value back to a valid java enumeration - public static String toJavaEnum(String inStr) { - if (inStr == null) { - return (null); - } else if (inStr.length() == 0) { - return (inStr); - } - - //This will strip out all periods, which cannot be in a java enum - inStr = inStr.replaceAll("\\.", ""); - - String[] terms = inStr.split("-"); - StringBuffer sbuff = new StringBuffer(); - - //appends an _ if the string starts with a digit to make it a valid java enum - if (Character.isDigit(inStr.charAt(0))) { - sbuff.append('_'); - } - //If the string contains hyphens it will convert the string to upperCamelCase without hyphens - for (String term : terms) { - sbuff.append(term.substring(0, 1).toUpperCase()); - if (term.length() > 1) { - sbuff.append(term.substring(1)); - } - } - return (sbuff.toString()); - - } - - public static boolean isGetter(Method m) { - if (m == null) { - return (false); - } - - if (Modifier.isPublic(m.getModifiers()) && (m.getParameterTypes().length == 0)) { - if (m.getName().matches("^get[A-Z].*") && !m.getReturnType().equals(void.class)) { - if (!"getClass".equals(m.getName())) { - return (true); - } - } - - if (m.getName().matches("^get[A-Z].*") && m.getReturnType().equals(boolean.class)) { - return (true); - } - - if (m.getName().matches("^is[A-Z].*") && m.getReturnType().equals(Boolean.class)) { - return (true); - } - } - - return (false); - } - - public static boolean isSetter(Method m) { - if (m == null) { - return (false); - } - - if (Modifier.isPublic(m.getModifiers()) && (m.getParameterTypes().length == 1)) { - if (m.getName().matches("^set[A-Z].*")) { - Class[] paramTypes = m.getParameterTypes(); - if (paramTypes[0].isAssignableFrom(Identifier.class) || Identifier.class.isAssignableFrom(paramTypes[0])) { - return (false); - } else { - return (true); - } - } - - } - - return (false); - } - - public static String getFullPropertiesPath(String propertiesFileName) { - return "/opt/bvc/controller/configuration/" + propertiesFileName; - } - - //This is called when mapping a valid java enumeration back to the yang model value - public static String mapEnumeratedValue(String propertyName, String propertyValue) { - LOG.info("mapEnumeratedValue called with propertyName=" + propertyName + " and value=" + propertyValue); - String mappingKey = "yang." + propertyName + "." + propertyValue; - if (yangMappingProperties.containsKey(mappingKey)) { - return (yangMappingProperties.getProperty(mappingKey)); - } else { - LOG.info("yangMappingProperties did not contain the key " + mappingKey + " returning the original value."); - return propertyValue; - } - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/NotifyNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/NotifyNodeExecutor.java deleted file mode 100644 index 706014a32..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/NotifyNodeExecutor.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NotifyNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(NotifyNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String action = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("action"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("release node encountered - looking for resource class " - + plugin); - } - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - if (resourcePlugin != null) { - - try { - - switch (resourcePlugin.notify(resourceType, action, key, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/RecordNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/RecordNodeExecutor.java deleted file mode 100644 index 8ba14d276..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/RecordNodeExecutor.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicRecorder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RecordNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(RecordNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String outValue = "failure"; - - if (LOG.isTraceEnabled()) { - LOG.trace(node.getNodeType() - + " node encountered - looking for recorder class " - + plugin); - } - - Map parmMap = new HashMap(); - - Set> parmSet = node - .getParameterSet(); - boolean hasParms = false; - - for (Iterator> iter = parmSet - .iterator(); iter.hasNext();) { - hasParms = true; - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - SvcLogicExpression curExpr = curEnt.getValue(); - String curExprValue = SvcLogicExpressionResolver.evaluate(curExpr, - node, ctx); - - if (LOG.isTraceEnabled()) { - LOG.trace("executeRecordNode : parameter " + curName + " = " - + curExpr + " => " + curExprValue); - } - parmMap.put(curName, curExprValue); - } - - - SvcLogicRecorder recorder = getSvcLogicRecorder(plugin); - - if (recorder != null) { - - try { - recorder.record(parmMap); - } catch (SvcLogicException e) { - LOG.error("Caught exception from recorder plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicRecorder object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isTraceEnabled()) { - LOG.trace("no failure or Other branch found"); - } - } - return (nextNode); - } - - - - - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReleaseNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReleaseNodeExecutor.java deleted file mode 100644 index 0d8416cdd..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReleaseNodeExecutor.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ReleaseNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(ReleaseNodeExecutor.class); - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("release node encountered - looking for resource class " - + plugin); - } - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - if (resourcePlugin != null) { - - try { - - switch (resourcePlugin.release(resourceType, key, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReserveNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReserveNodeExecutor.java deleted file mode 100644 index f0bbda88f..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReserveNodeExecutor.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ReserveNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(ReserveNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - String pfx = SvcLogicExpressionResolver.evaluate(node.getAttribute("pfx"),node,ctx); - - - SvcLogicExpression selectExpr = node.getAttribute("select"); - String select = null; - - if (selectExpr != null) - { - select = SvcLogicExpressionResolver.evaluateAsKey(selectExpr, node, ctx); - } - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("reserve node encountered - looking for resource class " - + plugin); - } - - - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - - if (resourcePlugin != null) { - - try { - switch (resourcePlugin.reserve(resourceType, select, key, pfx, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReturnNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReturnNodeExecutor.java deleted file mode 100644 index 5cca47128..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/ReturnNodeExecutor.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ReturnNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(ReturnNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String status = SvcLogicExpressionResolver.evaluate( - node.getAttribute("status"), node, ctx); - - if (status != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Returning status " + status); - } - ctx.setStatus(status); - } else { - if (LOG.isWarnEnabled()) { - LOG.warn("Return node has no status attribute set"); - } - } - - Set> parameterSet = node - .getParameterSet(); - - for (Iterator> iter = parameterSet - .iterator(); iter.hasNext();) { - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - String curValue = SvcLogicExpressionResolver.evaluate( - curEnt.getValue(), node, ctx); - - if (LOG.isDebugEnabled()) { - LOG.debug("Setting context attribute " + curName + " to " - + curValue); - } - ctx.setAttribute(curName, curValue); - } - return null; - } - - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SaveNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SaveNodeExecutor.java deleted file mode 100644 index 57eac7f7b..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SaveNodeExecutor.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SaveNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(SaveNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - String forceStr = SvcLogicExpressionResolver.evaluate( - node.getAttribute("force"), node, ctx); - String localOnlyStr = SvcLogicExpressionResolver.evaluate( - node.getAttribute("local-only"), node, ctx); - String pfx = SvcLogicExpressionResolver.evaluate( - node.getAttribute("pfx"), node, ctx); - - boolean force = "true".equalsIgnoreCase(forceStr); - boolean localOnly = "true".equalsIgnoreCase(localOnlyStr); - - Map parmMap = new HashMap(); - - Set> parmSet = node - .getParameterSet(); - boolean hasParms = false; - - for (Iterator> iter = parmSet - .iterator(); iter.hasNext();) { - hasParms = true; - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - SvcLogicExpression curExpr = curEnt.getValue(); - if (curExpr != null) { - String curExprValue = SvcLogicExpressionResolver.evaluate( - curExpr, node, ctx); - - LOG.debug("Parameter " + curName + " = " - + curExpr.asParsedExpr() + " resolves to " - + curExprValue); - - parmMap.put(curName, curExprValue); - } - } - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("save node encountered - looking for resource class " - + plugin); - } - - - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - - if (resourcePlugin != null) { - - try { - switch (resourcePlugin.save(resourceType, force, localOnly, key, - parmMap, pfx, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SetNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SetNodeExecutor.java deleted file mode 100644 index 013997eda..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SetNodeExecutor.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicExpressionFactory; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SetNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(SetNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String ifunsetStr = SvcLogicExpressionResolver.evaluate( - node.getAttribute("only-if-unset"), node, ctx); - - boolean ifunset = "true".equalsIgnoreCase(ifunsetStr); - - Set> parameterSet = node - .getParameterSet(); - - for (Iterator> iter = parameterSet - .iterator(); iter.hasNext();) { - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - String lhsVarName = curName; - - // Resolve LHS of assignment (could contain index variables) - try { - SvcLogicExpression lhsExpr = SvcLogicExpressionFactory.parse(curName); - lhsVarName = SvcLogicExpressionResolver.resolveVariableName(lhsExpr, node, ctx); - } catch (Exception e) { - LOG.warn("Caught exception trying to resolve variable name ("+curName+")", e); - } - - - boolean setValue = true; - - if (curName.endsWith(".")) { - - // Copy subtree - value should be a variable name - SvcLogicExpression curValue = curEnt.getValue(); - - if (curValue != null) { - String rhsRoot = curValue.toString(); - - if ((rhsRoot != null) && (rhsRoot.length() > 0)) { - if (rhsRoot.endsWith(".")) { - rhsRoot = rhsRoot - .substring(0, rhsRoot.length() - 1); - } - - - // SDNGC-2321 : rhsRoot is variable name, possibly with subscript(s) to be resolved - try { - SvcLogicExpression rhsExpr = SvcLogicExpressionFactory.parse(rhsRoot); - rhsRoot = SvcLogicExpressionResolver.resolveVariableName(rhsExpr, node, ctx); - } catch (Exception e) { - LOG.warn("Caught exception trying to resolve variable name ("+rhsRoot+")", e); - } - - // See if the parameters are reversed (copying service-data to input) .. this - // was done as a workaround to earlier issue - if (curName.endsWith("-input.") && rhsRoot.startsWith("service-data")) { - LOG.warn("Arguments appear to be reversed .. will copy input to service-data instead"); - lhsVarName = rhsRoot + "."; - rhsRoot = curName.substring(0, curName.length()-1); - } - - rhsRoot = rhsRoot + "."; - String lhsPrefix = lhsVarName; - - if (lhsPrefix.endsWith(".")) { - lhsPrefix = lhsPrefix.substring(0, - lhsPrefix.length()-1); - } - int lhsPfxLength = lhsPrefix.length(); - HashMap parmsToAdd = new HashMap(); - - for (String sourceVarName : ctx.getAttributeKeySet()) { - - if (sourceVarName.startsWith(rhsRoot)) { - - String targetVar = lhsPrefix - + "." - + sourceVarName - .substring(rhsRoot.length()); - - LOG.debug("Copying " + sourceVarName - + " value to " + targetVar); - - parmsToAdd.put(targetVar, - ctx.getAttribute(sourceVarName)); - } - } - - for (String newParmName : parmsToAdd.keySet()) { - ctx.setAttribute(newParmName, parmsToAdd.get(newParmName)); - } - - } else { - // If RHS is empty, unset attributes in LHS - String lhsPrefix = lhsVarName.substring(0, - lhsVarName.length() - 1); - int lhsPfxLength = lhsPrefix.length(); - - LinkedList parmsToRemove = new LinkedList (); - - for (String curCtxVarname : ctx.getAttributeKeySet()) { - - if (curCtxVarname.startsWith(lhsPrefix)) { - LOG.debug("Unsetting " + curCtxVarname); - parmsToRemove.add(curCtxVarname); - } - } - - for (String parmName : parmsToRemove) { - ctx.setAttribute(parmName, null); - } - - } - } - - } else { - - if (ifunset) { - String ctxValue = ctx.getAttribute(lhsVarName); - - if ((ctxValue != null) && (ctxValue.length() > 0)) { - setValue = false; - LOG.debug("Attribute " - + lhsVarName - + " already set and only-if-unset is true, so not overriding"); - } - } - - if (setValue) { - String curValue = SvcLogicExpressionResolver.evaluate( - curEnt.getValue(), node, ctx); - - if (LOG.isDebugEnabled()) { - LOG.trace("Parameter value " - + curEnt.getValue().asParsedExpr() - + " resolves to " + curValue); - LOG.debug("Setting context attribute " + lhsVarName - + " to " + curValue); - } - ctx.setAttribute(lhsVarName, curValue); - } - } - } - - return null; - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicActivator.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicActivator.java deleted file mode 100644 index ae42e2c7e..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicActivator.java +++ /dev/null @@ -1,225 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.io.File; -import java.io.FileInputStream; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.Map; -import java.util.Properties; - -import org.openecomp.sdnc.sli.ConfigurationException; -import org.openecomp.sdnc.sli.SvcLogicAdaptor; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicStore; -import org.openecomp.sdnc.sli.SvcLogicStoreFactory; -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; - -import com.mysql.jdbc.Driver; - -public class SvcLogicActivator implements BundleActivator { - - private static final String SVCLOGIC_PROP_VAR = "SDNC_SLI_PROPERTIES"; - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final Map BUILTIN_NODES = new HashMap() { - { - put("block", new BlockNodeExecutor()); - put("call", new CallNodeExecutor()); - put("configure", new ConfigureNodeExecutor()); - put("delete", new DeleteNodeExecutor()); - put("execute", new ExecuteNodeExecutor()); - put("exists", new ExistsNodeExecutor()); - put("for", new ForNodeExecutor()); - put("get-resource", new GetResourceNodeExecutor()); - put("is-available", new IsAvailableNodeExecutor()); - put("notify", new NotifyNodeExecutor()); - put("record", new RecordNodeExecutor()); - put("release", new ReleaseNodeExecutor()); - put("reserve", new ReserveNodeExecutor()); - put("return", new ReturnNodeExecutor()); - put("save", new SaveNodeExecutor()); - put("set", new SetNodeExecutor()); - put("switch", new SwitchNodeExecutor()); - put("update", new UpdateNodeExecutor()); - put("break", new BreakNodeExecutor()); - - } - }; - - private static LinkedList registrations = new LinkedList(); - - private static HashMap adaptorMap = null; - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicActivator.class); - - private static Properties props = null; - - private static BundleContext bundleCtx = null; - - private static SvcLogicService svcLogicServiceImpl = null; - - @Override - public void start(BundleContext ctx) throws Exception { - - LOG.info("Activating SLI"); - - bundleCtx = ctx; - - // Read properties - props = new Properties(); - String propPath = System.getenv(SVCLOGIC_PROP_VAR); - - if (propPath == null) { - String propDir = System.getenv(SDNC_CONFIG_DIR); - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - propPath = propDir + "/svclogic.properties"; - LOG.warn("Environment variable "+SVCLOGIC_PROP_VAR+" unset - defaulting to "+propPath); - } - - File propFile = new File(propPath); - - if (!propFile.exists()) { - - throw new ConfigurationException( - "Missing configuration properties file : " - + propFile); - } - try { - - props.load(new FileInputStream(propFile)); - } catch (Exception e) { - throw new ConfigurationException( - "Could not load properties file " + propPath, e); - - } - - - if (registrations == null) { - - registrations = new LinkedList(); - } - - // Advertise SvcLogicService - svcLogicServiceImpl = new SvcLogicServiceImpl(); - - LOG.info("SLI: Registering service " + SvcLogicService.NAME - + " in bundle " + ctx.getBundle().getSymbolicName()); - ServiceRegistration reg = ctx.registerService(SvcLogicService.NAME, - svcLogicServiceImpl, null); - registrations.add(reg); - - // Initialize SvcLogicStore - try { - SvcLogicStore store = getStore(); - registerNodeTypes(store); - } catch (ConfigurationException e) { - LOG.warn("Could not initialize SvcLogicScore", e); - } - - LOG.info("SLI - done registering services"); - } - - @Override - public void stop(BundleContext ctx) throws Exception { - - if (registrations != null) { - for (ServiceRegistration reg : registrations) { - ServiceReference regRef = reg.getReference(); - /* Don't bother to remove node types from table - String nodeType = (String) regRef.getProperty("nodeType"); - if (nodeType != null) { - LOG.info("SLI - unregistering node type " + nodeType); - store.unregisterNodeType(nodeType); - } - */ - reg.unregister(); - } - registrations = null; - } - } - - public static SvcLogicStore getStore() throws SvcLogicException { - // Create and initialize SvcLogicStore object - used to access - // saved service logic. - - SvcLogicStore store = null; - - try { - Driver dvr = new Driver(); - store = SvcLogicStoreFactory.getSvcLogicStore(props); - } catch (Exception e) { - throw new ConfigurationException( - "Could not get service logic store", e); - - } - - try { - store.init(props); - } catch (Exception e) { - throw new ConfigurationException( - "Could not get service logic store", e); - } - - return(store); - } - - private static void registerNodeTypes(SvcLogicStore store) throws SvcLogicException { - - if (store == null) { - return; - } - // Advertise built-in node executors - LOG.info("SLI : Registering built-in node executors"); - Hashtable propTable = new Hashtable(); - - for (String nodeType : BUILTIN_NODES.keySet()) { - LOG.info("SLI - registering node type " + nodeType); - propTable.clear(); - propTable.put("nodeType", nodeType); - - ServiceRegistration reg = bundleCtx.registerService(SvcLogicNodeExecutor.class.getName(), - BUILTIN_NODES.get(nodeType), propTable); - registrations.add(reg); - - store.registerNodeType(nodeType); - - LOG.info("SLI - registering node executor"); - - ((SvcLogicServiceImpl)svcLogicServiceImpl).registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); - - } - - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicAdaptorFactory.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicAdaptorFactory.java deleted file mode 100644 index aa8c005a6..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicAdaptorFactory.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; - -import org.openecomp.sdnc.sli.SvcLogicAdaptor; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SvcLogicAdaptorFactory { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicAdaptorFactory.class); - - private static HashMap adaptorMap = new HashMap(); - - public static void registerAdaptor(SvcLogicAdaptor adaptor) { - String name = adaptor.getClass().getName(); - LOG.info("Registering adaptor " + name); - adaptorMap.put(name, adaptor); - - } - - public static void unregisterAdaptor(String name) { - if (adaptorMap.containsKey(name)) { - LOG.info("Unregistering " + name); - adaptorMap.remove(name); - } - } - - public static SvcLogicAdaptor getInstance(String name) { - if (adaptorMap.containsKey(name)) { - return (adaptorMap.get(name)); - } else { - BundleContext bctx = null; - try - { - bctx = FrameworkUtil.getBundle(SvcLogicAdaptorFactory.class) - .getBundleContext(); - } - catch (Exception e) - { - LOG.debug("Caught exception trying to locate device adaptor "+name, e); - return(null); - } - - ServiceReference sref = bctx.getServiceReference(name); - - if (sref != null) { - SvcLogicAdaptor adaptor = (SvcLogicAdaptor) bctx - .getService(sref); - - if (adaptor != null) { - registerAdaptor(adaptor); - - return (adaptor); - } - return (null); - } - } - return(null); - } -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolver.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolver.java deleted file mode 100644 index 5c17c7997..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolver.java +++ /dev/null @@ -1,605 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.List; - -import org.apache.commons.lang.StringUtils; -import org.openecomp.sdnc.sli.SvcLogicAtom; -import org.openecomp.sdnc.sli.SvcLogicAtom.AtomType; -import org.openecomp.sdnc.sli.SvcLogicBinaryExpression; -import org.openecomp.sdnc.sli.SvcLogicBinaryExpression.OperatorType; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicFunctionCall; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicVariableTerm; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SvcLogicExpressionResolver { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicExpressionResolver.class); - - public static String evaluate(SvcLogicExpression expr, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - if (expr == null) { - return (null); - } - - - - if (expr instanceof SvcLogicAtom) { - SvcLogicAtom atom = (SvcLogicAtom) expr; - - AtomType atomType = atom.getAtomType(); - switch (atomType) { - case NUMBER: - case STRING: - return (atom.toString()); - case CONTEXT_VAR: - case IDENTIFIER: - - String varName = resolveVariableName(atom, node, ctx); - - if (atomType == AtomType.CONTEXT_VAR) - { - LOG.trace("Evaluating context variable $"+varName); - - String varValue = ctx.getAttribute(varName); - - if (varValue == null) { - LOG.trace("Context variable $"+varName+" unset - treating as empty string"); - varValue = ""; - } - - return (varValue); - } - SvcLogicExpression parm = node.getParameter(varName); - if (parm != null) { - LOG.trace("Evaluating value of parameter "+varName+": "+parm.asParsedExpr()); - - return (evaluate(parm, node, ctx)); - } - else - { - return(varName); - } - default: - return(null); - } - - } else if (expr instanceof SvcLogicBinaryExpression) { - SvcLogicBinaryExpression binExpr = (SvcLogicBinaryExpression) expr; - List operators = binExpr.getOperators(); - if (operators.isEmpty()) - { - List operands = binExpr.getOperands(); - if (operands.size() == 1) - { - LOG.trace("SvcLogicBinaryExpression as no operator and one operand - evaluating its operand"); - return(evaluate(operands.get(0), node, ctx)); - } - else - { - if (operands.isEmpty()) - { - LOG.error("SvcLogicBinaryExpression has no operators and no operands - evaluating value as null"); - } - else - { - LOG.error("SvcLogicBinaryExpression has no operators and "+operands.size()+" operands - evaluating value as null"); - } - return(null); - } - } - switch (operators.get(0)) { - case addOp: - case subOp: - case multOp: - case divOp: - return(evalArithExpression(binExpr, node, ctx)); - case equalOp: - case neOp: - case ltOp: - case leOp: - case gtOp: - case geOp: - return (evalCompareExpression(binExpr, node, ctx)); - case andOp: - case orOp: - return(evalLogicExpression(binExpr, node, ctx)); - - default: - return(null); - } - } - else if (expr instanceof SvcLogicFunctionCall) - { - return(evalFunctionCall((SvcLogicFunctionCall)expr, node, ctx)); - } - else - { - throw new SvcLogicException("Unrecognized expression type ["+expr+"]"); - } - } - - private static String evalArithExpression(SvcLogicBinaryExpression binExpr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { - List operands = binExpr.getOperands(); - List operators = binExpr.getOperators(); - if (operands.size() != (operators.size()+1)) - { - throw new SvcLogicException("Invalid expression ("+binExpr+")"); - } - String retval = evaluate(operands.get(0), node, ctx); - String retsval = retval; - long retlval = 0; - boolean valueIsLong = false; - - int i = 1; - try - { - - if ((retval.length() > 0) && StringUtils.isNumeric(retval)) - { - retlval = Long.parseLong(retval); - valueIsLong = true; - } - for (OperatorType operator: operators) - { - String curOperandValue = evaluate(operands.get(i++), node, ctx); - switch(operator) { - case addOp: - retsval = retsval + curOperandValue; - if (valueIsLong) - { - if ((curOperandValue.length() > 0) && StringUtils.isNumeric(curOperandValue) ) - { - retlval = retlval + Long.parseLong(curOperandValue); - } - else - { - valueIsLong = false; - } - } - break; - case subOp: - retlval = retlval - Long.parseLong(curOperandValue); - break; - case multOp: - retlval = retlval * Long.parseLong(curOperandValue); - break; - case divOp: - retlval = retlval / Long.parseLong(curOperandValue); - break; - } - - } - } - catch (NumberFormatException e1) - { - throw new SvcLogicException("Illegal value in arithmetic expression", e1); - } - - if (valueIsLong) - { - return("" + retlval); - } - else - { - return(retsval); - } - - } - - - - private static String evalCompareExpression(SvcLogicBinaryExpression expr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException - { - - List operators = expr.getOperators(); - List operands = expr.getOperands(); - - if ((operators.size() != 1) || (operands.size() != 2)) - { - throw new SvcLogicException ("Invalid comparison expression : "+expr); - } - - OperatorType operator = operators.get(0); - String op1Value = evaluate(operands.get(0), node, ctx); - String op2Value = evaluate(operands.get(1), node, ctx); - - if ((StringUtils.isNotEmpty(op1Value) && StringUtils.isNumeric(op1Value) && StringUtils.isNotEmpty(op2Value) && StringUtils.isNumeric(op2Value))) - { - try - { - double op1dbl = Double.parseDouble(op1Value); - double op2dbl = Double.parseDouble(op2Value); - - switch(operator) - { - case equalOp: - return(Boolean.toString(op1dbl == op2dbl)); - case neOp: - return(Boolean.toString(op1dbl != op2dbl)); - case ltOp: - return(Boolean.toString(op1dbl < op2dbl)); - case leOp: - return(Boolean.toString(op1dbl <= op2dbl)); - case gtOp: - return(Boolean.toString(op1dbl > op2dbl)); - case geOp: - return(Boolean.toString(op1dbl >= op2dbl)); - default: - return(null); - } - } - catch (NumberFormatException e) - { - throw new SvcLogicException("Caught exception trying to compare numeric values", e); - } - } - else - { - - int compResult = 0; - - if (op1Value == null) { - compResult = -1; - } else if (op2Value == null ) { - compResult = 1; - } else { - compResult = op1Value.compareToIgnoreCase(op2Value); - } - - switch(operator) - { - case equalOp: - return(Boolean.toString(compResult == 0)); - case neOp: - return(Boolean.toString(compResult != 0)); - case ltOp: - return(Boolean.toString(compResult < 0)); - case leOp: - return(Boolean.toString(compResult <= 0)); - case gtOp: - return(Boolean.toString(compResult > 0)); - case geOp: - return(Boolean.toString(compResult >= 0)); - default: - return(null); - } - } - - } - - private static String evalLogicExpression(SvcLogicBinaryExpression expr, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException - { - boolean retval; - - List operands = expr.getOperands(); - List operators = expr.getOperators(); - - if (operands.size() != (operators.size()+1)) - { - throw new SvcLogicException("Invalid expression ("+expr+")"); - } - - try - { - retval = Boolean.parseBoolean(evaluate(operands.get(0), node, ctx)); - int i = 1; - for (OperatorType operator : operators) - { - if (operator == OperatorType.andOp) - { - retval = retval && Boolean.parseBoolean(evaluate(operands.get(i++), node, ctx)); - } - else - { - - retval = retval || Boolean.parseBoolean(evaluate(operands.get(i++), node, ctx)); - } - - } - } - catch (Exception e) - { - throw new SvcLogicException("Invalid expression ("+expr+")"); - } - - - return(Boolean.toString(retval)); - } - - private static String evalFunctionCall(SvcLogicFunctionCall func, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException - { - String funcName = func.getFunctionName(); - List operands = func.getOperands(); - - if ("length".equalsIgnoreCase(funcName)) - { - - if (operands.size() == 1) - { - String opValue = evaluate(operands.get(0), node, ctx); - return(""+opValue.length()); - } - else - { - throw new SvcLogicException("Invalid call to length() function"); - } - } - else if ("substr".equalsIgnoreCase(funcName)) - { - if (operands.size() == 3) - { - String op1Value = evaluate(operands.get(0), node, ctx); - String op2Value = evaluate(operands.get(1), node, ctx); - String op3Value = evaluate(operands.get(2), node, ctx); - - if (!StringUtils.isNumeric(op2Value) || !StringUtils.isNumeric(op3Value)) - { - throw new SvcLogicException("Invalid arguments to substr() function"); - } - - try - { - return(op1Value.substring(Integer.parseInt(op2Value), Integer.parseInt(op3Value))); - } - catch (Exception e) - { - throw new SvcLogicException("Caught exception trying to take substring", e); - } - } - else - { - - throw new SvcLogicException("Invalid call to substr() function"); - } - - } - else if ("toUpperCase".equalsIgnoreCase(funcName)) - { - if (operands.size() == 1) - { - String opValue = evaluate(operands.get(0), node, ctx); - if (opValue != null) { - return(opValue.toUpperCase()); - } else { - return(""); - } - } - else - { - throw new SvcLogicException("Invalid call to toUpperCase() function"); - } - } - else if ("toLowerCase".equalsIgnoreCase(funcName)) - { - if (operands.size() == 1) - { - String opValue = evaluate(operands.get(0), node, ctx); - if (opValue != null) { - return(opValue.toLowerCase()); - } else { - return(""); - } - } - else - { - throw new SvcLogicException("Invalid call to toLowerCase() function"); - } - } - else if ("convertBase".equalsIgnoreCase(funcName)) { - int fromBase = 10; - int toBase = 10; - String srcString = ""; - - if (operands.size() == 2) - { - fromBase = 10; - srcString = evaluate(operands.get(0), node, ctx); - toBase = Integer.parseInt(evaluate(operands.get(1), node, ctx)); - } else if (operands.size() == 3) { - - srcString = evaluate(operands.get(0), node, ctx); - fromBase = Integer.parseInt(evaluate(operands.get(1), node, ctx)); - toBase = Integer.parseInt(evaluate(operands.get(2), node, ctx)); - } else { - throw new SvcLogicException("Invalid call to convertBase() function"); - } - - long srcValue = Long.parseLong(srcString, fromBase); - return(Long.toString(srcValue, toBase)); - } - else - { - throw new SvcLogicException("Unrecognized function ("+funcName+")"); - } - - } - - public static String evaluateAsKey(SvcLogicExpression expr, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - if (expr == null) { - return (null); - } - - - - if (expr instanceof SvcLogicAtom) { - SvcLogicAtom atom = (SvcLogicAtom) expr; - - AtomType atomType = atom.getAtomType(); - StringBuffer varNameBuff = new StringBuffer(); - switch (atomType) { - case NUMBER: - return (atom.toString()); - case STRING: - return("'"+atom.toString()+"'"); - case CONTEXT_VAR: - case IDENTIFIER: - boolean needDot = false; - for (SvcLogicExpression term : atom.getOperands()) - { - if (needDot) - { - varNameBuff.append("."); - } - if (term instanceof SvcLogicVariableTerm) - { - SvcLogicVariableTerm vterm = (SvcLogicVariableTerm) term; - varNameBuff.append(vterm.getName()); - if (vterm.numOperands() > 0) - { - varNameBuff.append("["); - varNameBuff.append(evaluate(vterm.getSubscript(), node, ctx)); - varNameBuff.append("]"); - - } - } - else - { - varNameBuff.append(term.toString()); - } - needDot = true; - } - - String varName = varNameBuff.toString(); - LOG.debug("Evaluating context variable $"+varName); - String ctxValue = ctx.getAttribute(varName); - if (ctxValue == null) - { - return(null); - } - if (StringUtils.isNumeric(ctxValue)) - { - return(ctxValue); - } - else - { - return("'"+ctxValue+"'"); - } - - default: - return(null); - } - - } else if (expr instanceof SvcLogicBinaryExpression) { - SvcLogicBinaryExpression binExpr = (SvcLogicBinaryExpression) expr; - List operators = binExpr.getOperators(); - List operands = binExpr.getOperands(); - if (operators.isEmpty()) - { - if (operands.size() == 1) - { - LOG.debug("SvcLogicBinaryExpression as no operator and one operand - evaluating its operand"); - return(evaluateAsKey(operands.get(0), node, ctx)); - } - else - { - if (operands.isEmpty()) - { - LOG.error("SvcLogicBinaryExpression has no operators and no operands - evaluating value as null"); - } - else - { - LOG.error("SvcLogicBinaryExpression has no operators and "+operands.size()+" operands - evaluating value as null"); - } - return(null); - } - } - StringBuffer sbuff = new StringBuffer(); - sbuff.append(evaluateAsKey(operands.get(0), node, ctx)); - int i = 1; - for (OperatorType operator : operators) - { - sbuff.append(" "); - sbuff.append(operator.toString()); - sbuff.append(" "); - sbuff.append(evaluateAsKey(operands.get(i++), node,ctx)); - } - return(sbuff.toString()); - } - else if (expr instanceof SvcLogicFunctionCall) - { - StringBuffer sbuff = new StringBuffer(); - SvcLogicFunctionCall funcCall = (SvcLogicFunctionCall) expr; - sbuff.append(funcCall.getFunctionName()); - sbuff.append("("); - boolean needComma = false; - for (SvcLogicExpression operand : funcCall.getOperands()) - { - if (needComma) - { - sbuff.append(","); - } - else - { - needComma = true; - } - sbuff.append(evaluateAsKey(operand, node, ctx)); - } - sbuff.append(")"); - return(sbuff.toString()); - } - else - { - throw new SvcLogicException("Unrecognized expression type ["+expr+"]"); - } - } - - public static String resolveVariableName(SvcLogicExpression atom, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException - { - StringBuffer varNameBuff = new StringBuffer(); - - boolean needDot = false; - for (SvcLogicExpression term : atom.getOperands()) - { - if (needDot) - { - varNameBuff.append("."); - } - if (term instanceof SvcLogicVariableTerm) - { - SvcLogicVariableTerm vterm = (SvcLogicVariableTerm) term; - varNameBuff.append(vterm.getName()); - if (vterm.numOperands() > 0) - { - varNameBuff.append("["); - varNameBuff.append(evaluate(vterm.getSubscript(), node, ctx)); - varNameBuff.append("]"); - } - } - else - { - varNameBuff.append(term.toString()); - } - needDot = true; - } - return(varNameBuff.toString()); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicNodeExecutor.java deleted file mode 100644 index 0c8166ae1..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicNodeExecutor.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicAdaptor; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicRecorder; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.openecomp.sdnc.sli.SvcLogicStore; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class SvcLogicNodeExecutor { - - public abstract SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException; - - private static final Logger LOG = LoggerFactory.getLogger(SvcLogicNodeExecutor.class); - - protected String evaluateNodeTest(SvcLogicNode node, SvcLogicContext ctx) - throws SvcLogicException { - if (node == null) { - return null; - } - - return (SvcLogicExpressionResolver.evaluate(node.getAttribute("test"), - node, ctx)); - - } - - protected SvcLogicStore getStore() throws SvcLogicException { - return SvcLogicActivator.getStore(); - } - - protected SvcLogicAdaptor getAdaptor(String adaptorName) { - return SvcLogicAdaptorFactory.getInstance(adaptorName); - } - - protected SvcLogicResource getSvcLogicResource(String plugin) { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - - ServiceReference sref = bctx.getServiceReference(plugin); - if (sref != null) { - SvcLogicResource resourcePlugin = (SvcLogicResource) bctx - .getService(sref); - return resourcePlugin; - } - else { - LOG.warn("Could not find service reference object for plugin " + plugin); - return null; - } - } - - protected SvcLogicRecorder getSvcLogicRecorder(String plugin) { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - - ServiceReference sref = bctx.getServiceReference(plugin); - if (sref != null) { - SvcLogicRecorder resourcePlugin = (SvcLogicRecorder) bctx - .getService(sref); - return resourcePlugin; - } - else { - return null; - } - } - - protected SvcLogicJavaPlugin getSvcLogicJavaPlugin(String pluginName){ - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - - ServiceReference sref = bctx.getServiceReference(pluginName); - - if (sref == null) { - LOG.warn("Could not find service reference object for plugin " + pluginName); - return null; - } else { - SvcLogicJavaPlugin plugin = (SvcLogicJavaPlugin) bctx - .getService(sref); - return plugin; - } - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicService.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicService.java deleted file mode 100644 index f30b3fc06..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicService.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.Properties; - -import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; -import org.openecomp.sdnc.sli.SvcLogicException; - -public interface SvcLogicService { - - public static final String NAME = "org.openecomp.sdnc.sli.provider.SvcLogicService"; - - // public SvcLogicContext execute(SvcLogicGraph graph, SvcLogicContext ctx) throws SvcLogicException; - /** - * Check for existence of a directed graph - * @param module - module name - * @param rpc - rpc name - * @param version - version. If null, looks for active version - * @param mode - mode (sync/async) - * @return true if directed graph found, false otherwise - * @throws SvcLogicException - */ - public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException; - - /** - * Execute a directed graph - * - * @param module - module name - * @param rpc - rpc name - * @param version - version. If null, use active version - * @param mode - mode (sync/async) - * @param parms - parameters, used to set SvcLogicContext attributes - * @return final values of attributes from SvcLogicContext, as Properties - * @throws SvcLogicException - * - * - * @deprecated use execute(String module, String rpc, String version, String mode, DOMDataBroker dataBroker) instead - */ - @Deprecated - public Properties execute(String module, String rpc, String version, String mode, Properties parms) throws SvcLogicException; - - /** - * Execute a directed graph - * - * @param module - module name - * @param rpc - rpc name - * @param version - version. If null, use active version - * @param mode - mode (sync/async) - * @param parms - parameters, used to set SvcLogicContext attributes - * @param domDataBroker - DOMDataBroker object - * @return final values of attributes from SvcLogicContext, as Properties - * @throws SvcLogicException - */ - public Properties execute(String module, String rpc, String version, String mode, Properties parms, DOMDataBroker domDataBroker) throws SvcLogicException; - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicServiceImpl.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicServiceImpl.java deleted file mode 100644 index ba929bae7..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SvcLogicServiceImpl.java +++ /dev/null @@ -1,273 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; -import java.util.Properties; - -import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; -import org.openecomp.sdnc.sli.MetricLogger; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicGraph; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicStore; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceEvent; -import org.osgi.framework.ServiceListener; -import org.osgi.framework.ServiceReference; -import org.osgi.util.tracker.ServiceTracker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -public class SvcLogicServiceImpl implements SvcLogicService { - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicServiceImpl.class); - - private HashMap nodeExecutors = null; - - private BundleContext bctx = null; - - private void registerExecutors() { - - LOG.info("Entered register executors"); - if (bctx == null) { - bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - } - - if (nodeExecutors == null) { - nodeExecutors = new HashMap(); - } - - LOG.info("Opening service tracker"); - ServiceTracker tracker = new ServiceTracker(bctx, - SvcLogicNodeExecutor.class.getName(), null); - - tracker.open(); - - ServiceListener listener = new ServiceListener() { - - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch (ev.getType()) { - case ServiceEvent.REGISTERED: { - registerExecutor(sr); - } - break; - case ServiceEvent.UNREGISTERING: { - unregisterExecutor(sr); - } - break; - } - } - }; - - LOG.info("Adding service listener"); - String filter = "(objectclass=" + SvcLogicNodeExecutor.class.getName() - + ")"; - try { - bctx.addServiceListener(listener, filter); - ServiceReference[] srl = bctx.getServiceReferences( - SvcLogicNodeExecutor.class.getName(), null); - for (int i = 0; srl != null && i < srl.length; i++) { - listener.serviceChanged(new ServiceEvent( - ServiceEvent.REGISTERED, srl[i])); - } - } catch (InvalidSyntaxException e) { - e.printStackTrace(); - } - LOG.info("Done registerExecutors"); - } - - public void registerExecutor(ServiceReference sr) { - - String nodeName = (String) sr.getProperty("nodeType"); - if (nodeName != null) { - - SvcLogicNodeExecutor executor = null; - - try { - executor = (SvcLogicNodeExecutor) bctx.getService(sr); - } catch (Exception e) { - LOG.error("Cannot get service executor for " + nodeName); - return; - } - - registerExecutor(nodeName, executor); - - } - } - - public void registerExecutor(String nodeName, SvcLogicNodeExecutor executor) - { - if (nodeExecutors == null) { - nodeExecutors = new HashMap(); - } - LOG.info("SLI - registering executor for node type "+nodeName); - nodeExecutors.put(nodeName, executor); - } - - public void unregisterExecutor(ServiceReference sr) { - String nodeName = (String) sr.getProperty("nodeType"); - - if (nodeName != null) { - - unregisterExecutor(nodeName); - - } - - } - - public void unregisterExecutor(String nodeName) - { - - LOG.info("SLI - unregistering executor for node type "+nodeName); - nodeExecutors.remove(nodeName); - } - - - - - public SvcLogicContext execute(SvcLogicGraph graph, SvcLogicContext ctx) - throws SvcLogicException { - - if (nodeExecutors == null) { - registerExecutors(); - } - - // Set service name in MDC to reference current working directed graph - MDC.put(MetricLogger.SERVICE_NAME, graph.getModule()+":"+graph.getRpc()+"/v"+graph.getVersion()); - - SvcLogicNode curNode = graph.getRootNode(); - LOG.info("About to execute graph " + graph.toString()); - - - - while (curNode != null) { - LOG.info("About to execute node # "+curNode.getNodeId()+" ("+curNode.getNodeType()+")"); - - SvcLogicNode nextNode = executeNode(curNode, ctx); - curNode = nextNode; - } - - return (ctx); - } - - - public SvcLogicNode executeNode(SvcLogicNode node, SvcLogicContext ctx) - throws SvcLogicException { - if (node == null) { - return (null); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("Executing node " + node.getNodeId()); - } - - SvcLogicNodeExecutor executor = nodeExecutors.get(node.getNodeType()); - - if (executor != null) { - LOG.debug("Executing node executor for node type "+node.getNodeType()+" - "+executor.getClass().getName()); - return (executor.execute(this, node, ctx)); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug(node.getNodeType() + " node not implemented"); - } - SvcLogicNode nextNode = node.getOutcomeValue("failure"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute failure branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no failure or Other branch found"); - } - } - return (nextNode); - } - - } - - @Override - public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException - { - SvcLogicStore store = SvcLogicActivator.getStore(); - - return (store.hasGraph(module, rpc, version, mode)); - } - - @Override - public Properties execute(String module, String rpc, String version, String mode, Properties props) - throws SvcLogicException { - return(execute(module, rpc, version, mode, props, null)); - } - - - @Override - public Properties execute(String module, String rpc, String version, String mode, - Properties props, DOMDataBroker domDataBroker) throws SvcLogicException { - - - // See if there is a service logic defined - // - SvcLogicStore store = SvcLogicActivator.getStore(); - - LOG.info("Fetching service logic from data store"); - SvcLogicGraph graph = store.fetch(module, rpc, version, mode); - - - - if (graph == null) - { - Properties retProps = new Properties(); - retProps.setProperty("error-code", "401"); - retProps.setProperty("error-message", "No service logic found for ["+module+","+rpc+","+version+","+mode+"]"); - return(retProps); - - } - - SvcLogicContext ctx = new SvcLogicContext(props); - ctx.setAttribute("currentGraph", graph.toString()); - ctx.setAttribute("X-ECOMP-RequestID", MDC.get("X-ECOMP-RequestID")); - ctx.setDomDataBroker(domDataBroker); - - execute(graph, ctx); - - return(ctx.toProperties()); - } - - - - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SwitchNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SwitchNodeExecutor.java deleted file mode 100644 index e8ae7c89d..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/SwitchNodeExecutor.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SwitchNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(SwitchNodeExecutor.class); - - @Override - - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - - String testResult = evaluateNodeTest(node, ctx); - - if (LOG.isDebugEnabled()) { - LOG.debug("Executing switch node"); - - - LOG.debug("test expression (" + node.getAttribute("test") - + ") evaluates to " + testResult); - } - - SvcLogicNode nextNode = node.getOutcomeValue(testResult); - - if (LOG.isDebugEnabled()) { - if (nextNode != null) { - LOG.debug("Next node to execute is node " + nextNode.getNodeId()); - } else { - LOG.debug("No next node found"); - } - } - return (nextNode); - - } -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/UpdateNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/UpdateNodeExecutor.java deleted file mode 100644 index 9eeab65a3..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/UpdateNodeExecutor.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class UpdateNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory - .getLogger(UpdateNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - - String plugin = SvcLogicExpressionResolver.evaluate( - node.getAttribute("plugin"), node, ctx); - String resourceType = SvcLogicExpressionResolver.evaluate( - node.getAttribute("resource"), node, ctx); - String key = SvcLogicExpressionResolver.evaluateAsKey( - node.getAttribute("key"), node, ctx); - String pfx = SvcLogicExpressionResolver.evaluate( - node.getAttribute("pfx"), node, ctx); - - - Map parmMap = new HashMap(); - - Set> parmSet = node - .getParameterSet(); - boolean hasParms = false; - - for (Iterator> iter = parmSet - .iterator(); iter.hasNext();) { - hasParms = true; - Map.Entry curEnt = iter.next(); - String curName = curEnt.getKey(); - SvcLogicExpression curExpr = curEnt.getValue(); - if (curExpr != null) { - String curExprValue = SvcLogicExpressionResolver.evaluate( - curExpr, node, ctx); - - LOG.debug("Parameter " + curName + " = " - + curExpr.asParsedExpr() + " resolves to " - + curExprValue); - - parmMap.put(curName, curExprValue); - } - } - - String outValue = "failure"; - - if (LOG.isDebugEnabled()) { - LOG.debug("save node encountered - looking for resource class " - + plugin); - } - - - SvcLogicResource resourcePlugin = getSvcLogicResource(plugin); - - - if (resourcePlugin != null) { - - try { - switch (resourcePlugin.update(resourceType, key, - parmMap, pfx, ctx)) { - case SUCCESS: - outValue = "success"; - break; - case NOT_FOUND: - outValue = "not-found"; - break; - case FAILURE: - default: - outValue = "failure"; - } - } catch (SvcLogicException e) { - LOG.error("Caught exception from resource plugin", e); - outValue = "failure"; - } - } else { - LOG.warn("Could not find SvcLogicResource object for plugin " - + plugin); - } - - SvcLogicNode nextNode = node.getOutcomeValue(outValue); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute " + outValue + " branch"); - } - return (nextNode); - } - - nextNode = node.getOutcomeValue("Other"); - if (nextNode != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("about to execute Other branch"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("no "+outValue+" or Other branch found"); - } - } - return (nextNode); - } - -} diff --git a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/WhileNodeExecutor.java b/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/WhileNodeExecutor.java deleted file mode 100644 index 5bbab323b..000000000 --- a/sli/provider/src/main/java/org/openecomp/sdnc/sli/provider/WhileNodeExecutor.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.BreakNodeException; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WhileNodeExecutor extends SvcLogicNodeExecutor { - - private static final Logger LOG = LoggerFactory.getLogger(WhileNodeExecutor.class); - - @Override - public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { - - String testResult = evaluateNodeTest(node, ctx); - SvcLogicExpression silentFailureExpr = node.getAttribute("do"); - String doWhile = SvcLogicExpressionResolver.evaluate(silentFailureExpr, node, ctx); - if ("true".equals(doWhile)) { - LOG.debug("While loop will execute once regardless of expression because do is set to true"); - } - - try { - while ("true".equals(testResult) || "true".equals(doWhile)) { - if (!"true".equals(doWhile)) { - LOG.debug("Test expression (" + node.getAttribute("test") + ") evaluates to true, executing loop."); - } - int numOutcomes = node.getNumOutcomes() + 1; - for (int i = 0; i < numOutcomes; i++) { - SvcLogicNode nextNode = node.getOutcomeValue("" + (i + 1)); - if (nextNode != null) { - while (nextNode != null) { - nextNode = svc.executeNode(nextNode, ctx); - } - } else { - if ("true".equals(doWhile)) { - LOG.debug("Do executed, will only execute again if test expression is true."); - doWhile = "false"; - } - testResult = evaluateNodeTest(node, ctx); - LOG.debug("test expression (" + node.getAttribute("test") + ") evaluates to " + testResult); - } - } - } - LOG.debug("testResult was " + testResult + " which is not equal to true, exiting while loop."); - } catch (BreakNodeException e) { - LOG.debug("WhileNodeExecutor caught break"); - } - return (null); - } - -} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/BadPlugin.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/BadPlugin.java new file mode 100644 index 000000000..87273d0b1 --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/BadPlugin.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + +public class BadPlugin implements SvcLogicJavaPlugin { + public String selectLunch(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + String day = parameters.get("day"); + if (day == null || day.length() < 1) { + throw new SvcLogicException("What day is it?"); + } + switch (day) { + case ("monday"): { + return "pizza"; + } + case ("tuesday"): { + return "soup"; + } + case ("wednesday"): { + return "salad"; + } + case ("thursday"): { + return "sushi"; + } + case ("friday"): { + return "bbq"; + } + } + throw new SvcLogicException("Lunch cannot be served"); + } +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java new file mode 100644 index 000000000..4c16222b2 --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.Map.Entry; + +import org.onap.ccsdk.sli.core.sli.DuplicateValueException; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicServiceImpl; + +import junit.framework.TestCase; + +public class ExecuteNodeExecutorTest extends TestCase { + public class MockExecuteNodeExecutor extends ExecuteNodeExecutor { + + protected SvcLogicJavaPlugin getSvcLogicJavaPlugin(String pluginName) { + return (SvcLogicJavaPlugin) new LunchSelectorPlugin(); + } + + protected String evaluate(SvcLogicExpression expr, SvcLogicNode node, + SvcLogicContext ctx) throws SvcLogicException { + return "selectLunch"; + } + } + + public void testBadPlugin() throws DuplicateValueException, SvcLogicException { + LunchSelectorPlugin p = new LunchSelectorPlugin(); + MockExecuteNodeExecutor execute = new MockExecuteNodeExecutor(); + SvcLogicNode node = new SvcLogicNode(0, "", "", new SvcLogicGraph()); + node.setAttribute("method", "selectLunch"); + execute.execute(new SvcLogicServiceImpl(), new SvcLogicNode(0, "", "", new SvcLogicGraph()), new SvcLogicContext()); + } + +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/LunchSelectorPlugin.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/LunchSelectorPlugin.java new file mode 100644 index 000000000..4d6b0b4dd --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/LunchSelectorPlugin.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + + +public class LunchSelectorPlugin implements SvcLogicJavaPlugin { + public class UnknownLunchDayException extends Exception{ + + public UnknownLunchDayException(String string) { + super(string); + } + + } + class Sandwhich { + String meat; + String cheese; + + public Sandwhich(String meat, String cheese) { + this.meat = meat; + this.cheese = cheese; + } + } + + public String selectLunch(Map parameters, SvcLogicContext ctx) throws Exception { + String day = parameters.get("day"); + if (day == null || day.length() < 1) { + throw new UnknownLunchDayException("What day is it?"); + } + switch (day) { + case ("monday"): { + return "pizza"; + } + case ("tuesday"): { + return "soup"; + } + case ("wednesday"): { + return "salad"; + } + case ("thursday"): { + return "sushi"; + } + case ("friday"): { + return "bbq"; + } + } + throw new SvcLogicException("Lunch cannot be served"); + } + + public Sandwhich makeLunch(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + return new Sandwhich("ham", "american"); + } +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java new file mode 100644 index 000000000..8057dbd12 --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import junit.framework.TestCase; + +public class MdsalHelperTest extends TestCase { + + public static final String pathToSdnPropertiesFile = "./src/test/resources/l3sdn.properties"; + + public void testSdnProperties() { + MdsalHelperTesterUtil.loadProperties(pathToSdnPropertiesFile); + assertEquals("synccomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "Synccomplete")); + assertEquals("asynccomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "asynccomplete")); + assertEquals("notifycomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "notifycomplete")); + assertEquals("service-configuration-operation", MdsalHelperTesterUtil.mapEnumeratedValue("rpc-name", + "ServiceConfigurationOperation")); + } + + public void testNegativeSdnProperties() { + assertNotSame("synccomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "Synccomplete")); + } + +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTesterUtil.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTesterUtil.java new file mode 100644 index 000000000..75517a1e6 --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTesterUtil.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import org.onap.ccsdk.sli.core.sli.provider.MdsalHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MdsalHelperTesterUtil extends MdsalHelper { + + private static final Logger LOG = LoggerFactory.getLogger(MdsalHelperTesterUtil.class); + + //Normally static init of classes goes here for some weird classloader thing + static { + String str = "Hello World!"; + } + +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/PluginTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/PluginTest.java new file mode 100644 index 000000000..08ab5eebf --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/PluginTest.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicExpressionResolver; + +import junit.framework.TestCase; + +public class PluginTest extends TestCase { + + // The existing plugins work just like a VoidDummyPlugin + // They will return null simply because they are all void + // The attribute emitsOutcome will not be present, the expected outcome is success when no exception is thrown by the plugin + public void testOldPlugin() throws Exception { + ExecuteNodeExecutor executor = new ExecuteNodeExecutor(); + SvcLogicJavaPlugin plugin = new VoidDummyPlugin(); + + Class pluginClass = plugin.getClass(); + Method pluginMethod = pluginClass.getMethod("dummy", Map.class, SvcLogicContext.class); + Map parmMap = new HashMap(); + SvcLogicContext ctx = new SvcLogicContext(); + Object o = pluginMethod.invoke(plugin, parmMap, ctx); + + SvcLogicGraph graph = new SvcLogicGraph(); + SvcLogicNode node = new SvcLogicNode(1, "return", graph); + String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); + String outValue = executor.mapOutcome(o, emitsOutcome); + assertEquals("success",outValue); + } + + //Newer plugins can set the attribute emitsOutcome to true, if so they should return a string + //The string represents the outcome value + public void testNewPlugin() throws Exception { + ExecuteNodeExecutor executor = new ExecuteNodeExecutor(); + SvcLogicJavaPlugin plugin = new LunchSelectorPlugin(); + + Class pluginClass = plugin.getClass(); + Method pluginMethod = pluginClass.getMethod("selectLunch", Map.class, SvcLogicContext.class); + + Map parmMap = new HashMap(); + SvcLogicContext ctx = new SvcLogicContext(); + + parmMap.put("day", "monday"); + Object o = pluginMethod.invoke(plugin, parmMap, ctx); + SvcLogicGraph graph = new SvcLogicGraph(); + SvcLogicNode node = new SvcLogicNode(1, "return", graph); + node.setAttribute("emitsOutcome", "true"); + String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); + String outValue = executor.mapOutcome(o, emitsOutcome); + assertEquals("pizza", outValue); + + parmMap.put("day", "tuesday"); + outValue = (String) pluginMethod.invoke(plugin, parmMap, ctx); + o = pluginMethod.invoke(plugin, parmMap, ctx); + outValue = executor.mapOutcome(o, emitsOutcome); + assertEquals("soup",outValue); + + } + + //APPC had some legacy plugins returning objects which should not be treated as outcomes + //The attribute emitsOutcome will not be set + //The outcome should be success as it has always been + public void testObjPlugin() throws Exception{ + ExecuteNodeExecutor executor = new ExecuteNodeExecutor(); + SvcLogicJavaPlugin plugin = new LunchSelectorPlugin(); + + Class pluginClass = plugin.getClass(); + Method pluginMethod = pluginClass.getMethod("makeLunch", Map.class, SvcLogicContext.class); + + Map parmMap = new HashMap(); + SvcLogicContext ctx = new SvcLogicContext(); + Object o = pluginMethod.invoke(plugin, parmMap, ctx); + SvcLogicGraph graph = new SvcLogicGraph(); + SvcLogicNode node = new SvcLogicNode(1, "return", graph); + String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); + String outValue = executor.mapOutcome(o, emitsOutcome); + assertEquals("success",outValue); + } + +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolverTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolverTest.java new file mode 100644 index 000000000..1705e7902 --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicExpressionResolverTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicExprListener; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; +import org.onap.ccsdk.sli.core.sli.SvcLogicExpressionFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicExpressionResolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import junit.framework.Assert; +import junit.framework.TestCase; + +public class SvcLogicExpressionResolverTest extends TestCase { + + + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicExpressionResolver.class); + + public void testEvaluate() + { + InputStream testStr = getClass().getResourceAsStream("/expression.tests"); + BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); + + try + { + SvcLogicContext ctx = new SvcLogicContext(); + SvcLogicGraph graph = new SvcLogicGraph(); + SvcLogicNode node = new SvcLogicNode(1, "return", graph); + graph.setRootNode(node); + + String line = null; + int lineNo = 0; + while ((line = testsReader.readLine()) != null) { + ++lineNo; + if (line.startsWith("#")) + { + String testExpr = line.trim().substring(1).trim(); + String[] nameValue = testExpr.split("="); + String name = nameValue[0].trim(); + String value = nameValue[1].trim(); + + if (name.startsWith("$")) + { + LOG.info("Setting context attribute "+name+" = "+value); + ctx.setAttribute(name.substring(1), value); + } + else + { + + LOG.info("Setting node attribute "+name+" = "+value); + node.setAttribute(name, value); + + } + } + else + { + // if the line contains #, what comes before is the expression to evaluate, and what comes after + // is the expected value + String[] substrings = line.split("#"); + String expectedValue = substrings.length > 1 ? substrings[1].trim() : null; + String testExpr = substrings[0].trim(); + + LOG.info("Parsing expression "+testExpr); + SvcLogicExpression expr = SvcLogicExpressionFactory.parse(testExpr); + if (expr == null) + { + fail("Unable to parse expression "+testExpr); + } + else + { + LOG.info("Evaluating parsed expression "+expr.asParsedExpr()); + String exprValue = SvcLogicExpressionResolver.evaluate(expr, node, ctx); + if (exprValue == null) + { + fail("Unable to evaluate expression "+testExpr); + } + else + { + LOG.info("Expression " + testExpr + " evaluates to " + exprValue); + if (expectedValue != null) { + Assert.assertEquals("Line " + lineNo + ": " + testExpr, expectedValue, exprValue); + } + } + } + } + } + } + catch (Exception e) + { + LOG.error("Caught exception", e); + fail("Caught exception"); + } + } + +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicGraphExecutorTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicGraphExecutorTest.java new file mode 100644 index 000000000..b54f28460 --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicGraphExecutorTest.java @@ -0,0 +1,211 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.MetricLogger; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; +import org.onap.ccsdk.sli.core.sli.SvcLogicNode; +import org.onap.ccsdk.sli.core.sli.SvcLogicParser; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; +import org.onap.ccsdk.sli.core.sli.provider.BlockNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.CallNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ConfigureNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.DeleteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ExistsNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ForNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.GetResourceNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.IsAvailableNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.NotifyNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.RecordNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ReleaseNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ReserveNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ReturnNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SaveNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SetNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicServiceImpl; +import org.onap.ccsdk.sli.core.sli.provider.SwitchNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.UpdateNodeExecutor; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import junit.framework.TestCase; + +public class SvcLogicGraphExecutorTest extends TestCase { + private static final Logger LOG = LoggerFactory + .getLogger(SvcLogicGraph.class); + + private static final Map BUILTIN_NODES = new HashMap() { + { + put("block", new BlockNodeExecutor()); + put("call", new CallNodeExecutor()); + put("configure", new ConfigureNodeExecutor()); + put("delete", new DeleteNodeExecutor()); + put("execute", new ExecuteNodeExecutor()); + put("exists", new ExistsNodeExecutor()); + put("for", new ForNodeExecutor()); + put("get-resource", new GetResourceNodeExecutor()); + put("is-available", new IsAvailableNodeExecutor()); + put("notify", new NotifyNodeExecutor()); + put("record", new RecordNodeExecutor()); + put("release", new ReleaseNodeExecutor()); + put("reserve", new ReserveNodeExecutor()); + put("return", new ReturnNodeExecutor()); + put("save", new SaveNodeExecutor()); + put("set", new SetNodeExecutor()); + put("switch", new SwitchNodeExecutor()); + put("update", new UpdateNodeExecutor()); + + } + }; + + public void testExecute() { + + try { + InputStream testStr = getClass().getResourceAsStream("/executor.tests"); + BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); + + InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); + + SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(propStr); + + assertNotNull(store); + + store.registerNodeType("switch"); + store.registerNodeType("block"); + store.registerNodeType("get-resource"); + store.registerNodeType("reserve"); + store.registerNodeType("is-available"); + store.registerNodeType("exists"); + store.registerNodeType("configure"); + store.registerNodeType("return"); + store.registerNodeType("record"); + store.registerNodeType("allocate"); + store.registerNodeType("release"); + store.registerNodeType("for"); + store.registerNodeType("set"); + SvcLogicParser parser = new SvcLogicParser(store); + + // Loop through executor tests + + SvcLogicServiceImpl svc = new SvcLogicServiceImpl(); + + for (String nodeType : BUILTIN_NODES.keySet()) { + + LOG.info("SLI - registering node executor for node type "+nodeType); + + svc.registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); + + } + String testCaseLine = null; + while ((testCaseLine = testsReader.readLine()) != null) { + + String[] testCaseFields = testCaseLine.split(":"); + String testCaseFile = testCaseFields[0]; + String testCaseMethod = testCaseFields[1]; + String testCaseParameters = null; + + if (testCaseFields.length > 2) { + testCaseParameters = testCaseFields[2]; + } + + SvcLogicContext ctx = new SvcLogicContext(); + if (testCaseParameters != null) { + String[] testCaseParameterSettings = testCaseParameters.split(","); + + for (int i = 0 ; i < testCaseParameterSettings.length ; i++) { + String[] nameValue = testCaseParameterSettings[i].split("="); + if (nameValue != null) { + String name = nameValue[0]; + String value = ""; + if (nameValue.length > 1) { + value = nameValue[1]; + } + + ctx.setAttribute(name, value); + } + } + } + + testCaseFile = testCaseFile.trim(); + + if (testCaseFile.length() > 0) { + if (!testCaseFile.startsWith("/")) { + testCaseFile = "/"+testCaseFile; + } + URL testCaseUrl = getClass().getResource(testCaseFile); + if (testCaseUrl == null) { + fail("Could not resolve test case file "+testCaseFile); + } + + LinkedList graphs = parser.parse(testCaseUrl.getPath()); + + + assertNotNull(graphs); + + for (SvcLogicGraph graph: graphs) { + if (graph.getRpc().equals(testCaseMethod)) { + Properties props = ctx.toProperties(); + LOG.info("SvcLogicContext before executing "+testCaseMethod+":"); + for (Enumeration e1 = props.propertyNames(); e1.hasMoreElements() ; ) { + String propName = (String) e1.nextElement(); + LOG.info(propName+" = "+props.getProperty(propName)); + } + + svc.execute(graph, ctx); + + props = ctx.toProperties(); + LOG.info("SvcLogicContext after executing "+testCaseMethod+":"); + for (Enumeration e2 = props.propertyNames(); e2.hasMoreElements() ; ) { + String propName = (String) e2.nextElement(); + LOG.info(propName+" = "+props.getProperty(propName)); + } + } + } + + } + + + } + + + } catch (Exception e) { + LOG.error("Caught exception executing directed graphs", e); + fail("Exception executing graphs"); + } + } + + +} diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/VoidDummyPlugin.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/VoidDummyPlugin.java new file mode 100644 index 000000000..7c6eee9ab --- /dev/null +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/VoidDummyPlugin.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 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.sli.provider; + +import java.util.Map; + +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + + + +public class VoidDummyPlugin implements SvcLogicJavaPlugin { + + public void dummy(Map parameters, SvcLogicContext ctx) throws SvcLogicException { + return; + } + +} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/BadPlugin.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/BadPlugin.java deleted file mode 100644 index d1ab4cfdd..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/BadPlugin.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.Map; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; - - -public class BadPlugin implements SvcLogicJavaPlugin { - public String selectLunch(Map parameters, SvcLogicContext ctx) throws SvcLogicException { - String day = parameters.get("day"); - if (day == null || day.length() < 1) { - throw new SvcLogicException("What day is it?"); - } - switch (day) { - case ("monday"): { - return "pizza"; - } - case ("tuesday"): { - return "soup"; - } - case ("wednesday"): { - return "salad"; - } - case ("thursday"): { - return "sushi"; - } - case ("friday"): { - return "bbq"; - } - } - throw new SvcLogicException("Lunch cannot be served"); - } -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutorTest.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutorTest.java deleted file mode 100644 index 3d43ee11d..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/ExecuteNodeExecutorTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.Map.Entry; - -import org.openecomp.sdnc.sli.DuplicateValueException; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicGraph; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; -import org.openecomp.sdnc.sli.SvcLogicNode; - -import junit.framework.TestCase; - -public class ExecuteNodeExecutorTest extends TestCase { - public class MockExecuteNodeExecutor extends ExecuteNodeExecutor { - - protected SvcLogicJavaPlugin getSvcLogicJavaPlugin(String pluginName) { - return (SvcLogicJavaPlugin) new LunchSelectorPlugin(); - } - - protected String evaluate(SvcLogicExpression expr, SvcLogicNode node, - SvcLogicContext ctx) throws SvcLogicException { - return "selectLunch"; - } - } - - public void testBadPlugin() throws DuplicateValueException, SvcLogicException { - LunchSelectorPlugin p = new LunchSelectorPlugin(); - MockExecuteNodeExecutor execute = new MockExecuteNodeExecutor(); - SvcLogicNode node = new SvcLogicNode(0, "", "", new SvcLogicGraph()); - node.setAttribute("method", "selectLunch"); - execute.execute(new SvcLogicServiceImpl(), new SvcLogicNode(0, "", "", new SvcLogicGraph()), new SvcLogicContext()); - } - -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/LunchSelectorPlugin.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/LunchSelectorPlugin.java deleted file mode 100644 index b9156bcdc..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/LunchSelectorPlugin.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.Map; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; - - - -public class LunchSelectorPlugin implements SvcLogicJavaPlugin { - public class UnknownLunchDayException extends Exception{ - - public UnknownLunchDayException(String string) { - super(string); - } - - } - class Sandwhich { - String meat; - String cheese; - - public Sandwhich(String meat, String cheese) { - this.meat = meat; - this.cheese = cheese; - } - } - - public String selectLunch(Map parameters, SvcLogicContext ctx) throws Exception { - String day = parameters.get("day"); - if (day == null || day.length() < 1) { - throw new UnknownLunchDayException("What day is it?"); - } - switch (day) { - case ("monday"): { - return "pizza"; - } - case ("tuesday"): { - return "soup"; - } - case ("wednesday"): { - return "salad"; - } - case ("thursday"): { - return "sushi"; - } - case ("friday"): { - return "bbq"; - } - } - throw new SvcLogicException("Lunch cannot be served"); - } - - public Sandwhich makeLunch(Map parameters, SvcLogicContext ctx) throws SvcLogicException { - return new Sandwhich("ham", "american"); - } -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTest.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTest.java deleted file mode 100644 index a4e41bbad..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import junit.framework.TestCase; - -public class MdsalHelperTest extends TestCase { - - public static final String pathToSdnPropertiesFile = "./src/test/resources/l3sdn.properties"; - - public void testSdnProperties() { - MdsalHelperTesterUtil.loadProperties(pathToSdnPropertiesFile); - assertEquals("synccomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "Synccomplete")); - assertEquals("asynccomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "asynccomplete")); - assertEquals("notifycomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "notifycomplete")); - assertEquals("service-configuration-operation", MdsalHelperTesterUtil.mapEnumeratedValue("rpc-name", - "ServiceConfigurationOperation")); - } - - public void testNegativeSdnProperties() { - assertNotSame("synccomplete", MdsalHelperTesterUtil.mapEnumeratedValue("request-status", "Synccomplete")); - } - -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTesterUtil.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTesterUtil.java deleted file mode 100644 index 01e333f6e..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/MdsalHelperTesterUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import org.openecomp.sdnc.sli.provider.MdsalHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MdsalHelperTesterUtil extends MdsalHelper { - - private static final Logger LOG = LoggerFactory.getLogger(MdsalHelperTesterUtil.class); - - //Normally static init of classes goes here for some weird classloader thing - static { - String str = "Hello World!"; - } - -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/PluginTest.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/PluginTest.java deleted file mode 100644 index 035cd3e79..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/PluginTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicGraph; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; -import org.openecomp.sdnc.sli.SvcLogicNode; - -import junit.framework.TestCase; - -public class PluginTest extends TestCase { - - // The existing plugins work just like a VoidDummyPlugin - // They will return null simply because they are all void - // The attribute emitsOutcome will not be present, the expected outcome is success when no exception is thrown by the plugin - public void testOldPlugin() throws Exception { - ExecuteNodeExecutor executor = new ExecuteNodeExecutor(); - SvcLogicJavaPlugin plugin = new VoidDummyPlugin(); - - Class pluginClass = plugin.getClass(); - Method pluginMethod = pluginClass.getMethod("dummy", Map.class, SvcLogicContext.class); - Map parmMap = new HashMap(); - SvcLogicContext ctx = new SvcLogicContext(); - Object o = pluginMethod.invoke(plugin, parmMap, ctx); - - SvcLogicGraph graph = new SvcLogicGraph(); - SvcLogicNode node = new SvcLogicNode(1, "return", graph); - String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); - String outValue = executor.mapOutcome(o, emitsOutcome); - assertEquals("success",outValue); - } - - //Newer plugins can set the attribute emitsOutcome to true, if so they should return a string - //The string represents the outcome value - public void testNewPlugin() throws Exception { - ExecuteNodeExecutor executor = new ExecuteNodeExecutor(); - SvcLogicJavaPlugin plugin = new LunchSelectorPlugin(); - - Class pluginClass = plugin.getClass(); - Method pluginMethod = pluginClass.getMethod("selectLunch", Map.class, SvcLogicContext.class); - - Map parmMap = new HashMap(); - SvcLogicContext ctx = new SvcLogicContext(); - - parmMap.put("day", "monday"); - Object o = pluginMethod.invoke(plugin, parmMap, ctx); - SvcLogicGraph graph = new SvcLogicGraph(); - SvcLogicNode node = new SvcLogicNode(1, "return", graph); - node.setAttribute("emitsOutcome", "true"); - String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); - String outValue = executor.mapOutcome(o, emitsOutcome); - assertEquals("pizza", outValue); - - parmMap.put("day", "tuesday"); - outValue = (String) pluginMethod.invoke(plugin, parmMap, ctx); - o = pluginMethod.invoke(plugin, parmMap, ctx); - outValue = executor.mapOutcome(o, emitsOutcome); - assertEquals("soup",outValue); - - } - - //APPC had some legacy plugins returning objects which should not be treated as outcomes - //The attribute emitsOutcome will not be set - //The outcome should be success as it has always been - public void testObjPlugin() throws Exception{ - ExecuteNodeExecutor executor = new ExecuteNodeExecutor(); - SvcLogicJavaPlugin plugin = new LunchSelectorPlugin(); - - Class pluginClass = plugin.getClass(); - Method pluginMethod = pluginClass.getMethod("makeLunch", Map.class, SvcLogicContext.class); - - Map parmMap = new HashMap(); - SvcLogicContext ctx = new SvcLogicContext(); - Object o = pluginMethod.invoke(plugin, parmMap, ctx); - SvcLogicGraph graph = new SvcLogicGraph(); - SvcLogicNode node = new SvcLogicNode(1, "return", graph); - String emitsOutcome = SvcLogicExpressionResolver.evaluate(node.getAttribute("emitsOutcome"), node, ctx); - String outValue = executor.mapOutcome(o, emitsOutcome); - assertEquals("success",outValue); - } - -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolverTest.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolverTest.java deleted file mode 100644 index 618154883..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicExpressionResolverTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicExprListener; -import org.openecomp.sdnc.sli.SvcLogicExpression; -import org.openecomp.sdnc.sli.SvcLogicExpressionFactory; -import org.openecomp.sdnc.sli.SvcLogicGraph; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.provider.SvcLogicExpressionResolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.Assert; -import junit.framework.TestCase; - -public class SvcLogicExpressionResolverTest extends TestCase { - - - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicExpressionResolver.class); - - public void testEvaluate() - { - InputStream testStr = getClass().getResourceAsStream("/expression.tests"); - BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); - - try - { - SvcLogicContext ctx = new SvcLogicContext(); - SvcLogicGraph graph = new SvcLogicGraph(); - SvcLogicNode node = new SvcLogicNode(1, "return", graph); - graph.setRootNode(node); - - String line = null; - int lineNo = 0; - while ((line = testsReader.readLine()) != null) { - ++lineNo; - if (line.startsWith("#")) - { - String testExpr = line.trim().substring(1).trim(); - String[] nameValue = testExpr.split("="); - String name = nameValue[0].trim(); - String value = nameValue[1].trim(); - - if (name.startsWith("$")) - { - LOG.info("Setting context attribute "+name+" = "+value); - ctx.setAttribute(name.substring(1), value); - } - else - { - - LOG.info("Setting node attribute "+name+" = "+value); - node.setAttribute(name, value); - - } - } - else - { - // if the line contains #, what comes before is the expression to evaluate, and what comes after - // is the expected value - String[] substrings = line.split("#"); - String expectedValue = substrings.length > 1 ? substrings[1].trim() : null; - String testExpr = substrings[0].trim(); - - LOG.info("Parsing expression "+testExpr); - SvcLogicExpression expr = SvcLogicExpressionFactory.parse(testExpr); - if (expr == null) - { - fail("Unable to parse expression "+testExpr); - } - else - { - LOG.info("Evaluating parsed expression "+expr.asParsedExpr()); - String exprValue = SvcLogicExpressionResolver.evaluate(expr, node, ctx); - if (exprValue == null) - { - fail("Unable to evaluate expression "+testExpr); - } - else - { - LOG.info("Expression " + testExpr + " evaluates to " + exprValue); - if (expectedValue != null) { - Assert.assertEquals("Line " + lineNo + ": " + testExpr, expectedValue, exprValue); - } - } - } - } - } - } - catch (Exception e) - { - LOG.error("Caught exception", e); - fail("Caught exception"); - } - } - -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicGraphExecutorTest.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicGraphExecutorTest.java deleted file mode 100644 index 2e8b35e12..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/SvcLogicGraphExecutorTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Properties; - -import org.openecomp.sdnc.sli.MetricLogger; -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicGraph; -import org.openecomp.sdnc.sli.SvcLogicNode; -import org.openecomp.sdnc.sli.SvcLogicParser; -import org.openecomp.sdnc.sli.SvcLogicStore; -import org.openecomp.sdnc.sli.SvcLogicStoreFactory; -import org.openecomp.sdnc.sli.provider.BlockNodeExecutor; -import org.openecomp.sdnc.sli.provider.CallNodeExecutor; -import org.openecomp.sdnc.sli.provider.ConfigureNodeExecutor; -import org.openecomp.sdnc.sli.provider.DeleteNodeExecutor; -import org.openecomp.sdnc.sli.provider.ExecuteNodeExecutor; -import org.openecomp.sdnc.sli.provider.ExistsNodeExecutor; -import org.openecomp.sdnc.sli.provider.ForNodeExecutor; -import org.openecomp.sdnc.sli.provider.GetResourceNodeExecutor; -import org.openecomp.sdnc.sli.provider.IsAvailableNodeExecutor; -import org.openecomp.sdnc.sli.provider.NotifyNodeExecutor; -import org.openecomp.sdnc.sli.provider.RecordNodeExecutor; -import org.openecomp.sdnc.sli.provider.ReleaseNodeExecutor; -import org.openecomp.sdnc.sli.provider.ReserveNodeExecutor; -import org.openecomp.sdnc.sli.provider.ReturnNodeExecutor; -import org.openecomp.sdnc.sli.provider.SaveNodeExecutor; -import org.openecomp.sdnc.sli.provider.SetNodeExecutor; -import org.openecomp.sdnc.sli.provider.SvcLogicNodeExecutor; -import org.openecomp.sdnc.sli.provider.SvcLogicServiceImpl; -import org.openecomp.sdnc.sli.provider.SwitchNodeExecutor; -import org.openecomp.sdnc.sli.provider.UpdateNodeExecutor; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestCase; - -public class SvcLogicGraphExecutorTest extends TestCase { - private static final Logger LOG = LoggerFactory - .getLogger(SvcLogicGraph.class); - - private static final Map BUILTIN_NODES = new HashMap() { - { - put("block", new BlockNodeExecutor()); - put("call", new CallNodeExecutor()); - put("configure", new ConfigureNodeExecutor()); - put("delete", new DeleteNodeExecutor()); - put("execute", new ExecuteNodeExecutor()); - put("exists", new ExistsNodeExecutor()); - put("for", new ForNodeExecutor()); - put("get-resource", new GetResourceNodeExecutor()); - put("is-available", new IsAvailableNodeExecutor()); - put("notify", new NotifyNodeExecutor()); - put("record", new RecordNodeExecutor()); - put("release", new ReleaseNodeExecutor()); - put("reserve", new ReserveNodeExecutor()); - put("return", new ReturnNodeExecutor()); - put("save", new SaveNodeExecutor()); - put("set", new SetNodeExecutor()); - put("switch", new SwitchNodeExecutor()); - put("update", new UpdateNodeExecutor()); - - } - }; - - public void testExecute() { - - try { - InputStream testStr = getClass().getResourceAsStream("/executor.tests"); - BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); - - InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); - - SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(propStr); - - assertNotNull(store); - - store.registerNodeType("switch"); - store.registerNodeType("block"); - store.registerNodeType("get-resource"); - store.registerNodeType("reserve"); - store.registerNodeType("is-available"); - store.registerNodeType("exists"); - store.registerNodeType("configure"); - store.registerNodeType("return"); - store.registerNodeType("record"); - store.registerNodeType("allocate"); - store.registerNodeType("release"); - store.registerNodeType("for"); - store.registerNodeType("set"); - SvcLogicParser parser = new SvcLogicParser(store); - - // Loop through executor tests - - SvcLogicServiceImpl svc = new SvcLogicServiceImpl(); - - for (String nodeType : BUILTIN_NODES.keySet()) { - - LOG.info("SLI - registering node executor for node type "+nodeType); - - svc.registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); - - } - String testCaseLine = null; - while ((testCaseLine = testsReader.readLine()) != null) { - - String[] testCaseFields = testCaseLine.split(":"); - String testCaseFile = testCaseFields[0]; - String testCaseMethod = testCaseFields[1]; - String testCaseParameters = null; - - if (testCaseFields.length > 2) { - testCaseParameters = testCaseFields[2]; - } - - SvcLogicContext ctx = new SvcLogicContext(); - if (testCaseParameters != null) { - String[] testCaseParameterSettings = testCaseParameters.split(","); - - for (int i = 0 ; i < testCaseParameterSettings.length ; i++) { - String[] nameValue = testCaseParameterSettings[i].split("="); - if (nameValue != null) { - String name = nameValue[0]; - String value = ""; - if (nameValue.length > 1) { - value = nameValue[1]; - } - - ctx.setAttribute(name, value); - } - } - } - - testCaseFile = testCaseFile.trim(); - - if (testCaseFile.length() > 0) { - if (!testCaseFile.startsWith("/")) { - testCaseFile = "/"+testCaseFile; - } - URL testCaseUrl = getClass().getResource(testCaseFile); - if (testCaseUrl == null) { - fail("Could not resolve test case file "+testCaseFile); - } - - LinkedList graphs = parser.parse(testCaseUrl.getPath()); - - - assertNotNull(graphs); - - for (SvcLogicGraph graph: graphs) { - if (graph.getRpc().equals(testCaseMethod)) { - Properties props = ctx.toProperties(); - LOG.info("SvcLogicContext before executing "+testCaseMethod+":"); - for (Enumeration e1 = props.propertyNames(); e1.hasMoreElements() ; ) { - String propName = (String) e1.nextElement(); - LOG.info(propName+" = "+props.getProperty(propName)); - } - - svc.execute(graph, ctx); - - props = ctx.toProperties(); - LOG.info("SvcLogicContext after executing "+testCaseMethod+":"); - for (Enumeration e2 = props.propertyNames(); e2.hasMoreElements() ; ) { - String propName = (String) e2.nextElement(); - LOG.info(propName+" = "+props.getProperty(propName)); - } - } - } - - } - - - } - - - } catch (Exception e) { - LOG.error("Caught exception executing directed graphs", e); - fail("Exception executing graphs"); - } - } - - -} diff --git a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/VoidDummyPlugin.java b/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/VoidDummyPlugin.java deleted file mode 100644 index 6c8214ab7..000000000 --- a/sli/provider/src/test/java/org/openecomp/sdnc/sli/provider/VoidDummyPlugin.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdnc.sli.provider; - -import java.util.Map; - -import org.openecomp.sdnc.sli.SvcLogicContext; -import org.openecomp.sdnc.sli.SvcLogicException; -import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; - - - -public class VoidDummyPlugin implements SvcLogicJavaPlugin { - - public void dummy(Map parameters, SvcLogicContext ctx) throws SvcLogicException { - return; - } - -} diff --git a/sli/provider/src/test/resources/l3sdn_logic_v10.xml b/sli/provider/src/test/resources/l3sdn_logic_v10.xml index d81b8b789..56e1a81ef 100644 --- a/sli/provider/src/test/resources/l3sdn_logic_v10.xml +++ b/sli/provider/src/test/resources/l3sdn_logic_v10.xml @@ -1,10 +1,9 @@ + + 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 8ae9a2665..000000000 --- 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 000000000..201cc4019 --- /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 78b970bf5..46c003a5a 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 000000000..17c42ec83 --- /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 000000000..673ccbf03 --- /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 000000000..d2b164e3b --- /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 000000000..97ab08acf --- /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 000000000..ee3e0f033 --- /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 000000000..41011e55b --- /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 000000000..775898930 --- /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 000000000..117492d0b --- /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 000000000..0a032e8b7 --- /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 2aed6511d..de3682d8a 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 From cce6f1cd01d319d7d01b3bc9be0ff903621ce1ec Mon Sep 17 00:00:00 2001 From: shashikanth Date: Fri, 8 Sep 2017 14:24:06 +0530 Subject: Fix Blocker/Critical sonar issues Fix Blocker/Critical sonar issues in vnfapi module https://sonar.onap.org/component_issues?id=org.onap.ccsdk.sli.core%3Accsdk-sli-core#severities=BLOCKER Issue-Id: CCSDK-67 Change-Id: I0b779cb0db33f0742776062bd7fa7173f08d5e62 Signed-off-by: shashikanth.vh --- .../core/dblib/factory/AbstractResourceManagerFactory.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java index 6fc7e7a04..486d0ccc1 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java @@ -21,13 +21,8 @@ package org.onap.ccsdk.sli.core.dblib.factory; -import java.sql.SQLException; -import java.util.Set; -import java.util.concurrent.Callable; - import org.onap.ccsdk.sli.core.dblib.CachedDataSource; import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; -import org.onap.ccsdk.sli.core.dblib.DBConfigException; import org.onap.ccsdk.sli.core.dblib.DBResourceManager; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; @@ -35,6 +30,10 @@ import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.sql.SQLException; +import java.util.Set; +import java.util.concurrent.Callable; + /** * @version $Revision: 1.6 $ * Change Log @@ -85,7 +84,8 @@ public abstract class AbstractResourceManagerFactory { } }; if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Completed CachedDataSource.Call and notifyAll from " + ds.getDbConnectionName()); + LOGGER.debug("Completed CachedDataSource.Call and notifyAll from " + (ds != null ? ds + .getDbConnectionName() : null)); } Thread worker = new Thread(closure); worker.setDaemon(true); -- cgit 1.2.3-korg From d74c0195215fd495fa37e4e3712f634f06e4e0b3 Mon Sep 17 00:00:00 2001 From: shashikanth Date: Thu, 7 Sep 2017 18:15:52 +0530 Subject: Fix Blocker/Critical sonar issues Fix Blocker/Critical sonar issues in vnfapi module https://sonar.onap.org/component_issues?id=org.onap.ccsdk.sli.core%3Accsdk-sli-core#severities=BLOCKER Issue-Id: CCSDK-67 Change-Id: I9f1a7dc8144a2a3a777a2a4f24793bbf9317de33 Signed-off-by: shashikanth.vh --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 30 +++++++++++----------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 9dc262d07..1729bcec0 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -20,6 +20,18 @@ package org.onap.ccsdk.sli.core.dblib; +import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor.TestObject; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetProvider; import java.io.Closeable; import java.io.IOException; import java.io.PrintWriter; @@ -36,20 +48,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Observer; -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; -import javax.sql.rowset.RowSetProvider; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor.TestObject; - -import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; - /** * @version $Revision: 1.13 $ @@ -565,7 +563,9 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito retValue = false; } finally { try { - lock.close(); + if (lock != null) { + lock.close(); + } } catch(Exception exc) { } -- cgit 1.2.3-korg From ce8c59f72c30cc7e1f9b657795ad396fe325ba52 Mon Sep 17 00:00:00 2001 From: shashikanth Date: Mon, 11 Sep 2017 18:52:19 +0530 Subject: Fix Blocker/Critical sonar issues Fix Blocker/Critical sonar issues in ccsdk/core module https://sonar.onap.org/component_issues?id=org.openecomp.sdnc.core%3Asdnc-core#resolved=false|severities=BLOCKER Issue-Id: CCSDK-67 Change-Id: Iec86b90f7085f4b96d4f92adf4064b70640fcf22 Signed-off-by: shashikanth.vh --- .../ccsdk/sli/core/dblib/DBResourceManager.java | 44 +++++++++------------- 1 file changed, 17 insertions(+), 27 deletions(-) (limited to 'dblib/provider/src') 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 46c003a5a..7ed54306a 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 @@ -20,6 +20,19 @@ package org.onap.ccsdk.sli.core.dblib; +import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; +import org.onap.ccsdk.sli.core.dblib.factory.AbstractDBResourceManagerFactory; +import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; +import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; +import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLDataException; @@ -38,26 +51,9 @@ import java.util.PriorityQueue; import java.util.Properties; import java.util.Queue; import java.util.Set; -import java.util.Timer; import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; - -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; -import org.onap.ccsdk.sli.core.dblib.factory.AbstractDBResourceManagerFactory; -import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; -import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; -import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; - -import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @version $Revision: 1.15 $ @@ -336,11 +332,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } sources.remove(active); return active.getData(statement, arguments); - } catch(SQLDataException exc){ - throw exc; - } catch(SQLSyntaxErrorException exc){ - throw exc; - } catch(SQLIntegrityConstraintViolationException exc){ + } catch(SQLDataException | SQLSyntaxErrorException | SQLIntegrityConstraintViolationException exc){ throw exc; } catch(Throwable exc){ lastException = exc; @@ -432,7 +424,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } CachedDataSource findMaster() throws PoolExhaustedException, MySQLNonTransientConnectionException { - CachedDataSource master = null; + CachedDataSource master; CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); for(int i=0; i Date: Fri, 8 Sep 2017 18:52:46 -0400 Subject: Expose getConnection from DblibSeervice Exposed getConnection from DbLibService class so that it can be accessed from OSGi client. Prior to blueprint refactoring, this was accessible by casting DbLibService as DBResourceManager, but that cast no longer works if OSGi service is advertised by blueprint. It's cleaner to expose that method in the interface anyway. Change-Id: I36ed7fe82b0393a952d307a1c79d1d8c0ba11dd4 Issue-ID: CCSDK-86 Signed-off-by: Dan Timoney --- .../src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java index de9846679..0dea664d5 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java @@ -7,9 +7,9 @@ * 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. @@ -20,6 +20,7 @@ package org.onap.ccsdk.sli.core.dblib; +import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; @@ -43,4 +44,6 @@ public interface DbLibService { public abstract boolean isActive(); + public abstract Connection getConnection() throws SQLException; + } -- cgit 1.2.3-korg From 9eb50a48faf45d5f1dc01b1209778c1c1d5ed0ae Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Mon, 11 Sep 2017 16:36:49 +0530 Subject: Fix Sonar issues Few major issues in sli/core module Issue-id: CCSDK-67 Change-Id: Iad65b30a6b27814c1984d8db42d36f8569c5cb3f Signed-off-by: surya-huawei --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 37 +++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 1729bcec0..ee8ab2f33 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -92,12 +92,14 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito /* (non-Javadoc) * @see javax.sql.DataSource#getConnection() */ + @Override public Connection getConnection() throws SQLException { return ds.getConnection(); } - public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable + public CachedRowSet getData(String statement, ArrayList arguments) + throws SQLException, Throwable { TestObject testObject = null; testObject = monitor.registerRequest(); @@ -126,7 +128,8 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } } - public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable + public boolean writeData(String statement, ArrayList arguments) + throws SQLException, Throwable { TestObject testObject = null; testObject = monitor.registerRequest(); @@ -155,7 +158,8 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } } - CachedRowSet executePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable + CachedRowSet executePreparedStatement(Connection conn, String statement, + ArrayList arguments, boolean close) throws SQLException, Throwable { long time = System.currentTimeMillis(); @@ -168,9 +172,10 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } ResultSet rs = null; + PreparedStatement ps = null; try { data = RowSetProvider.newFactory().createCachedRowSet(); - PreparedStatement ps = conn.prepareStatement(statement); + ps = conn.prepareStatement(statement); if(arguments != null) { for(int i = 0, max = arguments.size(); i < max; i++){ @@ -220,6 +225,13 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } } catch(Exception exc){ + } + try { + if (ps != null){ + ps.close(); + } + } catch (Exception exc){ + } } @@ -296,6 +308,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito /* (non-Javadoc) * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) */ + @Override public Connection getConnection(String username, String password) throws SQLException { @@ -305,6 +318,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito /* (non-Javadoc) * @see javax.sql.DataSource#getLogWriter() */ + @Override public PrintWriter getLogWriter() throws SQLException { return ds.getLogWriter(); @@ -313,6 +327,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito /* (non-Javadoc) * @see javax.sql.DataSource#getLoginTimeout() */ + @Override public int getLoginTimeout() throws SQLException { return ds.getLoginTimeout(); @@ -321,6 +336,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito /* (non-Javadoc) * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) */ + @Override public void setLogWriter(PrintWriter out) throws SQLException { ds.setLogWriter(out); @@ -329,12 +345,14 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito /* (non-Javadoc) * @see javax.sql.DataSource#setLoginTimeout(int) */ + @Override public void setLoginTimeout(int seconds) throws SQLException { ds.setLoginTimeout(seconds); } + @Override public final String getDbConnectionName(){ return connectionName; } @@ -418,10 +436,12 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito return true; } + @Override public boolean isWrapperFor(Class iface) throws SQLException { return false; } + @Override public T unwrap(Class iface) throws SQLException { return null; } @@ -445,34 +465,42 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito monitor.deleteObserver(observer); } + @Override public long getInterval() { return interval; } + @Override public long getInitialDelay() { return initialDelay; } + @Override public void setInterval(long value) { interval = value; } + @Override public void setInitialDelay(long value) { initialDelay = value; } + @Override public long getExpectedCompletionTime() { return expectedCompletionTime; } + @Override public void setExpectedCompletionTime(long value) { expectedCompletionTime = value; } + @Override public long getUnprocessedFailoverThreshold() { return unprocessedFailoverThreshold; } + @Override public void setUnprocessedFailoverThreshold(long value) { this.unprocessedFailoverThreshold = value; } @@ -485,6 +513,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito canTakeOffLine = false; final Thread offLineTimer = new Thread() { + @Override public void run(){ try { Thread.sleep(30000L); -- cgit 1.2.3-korg From 223514867e05ce022705b6a42a4ed19bf88ee6ee Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Tue, 12 Sep 2017 15:50:07 +0530 Subject: Fix sonar issues few major issues in dblib module Issue-Id: CCSDK-87 Change-Id: I6bc1fe2cf04cec0a5ad3bfb65bc3a10e5f488eea Signed-off-by: surya-huawei --- .../org/onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java | 5 ----- .../onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java | 10 ++++++++++ 2 files changed, 10 insertions(+), 5 deletions(-) (limited to 'dblib/provider/src') 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 index 201cc4019..c7f760053 100644 --- 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 @@ -24,7 +24,6 @@ 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; @@ -35,10 +34,6 @@ import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibEnvVarFileResol 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; diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java index 127e6d376..b4d1ef679 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java @@ -33,38 +33,47 @@ public class TerminatingCachedDataSource extends CachedDataSource implements SQL super(jdbcElem); } + @Override protected void configure(BaseDBConfiguration jdbcElem) throws DBConfigException { // no action } + @Override public long getInterval() { return 1000; } + @Override public long getInitialDelay() { return 1000; } + @Override public long getExpectedCompletionTime() { return 50; } + @Override public void setExpectedCompletionTime(long value) { } + @Override public void setInterval(long value) { } + @Override public void setInitialDelay(long value) { } + @Override public long getUnprocessedFailoverThreshold() { return 3; } + @Override public void setUnprocessedFailoverThreshold(long value) { } @@ -74,6 +83,7 @@ public class TerminatingCachedDataSource extends CachedDataSource implements SQL return 0; } + @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO Auto-generated method stub return null; -- cgit 1.2.3-korg From 1ed8c1f3b0345fe28c61844df2a189a8b9b53594 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Tue, 12 Sep 2017 15:29:44 +0530 Subject: Fix Sonar Issues few major issues in sli/core/dblib module Issue-id: CCSDK-87 Change-Id: Ie3b13468d23c1e7dc2228bb7a0cd1bde5cc632e8 Signed-off-by: surya-huawei --- .../onap/ccsdk/sli/core/dblib/DBLibConnection.java | 11 ++++---- .../ccsdk/sli/core/dblib/DBResourceManager.java | 32 ++++++++++------------ 2 files changed, 21 insertions(+), 22 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java index 8181b1300..40d1a2382 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java @@ -43,7 +43,6 @@ import java.util.concurrent.Executor; import javax.sql.rowset.CachedRowSet; import org.apache.tomcat.jdbc.pool.PooledConnection; -import org.apache.tomcat.jdbc.pool.ProxyConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -65,7 +64,8 @@ public class DBLibConnection implements Connection { public boolean lockTable(String tablename) { this.tableName = tablename; - return locked = dataSource.lockTable(connection, tableName); + locked = dataSource.lockTable(connection, tableName); + return locked; } public void resetInactivityTimer() { @@ -80,12 +80,13 @@ public class DBLibConnection implements Connection { public boolean unlock() { dataSource.unlockTable(connection); - return locked = false; + locked = false; + return locked; } public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable { - ArrayList newList=new ArrayList(); + ArrayList newList= new ArrayList<>(); if(arguments != null && !arguments.isEmpty()) { newList.addAll(arguments); } @@ -95,7 +96,7 @@ public class DBLibConnection implements Connection { public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable { - ArrayList newList=new ArrayList(); + ArrayList newList= new ArrayList<>(); if(arguments != null && !arguments.isEmpty()) { newList.addAll(arguments); } 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 46c003a5a..ac67c3f94 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 @@ -38,9 +38,7 @@ import java.util.PriorityQueue; import java.util.Properties; import java.util.Queue; import java.util.Set; -import java.util.Timer; import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import javax.sql.DataSource; @@ -76,23 +74,22 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb protected final AtomicBoolean dsSelector = new AtomicBoolean(); // Queue dsQueue = new ConcurrentLinkedQueue(); - Queue dsQueue = new PriorityQueue(4, new Comparator(){ - + Queue dsQueue = new PriorityQueue<>(4, new Comparator() { @Override public int compare(CachedDataSource left, CachedDataSource right) { try { - if(!left.isSlave()) + if (!left.isSlave()) { return -1; - if(!right.isSlave()) + } + if (!right.isSlave()) { return 1; - + } } catch (Throwable e) { LOGGER.warn("", e); } return 0; } - - }); + }); protected final Set broken = Collections.synchronizedSet(new HashSet()); protected final Object monitor = new Object(); protected final Properties configProps; @@ -240,6 +237,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb class RecoveryMgr extends Thread { + @Override public void run() { while(!terminating) { @@ -295,7 +293,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb */ @Override public CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) throws SQLException { - ArrayList newList=new ArrayList(); + ArrayList newList= new ArrayList<>(); if(arguments != null && !arguments.isEmpty()) { newList.addAll(arguments); } @@ -310,7 +308,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb CachedDataSource active = null; // test if there are any connection pools available - LinkedList sources = new LinkedList(this.dsQueue); + LinkedList sources = new LinkedList<>(this.dsQueue); if(sources.isEmpty()){ LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); @@ -356,7 +354,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb handleGetConnectionException(active, exc); } finally { if(LOGGER.isDebugEnabled()){ - time = (System.currentTimeMillis() - time); + time = System.currentTimeMillis() - time; LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); } } @@ -410,7 +408,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } finally { if(LOGGER.isDebugEnabled()){ - time = (System.currentTimeMillis() - time); + time = System.currentTimeMillis() - time; LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); } } @@ -423,7 +421,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb @Override public boolean writeData(String statement, ArrayList arguments, String preferredDS) throws SQLException { - ArrayList newList=new ArrayList(); + ArrayList newList= new ArrayList<>(); if(arguments != null && !arguments.isEmpty()) { newList.addAll(arguments); } @@ -498,7 +496,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } finally { if(LOGGER.isDebugEnabled()){ - time = (System.currentTimeMillis() - time); + time = System.currentTimeMillis() - time; LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); } } @@ -710,7 +708,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public String getDBStatus(boolean htmlFormat) { StringBuilder buffer = new StringBuilder(); - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); list.addAll(dsQueue); list.addAll(broken); if (htmlFormat) @@ -795,7 +793,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public String getPreferredDataSourceName(AtomicBoolean flipper) { - LinkedList snapshot = new LinkedList(dsQueue); + LinkedList snapshot = new LinkedList<>(dsQueue); if(snapshot.size() > 1){ CachedDataSource first = snapshot.getFirst(); CachedDataSource last = snapshot.getLast(); -- cgit 1.2.3-korg From 14e10898473c9df8fb4ffc26bb1cd67ee2116a61 Mon Sep 17 00:00:00 2001 From: Ryan Goulding Date: Tue, 12 Sep 2017 15:13:44 -0400 Subject: Remove unused imports in java files Code sanitation-- remove unused imports. Issue-Id: SDNC-79 Change-Id: I5306a9b90f302086459fcac98d04f541ba7c79a4 Signed-off-by: Ryan Goulding --- .../onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java | 1 - .../onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java | 8 -------- .../org/onap/ccsdk/sli/core/dblib/DBLibConnection.java | 1 - .../org/onap/ccsdk/sli/core/dblib/DBResourceManager.java | 2 -- .../core/dblib/factory/AbstractResourceManagerFactory.java | 1 - .../ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java | 1 - .../sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java | 3 --- .../ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java | 1 - .../propertiesfileresolver/DblibEnvVarFileResolver.java | 1 + .../propertiesfileresolver/DblibJREFileResolverTest.java | 2 -- .../java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java | 4 ---- .../org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java | 1 - .../org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java | 14 +++++--------- .../java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java | 2 -- .../java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java | 1 - .../org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java | 6 ------ .../org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java | 4 ---- .../ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java | 3 --- .../ccsdk/sli/core/slipluginutils/CheckParametersTest.java | 1 - .../slipluginutils/SliPluginUtils_StaticFunctionsTest.java | 1 - .../core/slipluginutils/SliPluginUtils_ctxSortList.java | 1 - .../slipluginutils/SliPluginUtils_ctxSortListTest.java | 1 - .../ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java | 1 - .../sli/core/slipluginutils/SvcLogicContextListTest.java | 1 - 24 files changed, 6 insertions(+), 56 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java index 07e3dfab1..296fe70f1 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java @@ -24,7 +24,6 @@ package org.onap.ccsdk.sli.core.dblib; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; import org.onap.ccsdk.sli.core.dblib.jdbc.JdbcDBCachedDataSource; -import org.onap.ccsdk.sli.core.dblib.jdbc.MySQLCachedDataSource; /** * @version $Revision: 1.1 $ 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 index 201cc4019..062cd8408 100644 --- 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 @@ -20,11 +20,8 @@ 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; @@ -35,10 +32,6 @@ import org.onap.ccsdk.sli.core.dblib.propertiesfileresolver.DblibEnvVarFileResol 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; @@ -146,7 +139,6 @@ public class DBLIBResourceProvider { *
  • A dblib.properties file located in the karaf root directory
  • * */ - @VisibleForTesting File determinePropertiesFile(final DBLIBResourceProvider dblibResourceProvider) { for (final DblibPropertiesFileResolver dblibPropertiesFileResolver : dblibPropertiesFileResolvers) { diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java index 8181b1300..ccef4819c 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java @@ -43,7 +43,6 @@ import java.util.concurrent.Executor; import javax.sql.rowset.CachedRowSet; import org.apache.tomcat.jdbc.pool.PooledConnection; -import org.apache.tomcat.jdbc.pool.ProxyConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 46c003a5a..8e8bdb8a8 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 @@ -38,9 +38,7 @@ import java.util.PriorityQueue; import java.util.Properties; import java.util.Queue; import java.util.Set; -import java.util.Timer; import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import javax.sql.DataSource; diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java index 6fc7e7a04..741169c3b 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java @@ -27,7 +27,6 @@ import java.util.concurrent.Callable; import org.onap.ccsdk.sli.core.dblib.CachedDataSource; import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; -import org.onap.ccsdk.sli.core.dblib.DBConfigException; import org.onap.ccsdk.sli.core.dblib.DBResourceManager; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java index c024d0021..ffe834456 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -30,7 +30,6 @@ import org.apache.tomcat.jdbc.pool.PoolProperties; import org.onap.ccsdk.sli.core.dblib.CachedDataSource; import org.onap.ccsdk.sli.core.dblib.DBConfigException; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; -import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java index 978de0eb3..803e6b3e7 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java @@ -22,9 +22,7 @@ package org.onap.ccsdk.sli.core.dblib.jdbc; import java.sql.SQLException; -import java.util.Arrays; import java.util.HashSet; -import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -35,7 +33,6 @@ import java.util.concurrent.FutureTask; import org.onap.ccsdk.sli.core.dblib.CachedDataSource; import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.DataSourceComparator; import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java index 407209850..bea0d631f 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java @@ -26,7 +26,6 @@ import java.util.Properties; import org.onap.ccsdk.sli.core.dblib.CachedDataSource; import org.onap.ccsdk.sli.core.dblib.DBConfigException; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; -import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 index 17c42ec83..0b69109f9 100644 --- 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 @@ -21,6 +21,7 @@ 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; 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 index 117492d0b..65ebfbae2 100644 --- 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 @@ -2,8 +2,6 @@ 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 { diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java index 699ace2e8..5e19a52c6 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicAtom.java @@ -21,10 +21,6 @@ package org.onap.ccsdk.sli.core.sli; -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - public class SvcLogicAtom extends SvcLogicExpression { public enum AtomType { diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java index b8a47c45e..26783e70f 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpression.java @@ -22,7 +22,6 @@ package org.onap.ccsdk.sli.core.sli; import java.io.Serializable; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java index 451277576..23dff3e6e 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJavaPlugin.java @@ -21,14 +21,10 @@ package org.onap.ccsdk.sli.core.sli; -import java.util.Map; - +/** + * A marker interface, used to indicate that a class exposes methods that can be + * called from an node. Such methods must have the signature: + * void methodName(Map, SvcLogicContext) + */ public interface SvcLogicJavaPlugin { - - /** - * A marker interface, used to indicate that a class exposes methods that can be - * called from an node. Such methods must have the signature: - * void methodName(Map, SvcLogicContext) - */ - } diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java index 56ed53054..160107fea 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicNode.java @@ -36,8 +36,6 @@ import java.util.TreeMap; import org.apache.commons.lang3.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.xml.sax.Locator; - public class SvcLogicNode implements Serializable { diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java index 40295bd75..0e2c42574 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicResource.java @@ -21,7 +21,6 @@ package org.onap.ccsdk.sli.core.sli; -import java.sql.SQLException; import java.util.Map; public interface SvcLogicResource { diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java index ec18b8765..0e6000fb2 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java @@ -28,12 +28,6 @@ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import java.util.LinkedList; - -import org.onap.ccsdk.sli.core.sli.SvcLogicParser; -import org.onap.ccsdk.sli.core.sli.SvcLogicParserException; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; import junit.framework.TestCase; diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java index 60d70460d..3b9fff75e 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicContextTest.java @@ -21,17 +21,13 @@ package org.onap.ccsdk.sli.core.sli; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; import java.io.InputStream; -import java.io.InputStreamReader; import java.util.Enumeration; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java index 125ac5618..80df10cee 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionParserTest.java @@ -25,9 +25,6 @@ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; -import org.onap.ccsdk.sli.core.sli.SvcLogicExprListener; -import org.onap.ccsdk.sli.core.sli.SvcLogicExpression; -import org.onap.ccsdk.sli.core.sli.SvcLogicExpressionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/CheckParametersTest.java b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/CheckParametersTest.java index 106b0cf46..166a60e90 100644 --- a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/CheckParametersTest.java +++ b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/CheckParametersTest.java @@ -27,7 +27,6 @@ import java.util.Map; import org.junit.Test; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java index a46c85129..774aa1c84 100644 --- a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java +++ b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_StaticFunctionsTest.java @@ -32,7 +32,6 @@ import org.junit.Before; import org.junit.Test; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java index ba7a7660d..f9d70f2fb 100644 --- a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java +++ b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortList.java @@ -30,7 +30,6 @@ import org.junit.Before; import org.junit.Test; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java index 9768108de..bf7cc1399 100644 --- a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java +++ b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliPluginUtils_ctxSortListTest.java @@ -30,7 +30,6 @@ import org.junit.Before; import org.junit.Test; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java index 09683ac36..72b3264e9 100644 --- a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java +++ b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SliStringUtilsTest.java @@ -35,7 +35,6 @@ import org.junit.Before; import org.junit.Test; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.slipluginutils.SliStringUtils; /** * @author km991u diff --git a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java index 263ba1f1d..f916bbfca 100644 --- a/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java +++ b/sliPluginUtils/provider/src/test/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextListTest.java @@ -29,7 +29,6 @@ import java.util.HashMap; import org.junit.Before; import org.junit.Test; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.slipluginutils.SvcLogicContextList; public class SvcLogicContextListTest { //private static final Logger LOG = LoggerFactory.getLogger(SvcLogicContextTest.class); -- cgit 1.2.3-korg From 3fa9671f720dd95bf15a5a4668aa89a7c3dd93e7 Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Wed, 13 Sep 2017 16:32:45 -0400 Subject: Use oparent-odlparent in sli/core Update sli/core to use oparent-odlparent. To prevent verify builds from failing due to unit test errors, also changed unit tests that require database access to use MariaDB4j to start up a local MariaDB database. Change-Id: I928b7e1e83bdb328ca9e0785c8b81f67f982eeda Issue-ID: CCSDK-43 Signed-off-by: Dan Timoney --- .../DblibDefaultFileResolverTest.java | 24 ++ .../DblibEnvVarFileResolverTest.java | 23 ++ .../DblibJREFileResolverTest.java | 15 ++ .../DblibKarafRootFileResolverTest.java | 14 + .../DblibDefaultFileResolverTest.java | 24 -- .../DblibEnvVarFileResolverTest.java | 23 -- .../DblibJREFileResolverTest.java | 15 -- .../DblibKarafRootFileResolverTest.java | 14 - pom.xml | 2 +- sli/common/pom.xml | 297 +++++++++++---------- .../ccsdk/sli/core/sli/ITCaseSvcLogicParser.java | 78 ++++-- sli/common/src/test/resources/svclogic.properties | 12 +- sli/provider/pom.xml | 6 + .../sli/provider/ITCaseSvcLogicGraphExecutor.java | 100 ++++--- 14 files changed, 340 insertions(+), 307 deletions(-) create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java delete mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java delete mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java delete mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java delete mode 100644 dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java new file mode 100644 index 000000000..41011e55b --- /dev/null +++ b/dblib/provider/src/test/java/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/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java new file mode 100644 index 000000000..775898930 --- /dev/null +++ b/dblib/provider/src/test/java/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/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java new file mode 100644 index 000000000..65ebfbae2 --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java @@ -0,0 +1,15 @@ +package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; + +import static org.junit.Assert.*; + +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/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java new file mode 100644 index 000000000..0a032e8b7 --- /dev/null +++ b/dblib/provider/src/test/java/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/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 deleted file mode 100644 index 41011e55b..000000000 --- a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 775898930..000000000 --- a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 65ebfbae2..000000000 --- a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; - -import static org.junit.Assert.*; - -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 deleted file mode 100644 index 0a032e8b7..000000000 --- a/dblib/provider/src/test/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java +++ /dev/null @@ -1,14 +0,0 @@ -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/pom.xml b/pom.xml index 3bf8b1e64..469a2a696 100755 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ org.onap.ccsdk.parent odlparent-carbon-sr1 - 0.0.1-SNAPSHOT + 0.0.2-SNAPSHOT diff --git a/sli/common/pom.xml b/sli/common/pom.xml index f71ca35f6..c367dd779 100755 --- a/sli/common/pom.xml +++ b/sli/common/pom.xml @@ -1,150 +1,157 @@ - - 4.0.0 - - sli - org.onap.ccsdk.sli.core - 0.1.2-SNAPSHOT - - sli-common - bundle + + 4.0.0 + + sli + org.onap.ccsdk.sli.core + 0.1.2-SNAPSHOT + + sli-common + bundle - SLI - Common Classes - The SLI Common package includes common classes used by the various SLI subcomponents, as well as classes used by clients to interface with the service logic interpreter + SLI - Common Classes + The SLI Common package includes common classes used by the various SLI subcomponents, as well as classes used by clients to interface with the service logic interpreter - - - junit - junit - 3.8.1 - test - - - org.antlr - antlr4 - ${antlr.version} - jar - compile - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-simple - 1.7.5 - compile - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.opendaylight.mdsal - yang-binding - ${odl.mdsal.yang.binding.version} - - - org.opendaylight.yangtools - yang-common - ${odl.yangtools.version} - - - org.opendaylight.mdsal.model - ietf-inet-types - ${odl.ietf-inet-types.version} - - - org.opendaylight.mdsal.model - ietf-yang-types - ${odl.ietf-yang-types.version} - - - org.opendaylight.controller - sal-core-api - ${odl.mdsal.version} - - - org.opendaylight.yangtools - yang-data-impl - ${odl.yangtools.version} - - - equinoxSDK381 - org.eclipse.osgi - ${equinox.osgi.version} - - - mysql - mysql-connector-java - ${mysql.connector.version} - jar - compile - - - org.onap.ccsdk.sli.core - dblib-provider - ${sdnctl.dblib.version} - - + + + junit + junit + 3.8.1 + test + + + ch.vorburger.mariaDB4j + mariaDB4j + 2.2.3 + test + + + org.antlr + antlr4 + ${antlr.version} + jar + compile + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-simple + 1.7.5 + compile + + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + + + org.opendaylight.mdsal + yang-binding + ${odl.mdsal.yang.binding.version} + + + org.opendaylight.yangtools + yang-common + ${odl.yangtools.version} + + + org.opendaylight.mdsal.model + ietf-inet-types + ${odl.ietf-inet-types.version} + + + org.opendaylight.mdsal.model + ietf-yang-types + ${odl.ietf-yang-types.version} + + + org.opendaylight.controller + sal-core-api + ${odl.mdsal.version} + + + org.opendaylight.yangtools + yang-data-impl + ${odl.yangtools.version} + + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + + + mysql + mysql-connector-java + ${mysql.connector.version} + jar + compile + + + org.onap.ccsdk.sli.core + dblib-provider + ${sdnctl.dblib.version} + + - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - **/*.xsd - - - org.onap.ccsdk.sli.core.sli.SvcLogicParser - org.onap.ccsdk.sli.core.sli - true - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.onap.ccsdk.sli.core.sli;version=${project.version} - * - *;scope=compile;artifactId=commons-lang|commons-lang3 - true - - - - - org.antlr - antlr4-maven-plugin - ${antlr.version} - - - - ${project.basedir}/src/main/java/ - - antlr - - antlr4 - - - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + **/*.xsd + + + org.onap.ccsdk.sli.core.sli.SvcLogicParser + org.onap.ccsdk.sli.core.sli + true + + + + + + org.apache.felix + maven-bundle-plugin + true + + + org.onap.ccsdk.sli.core.sli;version=${project.version} + * + *;scope=compile;artifactId=commons-lang|commons-lang3 + true + + + + + org.antlr + antlr4-maven-plugin + ${antlr.version} + + + + ${project.basedir}/src/main/java/ + + antlr + + antlr4 + + + + + + diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java index 0e6000fb2..07f40a2ec 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java @@ -8,9 +8,9 @@ * 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. @@ -20,7 +20,7 @@ */ /** - * + * */ package org.onap.ccsdk.sli.core.sli; @@ -28,7 +28,10 @@ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; +import java.util.Properties; +import ch.vorburger.mariadb4j.DB; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; import junit.framework.TestCase; /** @@ -40,22 +43,43 @@ public class ITCaseSvcLogicParser extends TestCase { /** * Test method for {@link org.onap.ccsdk.sli.core.sli.SvcLogicParser#parse(java.lang.String)}. */ - - + + public void testParse() { - + try { + + URL propUrl = getClass().getResource("/svclogic.properties"); - + InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); - - SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(propStr); - + + Properties props = new Properties(); + + props.load(propStr); + + + // Start MariaDB4j database + DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); + config.setPort(0); // 0 => autom. detect free port + DB db = DB.newEmbeddedDB(config.build()); + db.start(); + + + + // Override jdbc URL and database name + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + + + + SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(props); + assertNotNull(store); - + store.registerNodeType("switch"); store.registerNodeType("block"); store.registerNodeType("get-resource"); @@ -69,15 +93,15 @@ public class ITCaseSvcLogicParser extends TestCase { store.registerNodeType("release"); store.registerNodeType("for"); store.registerNodeType("set"); - - + + InputStream testStr = getClass().getResourceAsStream("/parser-good.tests"); BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); String testCaseFile = null; while ((testCaseFile = testsReader.readLine()) != null) { - + testCaseFile = testCaseFile.trim(); - + if (testCaseFile.length() > 0) { if (!testCaseFile.startsWith("/")) @@ -94,23 +118,23 @@ public class ITCaseSvcLogicParser extends TestCase { SvcLogicParser.validate(testCaseUrl.getPath(), store); } catch (Exception e) { fail("Validation failure ["+e.getMessage()+"]"); - + } - - - + + + } } - + testStr = getClass().getResourceAsStream("/parser-bad.tests"); testsReader = new BufferedReader(new InputStreamReader(testStr)); testCaseFile = null; while ((testCaseFile = testsReader.readLine()) != null) { - + testCaseFile = testCaseFile.trim(); - + if (testCaseFile.length() > 0) { if (!testCaseFile.startsWith("/")) @@ -134,7 +158,7 @@ public class ITCaseSvcLogicParser extends TestCase { if (valid) { fail("Expected compiler error on "+testCaseFile+", but got success"); } - + } } @@ -148,10 +172,10 @@ public class ITCaseSvcLogicParser extends TestCase { e.printStackTrace(); fail("Caught exception processing test cases"); } - - + + } - - + + } diff --git a/sli/common/src/test/resources/svclogic.properties b/sli/common/src/test/resources/svclogic.properties index 25eb3bd47..33d7ae6e4 100644 --- a/sli/common/src/test/resources/svclogic.properties +++ b/sli/common/src/test/resources/svclogic.properties @@ -8,9 +8,9 @@ # 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. @@ -20,7 +20,7 @@ ### org.onap.ccsdk.sli.dbtype = jdbc -org.onap.ccsdk.sli.jdbc.url = jdbc:mysql://localhost:3306/sdnctl -org.onap.ccsdk.sli.jdbc.database = sdnctl -org.onap.ccsdk.sli.jdbc.user = sdnctl -org.onap.ccsdk.sli.jdbc.password = gamma +org.onap.ccsdk.sli.jdbc.url = jdbc:mysql://localhost:3306/test +org.onap.ccsdk.sli.jdbc.database = test +org.onap.ccsdk.sli.jdbc.user = test +org.onap.ccsdk.sli.jdbc.password = test123 diff --git a/sli/provider/pom.xml b/sli/provider/pom.xml index f665c56a1..529f97690 100755 --- a/sli/provider/pom.xml +++ b/sli/provider/pom.xml @@ -19,6 +19,12 @@ 3.8.1 test + + ch.vorburger.mariaDB4j + mariaDB4j + 2.2.3 + test + org.onap.ccsdk.sli.core sli-common diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java index 5e895aa3e..cdf837afe 100644 --- a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java @@ -8,9 +8,9 @@ * 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. @@ -31,43 +31,22 @@ import java.util.LinkedList; import java.util.Map; import java.util.Properties; -import org.onap.ccsdk.sli.core.sli.MetricLogger; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; -import org.onap.ccsdk.sli.core.sli.SvcLogicNode; import org.onap.ccsdk.sli.core.sli.SvcLogicParser; import org.onap.ccsdk.sli.core.sli.SvcLogicStore; import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; -import org.onap.ccsdk.sli.core.sli.provider.BlockNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.CallNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ConfigureNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.DeleteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ExistsNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ForNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.GetResourceNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.IsAvailableNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.NotifyNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.RecordNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ReleaseNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ReserveNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.ReturnNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SaveNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SetNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicServiceImpl; -import org.onap.ccsdk.sli.core.sli.provider.SwitchNodeExecutor; -import org.onap.ccsdk.sli.core.sli.provider.UpdateNodeExecutor; -import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import ch.vorburger.mariadb4j.DB; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; import junit.framework.TestCase; public class ITCaseSvcLogicGraphExecutor extends TestCase { private static final Logger LOG = LoggerFactory .getLogger(SvcLogicGraph.class); - + private static final Map BUILTIN_NODES = new HashMap() { { put("block", new BlockNodeExecutor()); @@ -91,19 +70,36 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { } }; - + public void testExecute() { - + try { InputStream testStr = getClass().getResourceAsStream("/executor.tests"); BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); - + InputStream propStr = getClass().getResourceAsStream("/svclogic.properties"); - - SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(propStr); - + + Properties svcprops = new Properties(); + svcprops.load(propStr); + + // Start MariaDB4j database + DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); + config.setPort(0); // 0 => autom. detect free port + DB db = DB.newEmbeddedDB(config.build()); + db.start(); + + + + // Override jdbc URL and database name + svcprops.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + svcprops.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + + + + SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(svcprops); + assertNotNull(store); - + store.registerNodeType("switch"); store.registerNodeType("block"); store.registerNodeType("get-resource"); @@ -118,26 +114,26 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { store.registerNodeType("for"); store.registerNodeType("set"); SvcLogicParser parser = new SvcLogicParser(store); - + // Loop through executor tests SvcLogicServiceImpl svc = new SvcLogicServiceImpl(); - + for (String nodeType : BUILTIN_NODES.keySet()) { LOG.info("SLI - registering node executor for node type "+nodeType); - + svc.registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); } String testCaseLine = null; while ((testCaseLine = testsReader.readLine()) != null) { - + String[] testCaseFields = testCaseLine.split(":"); String testCaseFile = testCaseFields[0]; String testCaseMethod = testCaseFields[1]; String testCaseParameters = null; - + if (testCaseFields.length > 2) { testCaseParameters = testCaseFields[2]; } @@ -145,7 +141,7 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { SvcLogicContext ctx = new SvcLogicContext(); if (testCaseParameters != null) { String[] testCaseParameterSettings = testCaseParameters.split(","); - + for (int i = 0 ; i < testCaseParameterSettings.length ; i++) { String[] nameValue = testCaseParameterSettings[i].split("="); if (nameValue != null) { @@ -154,14 +150,14 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { if (nameValue.length > 1) { value = nameValue[1]; } - + ctx.setAttribute(name, value); } } } - + testCaseFile = testCaseFile.trim(); - + if (testCaseFile.length() > 0) { if (!testCaseFile.startsWith("/")) { testCaseFile = "/"+testCaseFile; @@ -170,12 +166,12 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { if (testCaseUrl == null) { fail("Could not resolve test case file "+testCaseFile); } - + LinkedList graphs = parser.parse(testCaseUrl.getPath()); - + assertNotNull(graphs); - + for (SvcLogicGraph graph: graphs) { if (graph.getRpc().equals(testCaseMethod)) { Properties props = ctx.toProperties(); @@ -184,9 +180,9 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { String propName = (String) e1.nextElement(); LOG.info(propName+" = "+props.getProperty(propName)); } - + svc.execute(graph, ctx); - + props = ctx.toProperties(); LOG.info("SvcLogicContext after executing "+testCaseMethod+":"); for (Enumeration e2 = props.propertyNames(); e2.hasMoreElements() ; ) { @@ -197,16 +193,16 @@ public class ITCaseSvcLogicGraphExecutor extends TestCase { } } - - + + } - - + + } catch (Exception e) { LOG.error("Caught exception executing directed graphs", e); fail("Exception executing graphs"); } } - + } -- cgit 1.2.3-korg From 222513c30f3c0c0e7bfce48b6c96d9ddfba75dba Mon Sep 17 00:00:00 2001 From: Ryan Goulding Date: Wed, 13 Sep 2017 16:58:19 -0400 Subject: Clean up BaseDBConfiguration class This change isn't too big; it mainly just attempts to clean up the BaseDBConfiguration class using best practices. For example: * documentation is added surrounding public methods, public constants, protected variables, and class headers. * code logic for parsing "optional" integer properties is abstracted into a separate private static function, which returns a default value if the given input property cannot be parsed or is not present. * public functions where the NumberFormatException RuntimeException might be thrown have the appriorate "throws" modifier added to their function signatures to indicate that the consumer is responsible for exception handling. * constants are extracted in place of "magic numbers" This is really just code sanitation work. Change-Id: Ifaf092e10b17f54c7cce0a888aa49bfe8377cdd3 Issue-Id: SDNC-79 Signed-off-by: Ryan Goulding --- .../sli/core/dblib/config/BaseDBConfiguration.java | 289 +++++++++++++++------ 1 file changed, 211 insertions(+), 78 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java index 4b738d426..d53be0e7f 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java @@ -22,83 +22,216 @@ package org.onap.ccsdk.sli.core.dblib.config; import java.util.Properties; +/** + * Base class responsible for parsing business logic for database configuration from given Properties. + */ public abstract class BaseDBConfiguration { - public static final String DATABASE_TYPE = "org.onap.ccsdk.sli.dbtype"; - public static final String DATABASE_URL = "org.onap.ccsdk.sli.jdbc.url"; - public static final String DATABASE_NAME = "org.onap.ccsdk.sli.jdbc.database"; - public static final String CONNECTION_NAME = "org.onap.ccsdk.sli.jdbc.connection.name"; - public static final String DATABASE_USER = "org.onap.ccsdk.sli.jdbc.user"; - public static final String DATABASE_PSSWD = "org.onap.ccsdk.sli.jdbc.password"; - public static final String CONNECTION_TIMEOUT="org.onap.ccsdk.sli.jdbc.connection.timeout"; - public static final String REQUEST_TIMEOUT = "org.onap.ccsdk.sli.jdbc.request.timeout"; - public static final String MIN_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.min"; - public static final String MAX_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.max"; - public static final String INIT_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.init"; - public static final String DATABASE_HOSTS = "org.onap.ccsdk.sli.jdbc.hosts"; - - - protected final Properties props; - - public BaseDBConfiguration(Properties properties) { - this.props = properties; - } - - public int getConnTimeout() { - try { - String value = props.getProperty(CONNECTION_TIMEOUT); - return Integer.parseInt(value); - } catch(Exception exc) { - return -1; - } - } - - public int getRequestTimeout() { - try { - String value = props.getProperty(REQUEST_TIMEOUT); - if(value == null) - return -1; - return Integer.parseInt(value); - } catch(Exception exc) { - return -1; - } - } - - public String getDbConnectionName() { - return props.getProperty(CONNECTION_NAME); - } - - public String getDatabaseName() { - return props.getProperty(DATABASE_NAME); - } - - public String getDbUserId() { - return props.getProperty(DATABASE_USER); - } - - public String getDbPasswd() { - return props.getProperty(DATABASE_PSSWD); - } - - public int getDbMinLimit() { - String value = props.getProperty(MIN_LIMIT); - return Integer.parseInt(value); - } - - public int getDbMaxLimit() { - String value = props.getProperty(MAX_LIMIT); - return Integer.parseInt(value); - } - - public int getDbInitialLimit() { - String value = props.getProperty(INIT_LIMIT); - return Integer.parseInt(value); - } - - public String getDbUrl() { - return props.getProperty(DATABASE_URL); - } - - public String getServerGroup() { - return null; - } + + /** + * Property key within a properties configuration File for db type + */ + public static final String DATABASE_TYPE = "org.onap.ccsdk.sli.dbtype"; + + /** + * Property key with a properties configuration File for db url + */ + public static final String DATABASE_URL = "org.onap.ccsdk.sli.jdbc.url"; + + /** + * Property key with a properties configuration File for database name + */ + public static final String DATABASE_NAME = "org.onap.ccsdk.sli.jdbc.database"; + + /** + * Property key with a properties configuration File for db database connection name + */ + public static final String CONNECTION_NAME = "org.onap.ccsdk.sli.jdbc.connection.name"; + + /** + * Property key with a properties configuration File for database user + */ + public static final String DATABASE_USER = "org.onap.ccsdk.sli.jdbc.user"; + + /** + * Property key with a properties configuration File for database password for associated with + * org.onap.ccsdk.sli.jdbc.user. + */ + public static final String DATABASE_PSSWD = "org.onap.ccsdk.sli.jdbc.password"; + + /** + * Property key with a properties configuration File for database connection timeout + */ + public static final String CONNECTION_TIMEOUT="org.onap.ccsdk.sli.jdbc.connection.timeout"; + + /** + * Property key with a properties configuration File for database request timeout + */ + public static final String REQUEST_TIMEOUT = "org.onap.ccsdk.sli.jdbc.request.timeout"; + + /** + * Property key with a properties configuration File for database minimum limit + */ + public static final String MIN_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.min"; + + /** + * Property key with a properties configuration File for database maximum limit + */ + public static final String MAX_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.max"; + + /** + * Property key with a properties configuration File for database initial limit + */ + public static final String INIT_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.init"; + + /** + * Property key with a properties configuration File for database hosts + */ + public static final String DATABASE_HOSTS = "org.onap.ccsdk.sli.jdbc.hosts"; + + /** + * default value when the connection timeout is not present or cannot be parsed + */ + private static final int DEFAULT_CONNECTION_TIMEOUT = -1; + + /** + * default value when the request timeout is not present or cannot be parsed + */ + private static final int DEFAULT_REQUEST_TIMEOUT = -1; + + /** + * A set of properties with database configuration information. + */ + protected final Properties properties; + + /** + * Builds a configuration based on given properties + * + * @param properties properties represented by the public constant keys defined by this class + */ + public BaseDBConfiguration(final Properties properties) { + this.properties = properties; + } + + /** + * Extracts the connection timeout. + * + * @return the connection timeout, or DEFAULT_CONNECTION_TIMEOUT if not present + */ + public int getConnTimeout() { + return extractProperty(properties, CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); + } + + /** + * Extracts the request timeout. + * + * @return the request timeout, or DEFAULT_REQUEST_TIMEOUT if not present + */ + public int getRequestTimeout() { + return extractProperty(properties, REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT); + } + + /** + * A utility method to extract int property from Properties. + * + * @param properties a set of Properties + * @param propertyKey the key in question + * @param defaultValue the value to return if the key does not exist + * @return Either the property value for propertyKey or defaultValue if not present + */ + private static int extractProperty(final Properties properties, final String propertyKey, final int defaultValue) { + try { + final String valueString = properties.getProperty(propertyKey, Integer.toString(defaultValue)); + return Integer.parseInt(valueString); + } catch(final NumberFormatException e) { + return defaultValue; + } + } + + /** + * Extracts the db connection name. + * + * @return the db connection name, or null if not present + */ + public String getDbConnectionName() { + return properties.getProperty(CONNECTION_NAME); + } + + /** + * Extracts the db name. + * + * @return the db name, or null if not present + */ + public String getDatabaseName() { + return properties.getProperty(DATABASE_NAME); + } + + /** + * Extracts the db user id. + * + * @return the db user id, or null if not present + */ + public String getDbUserId() { + return properties.getProperty(DATABASE_USER); + } + + /** + * Extracts the db password. + * + * @return the db password, or null if not present + */ + public String getDbPasswd() { + return properties.getProperty(DATABASE_PSSWD); + } + + /** + * Extracts the db min limit. + * + * @return the db min limit + * @throws NumberFormatException if the property is not specified, or cannot be parsed as an Integer. + */ + public int getDbMinLimit() throws NumberFormatException { + String value = properties.getProperty(MIN_LIMIT); + return Integer.parseInt(value); + } + + /** + * Extracts the db max limit. + * + * @return the db max limit + * @throws NumberFormatException if the property is not specified, or cannot be parsed as an Integer. + */ + public int getDbMaxLimit() throws NumberFormatException { + String value = properties.getProperty(MAX_LIMIT); + return Integer.parseInt(value); + } + + /** + * Extracts the db initial limit. + * + * @return the db initial limit + * @throws NumberFormatException if the property is not specified, or cannot be parsed as an Integer. + */ + public int getDbInitialLimit() throws NumberFormatException { + String value = properties.getProperty(INIT_LIMIT); + return Integer.parseInt(value); + } + + /** + * Extracts the db url. + * + * @return the db url, or null if not present + */ + public String getDbUrl() { + return properties.getProperty(DATABASE_URL); + } + + /** + * Extracts the db server group. + * + * @return null + */ + @Deprecated + public String getServerGroup() { + return null; + } } -- cgit 1.2.3-korg From 7ea02fe1a8f40ffba9e54eb92391ee5dd6382ff5 Mon Sep 17 00:00:00 2001 From: Ryan Goulding Date: Thu, 14 Sep 2017 12:14:12 -0400 Subject: Clean up public interfaces The Java programming language assigns certain defaults for methods and constants defined in interfaces. This change removes the unnecessary redundant modifiers appropriately. For example: * interface methods are public by default * interface constants are public by default * interface methods are abstract unless "default" is specifically used (as of JDK8+). This is really just to get rid of annoying warnings present in IDE(s). Issue-Id: SDNC-79 Change-Id: I2e6b3e4fa02bad1beee2cbb49d3766722eff1ba0 Signed-off-by: Ryan Goulding --- .../ccsdk/sli/core/dblib/DBResourceObserver.java | 2 +- .../onap/ccsdk/sli/core/dblib/DataAccessor.java | 4 +- .../ccsdk/sli/core/dblib/DataSourceComparator.java | 6 +- .../onap/ccsdk/sli/core/dblib/DbLibService.java | 34 ++++----- .../core/dblib/pm/SQLExecutionMonitorObserver.java | 18 ++--- .../sli/core/sli/provider/SvcLogicService.java | 82 +++++++++++----------- .../core/slipluginutils/SvcLogicContextObject.java | 2 +- 7 files changed, 74 insertions(+), 74 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java index 2e1a6e953..f30212dca 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceObserver.java @@ -23,5 +23,5 @@ package org.onap.ccsdk.sli.core.dblib; import java.util.Observer; public interface DBResourceObserver extends Observer { - public boolean isMonitorDbResponse(); + boolean isMonitorDbResponse(); } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java index 7921fa5c5..fdfb47bca 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java @@ -27,7 +27,7 @@ import javax.sql.rowset.CachedRowSet; public interface DataAccessor { - public abstract CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) - throws SQLException; + CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) + throws SQLException; } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java index bc14fb8b9..4cfcc7318 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataSourceComparator.java @@ -24,10 +24,10 @@ import java.util.Comparator; public interface DataSourceComparator extends Comparator { - public abstract CachedDataSource getLastUsed(); + CachedDataSource getLastUsed(); - public abstract void setLastUsed(CachedDataSource lastUsed); + void setLastUsed(CachedDataSource lastUsed); - public abstract int compare(CachedDataSource ds1, CachedDataSource ds2); + int compare(CachedDataSource ds1, CachedDataSource ds2); } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java index 0dea664d5..b31de3547 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java @@ -28,22 +28,22 @@ import javax.sql.rowset.CachedRowSet; public interface DbLibService { - /* (non-Javadoc) - * @see DataAccessor#getData(java.lang.String, java.util.ArrayList) - */ - public abstract CachedRowSet getData(String statement, - ArrayList arguments, String preferredDS) - throws SQLException; - - /* (non-Javadoc) - * @see DataAccessor#writeData(java.lang.String, java.util.ArrayList) - */ - public abstract boolean writeData(String statement, - ArrayList arguments, String preferredDS) - throws SQLException; - - public abstract boolean isActive(); - - public abstract Connection getConnection() throws SQLException; + /* (non-Javadoc) + * @see DataAccessor#getData(java.lang.String, java.util.ArrayList) + */ + CachedRowSet getData(String statement, + ArrayList arguments, String preferredDS) + throws SQLException; + + /* (non-Javadoc) + * @see DataAccessor#writeData(java.lang.String, java.util.ArrayList) + */ + boolean writeData(String statement, + ArrayList arguments, String preferredDS) + throws SQLException; + + boolean isActive(); + + Connection getConnection() throws SQLException; } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java index c17696a80..2fdde1ee4 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitorObserver.java @@ -21,17 +21,17 @@ package org.onap.ccsdk.sli.core.dblib.pm; public interface SQLExecutionMonitorObserver { - public String getDbConnectionName(); + String getDbConnectionName(); - public long getInterval(); - public void setInterval(long value); + long getInterval(); + void setInterval(long value); - public long getInitialDelay(); - public void setInitialDelay(long value); + long getInitialDelay(); + void setInitialDelay(long value); - public long getExpectedCompletionTime(); - public void setExpectedCompletionTime(long value); + long getExpectedCompletionTime(); + void setExpectedCompletionTime(long value); - public long getUnprocessedFailoverThreshold(); - public void setUnprocessedFailoverThreshold(long value); + long getUnprocessedFailoverThreshold(); + void setUnprocessedFailoverThreshold(long value); } diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java index 23911b683..19d985dd4 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicService.java @@ -28,49 +28,49 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; public interface SvcLogicService { - public static final String NAME = "org.onap.ccsdk.sli.core.sli.provider.SvcLogicService"; + String NAME = "org.onap.ccsdk.sli.core.sli.provider.SvcLogicService"; - // public SvcLogicContext execute(SvcLogicGraph graph, SvcLogicContext ctx) throws SvcLogicException; - /** - * Check for existence of a directed graph - * @param module - module name - * @param rpc - rpc name - * @param version - version. If null, looks for active version - * @param mode - mode (sync/async) - * @return true if directed graph found, false otherwise - * @throws SvcLogicException - */ - public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException; + // public SvcLogicContext execute(SvcLogicGraph graph, SvcLogicContext ctx) throws SvcLogicException; + /** + * Check for existence of a directed graph + * @param module - module name + * @param rpc - rpc name + * @param version - version. If null, looks for active version + * @param mode - mode (sync/async) + * @return true if directed graph found, false otherwise + * @throws SvcLogicException + */ + boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException; - /** - * Execute a directed graph - * - * @param module - module name - * @param rpc - rpc name - * @param version - version. If null, use active version - * @param mode - mode (sync/async) - * @param parms - parameters, used to set SvcLogicContext attributes - * @return final values of attributes from SvcLogicContext, as Properties - * @throws SvcLogicException - * - * - * @deprecated use execute(String module, String rpc, String version, String mode, DOMDataBroker dataBroker) instead - */ - @Deprecated - public Properties execute(String module, String rpc, String version, String mode, Properties parms) throws SvcLogicException; + /** + * Execute a directed graph + * + * @param module - module name + * @param rpc - rpc name + * @param version - version. If null, use active version + * @param mode - mode (sync/async) + * @param parms - parameters, used to set SvcLogicContext attributes + * @return final values of attributes from SvcLogicContext, as Properties + * @throws SvcLogicException + * + * + * @deprecated use execute(String module, String rpc, String version, String mode, DOMDataBroker dataBroker) instead + */ + @Deprecated + Properties execute(String module, String rpc, String version, String mode, Properties parms) throws SvcLogicException; - /** - * Execute a directed graph - * - * @param module - module name - * @param rpc - rpc name - * @param version - version. If null, use active version - * @param mode - mode (sync/async) - * @param parms - parameters, used to set SvcLogicContext attributes - * @param domDataBroker - DOMDataBroker object - * @return final values of attributes from SvcLogicContext, as Properties - * @throws SvcLogicException - */ - public Properties execute(String module, String rpc, String version, String mode, Properties parms, DOMDataBroker domDataBroker) throws SvcLogicException; + /** + * Execute a directed graph + * + * @param module - module name + * @param rpc - rpc name + * @param version - version. If null, use active version + * @param mode - mode (sync/async) + * @param parms - parameters, used to set SvcLogicContext attributes + * @param domDataBroker - DOMDataBroker object + * @return final values of attributes from SvcLogicContext, as Properties + * @throws SvcLogicException + */ + Properties execute(String module, String rpc, String version, String mode, Properties parms, DOMDataBroker domDataBroker) throws SvcLogicException; } diff --git a/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java b/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java index eaa92c3f3..aa41a5c60 100644 --- a/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java +++ b/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/SvcLogicContextObject.java @@ -24,5 +24,5 @@ package org.onap.ccsdk.sli.core.slipluginutils; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; public interface SvcLogicContextObject { - public void writeToContext( SvcLogicContext ctx, String root ); + void writeToContext(SvcLogicContext ctx, String root ); } -- cgit 1.2.3-korg From d3913648518ce15fe7a74275394b86d0ecfb32a4 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Fri, 15 Sep 2017 01:02:37 +0000 Subject: Prepared DBLIB for multi-verndor JDBC Driver Changes made: 1. removed hardcoded JDBC driver's name and made it a property. 2. Optimized connection pool initialization 3. Removed unused factories. Change-Id: Id1d1868f7f1a6ae5a0429a97403042a8f6ee78d3 Issue-ID: CCSDK-92 Signed-off-by: Rich Tabedzki --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 5 +- .../ccsdk/sli/core/dblib/DBResourceManager.java | 169 +++++++++++++++---- .../sli/core/dblib/config/BaseDBConfiguration.java | 126 +++++++------- .../factory/AbstractDBResourceManagerFactory.java | 39 ----- .../factory/AbstractResourceManagerFactory.java | 104 ------------ .../dblib/factory/FactoryNotDefinedException.java | 37 ----- .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 46 +----- .../dblib/jdbc/JdbcDbResourceManagerFactory.java | 183 --------------------- 8 files changed, 210 insertions(+), 499 deletions(-) mode change 100644 => 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java mode change 100644 => 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java mode change 100644 => 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java mode change 100644 => 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java old mode 100644 new mode 100755 index ee8ab2f33..a5902d54b --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -20,7 +20,6 @@ package org.onap.ccsdk.sli.core.dblib; -import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; import org.apache.tomcat.jdbc.pool.PoolExhaustedException; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; @@ -535,7 +534,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito return monitor; } - protected boolean isSlave() throws PoolExhaustedException, MySQLNonTransientConnectionException { + protected boolean isSlave() throws PoolExhaustedException { CachedRowSet rs = null; boolean isSlave = true; String hostname = "UNDETERMINED"; @@ -547,7 +546,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito hostname = rs.getString(2); } isSlave = localSlave; - } catch(PoolExhaustedException | MySQLNonTransientConnectionException peexc){ + } catch(PoolExhaustedException peexc){ throw peexc; } catch (SQLException e) { LOGGER.error("", e); 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 old mode 100644 new mode 100755 index 7a27a20ce..a2eb0f9c1 --- 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 @@ -7,9 +7,9 @@ * 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. @@ -20,11 +20,8 @@ package org.onap.ccsdk.sli.core.dblib; -import com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException; import org.apache.tomcat.jdbc.pool.PoolExhaustedException; import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; -import org.onap.ccsdk.sli.core.dblib.factory.AbstractDBResourceManagerFactory; -import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; @@ -52,8 +49,21 @@ import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.TimerTask; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; + +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; +import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @version $Revision: 1.15 $ @@ -72,11 +82,18 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb protected final AtomicBoolean dsSelector = new AtomicBoolean(); // Queue dsQueue = new ConcurrentLinkedQueue(); - Queue dsQueue = new PriorityQueue<>(4, new Comparator() { + Queue dsQueue = new PriorityQueue(4, new Comparator() { @Override public int compare(CachedDataSource left, CachedDataSource right) { try { - if (!left.isSlave()) { + if(left == null){ + return 1; + } + if(right == null){ + return -1; + } + + if(!left.isSlave()) { return -1; } if (!right.isSlave()) { @@ -144,31 +161,108 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } private void config(Properties configProps) throws Exception { - + final ConcurrentLinkedQueue semaphore = new ConcurrentLinkedQueue(); 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()); - 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."); + long startTime = System.currentTimeMillis(); + + try { + JDBCConfiguration[] config = dbConfig.getJDBCbSourceArray(); + CachedDataSource[] cachedDS = new CachedDataSource[config.length]; + 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 < config.length; i++) { + cachedDS[i] = CachedDataSourceFactory.createDataSource(config[i]); + if(cachedDS[i] == null) + continue; + semaphore.add(cachedDS[i]); + cachedDS[i].setInterval(monitoringInterval); + cachedDS[i].setInitialDelay(monitoringInitialDelay); + cachedDS[i].setExpectedCompletionTime(expectedCompletionTime); + cachedDS[i].setUnprocessedFailoverThreshold(unprocessedFailoverThreshold); + cachedDS[i].addObserver(DBResourceManager.this); + } + +// CachedDataSource[] cachedDS = factory.initDBResourceManager(dbConfig, DBResourceManager.this, semaphore); + DataSourceTester[] tester = new DataSourceTester[config.length]; + + for(int i=0; i semaphoreQ; + + public DataSourceTester(CachedDataSource ds, DBResourceManager manager, ConcurrentLinkedQueue semaphore) { + this.ds = ds; + this.manager = manager; + this.semaphoreQ = semaphore; } - for (final CachedDataSource ds : cachedDS) { - if(ds != null && ds.isInitialized()){ - setDataSource(ds); - ds.setInterval(monitoringInterval); - ds.setInitialDelay(monitoringInitialDelay); - ds.setExpectedCompletionTime(expectedCompletionTime); - ds.setUnprocessedFailoverThreshold(unprocessedFailoverThreshold); - ds.addObserver(this); + @Override + public void run() { + manager.setDataSource(ds); + boolean slave = true; + if(ds != null) { + try { + slave = ds.isSlave(); + } catch (Exception exc) { + LOGGER.warn("", exc); + } } + if(!slave) { + LOGGER.info(String.format("Adding MASTER (%s) to active queue", ds.getDbConnectionName())); + try { + synchronized (semaphoreQ) { + semaphoreQ.notifyAll(); + } + } catch(Exception exc) { + LOGGER.warn("", exc); + } } + try { + synchronized (semaphoreQ) { + semaphoreQ.remove(ds); + } + if(semaphoreQ.isEmpty()) { + synchronized (semaphoreQ) { + semaphoreQ.notifyAll(); + } + } + } catch(Exception exc) { + LOGGER.warn("", exc); + } + LOGGER.info(String.format("Thread DataSourceTester terminated %s for %s", this.getName(), ds.getDbConnectionName())); + } + } + private long getLongFromProperties(Properties props, String property, long defaultValue) { String value = null; @@ -306,7 +400,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb CachedDataSource active = null; // test if there are any connection pools available - LinkedList sources = new LinkedList<>(this.dsQueue); + LinkedList sources = new LinkedList(this.dsQueue); if(sources.isEmpty()){ LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); @@ -423,8 +517,8 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb return writeDataNoRecovery(statement, newList, preferredDS); } - CachedDataSource findMaster() throws PoolExhaustedException, MySQLNonTransientConnectionException { - CachedDataSource master; + CachedDataSource findMaster() throws PoolExhaustedException { + CachedDataSource master = null; CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); for(int i=0; i list = new ArrayList<>(); + ArrayList list = new ArrayList(); list.addAll(dsQueue); list.addAll(broken); if (htmlFormat) @@ -785,7 +880,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public String getPreferredDataSourceName(AtomicBoolean flipper) { - LinkedList snapshot = new LinkedList<>(dsQueue); + LinkedList snapshot = new LinkedList(dsQueue); if(snapshot.size() > 1){ CachedDataSource first = snapshot.getFirst(); CachedDataSource last = snapshot.getLast(); @@ -849,4 +944,8 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb ds.getPoolInfo(false); } } + + public int poolSize() { + return dsQueue.size(); + } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java old mode 100644 new mode 100755 index d53be0e7f..a8bc58b8b --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java @@ -7,9 +7,9 @@ * 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. @@ -30,58 +30,68 @@ public abstract class BaseDBConfiguration { /** * Property key within a properties configuration File for db type */ - public static final String DATABASE_TYPE = "org.onap.ccsdk.sli.dbtype"; + public static final String DATABASE_TYPE = "org.onap.ccsdk.sli.dbtype"; /** * Property key with a properties configuration File for db url */ - public static final String DATABASE_URL = "org.onap.ccsdk.sli.jdbc.url"; + public static final String DATABASE_URL = "org.onap.ccsdk.sli.jdbc.url"; /** * Property key with a properties configuration File for database name */ - public static final String DATABASE_NAME = "org.onap.ccsdk.sli.jdbc.database"; + public static final String DATABASE_NAME = "org.onap.ccsdk.sli.jdbc.database"; + + /** + * Property key with a properties configuration File for jdbc driver + */ + public static final String DRIVER_NAME = "org.onap.ccsdk.sli.jdbc.driver"; /** * Property key with a properties configuration File for db database connection name */ - public static final String CONNECTION_NAME = "org.onap.ccsdk.sli.jdbc.connection.name"; + public static final String CONNECTION_NAME = "org.onap.ccsdk.sli.jdbc.connection.name"; /** * Property key with a properties configuration File for database user */ - public static final String DATABASE_USER = "org.onap.ccsdk.sli.jdbc.user"; + public static final String DATABASE_USER = "org.onap.ccsdk.sli.jdbc.user"; /** - * Property key with a properties configuration File for database password for associated with - * org.onap.ccsdk.sli.jdbc.user. + * Property key with a properties configuration File for database password + * for associated with org.onap.ccsdk.sli.jdbc.user. */ - public static final String DATABASE_PSSWD = "org.onap.ccsdk.sli.jdbc.password"; + public static final String DATABASE_PSSWD = "org.onap.ccsdk.sli.jdbc.password"; /** - * Property key with a properties configuration File for database connection timeout + * Property key with a properties configuration File for database connection + * timeout */ public static final String CONNECTION_TIMEOUT="org.onap.ccsdk.sli.jdbc.connection.timeout"; /** - * Property key with a properties configuration File for database request timeout + * Property key with a properties configuration File for database request + * timeout */ - public static final String REQUEST_TIMEOUT = "org.onap.ccsdk.sli.jdbc.request.timeout"; + public static final String REQUEST_TIMEOUT = "org.onap.ccsdk.sli.jdbc.request.timeout"; /** - * Property key with a properties configuration File for database minimum limit + * Property key with a properties configuration File for database minimum + * limit */ - public static final String MIN_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.min"; + public static final String MIN_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.min"; /** - * Property key with a properties configuration File for database maximum limit + * Property key with a properties configuration File for database maximum + * limit */ - public static final String MAX_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.max"; + public static final String MAX_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.max"; /** - * Property key with a properties configuration File for database initial limit + * Property key with a properties configuration File for database initial + * limit */ - public static final String INIT_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.init"; + public static final String INIT_LIMIT = "org.onap.ccsdk.sli.jdbc.limit.init"; /** * Property key with a properties configuration File for database hosts @@ -89,14 +99,10 @@ public abstract class BaseDBConfiguration { public static final String DATABASE_HOSTS = "org.onap.ccsdk.sli.jdbc.hosts"; /** - * default value when the connection timeout is not present or cannot be parsed - */ - private static final int DEFAULT_CONNECTION_TIMEOUT = -1; - - /** - * default value when the request timeout is not present or cannot be parsed + * default value when the connection timeout is not present or cannot be + * parsed. */ - private static final int DEFAULT_REQUEST_TIMEOUT = -1; + private static final String DEFAULT_REJECT_CHANGE_VALUE = "-1"; /** * A set of properties with database configuration information. @@ -106,7 +112,9 @@ public abstract class BaseDBConfiguration { /** * Builds a configuration based on given properties * - * @param properties properties represented by the public constant keys defined by this class + * @param properties + * properties represented by the public constant keys defined by + * this class */ public BaseDBConfiguration(final Properties properties) { this.properties = properties; @@ -115,35 +123,30 @@ public abstract class BaseDBConfiguration { /** * Extracts the connection timeout. * - * @return the connection timeout, or DEFAULT_CONNECTION_TIMEOUT if not present + * @return the connection timeout, or + * DEFAULT_REJECT_CHANGE_VALUE if not present */ public int getConnTimeout() { - return extractProperty(properties, CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); + try { + String value = properties.getProperty(CONNECTION_TIMEOUT, DEFAULT_REJECT_CHANGE_VALUE); + return Integer.parseInt(value); + } catch (Exception exc) { + return Integer.parseInt(DEFAULT_REJECT_CHANGE_VALUE); + } } /** * Extracts the request timeout. * - * @return the request timeout, or DEFAULT_REQUEST_TIMEOUT if not present + * @return the request timeout, or DEFAULT_REQUEST_TIMEOUT if + * not present */ public int getRequestTimeout() { - return extractProperty(properties, REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT); - } - - /** - * A utility method to extract int property from Properties. - * - * @param properties a set of Properties - * @param propertyKey the key in question - * @param defaultValue the value to return if the key does not exist - * @return Either the property value for propertyKey or defaultValue if not present - */ - private static int extractProperty(final Properties properties, final String propertyKey, final int defaultValue) { try { - final String valueString = properties.getProperty(propertyKey, Integer.toString(defaultValue)); - return Integer.parseInt(valueString); - } catch(final NumberFormatException e) { - return defaultValue; + String value = properties.getProperty(REQUEST_TIMEOUT, DEFAULT_REJECT_CHANGE_VALUE); + return Integer.parseInt(value); + } catch (Exception exc) { + return Integer.parseInt(DEFAULT_REJECT_CHANGE_VALUE); } } @@ -165,6 +168,15 @@ public abstract class BaseDBConfiguration { return properties.getProperty(DATABASE_NAME); } + /** + * Extracts the jdbc driver's name. + * + * @return the jdbc name, or com.mysql.jdbc.Driver if not present + */ + public String getDriverName() { + return properties.getProperty(DRIVER_NAME, "com.mysql.jdbc.Driver"); + } + /** * Extracts the db user id. * @@ -187,7 +199,9 @@ public abstract class BaseDBConfiguration { * Extracts the db min limit. * * @return the db min limit - * @throws NumberFormatException if the property is not specified, or cannot be parsed as an Integer. + * @throws NumberFormatException + * if the property is not specified, or cannot be parsed as an + * Integer. */ public int getDbMinLimit() throws NumberFormatException { String value = properties.getProperty(MIN_LIMIT); @@ -198,7 +212,9 @@ public abstract class BaseDBConfiguration { * Extracts the db max limit. * * @return the db max limit - * @throws NumberFormatException if the property is not specified, or cannot be parsed as an Integer. + * @throws NumberFormatException + * if the property is not specified, or cannot be parsed as an + * Integer. */ public int getDbMaxLimit() throws NumberFormatException { String value = properties.getProperty(MAX_LIMIT); @@ -209,7 +225,9 @@ public abstract class BaseDBConfiguration { * Extracts the db initial limit. * * @return the db initial limit - * @throws NumberFormatException if the property is not specified, or cannot be parsed as an Integer. + * @throws NumberFormatException + * if the property is not specified, or cannot be parsed as an + * Integer. */ public int getDbInitialLimit() throws NumberFormatException { String value = properties.getProperty(INIT_LIMIT); @@ -224,14 +242,4 @@ public abstract class BaseDBConfiguration { public String getDbUrl() { return properties.getProperty(DATABASE_URL); } - - /** - * Extracts the db server group. - * - * @return null - */ - @Deprecated - public String getServerGroup() { - return null; - } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java deleted file mode 100644 index e88734d2e..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractDBResourceManagerFactory.java +++ /dev/null @@ -1,39 +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.factory; - -import org.onap.ccsdk.sli.core.dblib.jdbc.JdbcDbResourceManagerFactory; - -/** - * @version $Revision: 1.1 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class AbstractDBResourceManagerFactory { - - public static AbstractResourceManagerFactory getFactory(String type) throws FactoryNotDefinedException { - - // JDBC - return JdbcDbResourceManagerFactory.createIntstance(); - } -} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java deleted file mode 100644 index 486d0ccc1..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/AbstractResourceManagerFactory.java +++ /dev/null @@ -1,104 +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.factory; - - -import org.onap.ccsdk.sli.core.dblib.CachedDataSource; -import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; -import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; -import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.SQLException; -import java.util.Set; -import java.util.concurrent.Callable; - -/** - * @version $Revision: 1.6 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public abstract class AbstractResourceManagerFactory { - private static Logger LOGGER = LoggerFactory.getLogger(AbstractResourceManagerFactory.class); - - public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager) throws Exception; - public abstract CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager dbResourceManager, String sourceName) throws SQLException ; - - - public static AbstractResourceManagerFactory createIntstance() throws FactoryNotDefinedException { - throw new FactoryNotDefinedException("Factory method 'createIntstance' needs to be overriden in DBResourceManagerFactory"); - } - - public class DBInitTask implements Callable - { - private BaseDBConfiguration config = null; - private Set activeTasks; - - public DBInitTask(JDBCConfiguration jdbcconfig, Set tasks) { - this.config = jdbcconfig; - this.activeTasks = tasks; - } - - public CachedDataSource call() throws Exception { - CachedDataSource ds = null; - try { - ds = CachedDataSourceFactory.createDataSource(config); - return ds; - } finally { - synchronized(activeTasks) { - activeTasks.remove(this); - if (activeTasks.isEmpty()) { - final Runnable closure = new Runnable() { - - public void run() { - try { - Thread.sleep(300); - } catch (Exception e) { - } - synchronized(activeTasks) { - activeTasks.notifyAll(); - } - } - }; - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Completed CachedDataSource.Call and notifyAll from " + (ds != null ? ds - .getDbConnectionName() : null)); - } - Thread worker = new Thread(closure); - worker.setDaemon(true); - worker.start(); - } else { - if (LOGGER.isDebugEnabled()) { - if (ds != null) { - LOGGER.debug("Completed CachedDataSource.Call from " + ds.getDbConnectionName()); - } - } - } - } - } - } - } -} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java deleted file mode 100644 index b6383a53b..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/FactoryNotDefinedException.java +++ /dev/null @@ -1,37 +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.factory; - - -/** - * @version 1.3 - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki 01/16/08 Initial version - */ -public class FactoryNotDefinedException extends Exception { - - public FactoryNotDefinedException(String message) { - super(message); - } - -} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java old mode 100644 new mode 100755 index ffe834456..3ec4f2edf --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -33,19 +33,10 @@ import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.mysql.jdbc.Driver; - - -/** - * @version $Revision: 1.7 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ public class JdbcDBCachedDataSource extends CachedDataSource { + private String dbDriver; private String dbUserId; private String dbPasswd; private String dbUrl; @@ -96,15 +87,14 @@ public class JdbcDBCachedDataSource extends CachedDataSource LOGGER.error(AS_CONF_ERROR + errorMsg); throw new DBConfigException(errorMsg); } - /* - dbDriver = jdbcConfig.getDbDriver(); + + dbDriver = jdbcConfig.getDriverName(); if (dbDriver == null) { String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new ScpTblUpdateError(errorMsg); + throw new DBConfigException(errorMsg); } - */ minLimit = jdbcConfig.getDbMinLimit(); // if (minLimit == null) @@ -136,11 +126,10 @@ public class JdbcDBCachedDataSource extends CachedDataSource } try { - Driver dr = new com.mysql.jdbc.Driver(); - Class clazz = Class.forName("com.mysql.jdbc.Driver") ; + Class clazz = Class.forName(dbDriver) ; PoolProperties p = new PoolProperties(); - p.setDriverClassName("com.mysql.jdbc.Driver"); + p.setDriverClassName(dbDriver); p.setUrl(dbUrl); p.setUsername(dbUserId); p.setPassword(dbPasswd); @@ -172,30 +161,9 @@ public class JdbcDBCachedDataSource extends CachedDataSource PreparedStatement st = null; ResultSet rs = null; - try { - con = dataSource.getConnection(); - st = con.prepareStatement("Select 1 FROM DUAL"); - rs = st.executeQuery(); - } catch(Exception exc) { - LOGGER.error(exc.getMessage()); - } finally { - if(rs != null) rs.close(); - if(st != null) st.close(); - if(con != null) con.close(); - } - initialized = true; - LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); + LOGGER.info("JdbcDBCachedDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); } - -// } catch (SQLException exc) { -// initialized = false; -// StringBuffer sb = new StringBuffer(); -// sb.append("Failed to initialize MySQLDataSource<"); -// sb.append(dbConnectionName).append(">. Reason: "); -// sb.append(exc.getMessage()); -// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -//// throw new DBConfigException(e.getMessage()); } catch (Exception exc) { initialized = false; StringBuffer sb = new StringBuffer(); diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java deleted file mode 100644 index 803e6b3e7..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDbResourceManagerFactory.java +++ /dev/null @@ -1,183 +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.jdbc; - - -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; - -import org.onap.ccsdk.sli.core.dblib.CachedDataSource; -import org.onap.ccsdk.sli.core.dblib.CachedDataSourceFactory; -import org.onap.ccsdk.sli.core.dblib.DBResourceManager; -import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; -import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; -import org.onap.ccsdk.sli.core.dblib.factory.AbstractResourceManagerFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @version $Revision: 1.6 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ -public class JdbcDbResourceManagerFactory extends AbstractResourceManagerFactory { - private static Logger LOGGER = LoggerFactory.getLogger(JdbcDbResourceManagerFactory.class ); - private JdbcDbResourceManagerFactory(){ - - } - - class MyFutureTask extends FutureTask - { - - public MyFutureTask(Callable result) { - super(result); - } - - } - - public CachedDataSource[] initDBResourceManager(DbConfigPool dbConfig, DBResourceManager manager, String sourceName) throws SQLException - { - // here create the data sources objects - JDBCConfiguration[] list = dbConfig.getJDBCbSourceArray(); - CachedDataSource[] cachedDS = new CachedDataSource[1]; - - for(int i=0, max=list.length; i tasks = new HashSet(); - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("Creating " + list.length + " datasources."); - } - - for(int i=0, max=list.length; i Date: Tue, 19 Sep 2017 17:33:48 -0400 Subject: Remove mysql dependencies in sli/core Remove lingering mysql dependencies in sli/core, which prevented odlsli container from starting up clean. Note: tested this using bareodl container and verified that these changes install clean AFTER changing incorrect driver property name in dblib.properties. This patch is fine, but a second patch to ccsdk/distribution is needed to fix that property file. Change-Id: I6a900d1c29998867bfbae29d5e113c4e392a8bb9 Issue-ID: CCSDK-95 Signed-off-by: Dan Timoney --- dblib/features/src/main/resources/features.xml | 2 +- dblib/provider/pom.xml | 5 - .../sli/core/dblib/jdbc/MySQLCachedDataSource.java | 216 --------------------- .../onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java | 2 +- sli/features/src/main/resources/features.xml | 2 +- .../sli/core/sli/provider/SvcLogicActivator.java | 46 +++-- .../features/src/main/resources/features.xml | 5 +- 7 files changed, 27 insertions(+), 251 deletions(-) delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java (limited to 'dblib/provider/src') diff --git a/dblib/features/src/main/resources/features.xml b/dblib/features/src/main/resources/features.xml index 36d794139..aa31db751 100755 --- a/dblib/features/src/main/resources/features.xml +++ b/dblib/features/src/main/resources/features.xml @@ -12,7 +12,7 @@ odl-mdsal-broker wrap:mvn:org.apache.tomcat/tomcat-jdbc/${tomcat-jdbc.version}/$DynamicImport-Package=org.mariadb.*&overwrite=merge mvn:org.onap.ccsdk.sli.core/dblib-provider/${project.version} - mvn:org/mariadb/jdbc/mariadb-java-client/${mariadb.connector.version} + mvn:org.mariadb.jdbc/mariadb-java-client/${mariadb.connector.version} diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index 765f73798..8ff109417 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -42,11 +42,6 @@ ${slf4j.version} test - - mysql - mysql-connector-java - ${mysql.connector.version} - org.mariadb.jdbc mariadb-java-client diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java deleted file mode 100644 index bea0d631f..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/MySQLCachedDataSource.java +++ /dev/null @@ -1,216 +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.jdbc; - -import java.sql.SQLFeatureNotSupportedException; -import java.util.Properties; - -import org.onap.ccsdk.sli.core.dblib.CachedDataSource; -import org.onap.ccsdk.sli.core.dblib.DBConfigException; -import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; - - - - -/** - * @version $Revision: 1.7 $ - * Change Log - * Author Date Comments - * ============== ======== ==================================================== - * Rich Tabedzki - */ - -public class MySQLCachedDataSource extends CachedDataSource -{ - private String dbUserId; - private String dbPasswd; - private String dbUrl; - - private String minLimit; - private String maxLimit; - private String initialLimit; - - private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; - - private static Logger LOGGER = LoggerFactory.getLogger(MySQLCachedDataSource.class); - - /** - * @param jdbcElem - */ - public MySQLCachedDataSource(BaseDBConfiguration jdbcElem) - { - super(jdbcElem); - } - - @Override - protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException - { - BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem; - if(jdbcConfig.getConnTimeout() > 0){ - this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); - } - if(jdbcConfig.getRequestTimeout() > 0){ - this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); - } - - // set connection pool name - String dbConnectionName = jdbcConfig.getDbConnectionName(); - super.setDbConnectionName(dbConnectionName); - // Configure the JDBC connection - dbUserId = jdbcConfig.getDbUserId(); - if (dbUserId == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - dbPasswd = jdbcConfig.getDbPasswd(); - if (dbPasswd == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - /* - dbDriver = jdbcConfig.getDbDriver(); - if (dbDriver == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new ScpTblUpdateError(errorMsg); - } - */ - - minLimit = Integer.toString(jdbcConfig.getDbMinLimit()); - if (minLimit == null) - { - String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - maxLimit = Integer.toString(jdbcConfig.getDbMaxLimit()); - if (maxLimit == null) - { - String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - initialLimit = Integer.toString(jdbcConfig.getDbInitialLimit()); - if (initialLimit == null) - { - String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - dbUrl = jdbcConfig.getDbUrl(); - if(dbUrl == null){ - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); - } - - try { - - MysqlDataSource dataSource = new MysqlDataSource(); - dataSource.setUser(dbUserId); - dataSource.setPassword(dbPasswd); - dataSource.setURL(dbUrl); -// dataSource.setInitialSize(5); -// dataSource.setMaxTotal(60); -// dataSource.setMaxActive(100); -// dataSource.setMaxWait(10000); -// dataSource.setMaxIdle(10); - - Properties connAttr = new Properties(); - - connAttr.setProperty("MinLimit", minLimit); - connAttr.setProperty("MaxLimit", maxLimit); - connAttr.setProperty("InitialLimit", initialLimit); - connAttr.setProperty("TRANSACTION_ISOLATION","SERIALIZABLE"); - connAttr.setProperty("CONNECTION_TAG", dbConnectionName.toUpperCase()+"_CONNECTION"); - connAttr.setProperty("InactivityTimeout", "900"); - connAttr.setProperty("AbandonedConnectionTimeout", "600"); - connAttr.setProperty("PropertyCheckInterval", "60"); - connAttr.setProperty("ValidateConnection", "true"); - - - synchronized(this) - { - this.ds = dataSource; - - initialized = true; - LOGGER.info("MySQLDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); - } - -// } catch (SQLException exc) { -// initialized = false; -// StringBuffer sb = new StringBuffer(); -// sb.append("Failed to initialize MySQLDataSource<"); -// sb.append(dbConnectionName).append(">. Reason: "); -// sb.append(exc.getMessage()); -// LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -//// throw new DBConfigException(e.getMessage()); - } catch (Exception exc) { - initialized = false; - StringBuffer sb = new StringBuffer(); - sb.append("Failed to initialize MySQLCachedDataSource <"); - sb.append(dbConnectionName).append(">. Reason: "); - sb.append(exc.getMessage()); - LOGGER.error("AS_CONF_ERROR: " + sb.toString()); -// throw new DBConfigException(e.getMessage()); - } - } - - public final String getDbUrl() - { - return dbUrl; - } - - public final String getDbUserId() - { - return dbUserId; - } - - public final String getDbPasswd() - { - return dbPasswd; - } - - public static MySQLCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { - return new MySQLCachedDataSource(config); - } - - public String toString(){ - return getDbConnectionName(); - } - - public java.util.logging.Logger getParentLogger() - throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub - return null; - } -} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java index 71926e415..1e4b71cd8 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java @@ -73,7 +73,7 @@ public class SvcLogicJdbcStore implements SvcLogicStore { jdbcProps.setProperty("password", dbPasswd); try { - Driver dvr = new com.mysql.jdbc.Driver(); + Driver dvr = new org.mariadb.jdbc.Driver(); if (dvr.acceptsURL(dbUrl)) { LOG.debug("Driver com.mysql.jdbc.Driver accepts {}", dbUrl); diff --git a/sli/features/src/main/resources/features.xml b/sli/features/src/main/resources/features.xml index 692d9ff0a..1f17c1a95 100644 --- a/sli/features/src/main/resources/features.xml +++ b/sli/features/src/main/resources/features.xml @@ -33,7 +33,7 @@ mvn:org.onap.ccsdk.sli.core/sli-provider/${project.version} mvn:org.onap.ccsdk.sli.core/sli-recording/${project.version} sdnc-dblib - mvn:org/mariadb/jdbc/mariadb-java-client/${mariadb.connector.version} + mvn:org.mariadb.jdbc/mariadb-java-client/${mariadb.connector.version} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java index 4a13000aa..a578dc6ae 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java @@ -8,9 +8,9 @@ * 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. @@ -41,7 +41,6 @@ import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.mysql.jdbc.Driver; public class SvcLogicActivator implements BundleActivator { @@ -76,47 +75,47 @@ public class SvcLogicActivator implements BundleActivator { private static LinkedList registrations = new LinkedList(); private static HashMap adaptorMap = null; - + private static final Logger LOG = LoggerFactory .getLogger(SvcLogicActivator.class); - + private static Properties props = null; private static BundleContext bundleCtx = null; - + private static SvcLogicService svcLogicServiceImpl = null; - + @Override public void start(BundleContext ctx) throws Exception { LOG.info("Activating SLI"); - + bundleCtx = ctx; // Read properties props = new Properties(); String propPath = System.getenv(SVCLOGIC_PROP_VAR); - + if (propPath == null) { String propDir = System.getenv(SDNC_CONFIG_DIR); if (propDir == null) { - + propDir = "/opt/sdnc/data/properties"; } propPath = propDir + "/svclogic.properties"; LOG.warn("Environment variable "+SVCLOGIC_PROP_VAR+" unset - defaulting to "+propPath); } - + File propFile = new File(propPath); - + if (!propFile.exists()) { - + throw new ConfigurationException( "Missing configuration properties file : " + propFile); } try { - + props.load(new FileInputStream(propFile)); } catch (Exception e) { throw new ConfigurationException( @@ -168,15 +167,14 @@ public class SvcLogicActivator implements BundleActivator { registrations = null; } } - + public static SvcLogicStore getStore() throws SvcLogicException { // Create and initialize SvcLogicStore object - used to access // saved service logic. - + SvcLogicStore store = null; - + try { - Driver dvr = new Driver(); store = SvcLogicStoreFactory.getSvcLogicStore(props); } catch (Exception e) { throw new ConfigurationException( @@ -190,12 +188,12 @@ public class SvcLogicActivator implements BundleActivator { throw new ConfigurationException( "Could not get service logic store", e); } - + return(store); } - + private static void registerNodeTypes(SvcLogicStore store) throws SvcLogicException { - + if (store == null) { return; } @@ -213,13 +211,13 @@ public class SvcLogicActivator implements BundleActivator { registrations.add(reg); store.registerNodeType(nodeType); - + LOG.info("SLI - registering node executor"); - + ((SvcLogicServiceImpl)svcLogicServiceImpl).registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); } - + } } diff --git a/sliPluginUtils/features/src/main/resources/features.xml b/sliPluginUtils/features/src/main/resources/features.xml index e8d0d3cc2..f59cea423 100644 --- a/sliPluginUtils/features/src/main/resources/features.xml +++ b/sliPluginUtils/features/src/main/resources/features.xml @@ -9,9 +9,9 @@ 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. @@ -33,7 +33,6 @@ odl-mdsal-broker sdnc-sli mvn:org.onap.ccsdk.sli.core/sliPluginUtils-provider/${project.version} - mvn:mysql/mysql-connector-java/${mysql.connector.version} -- cgit 1.2.3-korg From 5e31510dba7647b0d0873d9864a0ee6c309e2247 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Tue, 19 Sep 2017 14:57:17 +0530 Subject: Fix Sonar Issue One blocker issue in sli/core module *Check for null dereferencing Issue-Id: CCSDK-87 Change-Id: I5ebaef24b3fd6534b5e818c3087e3d8213ed770c Signed-off-by: surya-huawei --- .../java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index a5902d54b..4d920e6a0 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -603,22 +603,14 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito protected boolean unlockTable(Connection conn) { boolean retValue = false; - Statement lock = null; - try { + try (Statement lock = conn.createStatement()){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); } - lock = conn.createStatement(); retValue = lock.execute("UNLOCK TABLES"); } catch(Exception exc){ LOGGER.error("", exc); retValue = false; - } finally { - try { - lock.close(); - } catch(Exception exc) { - - } } return retValue; } -- cgit 1.2.3-korg From 297671bfc3682d09962d24ab9b7788ccb1e9359b Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Wed, 20 Sep 2017 15:35:23 +0530 Subject: Fix Sonar Issues in sli/core module Few major issues *Remove unused imports To increase code readability *Replace the type specification with the diamond operator To reduce the verbosity of generics code *Add the "@Override" annotation above this method signature To increase code readability *Remove this unnecessary cast to "String" Unnecessary casting expressions pollutes code Issue-Id: CCSDK-87 Change-Id: I38952f5026a5c61af73ac16706e8ddc278566b13 Signed-off-by: surya-huawei --- .../ccsdk/sli/core/dblib/DBResourceManager.java | 39 +++++++++++----------- 1 file changed, 20 insertions(+), 19 deletions(-) (limited to 'dblib/provider/src') 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 a2eb0f9c1..014dab31a 100755 --- 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 @@ -52,18 +52,7 @@ import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; - -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; -import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; -import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * @version $Revision: 1.15 $ @@ -161,7 +150,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } private void config(Properties configProps) throws Exception { - final ConcurrentLinkedQueue semaphore = new ConcurrentLinkedQueue(); + final ConcurrentLinkedQueue semaphore = new ConcurrentLinkedQueue<>(); final DbConfigPool dbConfig = DBConfigFactory.createConfig(configProps); long startTime = System.currentTimeMillis(); @@ -268,7 +257,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb String value = null; long tmpLongValue = defaultValue; try { - value = (String)props.getProperty(property); + value = props.getProperty(property); if(value != null) tmpLongValue = Long.parseLong(value); @@ -288,7 +277,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb String value = null; try { - value = (String)props.getProperty(property); + value = props.getProperty(property); if(value != null) tmpValue = Boolean.parseBoolean(value); @@ -303,6 +292,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } + @Override public void update(Observable observable, Object data) { // if observable is active and there is a standby available, switch if(observable instanceof SQLExecutionMonitor) @@ -400,7 +390,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb CachedDataSource active = null; // test if there are any connection pools available - LinkedList sources = new LinkedList(this.dsQueue); + LinkedList sources = new LinkedList<>(this.dsQueue); if(sources.isEmpty()){ LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); @@ -603,6 +593,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } + @Override public Connection getConnection() throws SQLException { Throwable lastException = null; CachedDataSource active = null; @@ -664,6 +655,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } + @Override public Connection getConnection(String username, String password) throws SQLException { CachedDataSource active = null; @@ -754,18 +746,22 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } + @Override public PrintWriter getLogWriter() throws SQLException { return ((CachedDataSource)this.dsQueue.peek()).getLogWriter(); } + @Override public int getLoginTimeout() throws SQLException { return ((CachedDataSource)this.dsQueue.peek()).getLoginTimeout(); } + @Override public void setLogWriter(PrintWriter out) throws SQLException { ((CachedDataSource)this.dsQueue.peek()).setLogWriter(out); } + @Override public void setLoginTimeout(int seconds) throws SQLException { ((CachedDataSource)this.dsQueue.peek()).setLoginTimeout(seconds); } @@ -795,7 +791,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public String getDBStatus(boolean htmlFormat) { StringBuilder buffer = new StringBuilder(); - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); list.addAll(dsQueue); list.addAll(broken); if (htmlFormat) @@ -843,10 +839,12 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb return buffer.toString(); } + @Override public boolean isWrapperFor(Class iface) throws SQLException { return false; } + @Override public T unwrap(Class iface) throws SQLException { return null; } @@ -854,6 +852,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb /** * @return the monitorDbResponse */ + @Override public final boolean isMonitorDbResponse() { return recoveryMode && monitorDbResponse; } @@ -880,7 +879,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public String getPreferredDataSourceName(AtomicBoolean flipper) { - LinkedList snapshot = new LinkedList(dsQueue); + LinkedList snapshot = new LinkedList<>(dsQueue); if(snapshot.size() > 1){ CachedDataSource first = snapshot.getFirst(); CachedDataSource last = snapshot.getLast(); @@ -901,6 +900,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb return snapshot.peek().getDbConnectionName(); } + @Override public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; @@ -916,7 +916,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb private String getMasterDataSourceName(AtomicBoolean flipper) { - LinkedList snapshot = new LinkedList(dsQueue); + LinkedList snapshot = new LinkedList<>(dsQueue); if(snapshot.size() > 1){ CachedDataSource first = snapshot.getFirst(); CachedDataSource last = snapshot.getLast(); @@ -938,7 +938,8 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } class RemindTask extends TimerTask { - public void run() { + @Override + public void run() { CachedDataSource ds = dsQueue.peek(); if(ds != null) ds.getPoolInfo(false); -- cgit 1.2.3-korg From 03235aa6cc35871630ee3e09fe467eca79ce315e Mon Sep 17 00:00:00 2001 From: Ryan Goulding Date: Tue, 19 Sep 2017 11:14:41 -0400 Subject: Abstract utility classes for re-use When looking at the existing uses of BundleActivator(s), it became immediately clear that other parts of the code have a strategy based properties file resolution very similar to those abstracted by dblib. This change aggregates a separate utils bundle for this functionality, which is further abstracted for potential reuse with other use cases. The next use case is in the sli bundle, which will be handled in a follow-up patch. Issue-Id: SDNC-54 Change-Id: Ie4d4bb679617474b1983e6044c08cca1742b9893 Signed-off-by: Ryan Goulding --- dblib/provider/pom.xml | 5 ++ .../sli/core/dblib/DBLIBResourceProvider.java | 20 +++--- .../DblibDefaultFileResolver.java | 63 ------------------ .../DblibEnvVarFileResolver.java | 69 -------------------- .../DblibJREFileResolver.java | 73 --------------------- .../DblibKarafRootFileResolver.java | 64 ------------------- .../DblibPropertiesFileResolver.java | 45 ------------- .../DblibDefaultFileResolverTest.java | 24 ------- .../DblibEnvVarFileResolverTest.java | 23 ------- .../DblibJREFileResolverTest.java | 15 ----- .../DblibKarafRootFileResolverTest.java | 14 ---- pom.xml | 1 + utils/pom.xml | 56 ++++++++++++++++ .../ccsdk/sli/core/utils/DefaultFileResolver.java | 61 ++++++++++++++++++ .../ccsdk/sli/core/utils/EnvVarFileResolver.java | 70 ++++++++++++++++++++ .../onap/ccsdk/sli/core/utils/JREFileResolver.java | 74 ++++++++++++++++++++++ .../sli/core/utils/KarafRootFileResolver.java | 63 ++++++++++++++++++ .../sli/core/utils/PropertiesFileResolver.java | 45 +++++++++++++ .../core/utils/dblib/DblibDefaultFileResolver.java | 17 +++++ .../core/utils/dblib/DblibEnvVarFileResolver.java | 15 +++++ .../ccsdk/sli/core/utils/JREFileResolverTest.java | 15 +++++ .../sli/core/utils/KarafRootFileResolverTest.java | 14 ++++ .../utils/dblib/DblibDefaultFileResolverTest.java | 25 ++++++++ .../utils/dblib/DblibEnvVarFileResolverTest.java | 24 +++++++ 24 files changed, 495 insertions(+), 400 deletions(-) delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolver.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolver.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolver.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolver.java delete mode 100644 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibPropertiesFileResolver.java delete mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java delete mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java delete mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java delete mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java create mode 100644 utils/pom.xml create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/DefaultFileResolver.java create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolver.java create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/PropertiesFileResolver.java create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java create mode 100644 utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java create mode 100644 utils/src/test/java/org/onap/ccsdk/sli/core/utils/JREFileResolverTest.java create mode 100644 utils/src/test/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolverTest.java create mode 100644 utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolverTest.java create mode 100644 utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolverTest.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index 8ff109417..ad1cc9d28 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -56,6 +56,11 @@ com.google.guava guava + + org.onap.ccsdk.sli.core + utils + ${project.version} + 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 index 062cd8408..8e0b534f0 100644 --- 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 @@ -27,11 +27,11 @@ 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.onap.ccsdk.sli.core.utils.dblib.DblibDefaultFileResolver; +import org.onap.ccsdk.sli.core.utils.dblib.DblibEnvVarFileResolver; +import org.onap.ccsdk.sli.core.utils.JREFileResolver; +import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,7 +58,7 @@ public class DBLIBResourceProvider { /** * A prioritized list of strategies for resolving dblib properties files. */ - private Vector dblibPropertiesFileResolvers = new Vector(); + private Vector dblibPropertiesFileResolvers = new Vector(); /** * The configuration properties for the db connection. @@ -75,10 +75,10 @@ public class DBLIBResourceProvider { 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 JREFileResolver( + "Using property file (2) from JRE argument", DBLIBResourceProvider.class )); - dblibPropertiesFileResolvers.add(new DblibKarafRootFileResolver( + dblibPropertiesFileResolvers.add(new KarafRootFileResolver( "Using property file (4) from karaf root", this)); // determines properties file as according to the priority described in the class header comment @@ -141,7 +141,7 @@ public class DBLIBResourceProvider { */ File determinePropertiesFile(final DBLIBResourceProvider dblibResourceProvider) { - for (final DblibPropertiesFileResolver dblibPropertiesFileResolver : dblibPropertiesFileResolvers) { + for (final PropertiesFileResolver dblibPropertiesFileResolver : dblibPropertiesFileResolvers) { final Optional fileOptional = dblibPropertiesFileResolver.resolveFile(DBLIB_PROP_FILE_NAME); if (fileOptional.isPresent()) { return reportSuccess(dblibPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional); diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolver.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolver.java deleted file mode 100644 index a7797d9f7..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolver.java +++ /dev/null @@ -1,63 +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.propertiesfileresolver; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Optional; - -/** - * Resolves dblib properties files relative to the default file path. In Unix, this is represented by: - * /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 deleted file mode 100644 index 0b69109f9..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolver.java +++ /dev/null @@ -1,69 +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.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 deleted file mode 100644 index 673ccbf03..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolver.java +++ /dev/null @@ -1,73 +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.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 deleted file mode 100644 index d2b164e3b..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolver.java +++ /dev/null @@ -1,64 +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.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 deleted file mode 100644 index 97ab08acf..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibPropertiesFileResolver.java +++ /dev/null @@ -1,45 +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.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/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java deleted file mode 100644 index 41011e55b..000000000 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibDefaultFileResolverTest.java +++ /dev/null @@ -1,24 +0,0 @@ -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/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java deleted file mode 100644 index 775898930..000000000 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibEnvVarFileResolverTest.java +++ /dev/null @@ -1,23 +0,0 @@ -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/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java deleted file mode 100644 index 65ebfbae2..000000000 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibJREFileResolverTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.onap.ccsdk.sli.core.dblib.propertiesfileresolver; - -import static org.junit.Assert.*; - -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/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java deleted file mode 100644 index 0a032e8b7..000000000 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/propertiesfileresolver/DblibKarafRootFileResolverTest.java +++ /dev/null @@ -1,14 +0,0 @@ -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/pom.xml b/pom.xml index 1c6cd4ae5..a36918109 100755 --- a/pom.xml +++ b/pom.xml @@ -114,6 +114,7 @@ filters sliPluginUtils sliapi + utils ONAP diff --git a/utils/pom.xml b/utils/pom.xml new file mode 100644 index 000000000..93326a9dc --- /dev/null +++ b/utils/pom.xml @@ -0,0 +1,56 @@ + + + + + org.onap.ccsdk.sli.core + ccsdk-sli-core + 0.1.2-SNAPSHOT + + + 4.0.0 + bundle + utils + SLI Core Utilities Package + + + The SLI Core Utilities Package provides common functionality for setting up SLI connectivity. + + + + + com.google.guava + guava + + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + + + + + org.mockito + mockito-core + test + + + junit + junit + test + + + + + + + org.apache.felix + maven-bundle-plugin + ${bundle.plugin.version} + + + + + Inocybe Technologies and Others + + diff --git a/utils/src/main/java/org/onap/ccsdk/sli/core/utils/DefaultFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/DefaultFileResolver.java new file mode 100644 index 000000000..8938aa6e7 --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/DefaultFileResolver.java @@ -0,0 +1,61 @@ +/*- + * ============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.utils; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Optional; + +/** + * Resolves dblib properties files relative to the default file path. In Unix, this is represented by: + * /opt/sdnc/data/properties + */ +public abstract class DefaultFileResolver implements PropertiesFileResolver { + + private final String successMessage; + + private final Path propertyPath; + + public DefaultFileResolver(final String successMessage, final Path propertyPath) { + this.successMessage = successMessage; + this.propertyPath = propertyPath; + } + + /** + * 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 filename) { + final File fileFromDefaultDblibDir = propertyPath.resolve(filename).toFile(); + if (fileFromDefaultDblibDir.exists()) { + return Optional.of(fileFromDefaultDblibDir); + } + return Optional.empty(); + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/utils/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java new file mode 100644 index 000000000..3e438d1a9 --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java @@ -0,0 +1,70 @@ +/*- + * ============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.utils; + +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 abstract class EnvVarFileResolver implements PropertiesFileResolver { + + /** + * Key for environment variable representing the configuration directory + */ + private final String propertyKey; + + private final String successMessage; + + public EnvVarFileResolver(final String successMessage, final String propertyKey) { + this.successMessage = successMessage; + this.propertyKey = propertyKey; + } + + /** + * 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 filename) { + // attempt to resolve the property directory from the corresponding environment variable + final String propDirectoryFromEnvVariable = System.getenv(propertyKey); + final File fileFromEnvVariable; + if (!Strings.isNullOrEmpty(propDirectoryFromEnvVariable)) { + fileFromEnvVariable = Paths.get(propDirectoryFromEnvVariable).resolve(filename).toFile(); + if(fileFromEnvVariable.exists()) { + return Optional.of(fileFromEnvVariable); + } + } + return Optional.empty(); + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/utils/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java new file mode 100644 index 000000000..5cd6c3606 --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java @@ -0,0 +1,74 @@ +/*- + * ============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.utils; + +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.osgi.framework.FrameworkUtil; + +/** + * Resolves dblib properties files relative to the directory identified by the JRE property + * dblib.properties. + */ +public class JREFileResolver implements PropertiesFileResolver { + + /** + * Key for JRE argument representing the configuration directory + */ + private static final String DBLIB_JRE_PROPERTY_KEY = "dblib.properties"; + + private final String successMessage; + private final Class clazz; + + public JREFileResolver(final String successMessage, final Class clazz) { + this.successMessage = successMessage; + this.clazz = clazz; + } + + /** + * 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 filename) { + final URL jreArgumentUrl = FrameworkUtil.getBundle(this.clazz) + .getResource(DBLIB_JRE_PROPERTY_KEY); + try { + if (jreArgumentUrl == null) { + return Optional.empty(); + } + final Path dblibPath = Paths.get(jreArgumentUrl.toURI()); + return Optional.of(dblibPath.resolve(filename).toFile()); + } catch(final URISyntaxException e) { + return Optional.empty(); + } + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/utils/src/main/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolver.java new file mode 100644 index 000000000..0cb754504 --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolver.java @@ -0,0 +1,63 @@ +/*- + * ============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.utils; + +import java.io.File; +import java.net.URL; +import java.util.Optional; + +/** + * Resolves dblib properties files relative to the karaf root directory. + */ +public class KarafRootFileResolver implements PropertiesFileResolver { + + final Object provider; + + private final String successMessage; + + public KarafRootFileResolver(final String successMessage, final Object provider) { + this.successMessage = successMessage; + this.provider = provider; + } + + /** + * 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 filename) { + final URL fromKarafRoot = provider.getClass().getResource(filename); + 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/utils/src/main/java/org/onap/ccsdk/sli/core/utils/PropertiesFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/PropertiesFileResolver.java new file mode 100644 index 000000000..bfb417dca --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/PropertiesFileResolver.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.utils; + +import java.io.File; +import java.util.Optional; + +/** + * Strategy for resolving dblib properties. + */ +public interface PropertiesFileResolver { + + /** + * Resolve dblib properties file. + * + * @param filename the name of the file to look for at the specific location. + * @return An optional File or empty. + */ + Optional resolveFile(final String filename); + + /** + * A success message, used only for logging now. + * + * @return a success message, used only for logging now. + */ + String getSuccessfulResolutionMessage(); +} diff --git a/utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java new file mode 100644 index 000000000..56b4ca1b6 --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java @@ -0,0 +1,17 @@ +package org.onap.ccsdk.sli.core.utils.dblib; + +import java.nio.file.Path; +import java.nio.file.Paths; +import org.onap.ccsdk.sli.core.utils.DefaultFileResolver; + +public class DblibDefaultFileResolver extends DefaultFileResolver { + + /** + * Default path to look for the configuration directory + */ + private static final Path DEFAULT_DBLIB_PROP_DIR = Paths.get("opt", "sdnc", "data", "properties"); + + public DblibDefaultFileResolver(final String successMessage) { + super(successMessage, DEFAULT_DBLIB_PROP_DIR); + } +} diff --git a/utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java new file mode 100644 index 000000000..9eef4cee2 --- /dev/null +++ b/utils/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java @@ -0,0 +1,15 @@ +package org.onap.ccsdk.sli.core.utils.dblib; + +import org.onap.ccsdk.sli.core.utils.EnvVarFileResolver; + +public class DblibEnvVarFileResolver extends EnvVarFileResolver { + + /** + * Key for environment variable representing the configuration directory + */ + private static final String SDNC_CONFIG_DIR_PROP_KEY = "SDNC_CONFIG_DIR"; + + public DblibEnvVarFileResolver(final String successMessage) { + super(successMessage, SDNC_CONFIG_DIR_PROP_KEY); + } +} diff --git a/utils/src/test/java/org/onap/ccsdk/sli/core/utils/JREFileResolverTest.java b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/JREFileResolverTest.java new file mode 100644 index 000000000..e5051d65a --- /dev/null +++ b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/JREFileResolverTest.java @@ -0,0 +1,15 @@ +package org.onap.ccsdk.sli.core.utils; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class JREFileResolverTest { + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new JREFileResolver("success", JREFileResolverTest.class); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/utils/src/test/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolverTest.java b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolverTest.java new file mode 100644 index 000000000..5e407daf6 --- /dev/null +++ b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/KarafRootFileResolverTest.java @@ -0,0 +1,14 @@ +package org.onap.ccsdk.sli.core.utils; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class KarafRootFileResolverTest { + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new KarafRootFileResolver("success", null); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolverTest.java b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolverTest.java new file mode 100644 index 000000000..4b28d449d --- /dev/null +++ b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolverTest.java @@ -0,0 +1,25 @@ +package org.onap.ccsdk.sli.core.utils.dblib; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; + +public class DblibDefaultFileResolverTest { + + @Test + public void resolveFile() throws Exception { + final PropertiesFileResolver resolver = new DblibDefaultFileResolver("success"); + final Optional file = resolver.resolveFile("doesnotexist.cfg"); + assertFalse(file.isPresent()); + } + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new DblibDefaultFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolverTest.java b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolverTest.java new file mode 100644 index 000000000..bae4168d8 --- /dev/null +++ b/utils/src/test/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolverTest.java @@ -0,0 +1,24 @@ +package org.onap.ccsdk.sli.core.utils.dblib; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; + +public class DblibEnvVarFileResolverTest { + @Test + public void resolveFile() throws Exception { + final PropertiesFileResolver resolver = new DblibEnvVarFileResolver("success"); + final Optional file = resolver.resolveFile("doesnotexist.cfg"); + assertFalse(file.isPresent()); + } + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new DblibEnvVarFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file -- cgit 1.2.3-korg From ed6aaf35dabae4070dba5c41798e351c25e8ce4d Mon Sep 17 00:00:00 2001 From: Bharat saraswal Date: Thu, 21 Sep 2017 11:17:57 +0530 Subject: Fix Sonar Issues in sli/core module Few major issues *Remove unused variables To increase code readability *Replace the type specification with the diamond operator *Add the "@Override" annotation above this method signature To increase code readability" Issue-Id: CCSDK-87 Change-Id: I2f0c16a83ab10a0a3e39a2a1d4db3c195ec2bba8 Signed-off-by: Bharat saraswal --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 4 +- .../ccsdk/sli/core/dblib/DBResourceManager.java | 4 +- .../sli/core/dblib/factory/DBConfigFactory.java | 120 +++---- .../sli/core/dblib/pm/SQLExecutionMonitor.java | 383 ++++++++++----------- 4 files changed, 249 insertions(+), 262 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 4d920e6a0..072a6f470 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -123,7 +123,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito connection = null; } - monitor.deregisterReguest(testObject); + monitor.deregisterRequest(testObject); } } @@ -153,7 +153,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito connection = null; } - monitor.deregisterReguest(testObject); + monitor.deregisterRequest(testObject); } } 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 014dab31a..e7a94e64c 100755 --- 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 @@ -884,7 +884,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb CachedDataSource first = snapshot.getFirst(); CachedDataSource last = snapshot.getLast(); - int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); + int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); if(delta < 0) { flipper.set(false); } else if(delta > 0) { @@ -921,7 +921,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb CachedDataSource first = snapshot.getFirst(); CachedDataSource last = snapshot.getLast(); - int delta = first.getMonitor().getPorcessedConnectionsCount() - last.getMonitor().getPorcessedConnectionsCount(); + int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); if(delta < 0) { flipper.set(false); } else if(delta > 0) { diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java index 3caa7767e..c3503576e 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java @@ -24,7 +24,6 @@ package org.onap.ccsdk.sli.core.dblib.factory; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; - import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; @@ -39,61 +38,66 @@ import org.slf4j.LoggerFactory; */ public class DBConfigFactory { - public static DbConfigPool createConfig(Properties resource) { - return getConfigparams(resource); - } - - static DbConfigPool getConfigparams(Properties properties){ - DbConfigPool xmlConfig = new DbConfigPool(properties); - ArrayList propertySets = new ArrayList(); - - if("JDBC".equalsIgnoreCase(xmlConfig.getType())) { - String hosts = properties.getProperty(BaseDBConfiguration.DATABASE_HOSTS); - if(hosts == null || hosts.isEmpty()) { - propertySets.add(properties); - } else { - String[] newhost = hosts.split(","); - for(int i=0; i< newhost.length; i++) { - Properties localset = new Properties(); - localset.putAll(properties); - String url = localset.getProperty(BaseDBConfiguration.DATABASE_URL); - if(url.contains("DBHOST")) - url = url.replace("DBHOST", newhost[i]); - if(url.contains("dbhost")) - url = url.replace("dbhost", newhost[i]); - localset.setProperty(BaseDBConfiguration.DATABASE_URL, url); - localset.setProperty(BaseDBConfiguration.CONNECTION_NAME, newhost[i]); - propertySets.add(localset); - } - } - } else { - propertySets.add(properties); - } - try { - Iterator it = propertySets.iterator(); - while(it.hasNext()) { - BaseDBConfiguration config = parse(it.next()); - xmlConfig.addConfiguration(config); - } - - } catch (Exception e) { - LoggerFactory.getLogger(DBConfigFactory.class).warn("",e); - } - - return xmlConfig; - } - - public static BaseDBConfiguration parse(Properties props) throws Exception { - - String type = props.getProperty(BaseDBConfiguration.DATABASE_TYPE); - - BaseDBConfiguration config = null; - - if("JDBC".equalsIgnoreCase(type)) { - config = new JDBCConfiguration(props); - } - - return config; - - } + public static DbConfigPool createConfig(Properties resource) { + return getConfigparams(resource); + } + + static DbConfigPool getConfigparams(Properties properties) { + DbConfigPool xmlConfig = new DbConfigPool(properties); + ArrayList propertySets = new ArrayList(); + + if ("JDBC".equalsIgnoreCase(xmlConfig.getType())) { + String hosts = properties.getProperty(BaseDBConfiguration.DATABASE_HOSTS); + if (hosts == null || hosts.isEmpty()) { + propertySets.add(properties); + } else { + setPropertyWhenHostsNonEmpty(hosts, properties, propertySets); + } + } else { + propertySets.add(properties); + } + try { + Iterator it = propertySets.iterator(); + while (it.hasNext()) { + BaseDBConfiguration config = parse(it.next()); + xmlConfig.addConfiguration(config); + } + } catch (Exception e) { + LoggerFactory.getLogger(DBConfigFactory.class).warn("", e); + } + + return xmlConfig; + } + + private static void setPropertyWhenHostsNonEmpty(String hosts, Properties properties, ArrayList + propertySets) { + String[] newhost = hosts.split(","); + for (String aNewhost : newhost) { + Properties localSet = new Properties(); + localSet.putAll(properties); + String url = localSet.getProperty(BaseDBConfiguration.DATABASE_URL); + if (url.contains("DBHOST")) { + url = url.replace("DBHOST", aNewhost); + } + if (url.contains("dbhost")) { + url = url.replace("dbhost", aNewhost); + } + localSet.setProperty(BaseDBConfiguration.DATABASE_URL, url); + localSet.setProperty(BaseDBConfiguration.CONNECTION_NAME, aNewhost); + propertySets.add(localSet); + } + } + + public static BaseDBConfiguration parse(Properties props) throws Exception { + + String type = props.getProperty(BaseDBConfiguration.DATABASE_TYPE); + + BaseDBConfiguration config = null; + + if ("JDBC".equalsIgnoreCase(type)) { + config = new JDBCConfiguration(props); + } + + return config; + } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java index bcd4360e4..95172ad7a 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java @@ -23,6 +23,7 @@ package org.onap.ccsdk.sli.core.dblib.pm; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; +import java.util.Objects; import java.util.Observable; import java.util.Observer; import java.util.SortedSet; @@ -30,208 +31,190 @@ import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; - import org.onap.ccsdk.sli.core.dblib.DBResourceObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class SQLExecutionMonitor extends Observable -{ - private static Logger LOGGER = LoggerFactory.getLogger(SQLExecutionMonitor.class); - - final static long MILISECOND = 1000000L; - final static long SECOND = 1000L*MILISECOND; - - private final Timer timer; - // collection - private final SortedSet innerSet; - private SQLExecutionMonitorObserver parent = null; - private final AtomicLong completionCounter; - private boolean activeState = false; - private final long interval; - private final long initialDelay; - private final long EXPECTED_TIME_TO_COMPLETE; - private final long UNPROCESSED_FAILOVER_THRESHOLD; - - private final class MonitoringTask extends TimerTask - { - - public void run() - { - try { - TestObject testObj = new TestObject(); - testObj.setStartTime(testObj.getStartTime() - EXPECTED_TIME_TO_COMPLETE); - - // take a snapshot of the current task list - TestObject[] array = innerSet.toArray(new TestObject[0]); - SortedSet copyCurrent = new TreeSet(Arrays.asList(array)); - // get the list of the tasks that are older than the specified - // interval. - SortedSet unprocessed = copyCurrent.headSet(testObj); - - long succesfulCount = completionCounter.get(); - int unprocessedCount = unprocessed.size(); - - if (!unprocessed.isEmpty() && unprocessedCount > UNPROCESSED_FAILOVER_THRESHOLD && succesfulCount == 0) - { - // switch the Connection Pool to passive - setChanged(); - notifyObservers("Open JDBC requests=" + unprocessedCount+" in "+SQLExecutionMonitor.this.parent.getDbConnectionName()); - } - } catch (Exception exc) { - LOGGER.error("", exc); - } finally { - completionCounter.set(0L); - } - } - } - - public static class TestObject implements Comparable, Serializable - { - - private static final long serialVersionUID = 1L; - private long starttime; - private long randId; - - public TestObject() - { - starttime = System.nanoTime(); - } - - public long getStartTime() - { - return starttime; - } - - public void setStartTime(long newTime) - { - starttime = newTime; - } - - public int compareTo(TestObject o) - { - if( this == o) - return 0; - if(this.starttime > o.getStartTime()) - return 1; - if(this.starttime < o.getStartTime()) - return -1; - - if(this.hashCode() > o.hashCode()) - return 1; - if(this.hashCode() < o.hashCode()) - return -1; - - return 0; - } - - public String toString() - { - return Long.toString(starttime)+"#"+ this.hashCode(); - } - - public boolean equals(Object obj) - { - if (this == obj) - return true; - - return (obj instanceof TestObject - && starttime == ((TestObject) obj).getStartTime() - && hashCode() == ((TestObject) obj).hashCode()); - } - } - - public SQLExecutionMonitor(SQLExecutionMonitorObserver parent) - { - this.parent = parent; - completionCounter = new AtomicLong(0L); - interval = parent.getInterval(); - initialDelay = parent.getInitialDelay(); - this.UNPROCESSED_FAILOVER_THRESHOLD = parent.getUnprocessedFailoverThreshold(); - this.EXPECTED_TIME_TO_COMPLETE = parent.getExpectedCompletionTime()*MILISECOND; - - innerSet = Collections.synchronizedSortedSet(new TreeSet()); - timer = new Timer(); - } - - public void cleanup() - { - timer.cancel(); - } - - // registerRequest - public TestObject registerRequest() - { - if(activeState) - { - TestObject test = new TestObject(); - if(innerSet.add(test)) - return test; - } - return null; - } - - // deregisterSuccessfulReguest - public boolean deregisterReguest(TestObject test) - { - if(test == null) - return false; - // remove from the collection - if(innerSet.remove(test) && activeState) - { - completionCounter.incrementAndGet(); - return true; - } - return false; - } - - public void terminate() { - timer.cancel(); - } - - /** - * @return the parent - */ - public final Object getParent() { - return parent; - } - - public void addObserver(Observer observer) - { - if(observer instanceof DBResourceObserver) - { - DBResourceObserver dbObserver = (DBResourceObserver)observer; - if(dbObserver.isMonitorDbResponse()) - { - if(countObservers() == 0) - { - TimerTask remindTask = new MonitoringTask(); - timer.schedule(remindTask, initialDelay, interval); - activeState = true; - } - } - } - super.addObserver(observer); - } - - public void deleteObserver(Observer observer) - { - super.deleteObserver(observer); - if(observer instanceof DBResourceObserver) - { - DBResourceObserver dbObserver = (DBResourceObserver)observer; - if(dbObserver.isMonitorDbResponse()) - { - if(countObservers() == 0) - { - timer.cancel(); - activeState = false; - } - } - } - } - - public final int getPorcessedConnectionsCount() { - return innerSet.size(); - } +public class SQLExecutionMonitor extends Observable { + + private static final Logger LOGGER = LoggerFactory.getLogger(SQLExecutionMonitor.class); + + static final long MILISECOND = 1000000L; + static final long SECOND = 1000L * MILISECOND; + + private final Timer timer; + // collection + private final SortedSet innerSet; + private SQLExecutionMonitorObserver parent = null; + private final AtomicLong completionCounter; + private boolean activeState = false; + private final long interval; + private final long initialDelay; + private final long EXPECTED_TIME_TO_COMPLETE; + private final long UNPROCESSED_FAILOVER_THRESHOLD; + + private final class MonitoringTask extends TimerTask { + + public void run() { + try { + TestObject testObj = new TestObject(); + testObj.setStartTime(testObj.getStartTime() - EXPECTED_TIME_TO_COMPLETE); + + // take a snapshot of the current task list + TestObject[] array = innerSet.toArray(new TestObject[0]); + SortedSet copyCurrent = new TreeSet<>(Arrays.asList(array)); + // get the list of the tasks that are older than the specified + // interval. + SortedSet unprocessed = copyCurrent.headSet(testObj); + + long successfulCount = completionCounter.get(); + int unprocessedCount = unprocessed.size(); + + if (!unprocessed.isEmpty() && unprocessedCount > UNPROCESSED_FAILOVER_THRESHOLD + && successfulCount == 0) { + // switch the Connection Pool to passive + setChanged(); + notifyObservers("Open JDBC requests=" + unprocessedCount + " in " + SQLExecutionMonitor.this.parent + .getDbConnectionName()); + } + } catch (Exception exc) { + LOGGER.error("", exc); + } finally { + completionCounter.set(0L); + } + } + } + + public static class TestObject implements Comparable, Serializable { + + private static final long serialVersionUID = 1L; + private long startTime; + private long randId; + + public TestObject() { + startTime = System.nanoTime(); + } + + public long getStartTime() { + return startTime; + } + + public void setStartTime(long newTime) { + startTime = newTime; + } + + public int compareTo(TestObject o) { + if (this == o) { + return 0; + } + if (this.startTime > o.getStartTime()) { + return 1; + } + if (this.startTime < o.getStartTime()) { + return -1; + } + + if (this.hashCode() > o.hashCode()) { + return 1; + } + if (this.hashCode() < o.hashCode()) { + return -1; + } + + return 0; + } + + public String toString() { + return Long.toString(startTime) + "#" + this.hashCode(); + } + + public int hashCode() { + return Objects.hash(startTime, randId); + } + + public boolean equals(Object obj) { + return this == obj || (obj instanceof TestObject && startTime == ((TestObject) obj).getStartTime() + && hashCode() == obj.hashCode()); + } + } + + public SQLExecutionMonitor(SQLExecutionMonitorObserver parent) { + this.parent = parent; + completionCounter = new AtomicLong(0L); + interval = parent.getInterval(); + initialDelay = parent.getInitialDelay(); + this.UNPROCESSED_FAILOVER_THRESHOLD = parent.getUnprocessedFailoverThreshold(); + this.EXPECTED_TIME_TO_COMPLETE = parent.getExpectedCompletionTime() * MILISECOND; + + innerSet = Collections.synchronizedSortedSet(new TreeSet()); + timer = new Timer(); + } + + public void cleanup() { + timer.cancel(); + } + + // registerRequest + public TestObject registerRequest() { + if (activeState) { + TestObject test = new TestObject(); + if (innerSet.add(test)) { + return test; + } + } + return null; + } + + // deregisterSuccessfulRequest + public boolean deregisterRequest(TestObject test) { + if (test == null) { + return false; + } + // remove from the collection + if (innerSet.remove(test) && activeState) { + completionCounter.incrementAndGet(); + return true; + } + return false; + } + + public void terminate() { + timer.cancel(); + } + + /** + * @return the parent + */ + public final Object getParent() { + return parent; + } + + @Override + public void addObserver(Observer observer) { + if (observer instanceof DBResourceObserver) { + DBResourceObserver dbObserver = (DBResourceObserver) observer; + if (dbObserver.isMonitorDbResponse() && countObservers() == 0) { + TimerTask remindTask = new MonitoringTask(); + timer.schedule(remindTask, initialDelay, interval); + activeState = true; + } + } + super.addObserver(observer); + } + + @Override + public void deleteObserver(Observer observer) { + super.deleteObserver(observer); + if (observer instanceof DBResourceObserver) { + DBResourceObserver dbObserver = (DBResourceObserver) observer; + if (dbObserver.isMonitorDbResponse() && countObservers() == 0) { + timer.cancel(); + activeState = false; + } + } + } + + public final int getProcessedConnectionsCount() { + return innerSet.size(); + } } -- cgit 1.2.3-korg From 91c7a03545690834a2b7d8b5fac6f677e9c2bc20 Mon Sep 17 00:00:00 2001 From: Bharat saraswal Date: Thu, 21 Sep 2017 16:23:11 +0530 Subject: Resolved sonar issue. Related to exception handling. @Override method Redundant code and resulable parameters Issue-Id:CCSDK-87 Change-Id: I82e2aad453edf5cd647c87322fc75b2a56c37566 Signed-off-by: Bharat saraswal --- .../sli/core/dblib/DBLIBResourceProvider.java | 12 +- .../onap/ccsdk/sli/core/dblib/DBLibConnection.java | 680 ++++++++++----------- 2 files changed, 345 insertions(+), 347 deletions(-) (limited to 'dblib/provider/src') 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 index 8e0b534f0..411f04705 100644 --- 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 @@ -84,8 +84,7 @@ public class DBLIBResourceProvider { // 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); + try(FileInputStream fileInputStream = new FileInputStream(propertiesFile)) { properties = new Properties(); properties.load(fileInputStream); } catch (final IOException e) { @@ -113,9 +112,12 @@ public class DBLIBResourceProvider { * @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; + if(fileOptional.isPresent()) { + final File file = fileOptional.get(); + LOG.info("{} {}", message, file.getPath()); + return file; + } + return null; } /** diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java index 40d1a2382..65d0b9512 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLibConnection.java @@ -36,356 +36,352 @@ import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; - import javax.sql.rowset.CachedRowSet; - import org.apache.tomcat.jdbc.pool.PooledConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DBLibConnection implements Connection { - private static Logger LOGGER = LoggerFactory.getLogger(DBLibConnection.class); - - private final Connection connection; - private final CachedDataSource dataSource; - private boolean locked = false; - private String tableName = null; - - public DBLibConnection(Connection con, CachedDataSource dataSource){ - this.connection = con; - this.dataSource = dataSource; - locked = false; - dataSource.getPoolInfo(true); - } - - public boolean lockTable(String tablename) { - this.tableName = tablename; - locked = dataSource.lockTable(connection, tableName); - return locked; - } - - public void resetInactivityTimer() { - Class iface = PooledConnection.class; - try { - PooledConnection pc = connection.unwrap(iface); - pc.setTimestamp(System.currentTimeMillis()); - } catch (SQLException e) { - LOGGER.warn("Failed resetting timeout timer", e); - } - } - - public boolean unlock() { - dataSource.unlockTable(connection); - locked = false; - return locked; - } - - public boolean writeData(String statement, ArrayList arguments) throws SQLException, Throwable - { - ArrayList newList= new ArrayList<>(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - resetInactivityTimer(); - return dataSource.executeUpdatePreparedStatement(connection, statement, newList, false); - } - - public CachedRowSet getData(String statement, ArrayList arguments) throws SQLException, Throwable - { - ArrayList newList= new ArrayList<>(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - resetInactivityTimer(); - return dataSource.executePreparedStatement(connection, statement, newList, false); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return connection.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return connection.isWrapperFor(iface); - } - - @Override - public Statement createStatement() throws SQLException { - return connection.createStatement(); - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { - return connection.prepareStatement(sql); - } - - @Override - public CallableStatement prepareCall(String sql) throws SQLException { - return connection.prepareCall(sql); - } - - @Override - public String nativeSQL(String sql) throws SQLException { - return connection.nativeSQL(sql); - } - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - connection.setAutoCommit(autoCommit); - } - - @Override - public boolean getAutoCommit() throws SQLException { - return connection.getAutoCommit(); - } - - @Override - public void commit() throws SQLException { - connection.commit(); - } - - @Override - public void rollback() throws SQLException { - connection.rollback(); - } - - @Override - public void close() throws SQLException { - if(this.locked) { - try { - this.unlock(); - } catch(Throwable th) { - LOGGER.error("Failed unlocking",th); - } - } - if(connection != null && !connection.isClosed()) { - connection.close(); - } - dataSource.getPoolInfo(false); - } - - @Override - public boolean isClosed() throws SQLException { - return connection.isClosed(); - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - return connection.getMetaData(); - } - - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - connection.setReadOnly(readOnly); - } - - @Override - public boolean isReadOnly() throws SQLException { - return connection.isReadOnly(); - } - - @Override - public void setCatalog(String catalog) throws SQLException { - connection.setCatalog(catalog); - } - - @Override - public String getCatalog() throws SQLException { - return connection.getCatalog(); - } - - @Override - public void setTransactionIsolation(int level) throws SQLException { - connection.setTransactionIsolation(level); - } - - @Override - public int getTransactionIsolation() throws SQLException { - return connection.getTransactionIsolation(); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return connection.getWarnings(); - } - - @Override - public void clearWarnings() throws SQLException { - connection.clearWarnings(); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return connection.createStatement(resultSetType, resultSetConcurrency); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) - throws SQLException { - return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return connection.prepareCall(sql, resultSetType, resultSetConcurrency); - } - - @Override - public Map> getTypeMap() throws SQLException { - return connection.getTypeMap(); - } - - @Override - public void setTypeMap(Map> map) throws SQLException { - connection.setTypeMap(map); - } - - @Override - public void setHoldability(int holdability) throws SQLException { - connection.setHoldability(holdability); - } - - @Override - public int getHoldability() throws SQLException { - return connection.getHoldability(); - } - - @Override - public Savepoint setSavepoint() throws SQLException { - return connection.setSavepoint(); - } - - @Override - public Savepoint setSavepoint(String name) throws SQLException { - return connection.setSavepoint(name); - } - - @Override - public void rollback(Savepoint savepoint) throws SQLException { - connection.rollback(savepoint); - } - - @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - connection.releaseSavepoint(savepoint); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException { - return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { - return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return connection.prepareStatement(sql, autoGeneratedKeys); - } - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return connection.prepareStatement(sql, columnIndexes); - } - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return connection.prepareStatement(sql, columnNames); - } - - @Override - public Clob createClob() throws SQLException { - return connection.createClob(); - } - - @Override - public Blob createBlob() throws SQLException { - return connection.createBlob(); - } - - @Override - public NClob createNClob() throws SQLException { - return connection.createNClob(); - } - - @Override - public SQLXML createSQLXML() throws SQLException { - return connection.createSQLXML(); - } - - @Override - public boolean isValid(int timeout) throws SQLException { - return connection.isValid(timeout); - } - - @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { - connection.setClientInfo(name, value); - } - - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { - connection.setClientInfo(properties); - } - - @Override - public String getClientInfo(String name) throws SQLException { - return connection.getClientInfo(name); - } - - @Override - public Properties getClientInfo() throws SQLException { - return connection.getClientInfo(); - } - - @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return connection.createArrayOf(typeName, elements); - } - - @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return connection.createStruct(typeName, attributes); - } - - @Override - public void setSchema(String schema) throws SQLException { - connection.setSchema(schema); - } - - @Override - public String getSchema() throws SQLException { - return connection.getSchema(); - } - - @Override - public void abort(Executor executor) throws SQLException { - connection.abort(executor); - } - - @Override - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - connection.setNetworkTimeout(executor, milliseconds); - } - - @Override - public int getNetworkTimeout() throws SQLException { - return connection.getNetworkTimeout(); - } - + private static final Logger LOGGER = LoggerFactory.getLogger(DBLibConnection.class); + + private final Connection connection; + private final CachedDataSource dataSource; + private boolean locked = false; + private String tableName = null; + + public DBLibConnection(Connection con, CachedDataSource dataSource) { + this.connection = con; + this.dataSource = dataSource; + locked = false; + dataSource.getPoolInfo(true); + } + + public boolean lockTable(String tablename) { + this.tableName = tablename; + locked = dataSource.lockTable(connection, tableName); + return locked; + } + + public void resetInactivityTimer() { + Class iface = PooledConnection.class; + try { + PooledConnection pc = connection.unwrap(iface); + pc.setTimestamp(System.currentTimeMillis()); + } catch (SQLException e) { + LOGGER.warn("Failed resetting timeout timer", e); + } + } + + public boolean unlock() { + dataSource.unlockTable(connection); + locked = false; + return false; + } + + public boolean writeData(String statement, List arguments) throws Throwable { + ArrayList newList = new ArrayList<>(); + if (arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + resetInactivityTimer(); + return dataSource.executeUpdatePreparedStatement(connection, statement, newList, false); + } + + public CachedRowSet getData(String statement, List arguments) throws Throwable { + ArrayList newList = new ArrayList<>(); + if (arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + resetInactivityTimer(); + return dataSource.executePreparedStatement(connection, statement, newList, false); + } + + @Override + public T unwrap(Class iFace) throws SQLException { + return connection.unwrap(iFace); + } + + @Override + public boolean isWrapperFor(Class iFace) throws SQLException { + return connection.isWrapperFor(iFace); + } + + @Override + public Statement createStatement() throws SQLException { + return connection.createStatement(); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + return connection.prepareStatement(sql); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + return connection.prepareCall(sql); + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return connection.nativeSQL(sql); + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + connection.setAutoCommit(autoCommit); + } + + @Override + public boolean getAutoCommit() throws SQLException { + return connection.getAutoCommit(); + } + + @Override + public void commit() throws SQLException { + connection.commit(); + } + + @Override + public void rollback() throws SQLException { + connection.rollback(); + } + + @Override + public void close() throws SQLException { + if (this.locked) { + try { + this.unlock(); + } catch (Exception th) { + LOGGER.error("Failed unlocking", th); + } + } + if (connection != null && !connection.isClosed()) { + connection.close(); + } + dataSource.getPoolInfo(false); + } + + @Override + public boolean isClosed() throws SQLException { + return connection.isClosed(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return connection.getMetaData(); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + connection.setReadOnly(readOnly); + } + + @Override + public boolean isReadOnly() throws SQLException { + return connection.isReadOnly(); + } + + @Override + public void setCatalog(String catalog) throws SQLException { + connection.setCatalog(catalog); + } + + @Override + public String getCatalog() throws SQLException { + return connection.getCatalog(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + connection.setTransactionIsolation(level); + } + + @Override + public int getTransactionIsolation() throws SQLException { + return connection.getTransactionIsolation(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return connection.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + connection.clearWarnings(); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return connection.createStatement(resultSetType, resultSetConcurrency); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return connection.prepareCall(sql, resultSetType, resultSetConcurrency); + } + + @Override + public Map> getTypeMap() throws SQLException { + return connection.getTypeMap(); + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + connection.setTypeMap(map); + } + + @Override + public void setHoldability(int holdability) throws SQLException { + connection.setHoldability(holdability); + } + + @Override + public int getHoldability() throws SQLException { + return connection.getHoldability(); + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return connection.setSavepoint(); + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return connection.setSavepoint(name); + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + connection.rollback(savepoint); + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + connection.releaseSavepoint(savepoint); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return connection.prepareStatement(sql, autoGeneratedKeys); + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return connection.prepareStatement(sql, columnIndexes); + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return connection.prepareStatement(sql, columnNames); + } + + @Override + public Clob createClob() throws SQLException { + return connection.createClob(); + } + + @Override + public Blob createBlob() throws SQLException { + return connection.createBlob(); + } + + @Override + public NClob createNClob() throws SQLException { + return connection.createNClob(); + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return connection.createSQLXML(); + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return connection.isValid(timeout); + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + connection.setClientInfo(name, value); + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + connection.setClientInfo(properties); + } + + @Override + public String getClientInfo(String name) throws SQLException { + return connection.getClientInfo(name); + } + + @Override + public Properties getClientInfo() throws SQLException { + return connection.getClientInfo(); + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return connection.createArrayOf(typeName, elements); + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return connection.createStruct(typeName, attributes); + } + + @Override + public void setSchema(String schema) throws SQLException { + connection.setSchema(schema); + } + + @Override + public String getSchema() throws SQLException { + return connection.getSchema(); + } + + @Override + public void abort(Executor executor) throws SQLException { + connection.abort(executor); + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + connection.setNetworkTimeout(executor, milliseconds); + } + + @Override + public int getNetworkTimeout() throws SQLException { + return connection.getNetworkTimeout(); + } } -- cgit 1.2.3-korg From 6d585c2900751d0269772de6ca21476c51fcc942 Mon Sep 17 00:00:00 2001 From: Bharat saraswal Date: Thu, 21 Sep 2017 15:09:52 +0530 Subject: Sql query blocker issue fixed. Rdundant code and complextity of methods reduced. @override annotaiton added. Exception handling and logging impoved. Issue-ID:CCSDK-87 Change-Id: I3907be73a2f6ccdfadeaed79c87705ae7afdb4ab Signed-off-by: Bharat saraswal --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 1087 +++++++++----------- .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 269 +++-- 2 files changed, 627 insertions(+), 729 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 072a6f470..356f5ee8b 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -20,17 +20,6 @@ package org.onap.ccsdk.sli.core.dblib; -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor.TestObject; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; -import javax.sql.rowset.RowSetProvider; import java.io.Closeable; import java.io.IOException; import java.io.PrintWriter; @@ -45,8 +34,18 @@ import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Observer; - +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetProvider; +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor.TestObject; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @version $Revision: 1.13 $ @@ -56,582 +55,502 @@ import java.util.Observer; * Rich Tabedzki */ -public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver -{ - private static Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); - - protected static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; - - protected long CONN_REQ_TIMEOUT = 30L; - protected long DATA_REQ_TIMEOUT = 100L; - - private final SQLExecutionMonitor monitor; - protected DataSource ds = null; - protected String connectionName = null; - protected boolean initialized = false; - - private long interval = 1000; - private long initialDelay = 5000; - private long expectedCompletionTime = 50L; - private boolean canTakeOffLine = true; - private long unprocessedFailoverThreshold = 3L; - - private long nextErrorReportTime = 0L; - - private String globalHostName = null; - - - public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException - { - configure(jdbcElem); - monitor = new SQLExecutionMonitor(this); - } - - protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; - /* (non-Javadoc) - * @see javax.sql.DataSource#getConnection() - */ - @Override - public Connection getConnection() throws SQLException - { - return ds.getConnection(); - } - - public CachedRowSet getData(String statement, ArrayList arguments) - throws SQLException, Throwable - { - TestObject testObject = null; - testObject = monitor.registerRequest(); - - Connection connection = null; - try { - connection = this.getConnection(); - if(connection == null ) { - throw new SQLException("Connection invalid"); - } - if(LOGGER.isDebugEnabled()) - LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); - return executePreparedStatement(connection, statement, arguments, true); - } finally { - try { - if(connection != null && !connection.isClosed()) { - connection.close(); - } - } catch(Throwable exc) { - // the exception not monitored - } finally { - connection = null; - } - - monitor.deregisterRequest(testObject); - } - } - - public boolean writeData(String statement, ArrayList arguments) - throws SQLException, Throwable - { - TestObject testObject = null; - testObject = monitor.registerRequest(); - - Connection connection = null; - try { - connection = this.getConnection(); - if(connection == null ) { - throw new SQLException("Connection invalid"); - } - if(LOGGER.isDebugEnabled()) - LOGGER.debug("Obtained connection <" + connectionName + ">: "+connection.toString()); - return executeUpdatePreparedStatement(connection, statement, arguments, true); - } finally { - try { - if(connection != null && !connection.isClosed()) { - connection.close(); - } - } catch(Throwable exc) { - // the exception not monitored - } finally { - connection = null; - } - - monitor.deregisterRequest(testObject); - } - } - - CachedRowSet executePreparedStatement(Connection conn, String statement, - ArrayList arguments, boolean close) throws SQLException, Throwable - { - long time = System.currentTimeMillis(); - - CachedRowSet data = null; - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL Statement: "+ statement); - if(arguments != null && !arguments.isEmpty()) { - LOGGER.debug("Argunments: "+ Arrays.toString(arguments.toArray())); - } - } - - ResultSet rs = null; - PreparedStatement ps = null; - try { - data = RowSetProvider.newFactory().createCachedRowSet(); - ps = conn.prepareStatement(statement); - if(arguments != null) - { - for(int i = 0, max = arguments.size(); i < max; i++){ - ps.setObject(i+1, arguments.get(i)); - } - } - rs = ps.executeQuery(); - data.populate(rs); - // Point the rowset Cursor to the start - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); } - } catch(SQLException exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - try { conn.rollback(); } catch(Throwable thr){} - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; - } catch(Throwable exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; // new SQLException(exc); - } finally { - - try { - if(rs != null){ - rs.close(); - rs = null; - } - } catch(Exception exc){ - - } - try { - if(conn != null && close){ - conn.close(); - conn = null; - } - } catch(Exception exc){ - - } - try { - if (ps != null){ - ps.close(); - } - } catch (Exception exc){ - - } - } - - return data; - } - - boolean executeUpdatePreparedStatement(Connection conn, String statement, ArrayList arguments, boolean close) throws SQLException, Throwable { - long time = System.currentTimeMillis(); - - CachedRowSet data = null; - - int rs = -1; - try { - data = RowSetProvider.newFactory().createCachedRowSet(); - PreparedStatement ps = conn.prepareStatement(statement); - if(arguments != null) - { - for(int i = 0, max = arguments.size(); i < max; i++){ - if(arguments.get(i) instanceof Blob) { - ps.setBlob(i+1, (Blob)arguments.get(i)); - } else if(arguments.get(i) instanceof Timestamp) { - ps.setTimestamp(i+1, (Timestamp)arguments.get(i)); - } else if(arguments.get(i) instanceof Integer) { - ps.setInt(i+1, (Integer)arguments.get(i)); - } else if(arguments.get(i) instanceof Long) { - ps.setLong(i+1, (Long)arguments.get(i)); - } else if(arguments.get(i) instanceof Date) { - ps.setDate(i+1, (Date)arguments.get(i)); - } else { - ps.setObject(i+1, arguments.get(i)); - } - } - } - rs = ps.executeUpdate(); - // Point the rowset Cursor to the start - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL SUCCESS. rows returned: " + data.size()+ ", time(ms): "+ (System.currentTimeMillis() - time)); - } - } catch(SQLException exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - try { conn.rollback(); } catch(Throwable thr){} - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; - } catch(Throwable exc){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL FAILURE. time(ms): "+ (System.currentTimeMillis() - time)); - } - if(arguments != null && !arguments.isEmpty()) { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with arguments: "+arguments.toString(), exc); - } else { - LOGGER.error("<"+connectionName+"> Failed to execute: "+ statement + " with no arguments. ", exc); - } - throw exc; // new SQLException(exc); - } finally { - try { - if(conn != null && close){ - conn.close(); - conn = null; - } - } catch(Exception exc){ - - } - } - - return true; - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ - @Override - public Connection getConnection(String username, String password) - throws SQLException - { - return ds.getConnection(username, password); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getLogWriter() - */ - @Override - public PrintWriter getLogWriter() throws SQLException - { - return ds.getLogWriter(); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getLoginTimeout() - */ - @Override - public int getLoginTimeout() throws SQLException - { - return ds.getLoginTimeout(); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) - */ - @Override - public void setLogWriter(PrintWriter out) throws SQLException - { - ds.setLogWriter(out); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#setLoginTimeout(int) - */ - @Override - public void setLoginTimeout(int seconds) throws SQLException - { - ds.setLoginTimeout(seconds); - } - - - @Override - public final String getDbConnectionName(){ - return connectionName; - } - - protected final void setDbConnectionName(String name) { - this.connectionName = name; - } - - public void cleanUp(){ - if(ds != null && ds instanceof Closeable) { - try { - ((Closeable)ds).close(); - } catch (IOException e) { - LOGGER.warn(e.getMessage()); - } - } - ds = null; - monitor.deleteObservers(); - monitor.cleanup(); - } - - public boolean isInitialized() { - return initialized; - } - - protected boolean testConnection(){ - return testConnection(false); - } - - protected boolean testConnection(boolean error_level){ - Connection conn = null; - ResultSet rs = null; - Statement stmt = null; - try - { - Boolean readOnly = null; - String hostname = null; - conn = this.getConnection(); - stmt = conn.createStatement(); - rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); //("SELECT 1 FROM DUAL"); //"select BANNER from SYS.V_$VERSION" - while(rs.next()) - { - readOnly = rs.getBoolean(1); - hostname = rs.getString(2); - - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("SQL DataSource <"+getDbConnectionName() + "> connected to " + hostname + ", read-only is " + readOnly + ", tested successfully "); - } - } - - } catch (Throwable exc) { - if(error_level) { - LOGGER.error("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } else { - LOGGER.info("SQL DataSource <" + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } - return false; - } finally { - if(rs != null) { - try { - rs.close(); - rs = null; - } catch (SQLException e) { - } - } - if(stmt != null) { - try { - stmt.close(); - stmt = null; - } catch (SQLException e) { - } - } - if(conn !=null){ - try { - conn.close(); - conn = null; - } catch (SQLException e) { - } - } - } - return true; - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - @SuppressWarnings("deprecation") - public void setConnectionCachingEnabled(boolean state) - { +public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver { + + private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); + + private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; + private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; + private static final String WITH_ARGUMENTS = " with arguments: "; + private static final String WITH_NO_ARGUMENTS = " with no arguments. "; + private static final String SQL_DATA_SOURCE = "SQL DataSource <"; + + + protected long connReqTimeout = 30L; + protected long dataReqTimeout = 100L; + + private final SQLExecutionMonitor monitor; + protected DataSource ds = null; + protected String connectionName = null; + protected boolean initialized = false; + + private long interval = 1000; + private long initialDelay = 5000; + private long expectedCompletionTime = 50L; + private boolean canTakeOffLine = true; + private long unprocessedFailoverThreshold = 3L; + + private long nextErrorReportTime = 0L; + + private String globalHostName = null; + + + public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { + configure(jdbcElem); + monitor = new SQLExecutionMonitor(this); + } + + protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + + /* (non-Javadoc) + * @see javax.sql.DataSource#getConnection() + */ + @Override + public Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + public CachedRowSet getData(String statement, List arguments) + throws SQLException { + TestObject testObject = monitor.registerRequest(); + + try (Connection connection = this.getConnection()) { + if (connection == null) { + throw new SQLException("Connection invalid"); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Obtained connection <" + connectionName + ">: " + connection.toString()); + } + return executePreparedStatement(connection, statement, arguments, true); + } finally { + monitor.deregisterRequest(testObject); + } + } + + public boolean writeData(String statement, List arguments) + throws SQLException { + TestObject testObject = monitor.registerRequest(); + + try (Connection connection = this.getConnection()) { + if (connection == null) { + throw new SQLException("Connection invalid"); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Obtained connection <" + connectionName + ">: " + connection.toString()); + } + return executeUpdatePreparedStatement(connection, statement, arguments, true); + } finally { + monitor.deregisterRequest(testObject); + } + } + + CachedRowSet executePreparedStatement(Connection conn, String statement, + List arguments, boolean close) throws SQLException { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL Statement: " + statement); + if (arguments != null && !arguments.isEmpty()) { + LOGGER.debug("Argunments: " + Arrays.toString(arguments.toArray())); + } + } + + ResultSet rs = null; + try (PreparedStatement ps = conn.prepareStatement(statement)) { + data = RowSetProvider.newFactory().createCachedRowSet(); + if (arguments != null) { + for (int i = 0, max = arguments.size(); i < max; i++) { + ps.setObject(i + 1, arguments.get(i)); + } + } + rs = ps.executeQuery(); + data.populate(rs); + // Point the rowset Cursor to the start + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL SUCCESS. rows returned: " + data.size() + ", time(ms): " + (System.currentTimeMillis() + - time)); + } + } catch (SQLException exc) { + handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); + } finally { + handleFinallyBlockForExecutePreparedStatement(rs, conn, close); + } + + return data; + } + + private void handleSqlExceptionForExecuteStatement(Connection conn, String statement, + List arguments, SQLException exc, long time) throws SQLException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(SQL_FAILURE + (System.currentTimeMillis() - time)); + } + try { + conn.rollback(); + } catch (Exception thr) { + LOGGER.error(thr.getLocalizedMessage(), thr); + } + if (arguments != null && !arguments.isEmpty()) { + LOGGER.error(String.format("<%s%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_ARGUMENTS, + arguments.toString()), exc); + } else { + LOGGER.error(String.format("<%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_NO_ARGUMENTS), + exc); + } + throw exc; + } + + private void handleFinallyBlockForExecutePreparedStatement(ResultSet rs, Connection conn, boolean close) { + try { + if (rs != null) { + rs.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + try { + if (conn != null && close) { + conn.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + } + + boolean executeUpdatePreparedStatement(Connection conn, String statement, List arguments, + boolean close) throws SQLException { + long time = System.currentTimeMillis(); + + CachedRowSet data; + + try (PreparedStatement ps = conn.prepareStatement(statement)) { + data = RowSetProvider.newFactory().createCachedRowSet(); + if (arguments != null) { + prepareStatementForExecuteUpdate(arguments, ps); + } + ps.executeUpdate(); + // Point the rowset Cursor to the start + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL SUCCESS. rows returned: " + data.size() + ", time(ms): " + (System.currentTimeMillis() + - time)); + } + ps.close(); + } catch (SQLException exc) { + handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); + } finally { + try { + if (close) { + conn.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + } + + return true; + } + + private void prepareStatementForExecuteUpdate(List arguments, PreparedStatement ps) + throws SQLException { + for (int i = 0, max = arguments.size(); i < max; i++) { + Object value = arguments.get(i); + if (value instanceof Blob) { + ps.setBlob(i + 1, (Blob) value); + } else if (value instanceof Timestamp) { + ps.setTimestamp(i + 1, (Timestamp) value); + } else if (value instanceof Integer) { + ps.setInt(i + 1, (Integer) value); + } else if (value instanceof Long) { + ps.setLong(i + 1, (Long) value); + } else if (value instanceof Date) { + ps.setDate(i + 1, (Date) value); + } else { + ps.setObject(i + 1, value); + } + } + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) + */ + @Override + public Connection getConnection(String username, String password) + throws SQLException { + return ds.getConnection(username, password); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getLogWriter() + */ + @Override + public PrintWriter getLogWriter() throws SQLException { + return ds.getLogWriter(); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#getLoginTimeout() + */ + @Override + public int getLoginTimeout() throws SQLException { + return ds.getLoginTimeout(); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) + */ + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + ds.setLogWriter(out); + } + + /* (non-Javadoc) + * @see javax.sql.DataSource#setLoginTimeout(int) + */ + @Override + public void setLoginTimeout(int seconds) throws SQLException { + ds.setLoginTimeout(seconds); + } + + + @Override + public final String getDbConnectionName() { + return connectionName; + } + + protected final void setDbConnectionName(String name) { + this.connectionName = name; + } + + public void cleanUp() { + if (ds != null && ds instanceof Closeable) { + try { + ((Closeable) ds).close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage()); + } + } + ds = null; + monitor.deleteObservers(); + monitor.cleanup(); + } + + public boolean isInitialized() { + return initialized; + } + + protected boolean testConnection() { + return testConnection(false); + } + + protected boolean testConnection(boolean errorLevel) { + ResultSet rs = null; + try (Connection conn = this.getConnection(); Statement stmt = conn.createStatement()) { + Boolean readOnly; + String hostname; + rs = stmt.executeQuery( + "SELECT @@global.read_only, @@global.hostname"); //("SELECT 1 FROM DUAL"); //"select BANNER from SYS.V_$VERSION" + while (rs.next()) { + readOnly = rs.getBoolean(1); + hostname = rs.getString(2); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + SQL_DATA_SOURCE + getDbConnectionName() + "> connected to " + hostname + ", read-only is " + + readOnly + ", tested successfully "); + } + } + } catch (Exception exc) { + if (errorLevel) { + LOGGER.error( + SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } else { + LOGGER.info( + SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } + return false; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + LOGGER.error(e.getLocalizedMessage(), e); + } + } + } + return true; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @SuppressWarnings("deprecation") + public void setConnectionCachingEnabled(boolean state) { // if(ds != null && ds instanceof OracleDataSource) // try { // ((OracleDataSource)ds).setConnectionCachingEnabled(true); // } catch (SQLException exc) { // LOGGER.warn("", exc); // } - } - - public void addObserver(Observer observer) { - monitor.addObserver(observer); - } - - public void deleteObserver(Observer observer) { - monitor.deleteObserver(observer); - } - - @Override - public long getInterval() { - return interval; - } - - @Override - public long getInitialDelay() { - return initialDelay; - } - - @Override - public void setInterval(long value) { - interval = value; - } - - @Override - public void setInitialDelay(long value) { - initialDelay = value; - } - - @Override - public long getExpectedCompletionTime() { - return expectedCompletionTime; - } - - @Override - public void setExpectedCompletionTime(long value) { - expectedCompletionTime = value; - } - - @Override - public long getUnprocessedFailoverThreshold() { - return unprocessedFailoverThreshold; - } - - @Override - public void setUnprocessedFailoverThreshold(long value) { - this.unprocessedFailoverThreshold = value; - } - - public boolean canTakeOffLine() { - return canTakeOffLine; - } - - public void blockImmediateOffLine() { - canTakeOffLine = false; - final Thread offLineTimer = new Thread() - { - @Override - public void run(){ - try { - Thread.sleep(30000L); - }catch(Throwable exc){ - - }finally{ - canTakeOffLine = true; - } - } - }; - offLineTimer.setDaemon(true); - offLineTimer.start(); - } - - /** - * @return the monitor - */ - final SQLExecutionMonitor getMonitor() { - return monitor; - } - - protected boolean isSlave() throws PoolExhaustedException { - CachedRowSet rs = null; - boolean isSlave = true; - String hostname = "UNDETERMINED"; - try { - boolean localSlave = true; - rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList()); - while(rs.next()) { - localSlave = rs.getBoolean(1); - hostname = rs.getString(2); - } - isSlave = localSlave; - } catch(PoolExhaustedException peexc){ - throw peexc; - } catch (SQLException e) { - LOGGER.error("", e); - isSlave = true; - } catch (Throwable e) { - LOGGER.error("", e); - isSlave = true; - } - if(isSlave){ - LOGGER.debug("SQL SLAVE : "+connectionName + " on server " + hostname); - } else { - LOGGER.debug("SQL MASTER : "+connectionName + " on server " + hostname); - } - return isSlave; - } - - public boolean isFabric() { - return false; - } - - protected boolean lockTable(Connection conn, String tableName) { - boolean retValue = false; - Statement lock = null; - try { - if(tableName != null) { - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); - if("SVC_LOGIC".equals(tableName)) { - Exception e = new Exception(); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - LOGGER.debug(sw.toString()); - } - } - lock = conn.createStatement(); - lock.execute("LOCK TABLES " + tableName + " WRITE"); - retValue = true; - } - } catch(Exception exc){ - LOGGER.error("", exc); - retValue = false; - } finally { - try { - if (lock != null) { - lock.close(); - } - } catch(Exception exc) { - - } - } - return retValue; - } - - protected boolean unlockTable(Connection conn) { - boolean retValue = false; - try (Statement lock = conn.createStatement()){ - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); - } - retValue = lock.execute("UNLOCK TABLES"); - } catch(Exception exc){ - LOGGER.error("", exc); - retValue = false; - } - return retValue; - } - - public void getPoolInfo(boolean allocation) { - - } - - public long getNextErrorReportTime() { - return nextErrorReportTime; - } - - public void setNextErrorReportTime(long nextTime) { - this.nextErrorReportTime = nextTime; - } - - public void setGlobalHostName(String hostname) { - this.globalHostName = hostname; - } - - public String getGlobalHostName() { - return globalHostName; - } + } + + public void addObserver(Observer observer) { + monitor.addObserver(observer); + } + + public void deleteObserver(Observer observer) { + monitor.deleteObserver(observer); + } + + @Override + public long getInterval() { + return interval; + } + + @Override + public long getInitialDelay() { + return initialDelay; + } + + @Override + public void setInterval(long value) { + interval = value; + } + + @Override + public void setInitialDelay(long value) { + initialDelay = value; + } + + @Override + public long getExpectedCompletionTime() { + return expectedCompletionTime; + } + + @Override + public void setExpectedCompletionTime(long value) { + expectedCompletionTime = value; + } + + @Override + public long getUnprocessedFailoverThreshold() { + return unprocessedFailoverThreshold; + } + + @Override + public void setUnprocessedFailoverThreshold(long value) { + this.unprocessedFailoverThreshold = value; + } + + public boolean canTakeOffLine() { + return canTakeOffLine; + } + + public void blockImmediateOffLine() { + canTakeOffLine = false; + final Thread offLineTimer = new Thread(() -> { + try { + Thread.sleep(30000L); + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } finally { + canTakeOffLine = true; + } + }); + offLineTimer.setDaemon(true); + offLineTimer.start(); + } + + /** + * @return the monitor + */ + final SQLExecutionMonitor getMonitor() { + return monitor; + } + + protected boolean isSlave() throws PoolExhaustedException { + CachedRowSet rs = null; + boolean isSlave = true; + String hostname = "UNDETERMINED"; + try { + boolean localSlave = true; + rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList()); + while (rs.next()) { + localSlave = rs.getBoolean(1); + hostname = rs.getString(2); + } + isSlave = localSlave; + } catch (PoolExhaustedException peexc) { + throw peexc; + } catch (Exception e) { + LOGGER.error("", e); + isSlave = true; + } + if (isSlave) { + LOGGER.debug(String.format("SQL SLAVE : %s on server %s", connectionName, hostname)); + } else { + LOGGER.debug(String.format("SQL MASTER : %s on server %s", connectionName, hostname)); + } + return isSlave; + } + + public boolean isFabric() { + return false; + } + + protected boolean lockTable(Connection conn, String tableName) { + boolean retValue = false; + String query = "LOCK TABLES " + tableName + " WRITE"; + try (Statement preStmt = conn.createStatement(); Statement lock = conn.prepareStatement(query); + ResultSet rs = preStmt.executeQuery("GETDATE()")) { + if (tableName != null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); + if ("SVC_LOGIC".equals(tableName)) { + Exception e = new Exception(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + LOGGER.debug(sw.toString()); + } + } + lock.execute(query); + retValue = true; + } + } catch (Exception exc) { + LOGGER.error("", exc); + retValue = false; + } + return retValue; + } + + protected boolean unlockTable(Connection conn) { + boolean retValue; + try (Statement lock = conn.createStatement()) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); + } + retValue = lock.execute("UNLOCK TABLES"); + } catch (Exception exc) { + LOGGER.error("", exc); + retValue = false; + } + return retValue; + } + + public void getPoolInfo(boolean allocation) { + + } + + public long getNextErrorReportTime() { + return nextErrorReportTime; + } + + public void setNextErrorReportTime(long nextTime) { + this.nextErrorReportTime = nextTime; + } + + public void setGlobalHostName(String hostname) { + this.globalHostName = hostname; + } + + public String getGlobalHostName() { + return globalHostName; + } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java index 3ec4f2edf..ca16834c4 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -20,11 +20,7 @@ package org.onap.ccsdk.sli.core.dblib.jdbc; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; import java.sql.SQLFeatureNotSupportedException; - import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; import org.onap.ccsdk.sli.core.dblib.CachedDataSource; @@ -34,66 +30,61 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class JdbcDBCachedDataSource extends CachedDataSource -{ - private String dbDriver; - private String dbUserId; - private String dbPasswd; - private String dbUrl; - - private int minLimit; - private int maxLimit; - private int initialLimit; - - private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; - - private static Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class); - - /** - * @param jdbcElem - */ - public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem) - { - super(jdbcElem); - } - - @Override - protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException - { - BaseDBConfiguration jdbcConfig = (BaseDBConfiguration)xmlElem; - if(jdbcConfig.getConnTimeout() > 0){ - this.CONN_REQ_TIMEOUT = jdbcConfig.getConnTimeout(); - } - if(jdbcConfig.getRequestTimeout() > 0){ - this.DATA_REQ_TIMEOUT = jdbcConfig.getRequestTimeout(); - } - - // set connection pool name - String dbConnectionName = jdbcConfig.getDbConnectionName(); - super.setDbConnectionName(dbConnectionName); - // Configure the JDBC connection - dbUserId = jdbcConfig.getDbUserId(); - if (dbUserId == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); +public class JdbcDBCachedDataSource extends CachedDataSource { + + private String dbDriver; + private String dbUserId; + private String dbPasswd; + private String dbUrl; + + private int minLimit; + private int maxLimit; + private int initialLimit; + + private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; + + private static final Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class); + + /** + * @param jdbcElem + */ + public JdbcDBCachedDataSource(BaseDBConfiguration jdbcElem) { + super(jdbcElem); + } + + @Override + protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException { + BaseDBConfiguration jdbcConfig = xmlElem; + if (jdbcConfig.getConnTimeout() > 0) { + this.connReqTimeout = jdbcConfig.getConnTimeout(); + } + if (jdbcConfig.getRequestTimeout() > 0) { + this.dataReqTimeout = jdbcConfig.getRequestTimeout(); + } + + // set connection pool name + String dbConnectionName = jdbcConfig.getDbConnectionName(); + super.setDbConnectionName(dbConnectionName); + // Configure the JDBC connection + dbUserId = jdbcConfig.getDbUserId(); + if (dbUserId == null) { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUserId attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); throw new DBConfigException(errorMsg); } dbPasswd = jdbcConfig.getDbPasswd(); - if (dbPasswd == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); + if (dbPasswd == null) { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbPasswd attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); throw new DBConfigException(errorMsg); } dbDriver = jdbcConfig.getDriverName(); - if (dbDriver == null) - { - String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); - throw new DBConfigException(errorMsg); + if (dbDriver == null) { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbDriver attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + throw new DBConfigException(errorMsg); } minLimit = jdbcConfig.getDbMinLimit(); @@ -103,14 +94,14 @@ public class JdbcDBCachedDataSource extends CachedDataSource // LOGGER.error(AS_CONF_ERROR + errorMsg); // throw new DBConfigException(errorMsg); // } - maxLimit = jdbcConfig.getDbMaxLimit(); + maxLimit = jdbcConfig.getDbMaxLimit(); // if (maxLimit == null) // { // String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; // LOGGER.error(AS_CONF_ERROR + errorMsg); // throw new DBConfigException(errorMsg); // } - initialLimit = jdbcConfig.getDbInitialLimit(); + initialLimit = jdbcConfig.getDbInitialLimit(); // if (initialLimit == null) // { // String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; @@ -119,98 +110,86 @@ public class JdbcDBCachedDataSource extends CachedDataSource // } dbUrl = jdbcConfig.getDbUrl(); - if(dbUrl == null){ - String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; - LOGGER.error(AS_CONF_ERROR + errorMsg); + if (dbUrl == null) { + String errorMsg = "Invalid XML contents: JDBCConnection missing dbUrl attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); throw new DBConfigException(errorMsg); } - try { - Class clazz = Class.forName(dbDriver) ; - - PoolProperties p = new PoolProperties(); - p.setDriverClassName(dbDriver); - p.setUrl(dbUrl); - p.setUsername(dbUserId); - p.setPassword(dbPasswd); - p.setJmxEnabled(true); - p.setTestWhileIdle(false); - p.setTestOnBorrow(true); - p.setValidationQuery("SELECT 1"); - p.setTestOnReturn(false); - p.setValidationInterval(30000); - p.setTimeBetweenEvictionRunsMillis(30000); - p.setInitialSize(initialLimit); - p.setMaxActive(maxLimit); - p.setMaxIdle(maxLimit); - p.setMaxWait(10000); - p.setRemoveAbandonedTimeout(60); - p.setMinEvictableIdleTimeMillis(30000); - p.setMinIdle(minLimit); - p.setLogAbandoned(true); - p.setRemoveAbandoned(true); - p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" - + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); - - DataSource dataSource = new DataSource(p); - - synchronized(this) - { - this.ds = dataSource; - Connection con = null; - PreparedStatement st = null; - ResultSet rs = null; - - initialized = true; - LOGGER.info("JdbcDBCachedDataSource <"+dbConnectionName+"> configured successfully. Using URL: "+dbUrl); - } - } catch (Exception exc) { - initialized = false; - StringBuffer sb = new StringBuffer(); - sb.append("Failed to initialize MySQLCachedDataSource <"); - sb.append(dbConnectionName).append(">. Reason: "); - sb.append(exc.getMessage()); - LOGGER.error("AS_CONF_ERROR: " + sb.toString()); + try { + + PoolProperties p = new PoolProperties(); + p.setDriverClassName(dbDriver); + p.setUrl(dbUrl); + p.setUsername(dbUserId); + p.setPassword(dbPasswd); + p.setJmxEnabled(true); + p.setTestWhileIdle(false); + p.setTestOnBorrow(true); + p.setValidationQuery("SELECT 1"); + p.setTestOnReturn(false); + p.setValidationInterval(30000); + p.setTimeBetweenEvictionRunsMillis(30000); + p.setInitialSize(initialLimit); + p.setMaxActive(maxLimit); + p.setMaxIdle(maxLimit); + p.setMaxWait(10000); + p.setRemoveAbandonedTimeout(60); + p.setMinEvictableIdleTimeMillis(30000); + p.setMinIdle(minLimit); + p.setLogAbandoned(true); + p.setRemoveAbandoned(true); + p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); + + DataSource dataSource = new DataSource(p); + + synchronized (this) { + this.ds = dataSource; + + initialized = true; + LOGGER.info(String.format("JdbcDBCachedDataSource <%s> configured successfully. Using URL: %s", + dbConnectionName, dbUrl)); + } + } catch (Exception exc) { + initialized = false; + LOGGER.error(String.format("AS_CONF_ERROR: Failed to initialize MySQLCachedDataSource <%s>. Reason: %s", + dbConnectionName, exc.getMessage())); // throw new DBConfigException(e.getMessage()); - } + } } - public final String getDbUrl() - { - return dbUrl; - } - - public final String getDbUserId() - { - return dbUserId; - } - - public final String getDbPasswd() - { - return dbPasswd; - } - - public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { - return new JdbcDBCachedDataSource(config); - } - - public String toString(){ - return getDbConnectionName(); - } - - public java.util.logging.Logger getParentLogger() - throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub - return null; - } - - public void cleanUp(){ - DataSource dataSource = (DataSource)ds; - dataSource.getPool().purge(); - int active = dataSource.getActive(); - int size = dataSource.getSize(); - dataSource.close(true); - super.cleanUp(); - } + public final String getDbUrl() { + return dbUrl; + } + + public final String getDbUserId() { + return dbUserId; + } + + public final String getDbPasswd() { + return dbPasswd; + } + + public static JdbcDBCachedDataSource createInstance(BaseDBConfiguration config) /*throws Exception*/ { + return new JdbcDBCachedDataSource(config); + } + + public String toString() { + return getDbConnectionName(); + } + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void cleanUp() { + DataSource dataSource = (DataSource) ds; + dataSource.getPool().purge(); + dataSource.close(true); + super.cleanUp(); + } } -- cgit 1.2.3-korg From b428ca0261f0333757d114680fb1efa0f424a781 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Fri, 22 Sep 2017 16:40:30 +0530 Subject: Add "@Override" annotation Added @Override annotation before method signature *This is to improve the readability of code Issue-Id: CCSDK-87 Change-Id: I979eb03ec81b9868012e5c16f48b595c8e53e26e Signed-off-by: surya-huawei --- .../main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java index 95172ad7a..b6664f3c3 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/SQLExecutionMonitor.java @@ -55,6 +55,7 @@ public class SQLExecutionMonitor extends Observable { private final class MonitoringTask extends TimerTask { + @Override public void run() { try { TestObject testObj = new TestObject(); @@ -103,6 +104,7 @@ public class SQLExecutionMonitor extends Observable { startTime = newTime; } + @Override public int compareTo(TestObject o) { if (this == o) { return 0; -- cgit 1.2.3-korg From 025e0ac819afe9ab5e05c7c75420814ff881ad03 Mon Sep 17 00:00:00 2001 From: "ramu.n" Date: Sat, 23 Sep 2017 22:28:03 +0530 Subject: Some minor refinements in CCSDK SLI Core module Fix few Critical/Major sonar issues in CCSDK SLI Core module * Define and throw a dedicated exception instead of using a generic one * Either log or rethrow the exception * Change "try" to a try-with-resources * Remove useless assignment to local variable * Use built-in logger method string formatting instead of string concatination * code indentation Change-Id: I83dc1fb931b8021118e259c722f7dfbc1621dce8 Issue-Id: CCSDK-67 Signed-off-by: Ramu N --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 31 +++++++++++----------- 1 file changed, 15 insertions(+), 16 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 356f5ee8b..d2331786e 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -7,9 +7,9 @@ * 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. @@ -33,7 +33,6 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Observer; import javax.sql.DataSource; @@ -109,7 +108,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito throw new SQLException("Connection invalid"); } if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Obtained connection <" + connectionName + ">: " + connection.toString()); + LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); } return executePreparedStatement(connection, statement, arguments, true); } finally { @@ -126,7 +125,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito throw new SQLException("Connection invalid"); } if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Obtained connection <" + connectionName + ">: " + connection.toString()); + LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); } return executeUpdatePreparedStatement(connection, statement, arguments, true); } finally { @@ -140,9 +139,9 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito CachedRowSet data = null; if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL Statement: " + statement); + LOGGER.debug("SQL Statement: {}", statement); if (arguments != null && !arguments.isEmpty()) { - LOGGER.debug("Argunments: " + Arrays.toString(arguments.toArray())); + LOGGER.debug("Argunments: {}", arguments); } } @@ -158,7 +157,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito data.populate(rs); // Point the rowset Cursor to the start if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL SUCCESS. rows returned: " + data.size() + ", time(ms): " + (System.currentTimeMillis() + LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), (System.currentTimeMillis() - time)); } } catch (SQLException exc) { @@ -182,7 +181,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } if (arguments != null && !arguments.isEmpty()) { LOGGER.error(String.format("<%s%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_ARGUMENTS, - arguments.toString()), exc); + arguments), exc); } else { LOGGER.error(String.format("<%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_NO_ARGUMENTS), exc); @@ -221,7 +220,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito ps.executeUpdate(); // Point the rowset Cursor to the start if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL SUCCESS. rows returned: " + data.size() + ", time(ms): " + (System.currentTimeMillis() + LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), (System.currentTimeMillis() - time)); } ps.close(); @@ -465,12 +464,12 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } protected boolean isSlave() throws PoolExhaustedException { - CachedRowSet rs = null; - boolean isSlave = true; + CachedRowSet rs; + boolean isSlave; String hostname = "UNDETERMINED"; try { boolean localSlave = true; - rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList()); + rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList<>()); while (rs.next()) { localSlave = rs.getBoolean(1); hostname = rs.getString(2); @@ -483,9 +482,9 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito isSlave = true; } if (isSlave) { - LOGGER.debug(String.format("SQL SLAVE : %s on server %s", connectionName, hostname)); + LOGGER.debug("SQL SLAVE : {} on server {}", connectionName, hostname); } else { - LOGGER.debug(String.format("SQL MASTER : %s on server %s", connectionName, hostname)); + LOGGER.debug("SQL MASTER : {} on server {}", connectionName, hostname); } return isSlave; } @@ -524,7 +523,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito boolean retValue; try (Statement lock = conn.createStatement()) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'UNLOCK TABLES' on connection " + conn.toString()); + LOGGER.debug("Executing 'UNLOCK TABLES' on connection {}", conn); } retValue = lock.execute("UNLOCK TABLES"); } catch (Exception exc) { -- cgit 1.2.3-korg From ea256b21bd4f2565ca9ae30e737748e40aa21f23 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Tue, 26 Sep 2017 17:19:32 +0000 Subject: Updated DBLIB svc definition Changes made: 1. updated DBLibService definition by adding javax.sql.DataSource Change-Id: I5dd63a81420f451b0ce9bbbc878d351d62ccd819 Issue-ID: CCSDK-102 Signed-off-by: Rich Tabedzki --- .../src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java index b31de3547..b30ad7bbf 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DbLibService.java @@ -24,9 +24,10 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; +import javax.sql.DataSource; import javax.sql.rowset.CachedRowSet; -public interface DbLibService { +public interface DbLibService extends DataSource { /* (non-Javadoc) * @see DataAccessor#getData(java.lang.String, java.util.ArrayList) -- cgit 1.2.3-korg From 38f77425e9515b061f7eca1683fc85c42997619a Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Thu, 28 Sep 2017 03:00:10 +0000 Subject: Refined DBLIB blueprint configuration Changes made: 1. updated DBLibService definition by registering service on two interfaces: a) javax.sql.DataSource b) org.onap.ccsdk.sli.core.dblib.DbLibService Change-Id: If187b07db83ebca5428c809a83f546d9178a2b7f Issue-ID: CCSDK-102 Signed-off-by: Rich Tabedzki --- .../main/resources/org/opendaylight/blueprint/dblib-blueprint.xml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) mode change 100644 => 100755 dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml (limited to 'dblib/provider/src') 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 old mode 100644 new mode 100755 index ee3e0f033..f1d5166db --- a/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml +++ b/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml @@ -8,6 +8,11 @@ - + + + javax.sql.DataSource + org.onap.ccsdk.sli.core.dblib.DbLibService + + \ No newline at end of file -- cgit 1.2.3-korg From a28fa047a9a304a40f5b26d9777cfc7cb9f9fe97 Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Thu, 28 Sep 2017 11:31:42 +0530 Subject: Remove redundant casts *Remove unnecessary cast to "CachedDataSource" These unnecessary casting expressions maked the code harder to read and understand *Replace type specification with diamond operator This is to reduce the verbosity of generics code Issue-Id: CCSDK-87 Change-Id: I6cd2f7d16886ffa6cc26e5dd300b8376705d9366 Signed-off-by: surya-huawei --- .../ccsdk/sli/core/dblib/DBResourceManager.java | 62 +++++++++++----------- 1 file changed, 31 insertions(+), 31 deletions(-) (limited to 'dblib/provider/src') 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 e7a94e64c..61fb000fb 100755 --- 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 @@ -71,29 +71,29 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb protected final AtomicBoolean dsSelector = new AtomicBoolean(); // Queue dsQueue = new ConcurrentLinkedQueue(); - Queue dsQueue = new PriorityQueue(4, new Comparator() { - @Override - public int compare(CachedDataSource left, CachedDataSource right) { - try { - if(left == null){ - return 1; - } - if(right == null){ - return -1; - } + Queue dsQueue = new PriorityQueue<>(4, new Comparator() { + @Override + public int compare(CachedDataSource left, CachedDataSource right) { + try { + if (left == null) { + return 1; + } + if (right == null) { + return -1; + } - if(!left.isSlave()) { - return -1; - } - if (!right.isSlave()) { - return 1; - } - } catch (Throwable e) { - LOGGER.warn("", e); + if (!left.isSlave()) { + return -1; + } + if (!right.isSlave()) { + return 1; } - return 0; + } catch (Throwable e) { + LOGGER.warn("", e); } - }); + return 0; + } +}); protected final Set broken = Collections.synchronizedSet(new HashSet()); protected final Object monitor = new Object(); protected final Properties configProps; @@ -313,7 +313,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public void testForceRecovery() { - CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + CachedDataSource active = this.dsQueue.peek(); handleGetConnectionException(active, new Exception("test")); } @@ -461,7 +461,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); } - CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + CachedDataSource active = this.dsQueue.peek(); long time = System.currentTimeMillis(); try { if(!active.isFabric()) { @@ -533,7 +533,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb boolean initialRequest = true; boolean retryAllowed = true; - CachedDataSource active = (CachedDataSource) this.dsQueue.peek(); + CachedDataSource active = this.dsQueue.peek(); long time = System.currentTimeMillis(); while(initialRequest) { initialRequest = false; @@ -724,7 +724,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public void cleanUp() { for(Iterator it=dsQueue.iterator();it.hasNext();){ - CachedDataSource cds = (CachedDataSource)it.next(); + CachedDataSource cds = it.next(); it.remove(); cds.cleanUp(); } @@ -748,28 +748,28 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb @Override public PrintWriter getLogWriter() throws SQLException { - return ((CachedDataSource)this.dsQueue.peek()).getLogWriter(); + return this.dsQueue.peek().getLogWriter(); } @Override public int getLoginTimeout() throws SQLException { - return ((CachedDataSource)this.dsQueue.peek()).getLoginTimeout(); + return this.dsQueue.peek().getLoginTimeout(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { - ((CachedDataSource)this.dsQueue.peek()).setLogWriter(out); + this.dsQueue.peek().setLogWriter(out); } @Override public void setLoginTimeout(int seconds) throws SQLException { - ((CachedDataSource)this.dsQueue.peek()).setLoginTimeout(seconds); + this.dsQueue.peek().setLoginTimeout(seconds); } public void displayState(){ if(LOGGER.isDebugEnabled()){ LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); - CachedDataSource current = (CachedDataSource)dsQueue.peek(); + CachedDataSource current = dsQueue.peek(); if(current != null) { LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); } @@ -800,7 +800,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb .append("Name:").append(""); for (int i = 0; i < list.size(); i++) { buffer.append(""); - buffer.append(((CachedDataSource) list.get(i)).getDbConnectionName()).append(""); + buffer.append(list.get(i).getDbConnectionName()).append(""); } buffer.append(""); @@ -820,7 +820,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } else { for (int i = 0; i < list.size(); i++) { - buffer.append("Name: ").append(((CachedDataSource) list.get(i)).getDbConnectionName()); + buffer.append("Name: ").append(list.get(i).getDbConnectionName()); buffer.append("\tState: "); if (broken.contains(list.get(i))) { buffer.append("in recovery"); -- cgit 1.2.3-korg From d73d257d76fa8211113fa3ef1a4e4058e67f4f2c Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Tue, 3 Oct 2017 08:17:38 -0400 Subject: Add unit tests for dblib Add unit test case for dblib/provider, using MariaDB4J as database. Change-Id: I18492595a9d54999c3d52b56ecfe33d0d2cae019 Issue-ID: CCSDK-106 Signed-off-by: Dan Timoney --- dblib/provider/pom.xml | 6 +++ .../sli/core/dblib/TestDBResourceManager.java | 55 ++++++++++++++++++++++ dblib/provider/src/test/resources/dblib.properties | 38 +++++++++++++++ 3 files changed, 99 insertions(+) create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java create mode 100644 dblib/provider/src/test/resources/dblib.properties (limited to 'dblib/provider/src') diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index d0dc72933..730919de0 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -21,6 +21,12 @@ ${junit.version} test + + ch.vorburger.mariaDB4j + mariaDB4j + 2.2.3 + test + equinoxSDK381 org.eclipse.osgi diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java new file mode 100644 index 000000000..dca07921b --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java @@ -0,0 +1,55 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import java.io.InputStream; +import java.net.URL; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +import ch.vorburger.mariadb4j.DB; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; + +public class TestDBResourceManager { + + DbLibService dblibSvc; + + @Before + public void setUp() throws Exception { + URL propUrl = getClass().getResource("/dblib.properties"); + + InputStream propStr = getClass().getResourceAsStream("/dblib.properties"); + + Properties props = new Properties(); + + props.load(propStr); + + + // Start MariaDB4j database + DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); + config.setPort(0); // 0 => autom. detect free port + DB db = DB.newEmbeddedDB(config.build()); + db.start(); + + + // Override jdbc URL and database name + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + + + dblibSvc = new DBResourceManager(props); + + dblibSvc.writeData("CREATE TABLE DBLIB_TEST (name varchar(20));", null, null); + dblibSvc.getData("SELECT * FROM DBLIB_TEST", null, null); + + } + + @Test + public void test() { + + + } + +} diff --git a/dblib/provider/src/test/resources/dblib.properties b/dblib/provider/src/test/resources/dblib.properties new file mode 100644 index 000000000..9506ac8d1 --- /dev/null +++ b/dblib/provider/src/test/resources/dblib.properties @@ -0,0 +1,38 @@ +### +# ============LICENSE_START======================================================= +# openECOMP : SDN-C +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# dblib.properrties +org.onap.ccsdk.sli.dbtype=jdbc + +org.onap.ccsdk.sli.jdbc.hosts=sdnctldb01 +org.onap.ccsdk.sli.jdbc.url=jdbc:mysql://dbhost:3306/sdnctl +org.onap.ccsdk.sli.jdbc.driver=org.mariadb.jdbc.Driver +org.onap.ccsdk.sli.jdbc.database=sdnctl +org.onap.ccsdk.sli.jdbc.user=sdnctl +org.onap.ccsdk.sli.jdbc.password=gamma +org.onap.ccsdk.sli.jdbc.connection.name=sdnctldb01 +org.onap.ccsdk.sli.jdbc.connection.timeout=50 +org.onap.ccsdk.sli.jdbc.request.timeout=100 +org.onap.ccsdk.sli.jdbc.limit.init=10 +org.onap.ccsdk.sli.jdbc.limit.min=10 +org.onap.ccsdk.sli.jdbc.limit.max=20 +org.onap.dblib.connection.recovery=false + -- cgit 1.2.3-korg From e940e23cd0b574f8239cdd24fc3b1e590326361e Mon Sep 17 00:00:00 2001 From: surya-huawei Date: Thu, 12 Oct 2017 11:48:42 +0530 Subject: Add @Override annotation *This is improve readability of source code Issue-Id: CCSDK-117 Change-Id: I4bb73a6e4b440ae861045c7548a7e985d1fbf02c Signed-off-by: surya-huawei --- .../src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java index b670a832d..4bfa058a8 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java @@ -102,6 +102,7 @@ public class PollingWorker implements Runnable { tasks.remove(object); } + @Override public void run() { for(;;){ Set data = new TreeSet(); @@ -150,6 +151,7 @@ public class PollingWorker implements Runnable { class MyTimerTask extends TimerTask{ + @Override public void run() { clearReqister(); @@ -198,6 +200,7 @@ public class PollingWorker implements Runnable { return endtime - starttime; } + @Override public int compareTo(Object o) { if(o instanceof TestSample){ TestSample x = (TestSample)o; -- cgit 1.2.3-korg From d3cd4dd5d5f300684be256eb1bf70d750a9a957e Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Fri, 5 Jan 2018 20:26:58 +0000 Subject: Generalization of CCSDK core/utils framework Changes made: * Created generalized version of core/utils/dblib as core/utils/common * Deprecated core/utils/dblib package Change-Id: I0992c43910278fbe254674d1e39d7e4fcad0a592 Issue-ID: CCSDK-168 Signed-off-by: Rich Tabedzki --- .../sli/core/dblib/DBLIBResourceProvider.java | 18 +- .../ccsdk/sli/core/dblib/DBResourceManager.java | 1759 ++++++++++---------- .../ccsdk/sli/core/utils/EnvVarFileResolver.java | 2 +- .../onap/ccsdk/sli/core/utils/JREFileResolver.java | 10 +- .../utils/common/BundleContextFileResolver.java | 80 + .../core/utils/common/CoreDefaultFileResolver.java | 41 + .../utils/common/SdncConfigEnvVarFileResolver.java | 38 + .../core/utils/dblib/DblibDefaultFileResolver.java | 10 +- .../core/utils/dblib/DblibEnvVarFileResolver.java | 8 + .../utils/common/BundleContexFileResolverTest.java | 16 + .../utils/common/CoreDefaultFileResolverTest.java | 25 + .../common/SdncConfigEnvVarFileResolverTest.java | 24 + 12 files changed, 1137 insertions(+), 894 deletions(-) mode change 100644 => 100755 utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java mode change 100644 => 100755 utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java create mode 100755 utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/BundleContextFileResolver.java create mode 100755 utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolver.java create mode 100755 utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolver.java mode change 100644 => 100755 utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java create mode 100644 utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/BundleContexFileResolverTest.java create mode 100644 utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolverTest.java create mode 100644 utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolverTest.java (limited to 'dblib/provider/src') 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 index 411f04705..ddfb73316 100644 --- 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 @@ -7,9 +7,9 @@ * 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. @@ -27,11 +27,11 @@ import java.util.Optional; import java.util.Properties; import java.util.Vector; -import org.onap.ccsdk.sli.core.utils.dblib.DblibDefaultFileResolver; -import org.onap.ccsdk.sli.core.utils.dblib.DblibEnvVarFileResolver; import org.onap.ccsdk.sli.core.utils.JREFileResolver; import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; +import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; +import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,7 +58,7 @@ public class DBLIBResourceProvider { /** * A prioritized list of strategies for resolving dblib properties files. */ - private Vector dblibPropertiesFileResolvers = new Vector(); + private Vector dblibPropertiesFileResolvers = new Vector<>(); /** * The configuration properties for the db connection. @@ -69,14 +69,14 @@ public class DBLIBResourceProvider { * Set up the prioritized list of strategies for resolving dblib properties files. */ public DBLIBResourceProvider() { - dblibPropertiesFileResolvers.add(new DblibEnvVarFileResolver( + dblibPropertiesFileResolvers.add(new SdncConfigEnvVarFileResolver( "Using property file (1) from environment variable" )); - dblibPropertiesFileResolvers.add(new DblibDefaultFileResolver( - "Using property file (1) from default directory" + dblibPropertiesFileResolvers.add(new CoreDefaultFileResolver( + "Using property file (2) from default directory" )); dblibPropertiesFileResolvers.add(new JREFileResolver( - "Using property file (2) from JRE argument", DBLIBResourceProvider.class + "Using property file (3) from JRE argument", DBLIBResourceProvider.class )); dblibPropertiesFileResolvers.add(new KarafRootFileResolver( "Using property file (4) from karaf root", this)); 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 61fb000fb..b31645d41 100755 --- 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 @@ -62,891 +62,892 @@ import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; * Rich Tabedzki */ public class DBResourceManager implements DataSource, DataAccessor, DBResourceObserver, DbLibService { - private static Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); - - transient boolean terminating = false; - transient protected long retryInterval = 10000L; - transient boolean recoveryMode = true; - - protected final AtomicBoolean dsSelector = new AtomicBoolean(); - -// Queue dsQueue = new ConcurrentLinkedQueue(); - Queue dsQueue = new PriorityQueue<>(4, new Comparator() { - @Override - public int compare(CachedDataSource left, CachedDataSource right) { - try { - if (left == null) { - return 1; - } - if (right == null) { - return -1; - } - - if (!left.isSlave()) { - return -1; - } - if (!right.isSlave()) { - return 1; - } - } catch (Throwable e) { - LOGGER.warn("", e); - } - return 0; - } + private static Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); + + transient boolean terminating = false; + transient protected long retryInterval = 10000L; + transient boolean recoveryMode = true; + + protected final AtomicBoolean dsSelector = new AtomicBoolean(); + + Queue dsQueue = new PriorityQueue<>(4, new Comparator() { + @Override + public int compare(CachedDataSource left, CachedDataSource right) { + try { + if (left == null) { + return 1; + } + if (right == null) { + return -1; + } + + if (!left.isSlave()) { + return -1; + } + if (!right.isSlave()) { + return 1; + } + } catch (Throwable e) { + LOGGER.warn("", e); + } + return 0; + } }); - protected final Set broken = Collections.synchronizedSet(new HashSet()); - protected final Object monitor = new Object(); - protected final Properties configProps; - protected final Thread worker; - - protected final long terminationTimeOut; - protected final boolean monitorDbResponse; - protected final long monitoringInterval; - protected final long monitoringInitialDelay; - protected final long expectedCompletionTime; - protected final long unprocessedFailoverThreshold; - - public DBResourceManager(final DBLIBResourceProvider configuration) { - this(configuration.getProperties()); - } - - public DBResourceManager(final Properties properties) { - this.configProps = properties; - - // get retry interval value - retryInterval = getLongFromProperties(properties, "org.onap.dblib.connection.retry", 10000L); - - // get recovery mode flag - 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(properties, "org.onap.dblib.termination.timeout", 300000L); - // get properties for monitoring - 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(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 configProps) throws Exception { - final ConcurrentLinkedQueue semaphore = new ConcurrentLinkedQueue<>(); - final DbConfigPool dbConfig = DBConfigFactory.createConfig(configProps); - - long startTime = System.currentTimeMillis(); - - try { - JDBCConfiguration[] config = dbConfig.getJDBCbSourceArray(); - CachedDataSource[] cachedDS = new CachedDataSource[config.length]; - 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 < config.length; i++) { - cachedDS[i] = CachedDataSourceFactory.createDataSource(config[i]); - if(cachedDS[i] == null) - continue; - semaphore.add(cachedDS[i]); - cachedDS[i].setInterval(monitoringInterval); - cachedDS[i].setInitialDelay(monitoringInitialDelay); - cachedDS[i].setExpectedCompletionTime(expectedCompletionTime); - cachedDS[i].setUnprocessedFailoverThreshold(unprocessedFailoverThreshold); - cachedDS[i].addObserver(DBResourceManager.this); - } - -// CachedDataSource[] cachedDS = factory.initDBResourceManager(dbConfig, DBResourceManager.this, semaphore); - DataSourceTester[] tester = new DataSourceTester[config.length]; - - for(int i=0; i semaphoreQ; - - public DataSourceTester(CachedDataSource ds, DBResourceManager manager, ConcurrentLinkedQueue semaphore) { - this.ds = ds; - this.manager = manager; - this.semaphoreQ = semaphore; - } - - @Override - public void run() { - manager.setDataSource(ds); - boolean slave = true; - if(ds != null) { - try { - slave = ds.isSlave(); - } catch (Exception exc) { - LOGGER.warn("", exc); - } - } - if(!slave) { - LOGGER.info(String.format("Adding MASTER (%s) to active queue", ds.getDbConnectionName())); - try { - synchronized (semaphoreQ) { - semaphoreQ.notifyAll(); - } - } catch(Exception exc) { - LOGGER.warn("", exc); - } - } - try { - synchronized (semaphoreQ) { - semaphoreQ.remove(ds); - } - if(semaphoreQ.isEmpty()) { - synchronized (semaphoreQ) { - semaphoreQ.notifyAll(); - } - } - } catch(Exception exc) { - LOGGER.warn("", exc); - } - LOGGER.info(String.format("Thread DataSourceTester terminated %s for %s", this.getName(), ds.getDbConnectionName())); - } - - } - - - private long getLongFromProperties(Properties props, String property, long defaultValue) - { - String value = null; - long tmpLongValue = defaultValue; - try { - value = props.getProperty(property); - if(value != null) - tmpLongValue = Long.parseLong(value); - - } catch(NumberFormatException exc) { - if(LOGGER.isWarnEnabled()){ - LOGGER.warn("'"+property+"'=" + value+" is invalid. It should be a numeric value"); - } - } catch(Exception exc) { - } - return tmpLongValue; - - } - - private boolean getBooleanFromProperties(Properties props, String property, boolean defaultValue) - { - boolean tmpValue = defaultValue; - String value = null; - - try { - value = props.getProperty(property); - if(value != null) - tmpValue = Boolean.parseBoolean(value); - - } catch(NumberFormatException exc) { - if(LOGGER.isWarnEnabled()){ - LOGGER.warn("'"+property+"'=" + value+" is invalid. It should be a boolean value"); - } - } catch(Exception exc) { - } - return tmpValue; - - } - - - @Override - public void update(Observable observable, Object data) { - // if observable is active and there is a standby available, switch - if(observable instanceof SQLExecutionMonitor) - { - SQLExecutionMonitor monitor = (SQLExecutionMonitor)observable; - if(monitor.getParent() instanceof CachedDataSource) - { - CachedDataSource dataSource = (CachedDataSource)monitor.getParent(); - if(dataSource == dsQueue.peek()) - { - if(recoveryMode && dsQueue.size() > 1){ - handleGetConnectionException(dataSource, new Exception(data.toString())); - } - } - } - } - } - - public void testForceRecovery() - { - CachedDataSource active = this.dsQueue.peek(); - handleGetConnectionException(active, new Exception("test")); - } - - class RecoveryMgr extends Thread { - - @Override - public void run() { - while(!terminating) - { - try { - Thread.sleep(retryInterval); - } catch (InterruptedException e1) { } - CachedDataSource brokenSource = null; - try { - if (!broken.isEmpty()) { - CachedDataSource[] sourceArray = broken.toArray(new CachedDataSource[0]); - for (int i = 0; i < sourceArray.length; i++) - { - brokenSource = sourceArray[i]; - if (brokenSource instanceof TerminatingCachedDataSource) - break; - if (resetConnectionPool(brokenSource)) { - broken.remove(brokenSource); - brokenSource.blockImmediateOffLine(); - dsQueue.add(brokenSource); - LOGGER.info("DataSource <" - + brokenSource.getDbConnectionName() - + "> recovered."); - } - brokenSource = null; - } - } - } catch (Exception exc) { - LOGGER.warn(exc.getMessage()); - if(brokenSource != null){ - try { - if(!broken.contains(brokenSource)) - broken.add(brokenSource); - brokenSource = null; - } catch (Exception e1) { } - } - } - } - LOGGER.info("DBResourceManager.RecoveryMgr <"+this.toString() +"> terminated." ); - } - - private boolean resetConnectionPool(CachedDataSource dataSource){ - try { - return dataSource.testConnection(); - } catch (Exception exc) { - LOGGER.info("DataSource <" + dataSource.getDbConnectionName() + "> resetCache failed with error: "+ exc.getMessage()); - return false; - } - } - } - - /* (non-Javadoc) - * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#getData(java.lang.String, java.util.ArrayList, java.lang.String) - */ - @Override - public CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) throws SQLException { - ArrayList newList= new ArrayList<>(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - if(recoveryMode) - return requestDataWithRecovery(statement, newList, preferredDS); - else - return requestDataNoRecovery(statement, newList, preferredDS); - } - - private CachedRowSet requestDataWithRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { - Throwable lastException = null; - CachedDataSource active = null; - - // test if there are any connection pools available - LinkedList sources = new LinkedList<>(this.dsQueue); - if(sources.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); - throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); - } - if(preferredDS != null && !sources.peek().getDbConnectionName().equals(preferredDS)) { - Collections.reverse(sources); - } - - - // loop through available data sources to retrieve data. - while(!sources.isEmpty()) - { - active = sources.peek(); - - long time = System.currentTimeMillis(); - try { - if(!active.isFabric()) { - CachedDataSource master = findMaster(); - if(master != null) { - active = master; - master = null; - } - } - sources.remove(active); - return active.getData(statement, arguments); - } catch(SQLDataException | SQLSyntaxErrorException | SQLIntegrityConstraintViolationException exc){ - throw exc; - } catch(Throwable exc){ - lastException = exc; - String message = exc.getMessage(); - if(message == null) { - if(exc.getCause() != null) { - message = exc.getCause().getMessage(); - } - if(message == null) - message = exc.getClass().getName(); - } - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); - handleGetConnectionException(active, exc); - } finally { - if(LOGGER.isDebugEnabled()){ - time = System.currentTimeMillis() - time; - LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); - } - } - } - if(lastException instanceof SQLException){ - throw (SQLException)lastException; - } - // repackage the exception - // you are here because either you run out of available data sources - // or the last exception was not of SQLException type. - // repackage the exception - if(lastException == null) { - throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); - } else { - SQLException exception = new DBLibException(lastException.getMessage()); - exception.setStackTrace(lastException.getStackTrace()); - if(lastException.getCause() instanceof SQLException) { - throw (SQLException)lastException.getCause(); - } - throw exception; - } - } - - private CachedRowSet requestDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { - if(dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); - throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); - } - CachedDataSource active = this.dsQueue.peek(); - long time = System.currentTimeMillis(); - try { - if(!active.isFabric()) { - CachedDataSource master = findMaster(); - if(master != null) - active = master; - } - return active.getData(statement, arguments); -// } catch(SQLDataException exc){ -// throw exc; - } catch(Throwable exc){ - String message = exc.getMessage(); - if(message == null) - message = exc.getClass().getName(); - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); - if(exc instanceof SQLException) - throw (SQLException)exc; - else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } finally { - if(LOGGER.isDebugEnabled()){ - time = System.currentTimeMillis() - time; - LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); - } - } - } - - - /* (non-Javadoc) - * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#writeData(java.lang.String, java.util.ArrayList, java.lang.String) - */ - @Override - public boolean writeData(String statement, ArrayList arguments, String preferredDS) throws SQLException + protected final Set broken = Collections.synchronizedSet(new HashSet()); + protected final Object monitor = new Object(); + protected final Properties configProps; + protected final Thread worker; + + protected final long terminationTimeOut; + protected final boolean monitorDbResponse; + protected final long monitoringInterval; + protected final long monitoringInitialDelay; + protected final long expectedCompletionTime; + protected final long unprocessedFailoverThreshold; + + public DBResourceManager(final DBLIBResourceProvider configuration) { + this(configuration.getProperties()); + } + + public DBResourceManager(final Properties properties) { + this.configProps = properties; + + // get retry interval value + retryInterval = getLongFromProperties(properties, "org.onap.dblib.connection.retry", 10000L); + + // get recovery mode flag + 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(properties, "org.onap.dblib.termination.timeout", 300000L); + // get properties for monitoring + 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(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 configProps) throws Exception { + final ConcurrentLinkedQueue semaphore = new ConcurrentLinkedQueue<>(); + final DbConfigPool dbConfig = DBConfigFactory.createConfig(configProps); + + long startTime = System.currentTimeMillis(); + + try { + JDBCConfiguration[] config = dbConfig.getJDBCbSourceArray(); + CachedDataSource[] cachedDS = new CachedDataSource[config.length]; + 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 < config.length; i++) { + cachedDS[i] = CachedDataSourceFactory.createDataSource(config[i]); + if(cachedDS[i] == null) + continue; + semaphore.add(cachedDS[i]); + cachedDS[i].setInterval(monitoringInterval); + cachedDS[i].setInitialDelay(monitoringInitialDelay); + cachedDS[i].setExpectedCompletionTime(expectedCompletionTime); + cachedDS[i].setUnprocessedFailoverThreshold(unprocessedFailoverThreshold); + cachedDS[i].addObserver(DBResourceManager.this); + } + +// CachedDataSource[] cachedDS = factory.initDBResourceManager(dbConfig, DBResourceManager.this, semaphore); + DataSourceTester[] tester = new DataSourceTester[config.length]; + + for(int i=0; i semaphoreQ; + + public DataSourceTester(CachedDataSource ds, DBResourceManager manager, ConcurrentLinkedQueue semaphore) { + this.ds = ds; + this.manager = manager; + this.semaphoreQ = semaphore; + } + + @Override + public void run() { + manager.setDataSource(ds); + boolean slave = true; + if(ds != null) { + try { + slave = ds.isSlave(); + } catch (Exception exc) { + LOGGER.warn("", exc); + } + } + if(!slave) { + LOGGER.info(String.format("Adding MASTER (%s) to active queue", ds.getDbConnectionName())); + try { + synchronized (semaphoreQ) { + semaphoreQ.notifyAll(); + } + } catch(Exception exc) { + LOGGER.warn("", exc); + } + } + try { + synchronized (semaphoreQ) { + semaphoreQ.remove(ds); + } + if(semaphoreQ.isEmpty()) { + synchronized (semaphoreQ) { + semaphoreQ.notifyAll(); + } + } + } catch(Exception exc) { + LOGGER.warn("", exc); + } + LOGGER.info(String.format("Thread DataSourceTester terminated %s for %s", this.getName(), ds.getDbConnectionName())); + } + + } + + + private long getLongFromProperties(Properties props, String property, long defaultValue) + { + String value = null; + long tmpLongValue = defaultValue; + try { + value = props.getProperty(property); + if(value != null) + tmpLongValue = Long.parseLong(value); + + } catch(NumberFormatException exc) { + if(LOGGER.isWarnEnabled()){ + LOGGER.warn("'"+property+"'=" + value+" is invalid. It should be a numeric value"); + } + } catch(Exception exc) { + } + return tmpLongValue; + + } + + private boolean getBooleanFromProperties(Properties props, String property, boolean defaultValue) + { + boolean tmpValue = defaultValue; + String value = null; + + try { + value = props.getProperty(property); + if(value != null) + tmpValue = Boolean.parseBoolean(value); + + } catch(NumberFormatException exc) { + if(LOGGER.isWarnEnabled()){ + LOGGER.warn("'"+property+"'=" + value+" is invalid. It should be a boolean value"); + } + } catch(Exception exc) { + } + return tmpValue; + + } + + + @Override + public void update(Observable observable, Object data) { + // if observable is active and there is a standby available, switch + if(observable instanceof SQLExecutionMonitor) { - ArrayList newList= new ArrayList<>(); - if(arguments != null && !arguments.isEmpty()) { - newList.addAll(arguments); - } - - return writeDataNoRecovery(statement, newList, preferredDS); - } - - CachedDataSource findMaster() throws PoolExhaustedException { - CachedDataSource master = null; - CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); - for(int i=0; i arguments, String preferredDS) throws SQLException { - if(dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); - throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); - } - - boolean initialRequest = true; - boolean retryAllowed = true; - CachedDataSource active = this.dsQueue.peek(); - long time = System.currentTimeMillis(); - while(initialRequest) { - initialRequest = false; - try { - if(!active.isFabric()) { - CachedDataSource master = findMaster(); - if(master != null) { - active = master; - } - } - - return active.writeData(statement, arguments); - } catch(Throwable exc){ - String message = exc.getMessage(); - if(message == null) - message = exc.getClass().getName(); - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); - if(exc instanceof SQLException) { - SQLException sqlExc = SQLException.class.cast(exc); - // handle read-only exception - if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { - LOGGER.warn("retrying due to: " + sqlExc.getMessage()); - dsQueue.remove(active); - dsQueue.add(active); - if(retryAllowed){ - retryAllowed = false; - initialRequest = true; - continue; - } - } - throw (SQLException)exc; - } else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } finally { - if(LOGGER.isDebugEnabled()){ - time = System.currentTimeMillis() - time; - LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); - } - } - } - return true; - } - - public void setDataSource(CachedDataSource dataSource) { - if(this.dsQueue.contains(dataSource)) - return; - if(this.broken.contains(dataSource)) - return; - - if(dataSource.testConnection(true)){ - this.dsQueue.add(dataSource); - } else { - this.broken.add(dataSource); - } - } - - @Override - public Connection getConnection() throws SQLException { - Throwable lastException = null; - CachedDataSource active = null; - - if(dsQueue.isEmpty()){ - throw new DBLibException("No active DB connection pools are available in GetConnection call."); - } - - try { - active = dsQueue.peek(); - CachedDataSource tmpActive = findMaster(); - if(tmpActive != null) { - active = tmpActive; - } - return new DBLibConnection(active.getConnection(), active); - } catch(javax.sql.rowset.spi.SyncFactoryException exc){ - LOGGER.debug("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); - LOGGER.warn("CLASSPATH issue. Allowing retry", exc); - lastException = exc; - } catch(PoolExhaustedException exc) { - throw new NoAvailableConnectionsException(exc); - } catch(Exception exc){ - lastException = exc; - if(recoveryMode){ - handleGetConnectionException(active, exc); - } else { - if(exc instanceof SQLException) { - throw (SQLException)exc; - } else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } - } catch (Throwable trwb) { - DBLibException excptn = new DBLibException(trwb.getMessage()); - excptn.setStackTrace(trwb.getStackTrace()); - throw excptn; - } finally { - if(LOGGER.isDebugEnabled()){ - displayState(); - } - } - - if(lastException instanceof SQLException){ - throw (SQLException)lastException; - } - // repackage the exception - if(lastException == null) { - throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); - } else { - SQLException exception = new DBLibException(lastException.getMessage()); - exception.setStackTrace(lastException.getStackTrace()); - if(lastException.getCause() instanceof SQLException) { -// exception.setNextException((SQLException)lastException.getCause()); - throw (SQLException)lastException.getCause(); - } - throw exception; - } - } - - @Override - public Connection getConnection(String username, String password) - throws SQLException { - CachedDataSource active = null; - - if(dsQueue.isEmpty()){ - throw new DBLibException("No active DB connection pools are available in GetConnection call."); - } - - - try { - active = dsQueue.peek(); - CachedDataSource tmpActive = findMaster(); - if(tmpActive != null) { - active = tmpActive; - } - return active.getConnection(username, password); - } catch(Throwable exc){ - if(recoveryMode){ - handleGetConnectionException(active, exc); - } else { - if(exc instanceof SQLException) - throw (SQLException)exc; - else { - DBLibException excptn = new DBLibException(exc.getMessage()); - excptn.setStackTrace(exc.getStackTrace()); - throw excptn; - } - } - - } - - throw new DBLibException("No connections available in DBResourceManager in GetConnection call."); - } - - private void handleGetConnectionException(CachedDataSource source, Throwable exc) { - try { - if(!source.canTakeOffLine()) - { - LOGGER.error("Could not switch due to blocking"); - return; - } - - boolean removed = dsQueue.remove(source); - if(!broken.contains(source)) - { - if(broken.add(source)) - { - LOGGER.warn("DB Recovery: DataSource <" + source.getDbConnectionName() + "> put in the recovery mode. Reason : " + exc.getMessage()); - } else { - LOGGER.warn("Error putting DataSource <" +source.getDbConnectionName()+ "> in recovery mode."); - } - } else { - LOGGER.info("DB Recovery: DataSource <" + source.getDbConnectionName() + "> already in recovery queue"); - } - if(removed) - { - if(!dsQueue.isEmpty()) - { - LOGGER.warn("DB DataSource <" + dsQueue.peek().getDbConnectionName() + "> became active"); - } - } - } catch (Exception e) { - LOGGER.error("", e); - } - } - - public void cleanUp() { - for(Iterator it=dsQueue.iterator();it.hasNext();){ - CachedDataSource cds = it.next(); - it.remove(); - cds.cleanUp(); - } - - try { - this.terminating = true; - if(broken != null) - { - try { - broken.add( new TerminatingCachedDataSource(null)); - } catch(Exception exc){ - LOGGER.error("Waiting for Worker to stop", exc); - } - } - worker.join(terminationTimeOut); - LOGGER.info("DBResourceManager.RecoveryMgr <"+worker.toString() +"> termination was successful: " + worker.getState()); - } catch(Exception exc){ - LOGGER.error("Waiting for Worker thread to terminate ", exc); - } - } - - @Override - public PrintWriter getLogWriter() throws SQLException { - return this.dsQueue.peek().getLogWriter(); - } - - @Override - public int getLoginTimeout() throws SQLException { - return this.dsQueue.peek().getLoginTimeout(); - } - - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - this.dsQueue.peek().setLogWriter(out); - } - - @Override - public void setLoginTimeout(int seconds) throws SQLException { - this.dsQueue.peek().setLoginTimeout(seconds); - } - - public void displayState(){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); - CachedDataSource current = dsQueue.peek(); - if(current != null) { - LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); - } - } - } - - /* (non-Javadoc) - * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#isActive() - */ - @Override - public boolean isActive() { - return this.dsQueue.size()>0; - } - - public String getActiveStatus(){ - return "Connected: " + dsQueue.size()+"\tIn-recovery: "+broken.size(); - } - - public String getDBStatus(boolean htmlFormat) { - StringBuilder buffer = new StringBuilder(); - - ArrayList list = new ArrayList<>(); - list.addAll(dsQueue); - list.addAll(broken); - if (htmlFormat) - { - buffer.append("") - .append("Name:").append(""); - for (int i = 0; i < list.size(); i++) { - buffer.append(""); - buffer.append(list.get(i).getDbConnectionName()).append(""); - } - buffer.append(""); - - buffer.append("State:"); - for (int i = 0; i < list.size(); i++) { - if (broken.contains(list.get(i))) { - buffer.append("in recovery"); - } - if (dsQueue.contains(list.get(i))) { - if (dsQueue.peek() == list.get(i)) - buffer.append("active"); - else - buffer.append("standby"); - } - } - buffer.append(""); - - } else { - for (int i = 0; i < list.size(); i++) { - buffer.append("Name: ").append(list.get(i).getDbConnectionName()); - buffer.append("\tState: "); - if (broken.contains(list.get(i))) { - buffer.append("in recovery"); - } else - if (dsQueue.contains(list.get(i))) { - if (dsQueue.peek() == list.get(i)) - buffer.append("active"); - else - buffer.append("standby"); - } - - buffer.append("\n"); - - } - } - return buffer.toString(); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - /** - * @return the monitorDbResponse - */ - @Override - public final boolean isMonitorDbResponse() { - return recoveryMode && monitorDbResponse; - } - - public void test(){ - CachedDataSource obj = dsQueue.peek(); - Exception ption = new Exception(); - try { - for(int i=0; i<5; i++) - { - handleGetConnectionException(obj, ption); - } - } catch(Throwable exc){ - LOGGER.warn("", exc); - } - } - - public String getPreferredDSName(){ - if(isActive()){ - return getPreferredDataSourceName(dsSelector); - } - return ""; - } - - public String getPreferredDataSourceName(AtomicBoolean flipper) { - - LinkedList snapshot = new LinkedList<>(dsQueue); - if(snapshot.size() > 1){ - CachedDataSource first = snapshot.getFirst(); - CachedDataSource last = snapshot.getLast(); - - int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); - if(delta < 0) { - flipper.set(false); - } else if(delta > 0) { - flipper.set(true); - } else { - // check the last value and return !last - flipper.getAndSet(!flipper.get()); - } - - if (flipper.get()) - Collections.reverse(snapshot); - } - return snapshot.peek().getDbConnectionName(); - } - - @Override - public java.util.logging.Logger getParentLogger() - throws SQLFeatureNotSupportedException { - return null; - } - - public String getMasterName() { - if(isActive()){ - return getMasterDataSourceName(dsSelector); - } - return ""; - } - - - private String getMasterDataSourceName(AtomicBoolean flipper) { - - LinkedList snapshot = new LinkedList<>(dsQueue); - if(snapshot.size() > 1){ - CachedDataSource first = snapshot.getFirst(); - CachedDataSource last = snapshot.getLast(); - - int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); - if(delta < 0) { - flipper.set(false); - } else if(delta > 0) { - flipper.set(true); - } else { - // check the last value and return !last - flipper.getAndSet(!flipper.get()); - } - - if (flipper.get()) - Collections.reverse(snapshot); - } - return snapshot.peek().getDbConnectionName(); - } + SQLExecutionMonitor monitor = (SQLExecutionMonitor)observable; + if(monitor.getParent() instanceof CachedDataSource) + { + CachedDataSource dataSource = (CachedDataSource)monitor.getParent(); + if(dataSource == dsQueue.peek()) + { + if(recoveryMode && dsQueue.size() > 1){ + handleGetConnectionException(dataSource, new Exception(data.toString())); + } + } + } + } + } + + public void testForceRecovery() + { + CachedDataSource active = this.dsQueue.peek(); + handleGetConnectionException(active, new Exception("test")); + } + + class RecoveryMgr extends Thread { + + @Override + public void run() { + while(!terminating) + { + try { + Thread.sleep(retryInterval); + } catch (InterruptedException e1) { } + CachedDataSource brokenSource = null; + try { + if (!broken.isEmpty()) { + CachedDataSource[] sourceArray = broken.toArray(new CachedDataSource[0]); + for (int i = 0; i < sourceArray.length; i++) + { + brokenSource = sourceArray[i]; + if (brokenSource instanceof TerminatingCachedDataSource) + break; + if (resetConnectionPool(brokenSource)) { + broken.remove(brokenSource); + brokenSource.blockImmediateOffLine(); + dsQueue.add(brokenSource); + LOGGER.info("DataSource <" + + brokenSource.getDbConnectionName() + + "> recovered."); + } + brokenSource = null; + } + } + } catch (Exception exc) { + LOGGER.warn(exc.getMessage()); + if(brokenSource != null){ + try { + if(!broken.contains(brokenSource)) + broken.add(brokenSource); + brokenSource = null; + } catch (Exception e1) { } + } + } + } + LOGGER.info("DBResourceManager.RecoveryMgr <"+this.toString() +"> terminated." ); + } + + private boolean resetConnectionPool(CachedDataSource dataSource){ + try { + return dataSource.testConnection(); + } catch (Exception exc) { + LOGGER.info("DataSource <" + dataSource.getDbConnectionName() + "> resetCache failed with error: "+ exc.getMessage()); + return false; + } + } + } + + /* (non-Javadoc) + * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#getData(java.lang.String, java.util.ArrayList, java.lang.String) + */ + @Override + public CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) throws SQLException { + ArrayList newList= new ArrayList<>(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + if(recoveryMode) + return requestDataWithRecovery(statement, newList, preferredDS); + else + return requestDataNoRecovery(statement, newList, preferredDS); + } + + private CachedRowSet requestDataWithRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { + Throwable lastException = null; + CachedDataSource active = null; + + // test if there are any connection pools available + LinkedList sources = new LinkedList<>(this.dsQueue); + if(sources.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); + } + if(preferredDS != null && !sources.peek().getDbConnectionName().equals(preferredDS)) { + Collections.reverse(sources); + } + + + // loop through available data sources to retrieve data. + while(!sources.isEmpty()) + { + active = sources.peek(); + + long time = System.currentTimeMillis(); + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + master = null; + } + } + sources.remove(active); + return active.getData(statement, arguments); + } catch(SQLDataException | SQLSyntaxErrorException | SQLIntegrityConstraintViolationException exc){ + throw exc; + } catch(Throwable exc){ + lastException = exc; + String message = exc.getMessage(); + if(message == null) { + if(exc.getCause() != null) { + message = exc.getCause().getMessage(); + } + if(message == null) + message = exc.getClass().getName(); + } + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + handleGetConnectionException(active, exc); + if(sources.contains(active)) + sources.remove(active); + } finally { + if(LOGGER.isDebugEnabled()){ + time = System.currentTimeMillis() - time; + LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + if(lastException instanceof SQLException){ + throw (SQLException)lastException; + } + // repackage the exception + // you are here because either you run out of available data sources + // or the last exception was not of SQLException type. + // repackage the exception + if(lastException == null) { + throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); + } else { + SQLException exception = new DBLibException(lastException.getMessage()); + exception.setStackTrace(lastException.getStackTrace()); + if(lastException.getCause() instanceof SQLException) { + throw (SQLException)lastException.getCause(); + } + throw exception; + } + } + + private CachedRowSet requestDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { + if(dsQueue.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + } + CachedDataSource active = this.dsQueue.peek(); + long time = System.currentTimeMillis(); + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) + active = master; + } + return active.getData(statement, arguments); +// } catch(SQLDataException exc){ +// throw exc; + } catch(Throwable exc){ + String message = exc.getMessage(); + if(message == null) + message = exc.getClass().getName(); + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + if(exc instanceof SQLException) + throw (SQLException)exc; + else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } finally { + if(LOGGER.isDebugEnabled()){ + time = System.currentTimeMillis() - time; + LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + + + /* (non-Javadoc) + * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#writeData(java.lang.String, java.util.ArrayList, java.lang.String) + */ + @Override + public boolean writeData(String statement, ArrayList arguments, String preferredDS) throws SQLException + { + ArrayList newList= new ArrayList<>(); + if(arguments != null && !arguments.isEmpty()) { + newList.addAll(arguments); + } + + return writeDataNoRecovery(statement, newList, preferredDS); + } + + CachedDataSource findMaster() throws PoolExhaustedException { + CachedDataSource master = null; + CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); + for(int i=0; i arguments, String preferredDS) throws SQLException { + if(dsQueue.isEmpty()){ + LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + } + + boolean initialRequest = true; + boolean retryAllowed = true; + CachedDataSource active = this.dsQueue.peek(); + long time = System.currentTimeMillis(); + while(initialRequest) { + initialRequest = false; + try { + if(!active.isFabric()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + } + } + + return active.writeData(statement, arguments); + } catch(Throwable exc){ + String message = exc.getMessage(); + if(message == null) + message = exc.getClass().getName(); + LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + if(exc instanceof SQLException) { + SQLException sqlExc = SQLException.class.cast(exc); + // handle read-only exception + if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { + LOGGER.warn("retrying due to: " + sqlExc.getMessage()); + dsQueue.remove(active); + dsQueue.add(active); + if(retryAllowed){ + retryAllowed = false; + initialRequest = true; + continue; + } + } + throw (SQLException)exc; + } else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } finally { + if(LOGGER.isDebugEnabled()){ + time = System.currentTimeMillis() - time; + LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + } + } + } + return true; + } + + public void setDataSource(CachedDataSource dataSource) { + if(this.dsQueue.contains(dataSource)) + return; + if(this.broken.contains(dataSource)) + return; + + if(dataSource.testConnection(true)){ + this.dsQueue.add(dataSource); + } else { + this.broken.add(dataSource); + } + } + + @Override + public Connection getConnection() throws SQLException { + Throwable lastException = null; + CachedDataSource active = null; + + if(dsQueue.isEmpty()){ + throw new DBLibException("No active DB connection pools are available in GetConnection call."); + } + + try { + active = dsQueue.peek(); + CachedDataSource tmpActive = findMaster(); + if(tmpActive != null) { + active = tmpActive; + } + return new DBLibConnection(active.getConnection(), active); + } catch(javax.sql.rowset.spi.SyncFactoryException exc){ + LOGGER.debug("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); + LOGGER.warn("CLASSPATH issue. Allowing retry", exc); + lastException = exc; + } catch(PoolExhaustedException exc) { + throw new NoAvailableConnectionsException(exc); + } catch(Exception exc){ + lastException = exc; + if(recoveryMode){ + handleGetConnectionException(active, exc); + } else { + if(exc instanceof SQLException) { + throw (SQLException)exc; + } else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } + } catch (Throwable trwb) { + DBLibException excptn = new DBLibException(trwb.getMessage()); + excptn.setStackTrace(trwb.getStackTrace()); + throw excptn; + } finally { + if(LOGGER.isDebugEnabled()){ + displayState(); + } + } + + if(lastException instanceof SQLException){ + throw (SQLException)lastException; + } + // repackage the exception + if(lastException == null) { + throw new DBLibException("The operation timed out while waiting to acquire a new connection." ); + } else { + SQLException exception = new DBLibException(lastException.getMessage()); + exception.setStackTrace(lastException.getStackTrace()); + if(lastException.getCause() instanceof SQLException) { +// exception.setNextException((SQLException)lastException.getCause()); + throw (SQLException)lastException.getCause(); + } + throw exception; + } + } + + @Override + public Connection getConnection(String username, String password) + throws SQLException { + CachedDataSource active = null; + + if(dsQueue.isEmpty()){ + throw new DBLibException("No active DB connection pools are available in GetConnection call."); + } + + + try { + active = dsQueue.peek(); + CachedDataSource tmpActive = findMaster(); + if(tmpActive != null) { + active = tmpActive; + } + return active.getConnection(username, password); + } catch(Throwable exc){ + if(recoveryMode){ + handleGetConnectionException(active, exc); + } else { + if(exc instanceof SQLException) + throw (SQLException)exc; + else { + DBLibException excptn = new DBLibException(exc.getMessage()); + excptn.setStackTrace(exc.getStackTrace()); + throw excptn; + } + } + + } + + throw new DBLibException("No connections available in DBResourceManager in GetConnection call."); + } + + private void handleGetConnectionException(CachedDataSource source, Throwable exc) { + try { + if(!source.canTakeOffLine()) + { + LOGGER.error("Could not switch due to blocking"); + return; + } + + boolean removed = dsQueue.remove(source); + if(!broken.contains(source)) + { + if(broken.add(source)) + { + LOGGER.warn("DB Recovery: DataSource <" + source.getDbConnectionName() + "> put in the recovery mode. Reason : " + exc.getMessage()); + } else { + LOGGER.warn("Error putting DataSource <" +source.getDbConnectionName()+ "> in recovery mode."); + } + } else { + LOGGER.info("DB Recovery: DataSource <" + source.getDbConnectionName() + "> already in recovery queue"); + } + if(removed) + { + if(!dsQueue.isEmpty()) + { + LOGGER.warn("DB DataSource <" + dsQueue.peek().getDbConnectionName() + "> became active"); + } + } + } catch (Exception e) { + LOGGER.error("", e); + } + } + + public void cleanUp() { + for(Iterator it=dsQueue.iterator();it.hasNext();){ + CachedDataSource cds = it.next(); + it.remove(); + cds.cleanUp(); + } + + try { + this.terminating = true; + if(broken != null) + { + try { + broken.add( new TerminatingCachedDataSource(null)); + } catch(Exception exc){ + LOGGER.error("Waiting for Worker to stop", exc); + } + } + worker.join(terminationTimeOut); + LOGGER.info("DBResourceManager.RecoveryMgr <"+worker.toString() +"> termination was successful: " + worker.getState()); + } catch(Exception exc){ + LOGGER.error("Waiting for Worker thread to terminate ", exc); + } + } + + @Override + public PrintWriter getLogWriter() throws SQLException { + return this.dsQueue.peek().getLogWriter(); + } + + @Override + public int getLoginTimeout() throws SQLException { + return this.dsQueue.peek().getLoginTimeout(); + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + this.dsQueue.peek().setLogWriter(out); + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + this.dsQueue.peek().setLoginTimeout(seconds); + } + + public void displayState(){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); + CachedDataSource current = dsQueue.peek(); + if(current != null) { + LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); + } + } + } + + /* (non-Javadoc) + * @see org.onap.ccsdk.sli.resource.dblib.DbLibService#isActive() + */ + @Override + public boolean isActive() { + return this.dsQueue.size()>0; + } + + public String getActiveStatus(){ + return "Connected: " + dsQueue.size()+"\tIn-recovery: "+broken.size(); + } + + public String getDBStatus(boolean htmlFormat) { + StringBuilder buffer = new StringBuilder(); + + ArrayList list = new ArrayList<>(); + list.addAll(dsQueue); + list.addAll(broken); + if (htmlFormat) + { + buffer.append("") + .append("Name:").append(""); + for (int i = 0; i < list.size(); i++) { + buffer.append(""); + buffer.append(list.get(i).getDbConnectionName()).append(""); + } + buffer.append(""); + + buffer.append("State:"); + for (int i = 0; i < list.size(); i++) { + if (broken.contains(list.get(i))) { + buffer.append("in recovery"); + } + if (dsQueue.contains(list.get(i))) { + if (dsQueue.peek() == list.get(i)) + buffer.append("active"); + else + buffer.append("standby"); + } + } + buffer.append(""); + + } else { + for (int i = 0; i < list.size(); i++) { + buffer.append("Name: ").append(list.get(i).getDbConnectionName()); + buffer.append("\tState: "); + if (broken.contains(list.get(i))) { + buffer.append("in recovery"); + } else + if (dsQueue.contains(list.get(i))) { + if (dsQueue.peek() == list.get(i)) + buffer.append("active"); + else + buffer.append("standby"); + } + + buffer.append("\n"); + + } + } + return buffer.toString(); + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + /** + * @return the monitorDbResponse + */ + @Override + public final boolean isMonitorDbResponse() { + return recoveryMode && monitorDbResponse; + } + + public void test(){ + CachedDataSource obj = dsQueue.peek(); + Exception ption = new Exception(); + try { + for(int i=0; i<5; i++) + { + handleGetConnectionException(obj, ption); + } + } catch(Throwable exc){ + LOGGER.warn("", exc); + } + } + + public String getPreferredDSName(){ + if(isActive()){ + return getPreferredDataSourceName(dsSelector); + } + return ""; + } + + public String getPreferredDataSourceName(AtomicBoolean flipper) { + + LinkedList snapshot = new LinkedList<>(dsQueue); + if(snapshot.size() > 1){ + CachedDataSource first = snapshot.getFirst(); + CachedDataSource last = snapshot.getLast(); + + int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); + if(delta < 0) { + flipper.set(false); + } else if(delta > 0) { + flipper.set(true); + } else { + // check the last value and return !last + flipper.getAndSet(!flipper.get()); + } + + if (flipper.get()) + Collections.reverse(snapshot); + } + return snapshot.peek().getDbConnectionName(); + } + + @Override + public java.util.logging.Logger getParentLogger() + throws SQLFeatureNotSupportedException { + return null; + } + + public String getMasterName() { + if(isActive()){ + return getMasterDataSourceName(dsSelector); + } + return ""; + } + + + private String getMasterDataSourceName(AtomicBoolean flipper) { + + LinkedList snapshot = new LinkedList<>(dsQueue); + if(snapshot.size() > 1){ + CachedDataSource first = snapshot.getFirst(); + CachedDataSource last = snapshot.getLast(); + + int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); + if(delta < 0) { + flipper.set(false); + } else if(delta > 0) { + flipper.set(true); + } else { + // check the last value and return !last + flipper.getAndSet(!flipper.get()); + } + + if (flipper.get()) + Collections.reverse(snapshot); + } + return snapshot.peek().getDbConnectionName(); + } class RemindTask extends TimerTask { @Override - public void run() { - CachedDataSource ds = dsQueue.peek(); - if(ds != null) - ds.getPoolInfo(false); + public void run() { + CachedDataSource ds = dsQueue.peek(); + if(ds != null) + ds.getPoolInfo(false); } } - public int poolSize() { - return dsQueue.size(); - } + public int poolSize() { + return dsQueue.size(); + } } diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java old mode 100644 new mode 100755 index 3e438d1a9..5e87412a5 --- a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/EnvVarFileResolver.java @@ -27,7 +27,7 @@ import java.nio.file.Paths; import java.util.Optional; /** - * Resolves dblib properties files relative to the directory identified by the SDNC_CONFIG_DIR + * Resolves properties files relative to the directory identified by the SDNC_CONFIG_DIR * environment variable. */ public abstract class EnvVarFileResolver implements PropertiesFileResolver { diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java old mode 100644 new mode 100755 index 5cd6c3606..844c6949c --- a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java @@ -23,13 +23,15 @@ package org.onap.ccsdk.sli.core.utils; import java.io.File; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.FileSystemNotFoundException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import org.osgi.framework.FrameworkUtil; +import org.slf4j.LoggerFactory; /** - * Resolves dblib properties files relative to the directory identified by the JRE property + * Resolves project properties files relative to the directory identified by the JRE property * dblib.properties. */ public class JREFileResolver implements PropertiesFileResolver { @@ -37,7 +39,6 @@ public class JREFileResolver implements PropertiesFileResolver { /** * Key for JRE argument representing the configuration directory */ - private static final String DBLIB_JRE_PROPERTY_KEY = "dblib.properties"; private final String successMessage; private final Class clazz; @@ -55,14 +56,15 @@ public class JREFileResolver implements PropertiesFileResolver { @Override public Optional resolveFile(final String filename) { final URL jreArgumentUrl = FrameworkUtil.getBundle(this.clazz) - .getResource(DBLIB_JRE_PROPERTY_KEY); + .getResource(filename); try { if (jreArgumentUrl == null) { return Optional.empty(); } final Path dblibPath = Paths.get(jreArgumentUrl.toURI()); return Optional.of(dblibPath.resolve(filename).toFile()); - } catch(final URISyntaxException e) { + } catch(final URISyntaxException | FileSystemNotFoundException e) { + LoggerFactory.getLogger(this.getClass()).error("", e); return Optional.empty(); } } diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/BundleContextFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/BundleContextFileResolver.java new file mode 100755 index 000000000..9496d90e2 --- /dev/null +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/BundleContextFileResolver.java @@ -0,0 +1,80 @@ +/*- + * ============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.utils.common; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Optional; + +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; +import org.osgi.framework.FrameworkUtil; +import org.slf4j.LoggerFactory; + +import com.google.common.base.Strings; + +/** + * Resolves properties files from runtime property value SDNC_CONFIG_DIR defined in the osgi properties. + */ +public class BundleContextFileResolver implements PropertiesFileResolver { + + /** + * Key for osgi variable representing the configuration directory + */ + private static final String SDNC_CONFIG_DIR_PROP_KEY = "SDNC_CONFIG_DIR"; + + private final String successMessage; + private final Class clazz; + + public BundleContextFileResolver(final String successMessage, final Class clazz) { + this.successMessage = successMessage; + this.clazz = clazz; + } + + /** + * 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 filename) { + if(FrameworkUtil.getBundle(clazz) == null) { + return Optional.empty(); + } else { + try { + final String pathProperty = FrameworkUtil.getBundle(this.clazz).getBundleContext().getProperty(SDNC_CONFIG_DIR_PROP_KEY); + if(Strings.isNullOrEmpty(pathProperty)) { + return Optional.empty(); + } + final Path dblibPath = Paths.get(pathProperty); + return Optional.of(dblibPath.resolve(filename).toFile()); + } catch(final Exception e) { + LoggerFactory.getLogger(this.getClass()).error("", e); + return Optional.empty(); + } + } + } + + @Override + public String getSuccessfulResolutionMessage() { + return this.successMessage; + } +} diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolver.java new file mode 100755 index 000000000..4d7e90261 --- /dev/null +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolver.java @@ -0,0 +1,41 @@ +/*- + * ============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.utils.common; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.onap.ccsdk.sli.core.utils.DefaultFileResolver; + +/** + * Resolve properties file location based on the default directory name. + */ +public class CoreDefaultFileResolver extends DefaultFileResolver { + + /** + * Default path to look for the configuration directory + */ + private static final Path DEFAULT_DBLIB_PROP_DIR = Paths.get("/opt", "sdnc", "data", "properties"); + + public CoreDefaultFileResolver(final String successMessage) { + super(successMessage, DEFAULT_DBLIB_PROP_DIR); + } +} diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolver.java new file mode 100755 index 000000000..51b6134f7 --- /dev/null +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolver.java @@ -0,0 +1,38 @@ +/*- + * ============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.utils.common; + +import org.onap.ccsdk.sli.core.utils.EnvVarFileResolver; + +/** + * Resolve properties file location based on the default directory name. + */ +public class SdncConfigEnvVarFileResolver extends EnvVarFileResolver { + + /** + * Key for environment variable representing the configuration directory + */ + private static final String SDNC_CONFIG_DIR_PROP_KEY = "SDNC_CONFIG_DIR"; + + public SdncConfigEnvVarFileResolver(final String successMessage) { + super(successMessage, SDNC_CONFIG_DIR_PROP_KEY); + } +} diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java old mode 100644 new mode 100755 index 56b4ca1b6..082bdf403 --- a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibDefaultFileResolver.java @@ -4,12 +4,20 @@ import java.nio.file.Path; import java.nio.file.Paths; import org.onap.ccsdk.sli.core.utils.DefaultFileResolver; +/** + * Resolve properties file location based on the default directory name. + * + * @deprecated + * This class has been replaced by generic version of this class + * {@link #CoreDefaultFileResolver} in common package. + */ +@Deprecated public class DblibDefaultFileResolver extends DefaultFileResolver { /** * Default path to look for the configuration directory */ - private static final Path DEFAULT_DBLIB_PROP_DIR = Paths.get("opt", "sdnc", "data", "properties"); + private static final Path DEFAULT_DBLIB_PROP_DIR = Paths.get("/opt", "sdnc", "data", "properties"); public DblibDefaultFileResolver(final String successMessage) { super(successMessage, DEFAULT_DBLIB_PROP_DIR); diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java index 9eef4cee2..959271cb7 100644 --- a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/dblib/DblibEnvVarFileResolver.java @@ -2,6 +2,14 @@ package org.onap.ccsdk.sli.core.utils.dblib; import org.onap.ccsdk.sli.core.utils.EnvVarFileResolver; +/** + * Resolve properties file location based on the default directory name. + * + * @deprecated + * This class has been replaced by generic version of this class + * {@link #SdncConfigEnvVarFileResolver} in common package. + */ +@Deprecated public class DblibEnvVarFileResolver extends EnvVarFileResolver { /** diff --git a/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/BundleContexFileResolverTest.java b/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/BundleContexFileResolverTest.java new file mode 100644 index 000000000..4ec5e1b48 --- /dev/null +++ b/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/BundleContexFileResolverTest.java @@ -0,0 +1,16 @@ +package org.onap.ccsdk.sli.core.utils.common; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; + +public class BundleContexFileResolverTest { + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new BundleContextFileResolver("success", BundleContexFileResolverTest.class); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolverTest.java b/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolverTest.java new file mode 100644 index 000000000..a4f8817fa --- /dev/null +++ b/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/CoreDefaultFileResolverTest.java @@ -0,0 +1,25 @@ +package org.onap.ccsdk.sli.core.utils.common; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; + +public class CoreDefaultFileResolverTest { + + @Test + public void resolveFile() throws Exception { + final PropertiesFileResolver resolver = new CoreDefaultFileResolver("success"); + final Optional file = resolver.resolveFile("doesnotexist.cfg"); + assertFalse(file.isPresent()); + } + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new CoreDefaultFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file diff --git a/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolverTest.java b/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolverTest.java new file mode 100644 index 000000000..0f3536b78 --- /dev/null +++ b/utils/provider/src/test/java/org/onap/ccsdk/sli/core/utils/common/SdncConfigEnvVarFileResolverTest.java @@ -0,0 +1,24 @@ +package org.onap.ccsdk.sli.core.utils.common; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Optional; +import org.junit.Test; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; + +public class SdncConfigEnvVarFileResolverTest { + @Test + public void resolveFile() throws Exception { + final PropertiesFileResolver resolver = new SdncConfigEnvVarFileResolver("success"); + final Optional file = resolver.resolveFile("doesnotexist.cfg"); + assertFalse(file.isPresent()); + } + + @Test + public void getSuccessfulResolutionMessage() throws Exception { + final PropertiesFileResolver resolver = new SdncConfigEnvVarFileResolver("success"); + assertEquals("success", resolver.getSuccessfulResolutionMessage()); + } + +} \ No newline at end of file -- cgit 1.2.3-korg From 131cb46f6109a6099a445cb8e1b12ff5b68ae6de Mon Sep 17 00:00:00 2001 From: Dan Timoney Date: Thu, 1 Feb 2018 16:57:00 -0500 Subject: Upgrade sli/core to Nitrogen Use Apache derby for dblib SingleFeatureTest Change-Id: I6b41f7ede1a98b33824fceea9100e75c1ce8dda4 Issue-ID: CCSDK-175 Signed-off-by: Dan Timoney Generalization of CCSDK core/utils framework Changes made: * Created generalized version of core/utils/dblib as core/utils/common * Deprecated core/utils/dblib package Change-Id: I0992c43910278fbe254674d1e39d7e4fcad0a592 Issue-ID: CCSDK-168 Signed-off-by: Rich Tabedzki Use Apache derby for dblib test Use Apache derby for dblib SingleFeatureTest Change-Id: Ie497557f162e203fa5c5c82c17ddc55ba0c11b38 Issue-ID: CCSDK-175 Signed-off-by: Dan Timoney --- dblib/features/ccsdk-dblib/pom.xml | 96 ++ .../ccsdk-dblib/src/main/feature/feature.xml | 14 + dblib/features/features-dblib/pom.xml | 29 + dblib/features/pom.xml | 143 +-- dblib/features/src/main/resources/features.xml | 18 - dblib/installer/pom.xml | 268 +++--- dblib/pom.xml | 87 +- dblib/provider/pom.xml | 90 +- .../ccsdk/sli/core/dblib/CachedDataSource.java | 1008 ++++++++++---------- dblib/provider/src/main/resources/dblib.properties | 7 +- filters/features/ccsdk-filters/pom.xml | 61 ++ filters/features/features-filters/pom.xml | 29 + filters/features/pom.xml | 105 +- filters/features/src/main/resources/features.xml | 32 - filters/installer/pom.xml | 23 +- filters/pom.xml | 87 +- filters/provider/pom.xml | 126 ++- pom.xml | 92 +- sli/common/pom.xml | 289 +++--- .../ccsdk/sli/core/sli/SvcLogicDblibStore.java | 42 +- sli/features/features-sli/pom.xml | 29 + sli/features/odl-sli/pom.xml | 86 ++ sli/features/pom.xml | 161 +--- sli/features/src/main/resources/features.xml | 39 - sli/installer/pom.xml | 25 +- sli/model/pom.xml | 89 +- sli/pom.xml | 61 +- sli/provider/pom.xml | 186 +--- .../sli/core/sli/provider/CallNodeExecutor.java | 38 +- .../sli/core/sli/provider/SvcLogicActivator.java | 181 ---- .../core/sli/provider/SvcLogicNodeExecutor.java | 21 +- .../sli/provider/SvcLogicPropertiesProvider.java | 188 ++++ .../sli/core/sli/provider/SvcLogicServiceImpl.java | 55 +- .../org/opendaylight/blueprint/sli-blueprint.xml | 21 + .../src/main/resources/svclogic.properties | 25 + .../core/sli/provider/ExecuteNodeExecutorTest.java | 7 +- .../sli/provider/ITCaseSvcLogicGraphExecutor.java | 7 +- .../src/test/resources/svclogic.properties | 11 +- sli/recording/pom.xml | 71 +- .../features/ccsdk-sliPluginUtils/pom.xml | 65 ++ .../features/features-sliPluginUtils/pom.xml | 29 + sliPluginUtils/features/pom.xml | 130 +-- .../features/src/main/resources/features.xml | 38 - sliPluginUtils/installer/pom.xml | 23 +- sliPluginUtils/pom.xml | 38 +- sliPluginUtils/provider/pom.xml | 47 +- .../slipluginutils/Dme2PropertiesProvider.java | 421 ++++---- .../provider/src/main/resources/dme2.properties | 7 + sliapi/features/ccsdk-sliapi/pom.xml | 60 ++ sliapi/features/features-sliapi/pom.xml | 29 + sliapi/features/pom.xml | 139 +-- sliapi/features/src/main/resources/features.xml | 39 - sliapi/installer/pom.xml | 24 +- .../src/assembly/assemble_mvnrepo_zip.xml | 10 +- sliapi/model/pom.xml | 78 +- sliapi/pom.xml | 56 +- sliapi/provider/pom.xml | 116 +-- .../onap/ccsdk/sli/core/sliapi/sliapiProvider.java | 17 +- .../impl/rev140523/SliapiProviderModule.java | 64 -- .../rev140523/SliapiProviderModuleFactory.java | 34 - .../src/main/resources/initial/sliapi-provider.xml | 70 -- .../opendaylight/blueprint/sliapi-blueprint.xml | 28 + utils/features/features-util/pom.xml | 29 + utils/features/features3-util/pom.xml | 141 +++ .../features3-util/src/main/resources/features.xml | 16 + utils/features/pom.xml | 146 +-- utils/features/sdnc-slicore-utils/pom.xml | 52 + utils/features/src/main/resources/features.xml | 16 - utils/installer/pom.xml | 25 +- utils/pom.xml | 87 +- utils/provider/pom.xml | 35 +- .../onap/ccsdk/sli/core/utils/JREFileResolver.java | 7 +- 72 files changed, 2728 insertions(+), 3335 deletions(-) create mode 100644 dblib/features/ccsdk-dblib/pom.xml create mode 100644 dblib/features/ccsdk-dblib/src/main/feature/feature.xml create mode 100644 dblib/features/features-dblib/pom.xml delete mode 100755 dblib/features/src/main/resources/features.xml create mode 100644 filters/features/ccsdk-filters/pom.xml create mode 100644 filters/features/features-filters/pom.xml delete mode 100644 filters/features/src/main/resources/features.xml create mode 100644 sli/features/features-sli/pom.xml create mode 100644 sli/features/odl-sli/pom.xml mode change 100755 => 100644 sli/features/pom.xml delete mode 100644 sli/features/src/main/resources/features.xml delete mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java create mode 100644 sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicPropertiesProvider.java create mode 100755 sli/provider/src/main/resources/org/opendaylight/blueprint/sli-blueprint.xml create mode 100644 sli/provider/src/main/resources/svclogic.properties create mode 100644 sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml create mode 100644 sliPluginUtils/features/features-sliPluginUtils/pom.xml delete mode 100644 sliPluginUtils/features/src/main/resources/features.xml create mode 100644 sliPluginUtils/provider/src/main/resources/dme2.properties create mode 100644 sliapi/features/ccsdk-sliapi/pom.xml create mode 100644 sliapi/features/features-sliapi/pom.xml delete mode 100644 sliapi/features/src/main/resources/features.xml delete mode 100644 sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModule.java delete mode 100644 sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModuleFactory.java delete mode 100644 sliapi/provider/src/main/resources/initial/sliapi-provider.xml create mode 100644 sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml create mode 100644 utils/features/features-util/pom.xml create mode 100755 utils/features/features3-util/pom.xml create mode 100755 utils/features/features3-util/src/main/resources/features.xml create mode 100644 utils/features/sdnc-slicore-utils/pom.xml delete mode 100755 utils/features/src/main/resources/features.xml (limited to 'dblib/provider/src') diff --git a/dblib/features/ccsdk-dblib/pom.xml b/dblib/features/ccsdk-dblib/pom.xml new file mode 100644 index 000000000..8cf1c93f3 --- /dev/null +++ b/dblib/features/ccsdk-dblib/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + single-feature-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + ccsdk-dblib + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: dblib :: ${project.artifactId} + + + + + org.opendaylight.mdsal.model + mdsal-model-artifacts + 0.11.1 + pom + import + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.opendaylight.controller + odl-mdsal-broker + xml + features + + + + ${project.groupId} + dblib-provider + ${project.version} + + + + org.mariadb.jdbc + mariadb-java-client + ${mariadb.connector.version} + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + org.onap.ccsdk.sli.core + utils-provider + ${project.version} + + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + provided + + + org.apache.derby + derby + 10.11.1.1 + + + + + + + org.apache.karaf.tooling + karaf-maven-plugin + true + + + slf4j-api + tomcat-jdbc + tomcat-juli + + + + + + diff --git a/dblib/features/ccsdk-dblib/src/main/feature/feature.xml b/dblib/features/ccsdk-dblib/src/main/feature/feature.xml new file mode 100644 index 000000000..514ce8de4 --- /dev/null +++ b/dblib/features/ccsdk-dblib/src/main/feature/feature.xml @@ -0,0 +1,14 @@ + + + mvn:org.opendaylight.controller/odl-mdsal-broker/1.6.1/xml/features + +
    Root POM to be used in place of odlparent for CCSDK based projects
    + odl-mdsal-broker + wrap + mvn:org.onap.ccsdk.sli.core/dblib-provider/${project.version} + mvn:org.mariadb.jdbc/mariadb-java-client/2.1.1 + wrap:mvn:org.apache.tomcat/tomcat-jdbc/8.5.14/$DynamicImport-Package=org.mariadb.*,org.apache.derby.*&overwrite=merge + wrap:mvn:org.apache.tomcat/tomcat-juli/8.5.14/$DynamicImport-Package=org.mariadb.*,org.apache.derby.*&overwrite=merge + mvn:org.onap.ccsdk.sli.core/utils-provider/${project.version} +
    +
    diff --git a/dblib/features/features-dblib/pom.xml b/dblib/features/features-dblib/pom.xml new file mode 100644 index 000000000..b7c2150dd --- /dev/null +++ b/dblib/features/features-dblib/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + feature-repo-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + features-dblib + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: dblib :: ${project.artifactId} + + + + ${project.groupId} + ccsdk-dblib + ${project.version} + xml + features + + + + diff --git a/dblib/features/pom.xml b/dblib/features/pom.xml index e9cb6dd0b..18f087397 100755 --- a/dblib/features/pom.xml +++ b/dblib/features/pom.xml @@ -1,138 +1,23 @@ 4.0.0 + - dblib - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - dblib-features - DBLIB Adaptor - Features - - jar - - - - - - org.onap.ccsdk.sli.core - dblib-provider - ${project.version} - - - - commons-lang - commons-lang - ${commons.lang.version} - compile - - - - org.opendaylight.mdsal - features-mdsal - ${odl.mdsal.features.version} - features - xml - - runtime - - - - org.apache.tomcat - tomcat-jdbc - ${tomcat-jdbc.version} - - - - - org.opendaylight.odlparent - opendaylight-karaf-empty - ${odl.karaf.empty.distro.version} - zip - - - - - org.opendaylight.odlparent - features-test - ${odl.commons.opendaylight.version} - test - - - org.opendaylight.yangtools - features-yangtools - ${odl.yangtools.version} - features - xml - runtime - - + org.onap.ccsdk.sli.core + dblib-feature-aggregator + 0.2.1-SNAPSHOT + pom - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - + + features-dblib + ccsdk-dblib + diff --git a/dblib/features/src/main/resources/features.xml b/dblib/features/src/main/resources/features.xml deleted file mode 100755 index aa31db751..000000000 --- a/dblib/features/src/main/resources/features.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features - - - - - odl-mdsal-broker - wrap:mvn:org.apache.tomcat/tomcat-jdbc/${tomcat-jdbc.version}/$DynamicImport-Package=org.mariadb.*&overwrite=merge - mvn:org.onap.ccsdk.sli.core/dblib-provider/${project.version} - mvn:org.mariadb.jdbc/mariadb-java-client/${mariadb.connector.version} - - - diff --git a/dblib/installer/pom.xml b/dblib/installer/pom.xml index bff158011..8d6147b72 100755 --- a/dblib/installer/pom.xml +++ b/dblib/installer/pom.xml @@ -1,143 +1,149 @@ - - 4.0.0 - - dblib - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT - - dblib-installer - DBLIB Adaptor - Karaf Installer - pom + + 4.0.0 - - sdnc-dblib - sdnc-dblib - mvn:org.onap.ccsdk.sli.core/dblib-features/${project.version}/xml/features - false - + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + - + org.onap.ccsdk.sli.core + dblib-installer + 0.2.1-SNAPSHOT + pom - - org.onap.ccsdk.sli.core - dblib-features - ${project.version} - features - xml - - - * - * - - - + ccsdk-sli-core :: dblib :: ${project.artifactId} - - org.onap.ccsdk.sli.core - dblib-provider - ${project.version} - + + ccsdk-dblib + ${application.name} + mvn:org.onap.ccsdk.sli.core/${features.boot}/${project.version}/xml/features + false + + - - org.apache.tomcat - tomcat-jdbc - ${tomcat-jdbc.version} - - + + org.onap.ccsdk.sli.core + ${application.name} + ${project.version} + xml + features + + + * + * + + + - - - - maven-assembly-plugin - - - maven-repo-zip - - single - - package - - false - stage/${application.name}-${project.version} - - src/assembly/assemble_mvnrepo_zip.xml - - false - - - - installer-zip - - single - - package - - true - ${application.name}-${project.version}-installer - - src/assembly/assemble_installer_zip.xml - - false - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - - copy-dependencies - - prepare-package - - false - ${project.build.directory}/assembly/system - false - true - true - true - false - false - org.onap.ccsdk.sli,org.apache.tomcat - sli-common,sli-provider - provided - - - - - - maven-resources-plugin - 2.6 - - - copy-version - - copy-resources - - validate - - ${basedir}/target/stage - - - src/main/resources/scripts - - install-feature.sh - - true - - - - + + org.onap.ccsdk.sli.core + dblib-provider + ${project.version} + - - - - + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + + + + maven-assembly-plugin + + + maven-repo-zip + + single + + package + + false + stage/${application.name}-${project.version} + + src/assembly/assemble_mvnrepo_zip.xml + + false + + + + installer-zip + + single + + package + + true + ${application.name}-${project.version}-installer + + src/assembly/assemble_installer_zip.xml + + false + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + + copy-dependencies + + prepare-package + + false + ${project.build.directory}/assembly/system + false + true + true + true + false + false + org.onap.ccsdk.sli,org.apache.tomcat + sli-common,sli-provider + provided + + + + + + maven-resources-plugin + 2.6 + + + copy-version + + copy-resources + + validate + + ${basedir}/target/stage + + + src/main/resources/scripts + + install-feature.sh + + true + + + + + + + + + + diff --git a/dblib/pom.xml b/dblib/pom.xml index e7743d81c..58f40ff69 100755 --- a/dblib/pom.xml +++ b/dblib/pom.xml @@ -1,77 +1,26 @@ - - - org.onap.ccsdk.sli.core - ccsdk-sli-core - 0.2.0-SNAPSHOT + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + org.onap.ccsdk.sli.core + dblib + 0.2.1-SNAPSHOT + pom - 4.0.0 - pom - org.onap.ccsdk.sli.core - dblib - - - DBLIB Adaptor - The DBLIB adaptor allows service logic to access persistent data in a local sql database - - 0.2.0-SNAPSHOT - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compile.plugin.version} - - ${java.version.source} - ${java.version.target} - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10 - - - - aggregate - - aggregate - - site - - - - - - maven-source-plugin - 2.1.1 - - - bundle-sources - package - - - jar-no-fork - - - test-jar-no-fork - - - - - - - - - - AT&T + ccsdk-sli-core :: dblib + The DBLIB adaptor allows service logic to access persistent data in a local sql database + + ONAP - + + provider features installer diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index 3bdd7e67b..e6fd1bcb1 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -1,19 +1,27 @@ - + 4.0.0 + - org.onap.ccsdk.sli.core - dblib - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core dblib-provider - 0.2.0-SNAPSHOT + 0.2.1-SNAPSHOT bundle - DBLIB Adaptor - Provider + + ccsdk-sli-core :: dblib :: ${project.artifactId} http://maven.apache.org + UTF-8 + junit @@ -21,12 +29,12 @@ ${junit.version} test - - ch.vorburger.mariaDB4j - mariaDB4j - 2.2.3 - test - + + ch.vorburger.mariaDB4j + mariaDB4j + 2.2.3 + test + equinoxSDK381 org.eclipse.osgi @@ -48,53 +56,31 @@ ${slf4j.version} test - - org.mariadb.jdbc - mariadb-java-client - ${mariadb.connector.version} - - org.apache.tomcat - tomcat-jdbc - ${tomcat-jdbc.version} + org.mariadb.jdbc + mariadb-java-client + ${mariadb.connector.version} + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + com.google.guava + guava - - com.google.guava - guava - org.onap.ccsdk.sli.core utils-provider ${project.version} - - - org.mockito - mockito-core - test - + + + org.mockito + mockito-core + test + - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.onap.ccsdk.sli.core.dblib - org.onap.ccsdk.sli.core.dblib;version=${project.version} - *,org.mariadb.jdbc - true - - - - - - - - diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index d2331786e..8dac33611 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -56,500 +56,516 @@ import org.slf4j.LoggerFactory; public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver { - private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); - - private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; - private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; - private static final String WITH_ARGUMENTS = " with arguments: "; - private static final String WITH_NO_ARGUMENTS = " with no arguments. "; - private static final String SQL_DATA_SOURCE = "SQL DataSource <"; - - - protected long connReqTimeout = 30L; - protected long dataReqTimeout = 100L; - - private final SQLExecutionMonitor monitor; - protected DataSource ds = null; - protected String connectionName = null; - protected boolean initialized = false; - - private long interval = 1000; - private long initialDelay = 5000; - private long expectedCompletionTime = 50L; - private boolean canTakeOffLine = true; - private long unprocessedFailoverThreshold = 3L; - - private long nextErrorReportTime = 0L; - - private String globalHostName = null; - - - public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { - configure(jdbcElem); - monitor = new SQLExecutionMonitor(this); - } - - protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; - - /* (non-Javadoc) - * @see javax.sql.DataSource#getConnection() - */ - @Override - public Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - public CachedRowSet getData(String statement, List arguments) - throws SQLException { - TestObject testObject = monitor.registerRequest(); - - try (Connection connection = this.getConnection()) { - if (connection == null) { - throw new SQLException("Connection invalid"); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); - } - return executePreparedStatement(connection, statement, arguments, true); - } finally { - monitor.deregisterRequest(testObject); - } - } - - public boolean writeData(String statement, List arguments) - throws SQLException { - TestObject testObject = monitor.registerRequest(); - - try (Connection connection = this.getConnection()) { - if (connection == null) { - throw new SQLException("Connection invalid"); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); - } - return executeUpdatePreparedStatement(connection, statement, arguments, true); - } finally { - monitor.deregisterRequest(testObject); - } - } - - CachedRowSet executePreparedStatement(Connection conn, String statement, - List arguments, boolean close) throws SQLException { - long time = System.currentTimeMillis(); - - CachedRowSet data = null; - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL Statement: {}", statement); - if (arguments != null && !arguments.isEmpty()) { - LOGGER.debug("Argunments: {}", arguments); - } - } - - ResultSet rs = null; - try (PreparedStatement ps = conn.prepareStatement(statement)) { - data = RowSetProvider.newFactory().createCachedRowSet(); - if (arguments != null) { - for (int i = 0, max = arguments.size(); i < max; i++) { - ps.setObject(i + 1, arguments.get(i)); - } - } - rs = ps.executeQuery(); - data.populate(rs); - // Point the rowset Cursor to the start - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), (System.currentTimeMillis() - - time)); - } - } catch (SQLException exc) { - handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); - } finally { - handleFinallyBlockForExecutePreparedStatement(rs, conn, close); - } - - return data; - } - - private void handleSqlExceptionForExecuteStatement(Connection conn, String statement, - List arguments, SQLException exc, long time) throws SQLException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(SQL_FAILURE + (System.currentTimeMillis() - time)); - } - try { - conn.rollback(); - } catch (Exception thr) { - LOGGER.error(thr.getLocalizedMessage(), thr); - } - if (arguments != null && !arguments.isEmpty()) { - LOGGER.error(String.format("<%s%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_ARGUMENTS, - arguments), exc); - } else { - LOGGER.error(String.format("<%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_NO_ARGUMENTS), - exc); - } - throw exc; - } - - private void handleFinallyBlockForExecutePreparedStatement(ResultSet rs, Connection conn, boolean close) { - try { - if (rs != null) { - rs.close(); - } - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } - try { - if (conn != null && close) { - conn.close(); - } - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } - } - - boolean executeUpdatePreparedStatement(Connection conn, String statement, List arguments, - boolean close) throws SQLException { - long time = System.currentTimeMillis(); - - CachedRowSet data; - - try (PreparedStatement ps = conn.prepareStatement(statement)) { - data = RowSetProvider.newFactory().createCachedRowSet(); - if (arguments != null) { - prepareStatementForExecuteUpdate(arguments, ps); - } - ps.executeUpdate(); - // Point the rowset Cursor to the start - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), (System.currentTimeMillis() - - time)); - } - ps.close(); - } catch (SQLException exc) { - handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); - } finally { - try { - if (close) { - conn.close(); - } - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } - } - - return true; - } - - private void prepareStatementForExecuteUpdate(List arguments, PreparedStatement ps) - throws SQLException { - for (int i = 0, max = arguments.size(); i < max; i++) { - Object value = arguments.get(i); - if (value instanceof Blob) { - ps.setBlob(i + 1, (Blob) value); - } else if (value instanceof Timestamp) { - ps.setTimestamp(i + 1, (Timestamp) value); - } else if (value instanceof Integer) { - ps.setInt(i + 1, (Integer) value); - } else if (value instanceof Long) { - ps.setLong(i + 1, (Long) value); - } else if (value instanceof Date) { - ps.setDate(i + 1, (Date) value); - } else { - ps.setObject(i + 1, value); - } - } - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ - @Override - public Connection getConnection(String username, String password) - throws SQLException { - return ds.getConnection(username, password); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getLogWriter() - */ - @Override - public PrintWriter getLogWriter() throws SQLException { - return ds.getLogWriter(); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#getLoginTimeout() - */ - @Override - public int getLoginTimeout() throws SQLException { - return ds.getLoginTimeout(); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) - */ - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - ds.setLogWriter(out); - } - - /* (non-Javadoc) - * @see javax.sql.DataSource#setLoginTimeout(int) - */ - @Override - public void setLoginTimeout(int seconds) throws SQLException { - ds.setLoginTimeout(seconds); - } - - - @Override - public final String getDbConnectionName() { - return connectionName; - } - - protected final void setDbConnectionName(String name) { - this.connectionName = name; - } - - public void cleanUp() { - if (ds != null && ds instanceof Closeable) { - try { - ((Closeable) ds).close(); - } catch (IOException e) { - LOGGER.warn(e.getMessage()); - } - } - ds = null; - monitor.deleteObservers(); - monitor.cleanup(); - } - - public boolean isInitialized() { - return initialized; - } - - protected boolean testConnection() { - return testConnection(false); - } - - protected boolean testConnection(boolean errorLevel) { - ResultSet rs = null; - try (Connection conn = this.getConnection(); Statement stmt = conn.createStatement()) { - Boolean readOnly; - String hostname; - rs = stmt.executeQuery( - "SELECT @@global.read_only, @@global.hostname"); //("SELECT 1 FROM DUAL"); //"select BANNER from SYS.V_$VERSION" - while (rs.next()) { - readOnly = rs.getBoolean(1); - hostname = rs.getString(2); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - SQL_DATA_SOURCE + getDbConnectionName() + "> connected to " + hostname + ", read-only is " - + readOnly + ", tested successfully "); - } - } - } catch (Exception exc) { - if (errorLevel) { - LOGGER.error( - SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } else { - LOGGER.info( - SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } - return false; - } finally { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - LOGGER.error(e.getLocalizedMessage(), e); - } - } - } - return true; - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - @SuppressWarnings("deprecation") - public void setConnectionCachingEnabled(boolean state) { -// if(ds != null && ds instanceof OracleDataSource) -// try { -// ((OracleDataSource)ds).setConnectionCachingEnabled(true); -// } catch (SQLException exc) { -// LOGGER.warn("", exc); -// } - } - - public void addObserver(Observer observer) { - monitor.addObserver(observer); - } - - public void deleteObserver(Observer observer) { - monitor.deleteObserver(observer); - } - - @Override - public long getInterval() { - return interval; - } - - @Override - public long getInitialDelay() { - return initialDelay; - } - - @Override - public void setInterval(long value) { - interval = value; - } - - @Override - public void setInitialDelay(long value) { - initialDelay = value; - } - - @Override - public long getExpectedCompletionTime() { - return expectedCompletionTime; - } - - @Override - public void setExpectedCompletionTime(long value) { - expectedCompletionTime = value; - } - - @Override - public long getUnprocessedFailoverThreshold() { - return unprocessedFailoverThreshold; - } - - @Override - public void setUnprocessedFailoverThreshold(long value) { - this.unprocessedFailoverThreshold = value; - } - - public boolean canTakeOffLine() { - return canTakeOffLine; - } - - public void blockImmediateOffLine() { - canTakeOffLine = false; - final Thread offLineTimer = new Thread(() -> { - try { - Thread.sleep(30000L); - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } finally { - canTakeOffLine = true; - } - }); - offLineTimer.setDaemon(true); - offLineTimer.start(); - } - - /** - * @return the monitor - */ - final SQLExecutionMonitor getMonitor() { - return monitor; - } - - protected boolean isSlave() throws PoolExhaustedException { - CachedRowSet rs; - boolean isSlave; - String hostname = "UNDETERMINED"; - try { - boolean localSlave = true; - rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList<>()); - while (rs.next()) { - localSlave = rs.getBoolean(1); - hostname = rs.getString(2); - } - isSlave = localSlave; - } catch (PoolExhaustedException peexc) { - throw peexc; - } catch (Exception e) { - LOGGER.error("", e); - isSlave = true; - } - if (isSlave) { - LOGGER.debug("SQL SLAVE : {} on server {}", connectionName, hostname); - } else { - LOGGER.debug("SQL MASTER : {} on server {}", connectionName, hostname); - } - return isSlave; - } - - public boolean isFabric() { - return false; - } - - protected boolean lockTable(Connection conn, String tableName) { - boolean retValue = false; - String query = "LOCK TABLES " + tableName + " WRITE"; - try (Statement preStmt = conn.createStatement(); Statement lock = conn.prepareStatement(query); - ResultSet rs = preStmt.executeQuery("GETDATE()")) { - if (tableName != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); - if ("SVC_LOGIC".equals(tableName)) { - Exception e = new Exception(); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - LOGGER.debug(sw.toString()); - } - } - lock.execute(query); - retValue = true; - } - } catch (Exception exc) { - LOGGER.error("", exc); - retValue = false; - } - return retValue; - } - - protected boolean unlockTable(Connection conn) { - boolean retValue; - try (Statement lock = conn.createStatement()) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'UNLOCK TABLES' on connection {}", conn); - } - retValue = lock.execute("UNLOCK TABLES"); - } catch (Exception exc) { - LOGGER.error("", exc); - retValue = false; - } - return retValue; - } - - public void getPoolInfo(boolean allocation) { - - } - - public long getNextErrorReportTime() { - return nextErrorReportTime; - } - - public void setNextErrorReportTime(long nextTime) { - this.nextErrorReportTime = nextTime; - } - - public void setGlobalHostName(String hostname) { - this.globalHostName = hostname; - } - - public String getGlobalHostName() { - return globalHostName; - } + private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); + + private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; + private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; + private static final String WITH_ARGUMENTS = " with arguments: "; + private static final String WITH_NO_ARGUMENTS = " with no arguments. "; + private static final String SQL_DATA_SOURCE = "SQL DataSource <"; + + protected long connReqTimeout = 30L; + protected long dataReqTimeout = 100L; + + private final SQLExecutionMonitor monitor; + protected DataSource ds = null; + protected String connectionName = null; + protected boolean initialized = false; + + private long interval = 1000; + private long initialDelay = 5000; + private long expectedCompletionTime = 50L; + private boolean canTakeOffLine = true; + private long unprocessedFailoverThreshold = 3L; + + private long nextErrorReportTime = 0L; + + private String globalHostName = null; + + private boolean isDerby = false; + + public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { + configure(jdbcElem); + + if ("org.apache.derby.jdbc.EmbeddedDriver".equals(jdbcElem.getDriverName())) { + isDerby = true; + } + monitor = new SQLExecutionMonitor(this); + } + + protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getConnection() + */ + @Override + public Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + public CachedRowSet getData(String statement, List arguments) throws SQLException { + TestObject testObject = monitor.registerRequest(); + + try (Connection connection = this.getConnection()) { + if (connection == null) { + throw new SQLException("Connection invalid"); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); + } + return executePreparedStatement(connection, statement, arguments, true); + } finally { + monitor.deregisterRequest(testObject); + } + } + + public boolean writeData(String statement, List arguments) throws SQLException { + TestObject testObject = monitor.registerRequest(); + + try (Connection connection = this.getConnection()) { + if (connection == null) { + throw new SQLException("Connection invalid"); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); + } + return executeUpdatePreparedStatement(connection, statement, arguments, true); + } finally { + monitor.deregisterRequest(testObject); + } + } + + CachedRowSet executePreparedStatement(Connection conn, String statement, List arguments, boolean close) + throws SQLException { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL Statement: {}", statement); + if (arguments != null && !arguments.isEmpty()) { + LOGGER.debug("Argunments: {}", arguments); + } + } + + ResultSet rs = null; + try (PreparedStatement ps = conn.prepareStatement(statement)) { + data = RowSetProvider.newFactory().createCachedRowSet(); + if (arguments != null) { + for (int i = 0, max = arguments.size(); i < max; i++) { + ps.setObject(i + 1, arguments.get(i)); + } + } + rs = ps.executeQuery(); + data.populate(rs); + // Point the rowset Cursor to the start + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), + (System.currentTimeMillis() - time)); + } + } catch (SQLException exc) { + handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); + } finally { + handleFinallyBlockForExecutePreparedStatement(rs, conn, close); + } + + return data; + } + + private void handleSqlExceptionForExecuteStatement(Connection conn, String statement, List arguments, + SQLException exc, long time) throws SQLException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(SQL_FAILURE + (System.currentTimeMillis() - time)); + } + try { + conn.rollback(); + } catch (Exception thr) { + LOGGER.error(thr.getLocalizedMessage(), thr); + } + if (arguments != null && !arguments.isEmpty()) { + LOGGER.error(String.format("<%s%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_ARGUMENTS, + arguments), exc); + } else { + LOGGER.error(String.format("<%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_NO_ARGUMENTS), + exc); + } + throw exc; + } + + private void handleFinallyBlockForExecutePreparedStatement(ResultSet rs, Connection conn, boolean close) { + try { + if (rs != null) { + rs.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + try { + if (conn != null && close) { + conn.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + } + + boolean executeUpdatePreparedStatement(Connection conn, String statement, List arguments, boolean close) + throws SQLException { + long time = System.currentTimeMillis(); + + CachedRowSet data; + + try (PreparedStatement ps = conn.prepareStatement(statement)) { + data = RowSetProvider.newFactory().createCachedRowSet(); + if (arguments != null) { + prepareStatementForExecuteUpdate(arguments, ps); + } + ps.executeUpdate(); + // Point the rowset Cursor to the start + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), + (System.currentTimeMillis() - time)); + } + ps.close(); + } catch (SQLException exc) { + handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); + } finally { + try { + if (close) { + conn.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + } + + return true; + } + + private void prepareStatementForExecuteUpdate(List arguments, PreparedStatement ps) throws SQLException { + for (int i = 0, max = arguments.size(); i < max; i++) { + Object value = arguments.get(i); + if (value instanceof Blob) { + ps.setBlob(i + 1, (Blob) value); + } else if (value instanceof Timestamp) { + ps.setTimestamp(i + 1, (Timestamp) value); + } else if (value instanceof Integer) { + ps.setInt(i + 1, (Integer) value); + } else if (value instanceof Long) { + ps.setLong(i + 1, (Long) value); + } else if (value instanceof Date) { + ps.setDate(i + 1, (Date) value); + } else { + ps.setObject(i + 1, value); + } + } + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) + */ + @Override + public Connection getConnection(String username, String password) throws SQLException { + return ds.getConnection(username, password); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getLogWriter() + */ + @Override + public PrintWriter getLogWriter() throws SQLException { + return ds.getLogWriter(); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getLoginTimeout() + */ + @Override + public int getLoginTimeout() throws SQLException { + return ds.getLoginTimeout(); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) + */ + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + ds.setLogWriter(out); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#setLoginTimeout(int) + */ + @Override + public void setLoginTimeout(int seconds) throws SQLException { + ds.setLoginTimeout(seconds); + } + + @Override + public final String getDbConnectionName() { + return connectionName; + } + + protected final void setDbConnectionName(String name) { + this.connectionName = name; + } + + public void cleanUp() { + if (ds != null && ds instanceof Closeable) { + try { + ((Closeable) ds).close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage()); + } + } + ds = null; + monitor.deleteObservers(); + monitor.cleanup(); + } + + public boolean isInitialized() { + return initialized; + } + + protected boolean testConnection() { + return testConnection(false); + } + + protected boolean testConnection(boolean errorLevel) { + ResultSet rs = null; + try (Connection conn = this.getConnection(); Statement stmt = conn.createStatement()) { + Boolean readOnly; + String hostname; + rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); // ("SELECT 1 FROM DUAL"); //"select + // BANNER from SYS.V_$VERSION" + while (rs.next()) { + readOnly = rs.getBoolean(1); + hostname = rs.getString(2); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(SQL_DATA_SOURCE + getDbConnectionName() + "> connected to " + hostname + + ", read-only is " + readOnly + ", tested successfully "); + } + } + } catch (Exception exc) { + if (errorLevel) { + LOGGER.error( + SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } else { + LOGGER.info( + SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } + return false; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + LOGGER.error(e.getLocalizedMessage(), e); + } + } + } + return true; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @SuppressWarnings("deprecation") + public void setConnectionCachingEnabled(boolean state) { + // if(ds != null && ds instanceof OracleDataSource) + // try { + // ((OracleDataSource)ds).setConnectionCachingEnabled(true); + // } catch (SQLException exc) { + // LOGGER.warn("", exc); + // } + } + + public void addObserver(Observer observer) { + monitor.addObserver(observer); + } + + public void deleteObserver(Observer observer) { + monitor.deleteObserver(observer); + } + + @Override + public long getInterval() { + return interval; + } + + @Override + public long getInitialDelay() { + return initialDelay; + } + + @Override + public void setInterval(long value) { + interval = value; + } + + @Override + public void setInitialDelay(long value) { + initialDelay = value; + } + + @Override + public long getExpectedCompletionTime() { + return expectedCompletionTime; + } + + @Override + public void setExpectedCompletionTime(long value) { + expectedCompletionTime = value; + } + + @Override + public long getUnprocessedFailoverThreshold() { + return unprocessedFailoverThreshold; + } + + @Override + public void setUnprocessedFailoverThreshold(long value) { + this.unprocessedFailoverThreshold = value; + } + + public boolean canTakeOffLine() { + return canTakeOffLine; + } + + public void blockImmediateOffLine() { + canTakeOffLine = false; + final Thread offLineTimer = new Thread(() -> { + try { + Thread.sleep(30000L); + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } finally { + canTakeOffLine = true; + } + }); + offLineTimer.setDaemon(true); + offLineTimer.start(); + } + + /** + * @return the monitor + */ + final SQLExecutionMonitor getMonitor() { + return monitor; + } + + protected boolean isSlave() throws PoolExhaustedException { + + // If using Apache derby, just return false + if (isDerby) { + return false; + } + CachedRowSet rs; + boolean isSlave; + String hostname = "UNDETERMINED"; + try { + boolean localSlave = true; + rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList<>()); + while (rs.next()) { + localSlave = rs.getBoolean(1); + hostname = rs.getString(2); + } + isSlave = localSlave; + } catch (PoolExhaustedException peexc) { + throw peexc; + } catch (Exception e) { + LOGGER.error("", e); + isSlave = true; + } + if (isSlave) { + LOGGER.debug("SQL SLAVE : {} on server {}", connectionName, hostname); + } else { + LOGGER.debug("SQL MASTER : {} on server {}", connectionName, hostname); + } + return isSlave; + } + + public boolean isFabric() { + return false; + } + + protected boolean lockTable(Connection conn, String tableName) { + boolean retValue = false; + String query = "LOCK TABLES " + tableName + " WRITE"; + try (Statement preStmt = conn.createStatement(); + Statement lock = conn.prepareStatement(query); + ResultSet rs = preStmt.executeQuery("GETDATE()")) { + if (tableName != null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); + if ("SVC_LOGIC".equals(tableName)) { + Exception e = new Exception(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + LOGGER.debug(sw.toString()); + } + } + lock.execute(query); + retValue = true; + } + } catch (Exception exc) { + LOGGER.error("", exc); + retValue = false; + } + return retValue; + } + + protected boolean unlockTable(Connection conn) { + boolean retValue; + try (Statement lock = conn.createStatement()) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'UNLOCK TABLES' on connection {}", conn); + } + retValue = lock.execute("UNLOCK TABLES"); + } catch (Exception exc) { + LOGGER.error("", exc); + retValue = false; + } + return retValue; + } + + public void getPoolInfo(boolean allocation) { + + } + + public long getNextErrorReportTime() { + return nextErrorReportTime; + } + + public void setNextErrorReportTime(long nextTime) { + this.nextErrorReportTime = nextTime; + } + + public void setGlobalHostName(String hostname) { + this.globalHostName = hostname; + } + + public String getGlobalHostName() { + return globalHostName; + } } diff --git a/dblib/provider/src/main/resources/dblib.properties b/dblib/provider/src/main/resources/dblib.properties index 3e62308fc..e0399cc31 100755 --- a/dblib/provider/src/main/resources/dblib.properties +++ b/dblib/provider/src/main/resources/dblib.properties @@ -1,9 +1,10 @@ org.onap.ccsdk.sli.dbtype=jdbc org.onap.ccsdk.sli.jdbc.hosts=sdnctldb01,sdnctldb02 -org.onap.ccsdk.sli.jdbc.url=jdbc:mysql://DBHOST:3306/sdnctl +org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true +org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver org.onap.ccsdk.sli.jdbc.database=sdnctl -org.onap.ccsdk.sli.jdbc.user={user for sdnctl} -org.onap.ccsdk.sli.jdbc.password={password for sdnctl} +org.onap.ccsdk.sli.jdbc.user=test +org.onap.ccsdk.sli.jdbc.password=test org.onap.ccsdk.sli.jdbc.connection.name=sdnctldb01 org.onap.ccsdk.sli.jdbc.connection.timeout=50 diff --git a/filters/features/ccsdk-filters/pom.xml b/filters/features/ccsdk-filters/pom.xml new file mode 100644 index 000000000..9b5c73bab --- /dev/null +++ b/filters/features/ccsdk-filters/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + single-feature-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + ccsdk-filters + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: filters :: ${project.artifactId} + + + + + org.opendaylight.mdsal.model + mdsal-model-artifacts + 0.11.1 + pom + import + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.opendaylight.controller + odl-mdsal-broker + xml + features + + + + ${project.groupId} + ccsdk-sli + ${project.version} + xml + features + + + + ${project.groupId} + filters-provider + ${project.version} + + + + diff --git a/filters/features/features-filters/pom.xml b/filters/features/features-filters/pom.xml new file mode 100644 index 000000000..5072971aa --- /dev/null +++ b/filters/features/features-filters/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + feature-repo-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + features-filters + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: filters :: ${project.artifactId} + + + + ${project.groupId} + ccsdk-filters + ${project.version} + xml + features + + + + diff --git a/filters/features/pom.xml b/filters/features/pom.xml index 3662f3368..bf9868404 100755 --- a/filters/features/pom.xml +++ b/filters/features/pom.xml @@ -1,101 +1,22 @@ 4.0.0 + - filters - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - filters-features - Filters - Features - - jar - - - - - - org.onap.ccsdk.sli.core - filters-provider - ${project.version} - - - + org.onap.ccsdk.sli.core + filters-features-aggregator + pom - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - + + features-filters + ccsdk-filters + diff --git a/filters/features/src/main/resources/features.xml b/filters/features/src/main/resources/features.xml deleted file mode 100644 index 7ede2083a..000000000 --- a/filters/features/src/main/resources/features.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - mvn:org.onap.ccsdk.sli.core/filters-provider/${project.version} - - - diff --git a/filters/installer/pom.xml b/filters/installer/pom.xml index a22e9ab72..a16b6a60c 100755 --- a/filters/installer/pom.xml +++ b/filters/installer/pom.xml @@ -1,18 +1,24 @@ 4.0.0 + - org.onap.ccsdk.sli.core - filters - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core filters-installer - Filters - Karaf Installer + 0.2.1-SNAPSHOT pom + ccsdk-sli-core :: filters :: ${project.artifactId} + - sdnc-filters - sdnc-filters + ccsdk-filters + ${application.name} mvn:org.onap.ccsdk.sli.core/filters-features/${project.version}/xml/features false @@ -21,10 +27,10 @@ org.onap.ccsdk.sli.core - filters-features + ${application.name} ${project.version} - features xml + features * @@ -134,5 +140,4 @@ - diff --git a/filters/pom.xml b/filters/pom.xml index 7780dcecb..b40d0d318 100644 --- a/filters/pom.xml +++ b/filters/pom.xml @@ -1,79 +1,26 @@ - - - - org.onap.ccsdk.sli.core - ccsdk-sli-core - 0.2.0-SNAPSHOT + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - 4.0.0 - pom - org.onap.ccsdk.sli.core - filters - - - Filters - Servlet filter to implement ECOMP logging spec - - 0.2.0-SNAPSHOT - - + org.onap.ccsdk.sli.core + filters + 0.2.1-SNAPSHOT + pom - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compile.plugin.version} - - ${java.version.source} - ${java.version.target} - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10 - - - - aggregate - - aggregate - - site - - - - - - - maven-source-plugin - 2.1.1 - - - bundle-sources - package - - - jar-no-fork - - - test-jar-no-fork - - - - - - - - - + ccsdk-sli-core :: filters + Servlet filter to implement ONAP logging spec + ONAP - + + provider features installer diff --git a/filters/provider/pom.xml b/filters/provider/pom.xml index 51d0c63aa..4fdd83280 100755 --- a/filters/provider/pom.xml +++ b/filters/provider/pom.xml @@ -1,82 +1,66 @@ - 4.0.0 - - org.onap.ccsdk.sli.core - filters - 0.2.0-SNAPSHOT - - filters-provider - bundle - Filters - Provider - http://maven.apache.org - - UTF-8 - - - - junit - junit - ${junit.version} - test - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - + 4.0.0 + + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + - - equinoxSDK381 - org.eclipse.osgi - ${equinox.osgi.version} - + org.onap.ccsdk.sli.core + filters-provider + 0.2.1-SNAPSHOT + bundle - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - - - commons-codec - commons-codec - ${commons.codec.version} - - - org.onap.ccsdk.sli.core - sli-common - ${project.version} - + ccsdk-sli-core :: filters :: ${project.artifactId} + http://maven.apache.org - + + UTF-8 + - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.onap.ccsdk.sli.core.filters - org.onap.ccsdk.sli.core.filters - org.onap.ccsdk.sli.core.filters - javax.servlet.*,java.io.*,org.osgi.framework.*,org.slf4j.*,org.apache.commons.codec.binary.* - true - - + + + junit + junit + ${junit.version} + test + + + javax.servlet + javax.servlet-api + - + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + provided + - - + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + + + commons-codec + commons-codec + ${commons.codec.version} + + + org.onap.ccsdk.sli.core + sli-common + ${project.version} + + + diff --git a/pom.xml b/pom.xml index c7885a9b6..7ab4d4630 100755 --- a/pom.xml +++ b/pom.xml @@ -1,20 +1,34 @@ - - + 4.0.0 - pom + + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core ccsdk-sli-core + 0.2.1-SNAPSHOT + pom ccsdk-sli-core - https://wiki.onap.org CCSDK core components contains the SLI, dblib + https://wiki.onap.org + + ONAP + - - org.onap.ccsdk.parent - odlparent-carbon-sr1 - 0.2.0-SNAPSHOT - + + utils + dblib + sli + filters + sliPluginUtils + sliapi + scm:git:ssh://git@${onap.git.host}/sdnc-code.git @@ -24,25 +38,6 @@ - - blackduck @@ -81,45 +76,4 @@ - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.17 - - false - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - https://${onap.nexus.host} - ${onap.nexus.staging.profile-id} - ${onap.nexus.staging.server-id} - - - - - - - - utils - dblib - sli - filters - sliPluginUtils - sliapi - - - ONAP - - 0.2.0-SNAPSHOT - - diff --git a/sli/common/pom.xml b/sli/common/pom.xml index 4c7daa395..167a776e4 100755 --- a/sli/common/pom.xml +++ b/sli/common/pom.xml @@ -1,163 +1,136 @@ - - 4.0.0 - - sli - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT - - sli-common - bundle + + + 4.0.0 - SLI - Common Classes - The SLI Common package includes common classes used by the various SLI subcomponents, as well as classes used by clients to interface with the service logic interpreter + + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + - - - junit - junit - ${junit.version} - test - - - ch.vorburger.mariaDB4j - mariaDB4j - 2.2.3 - test - - - org.antlr - antlr4 - ${antlr.version} - jar - compile - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-simple - 1.7.5 - compile - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - org.opendaylight.mdsal - yang-binding - ${odl.mdsal.yang.binding.version} - - - org.opendaylight.yangtools - yang-common - ${odl.yangtools.version} - - - org.opendaylight.mdsal.model - ietf-inet-types - ${odl.ietf-inet-types.version} - - - org.opendaylight.mdsal.model - ietf-yang-types - ${odl.ietf-yang-types.version} - - - org.opendaylight.controller - sal-core-api - ${odl.mdsal.version} - - - org.opendaylight.yangtools - yang-data-impl - ${odl.yangtools.version} - - - equinoxSDK381 - org.eclipse.osgi - ${equinox.osgi.version} - - - org.mariadb.jdbc - mariadb-java-client - ${mariadb.connector.version} - jar - compile - - - org.onap.ccsdk.sli.core - dblib-provider - ${sdnctl.dblib.version} - - - org.onap.ccsdk.sli.core - sliapi-model - ${project.version} - test - - + org.onap.ccsdk.sli.core + sli-common + 0.2.1-SNAPSHOT + bundle - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - **/*.xsd - - - org.onap.ccsdk.sli.core.sli.SvcLogicParser - org.onap.ccsdk.sli.core.sli - true - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.onap.ccsdk.sli.core.sli;version=${project.version} - * - *;scope=compile;artifactId=commons-lang|commons-lang3 - true - - - - - org.antlr - antlr4-maven-plugin - ${antlr.version} - - - - ${project.basedir}/src/main/java/ - - antlr - - antlr4 - - - - - - + ccsdk-sli-core :: sli :: ${project.artifactId} + The SLI Common package includes common classes used by the various SLI subcomponents, as well as classes used by clients to interface with the service logic interpreter + + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + ch.vorburger.mariaDB4j + mariaDB4j + 2.2.3 + test + + + org.antlr + antlr4 + ${antlr.version} + jar + compile + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-simple + 1.7.5 + compile + + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + + + org.mariadb.jdbc + mariadb-java-client + ${mariadb.connector.version} + jar + compile + + + org.onap.ccsdk.sli.core + dblib-provider + ${sdnctl.dblib.version} + + + org.onap.ccsdk.sli.core + sli-model + ${project.version} + test + + + org.opendaylight.mdsal.model + ietf-inet-types + + + org.opendaylight.mdsal.model + ietf-yang-types + + + org.opendaylight.controller + sal-core-api + + + + org.opendaylight.controller + sal-binding-api + + + + + junit + junit + test + + + + org.mockito + mockito-core + test + + + + + + + org.antlr + antlr4-maven-plugin + ${antlr.version} + + + + ${project.basedir}/src/main/java/ + + antlr + + antlr4 + + + + + + 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 74fa1dd66..ee3bcca5c 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 @@ -54,10 +54,22 @@ public class SvcLogicDblibStore implements SvcLogicStore { private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DbLibService"; + private DbLibService dbSvc; + + public SvcLogicDblibStore() + { + // Does nothing, but needed so that argumentless constructor + // still works. + } + + public SvcLogicDblibStore(DbLibService dbsvc) { + this.dbSvc = dbsvc; + } + @Override public void init(Properties props) throws ConfigurationException { - DbLibService dbSvc = getDbLibService(); + dbSvc = getDbLibService(); if(dbSvc == null) { LOG.error("SvcLogic cannot acquire DBLIB_SERVICE"); return; @@ -74,7 +86,7 @@ public class SvcLogicDblibStore implements SvcLogicStore { public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); + boolean retval = false; CachedRowSet results = null; @@ -124,7 +136,6 @@ public class SvcLogicDblibStore implements SvcLogicStore { public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); PreparedStatement fetchGraphStmt = null; Connection dbConn = null; SvcLogicGraph retval = null; @@ -210,7 +221,7 @@ public class SvcLogicDblibStore implements SvcLogicStore { public void store(SvcLogicGraph graph) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); + String storeGraphSql = "INSERT INTO SVC_LOGIC (module, rpc, version, mode, active, graph)" + " VALUES(?, ?, ?, ?, ?, ?)"; @@ -283,7 +294,7 @@ public class SvcLogicDblibStore implements SvcLogicStore { public void delete(String module, String rpc, String version, String mode) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); + String deleteGraphSql = "DELETE FROM SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; @@ -302,7 +313,7 @@ public class SvcLogicDblibStore implements SvcLogicStore { } public void activate(SvcLogicGraph graph) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); + String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; @@ -328,8 +339,11 @@ public class SvcLogicDblibStore implements SvcLogicStore { private DbLibService getDbLibService() { + if (dbSvc != null) { + return dbSvc; + } + // Get DbLibService interface object. - DbLibService dblibSvc = null; ServiceReference sref = null; BundleContext bctx = null; @@ -345,8 +359,8 @@ public class SvcLogicDblibStore implements SvcLogicStore { if (sref == null) { LOG.warn("Could not find service reference for DBLIB service ({})", DBLIB_SERVICE); } else { - dblibSvc = (DbLibService) bctx.getService(sref); - if (dblibSvc == null) { + dbSvc = (DbLibService) bctx.getService(sref); + if (dbSvc == null) { LOG.warn("Could not find service reference for DBLIB service ({})", DBLIB_SERVICE); } @@ -385,16 +399,16 @@ public class SvcLogicDblibStore implements SvcLogicStore { } try { - dblibSvc = new DBResourceManager(dblibProps); - JavaSingleton.setInstance(dblibSvc); + dbSvc = new DBResourceManager(dblibProps); + JavaSingleton.setInstance(dbSvc); } catch (Exception e) { LOG.warn("Caught exception trying to create DBResourceManager", e); } } else { - dblibSvc = JavaSingleton.getInstance(); + dbSvc = JavaSingleton.getInstance(); } } - return dblibSvc; + return dbSvc; } @@ -419,7 +433,7 @@ public class SvcLogicDblibStore implements SvcLogicStore { @Override public void activate(String module, String rpc, String version, String mode) throws SvcLogicException { - DbLibService dbSvc = getDbLibService(); + String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; diff --git a/sli/features/features-sli/pom.xml b/sli/features/features-sli/pom.xml new file mode 100644 index 000000000..de617baad --- /dev/null +++ b/sli/features/features-sli/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + feature-repo-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + features-sli + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: sli :: ${project.artifactId} + + + + ${project.groupId} + ccsdk-sli + ${project.version} + xml + features + + + + diff --git a/sli/features/odl-sli/pom.xml b/sli/features/odl-sli/pom.xml new file mode 100644 index 000000000..907cef6a2 --- /dev/null +++ b/sli/features/odl-sli/pom.xml @@ -0,0 +1,86 @@ + + + + 4.0.0 + + + org.onap.ccsdk.parent + single-feature-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + ccsdk-sli + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: sli :: ${project.artifactId} + + + + + org.opendaylight.mdsal.model + mdsal-model-artifacts + 0.11.1 + pom + import + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.onap.ccsdk.sli.core + sli-common + ${project.version} + + + + org.onap.ccsdk.sli.core + sli-provider + ${project.version} + + + + org.onap.ccsdk.sli.core + sli-recording + ${project.version} + + + + org.mariadb.jdbc + mariadb-java-client + ${mariadb.connector.version} + + + + org.onap.ccsdk.sli.core + ccsdk-dblib + ${project.version} + xml + features + + + org.opendaylight.controller + odl-mdsal-broker + xml + features + + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + provided + + + diff --git a/sli/features/pom.xml b/sli/features/pom.xml old mode 100755 new mode 100644 index 4630b7833..fbb864efa --- a/sli/features/pom.xml +++ b/sli/features/pom.xml @@ -1,137 +1,30 @@ - - 4.0.0 - - sli - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT - - sli-features - SLI - Features - - jar - - - - org.onap.ccsdk.sli.core - sli-common - ${project.version} - - - - - org.onap.ccsdk.sli.core - sli-recording - ${project.version} - - - commons-lang - commons-lang - ${commons.lang.version} - compile - - - - org.opendaylight.mdsal - features-mdsal - ${odl.mdsal.features.version} - features - xml - - runtime - - + - - - - - org.opendaylight.odlparent - features-test - ${odl.commons.opendaylight.version} - test - - - - org.opendaylight.yangtools - features-yangtools - ${odl.yangtools.version} - features - xml - runtime - - - - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - +This program and the accompanying materials are made available under the +terms of the Eclipse Public License v1.0 which accompanies this distribution, +and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL +--> + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + sli-feature-aggregator + 0.1.0 + pom + + ccsdk-sli-core :: sli :: ${project.artifactId} + + + features-sli + odl-sli + diff --git a/sli/features/src/main/resources/features.xml b/sli/features/src/main/resources/features.xml deleted file mode 100644 index 1f17c1a95..000000000 --- a/sli/features/src/main/resources/features.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features - - - - - odl-mdsal-broker - mvn:org.onap.ccsdk.sli.core/sli-common/${project.version} - mvn:org.onap.ccsdk.sli.core/sli-provider/${project.version} - mvn:org.onap.ccsdk.sli.core/sli-recording/${project.version} - sdnc-dblib - mvn:org.mariadb.jdbc/mariadb-java-client/${mariadb.connector.version} - - - diff --git a/sli/installer/pom.xml b/sli/installer/pom.xml index 23b747130..ec2b43cff 100755 --- a/sli/installer/pom.xml +++ b/sli/installer/pom.xml @@ -1,19 +1,25 @@ 4.0.0 + - sli - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core sli-installer - SLI - Karaf Installer + 0.2.1-SNAPSHOT pom + ccsdk-sli-core :: sli :: ${project.artifactId} + - sdnc-sli - sdnc-sli - mvn:org.onap.ccsdk.sli.core/sli-features/${project.version}/xml/features + ccsdk-sli + ${application.name} + mvn:org.onap.ccsdk.sli.core/${features.boot}/${project.version}/xml/features false @@ -21,10 +27,10 @@ org.onap.ccsdk.sli.core - sli-features + ${application.name} ${project.version} - features xml + features * @@ -145,5 +151,4 @@ - diff --git a/sli/model/pom.xml b/sli/model/pom.xml index 59658a3e1..3a78c4788 100755 --- a/sli/model/pom.xml +++ b/sli/model/pom.xml @@ -1,82 +1,29 @@ 4.0.0 + - sli - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core sli-model + 0.2.1-SNAPSHOT bundle - SLI - Model - - - - org.apache.felix - maven-bundle-plugin - true - - - * - - - - - org.opendaylight.yangtools - yang-maven-plugin - ${odl.yangtools.yang.maven.plugin.version} - - - org.opendaylight.mdsal - maven-sal-api-gen-plugin - ${odl.sal.api.gen.plugin.version} - jar - - - - - - generate-sources - - - ${yang.file.directory} - - - - org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl - ${salGeneratorPath} - - - true - - - - - - + ccsdk-sli-core :: sli :: ${project.artifactId} + - - org.opendaylight.mdsal - yang-binding - ${odl.mdsal.yang.binding.version} - - - org.opendaylight.yangtools - yang-common - ${odl.yangtools.version} - - - org.opendaylight.mdsal.model - ietf-inet-types - ${odl.ietf-inet-types.version} - - - org.opendaylight.mdsal.model - ietf-yang-types - ${odl.ietf-yang-types.version} - + + org.opendaylight.mdsal.model + ietf-inet-types + + + org.opendaylight.mdsal.model + ietf-yang-types + diff --git a/sli/pom.xml b/sli/pom.xml index 95417c3c8..985fa1d3e 100755 --- a/sli/pom.xml +++ b/sli/pom.xml @@ -1,53 +1,24 @@ - - + + 4.0.0 - org.onap.ccsdk.sli.core - ccsdk-sli-core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - 4.0.0 - pom + org.onap.ccsdk.sli.core sli + 0.2.1-SNAPSHOT + pom - - - - - org.onap.ccsdk.sli.core - sli-features - features - xml - ${project.version} - - - - org.onap.ccsdk.sli.core - sli-common - ${project.version} - - - - org.onap.ccsdk.sli.core - sli-provider - ${project.version} - - - - org.onap.ccsdk.sli.core - sli-recording - ${project.version} - - - - - - - - Service Logic Interpreter + ccsdk-sli-core :: sli The Service Logic Interpreter (SLI) allows service planners to design the flow of logic within the SDN controller in an XML format, without a need for custom Java code. + + ONAP + model @@ -57,10 +28,4 @@ features installer - - ONAP - - 0.2.0-SNAPSHOT - - diff --git a/sli/provider/pom.xml b/sli/provider/pom.xml index 4f410ab01..4a90ae005 100755 --- a/sli/provider/pom.xml +++ b/sli/provider/pom.xml @@ -1,25 +1,38 @@ - - 4.0.0 - - org.onap.ccsdk.sli.core - sli - 0.2.0-SNAPSHOT + + 4.0.0 + + + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + - sli-provider - bundle - SLI - Provider - + + org.onap.ccsdk.sli.core + sli-provider + 0.2.1-SNAPSHOT + bundle + + ccsdk-sli-core :: sli :: ${project.artifactId} + SLI Provider is the OSGi bundle that exposes the service logic interpreter as a service. + + UTF-8 - - - junit - junit - ${junit.version} - test - + + + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + ch.vorburger.mariaDB4j mariaDB4j @@ -60,129 +73,24 @@ compile - - - - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.onap.ccsdk.sli.core.sli.provider.SvcLogicActivator - org.onap.ccsdk.sli.core.sli.provider;version=${project.version} - - * + + org.opendaylight.controller + sal-binding-api + - org.onap.ccsdk.sli.core.sli;version="${project.version}",* + + + junit + junit + test + - *;scope=compile;artifactId=commons-lang|commons-lang3 + + org.mockito + mockito-core + test + - true - - - - - - org.opendaylight.yangtools - yang-maven-plugin - ${odl.yangtools.yang.maven.plugin.version} - - - config - - generate-sources - - - src/test/resources - - - - org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - - ${jmxGeneratorPath} - - - urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang - - - - - - org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl - - ${salGeneratorPath} - - - true - - - - - - org.opendaylight.mdsal - maven-sal-api-gen-plugin - ${odl.sal.api.gen.plugin.version} - jar - - - org.opendaylight.controller - yang-jmx-generator-plugin - ${odl.yang.jmx.generator.version} - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.8 - - - prepare-package - - run - - - - - - - - - - - - - - - - - - SLI Provider is the OSGi bundle that exposes the service logic interpreter as a service. + diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java index d11a2828d..24774af24 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/CallNodeExecutor.java @@ -8,9 +8,9 @@ * 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. @@ -34,15 +34,15 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { private static final Logger LOG = LoggerFactory .getLogger(CallNodeExecutor.class); - + @Override public SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException { String outValue = "not-found"; - + SvcLogicGraph myGraph = node.getGraph(); - + if (myGraph == null) { LOG.debug("execute: getGraph returned null"); @@ -51,17 +51,17 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { { LOG.debug("execute: got SvcLogicGraph"); } - + SvcLogicExpression moduleExpr = null; - + String module = null; - + moduleExpr = node.getAttribute("module"); if (moduleExpr != null) { module = SvcLogicExpressionResolver.evaluate(moduleExpr, node, ctx); } - + if ((module == null) || (module.length() == 0)) { if (myGraph != null) @@ -70,7 +70,7 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { LOG.debug("myGraph.getModule() returned "+module); } } - + SvcLogicExpression rpcExpr = null; String rpc = null; rpcExpr = node.getAttribute("rpc"); @@ -78,7 +78,7 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { { rpc = SvcLogicExpressionResolver.evaluate(rpcExpr, node, ctx); } - + if ((rpc == null) || (rpc.length() == 0)) { if (myGraph != null) @@ -87,9 +87,9 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { LOG.debug("myGraph.getRpc() returned "+rpc); } } - + String mode = null; - + moduleExpr = node.getAttribute("mode"); if (moduleExpr != null) { @@ -105,9 +105,9 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { LOG.debug("myGraph.getMode() returned "+mode); } } - + String version = null; - + moduleExpr = node.getAttribute("version"); if (moduleExpr != null) { @@ -116,9 +116,9 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { String parentGraph = ctx.getAttribute("currentGraph"); ctx.setAttribute("parentGraph", parentGraph); - - SvcLogicStore store = getStore(); - + + SvcLogicStore store = svc.getStore(); + if (store != null) { SvcLogicGraph calledGraph = store.fetch(module, rpc, version, mode); if (calledGraph != null) { @@ -132,7 +132,7 @@ public class CallNodeExecutor extends SvcLogicNodeExecutor { } else { LOG.debug("Could not get SvcLogicStore reference"); } - + SvcLogicNode nextNode = node.getOutcomeValue(outValue); if (nextNode != null) { if (LOG.isDebugEnabled()) { diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java deleted file mode 100644 index 95dfb2b88..000000000 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicActivator.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : CCSDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.sli.core.sli.provider; - -import java.io.File; -import java.io.FileInputStream; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.Map; -import java.util.Properties; -import org.onap.ccsdk.sli.core.sli.ConfigurationException; -import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import org.onap.ccsdk.sli.core.sli.SvcLogicStore; -import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; -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 SvcLogicActivator implements BundleActivator { - - private static final String SVCLOGIC_PROP_VAR = "SDNC_SLI_PROPERTIES"; - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final Map BUILTIN_NODES = new HashMap() { - { - put("block", new BlockNodeExecutor()); - put("call", new CallNodeExecutor()); - put("configure", new ConfigureNodeExecutor()); - put("delete", new DeleteNodeExecutor()); - put("execute", new ExecuteNodeExecutor()); - put("exists", new ExistsNodeExecutor()); - put("for", new ForNodeExecutor()); - put("get-resource", new GetResourceNodeExecutor()); - put("is-available", new IsAvailableNodeExecutor()); - put("notify", new NotifyNodeExecutor()); - put("record", new RecordNodeExecutor()); - put("release", new ReleaseNodeExecutor()); - put("reserve", new ReserveNodeExecutor()); - put("return", new ReturnNodeExecutor()); - put("save", new SaveNodeExecutor()); - put("set", new SetNodeExecutor()); - put("switch", new SwitchNodeExecutor()); - put("update", new UpdateNodeExecutor()); - put("break", new BreakNodeExecutor()); - put("while", new WhileNodeExecutor()); - } - }; - - private static final Logger LOG = LoggerFactory.getLogger(SvcLogicActivator.class); - - private static LinkedList registrations = new LinkedList<>(); - - private static HashMap adaptorMap; - - private static Properties props; - - private static BundleContext bundleCtx; - - private static SvcLogicService svcLogicServiceImpl; - - @Override - public void start(BundleContext ctx) throws Exception { - - LOG.info("Activating SLI"); - - synchronized (SvcLogicActivator.class) { - bundleCtx = ctx; - props = new Properties(); - } - - // Read properties - String propPath = System.getenv(SVCLOGIC_PROP_VAR); - - if (propPath == null) { - String propDir = System.getenv(SDNC_CONFIG_DIR); - if (propDir == null) { - - propDir = "/opt/sdnc/data/properties"; - } - propPath = propDir + "/svclogic.properties"; - LOG.warn("Environment variable {} unset - defaulting to {}", SVCLOGIC_PROP_VAR, propPath); - } - - File propFile = new File(propPath); - - if (!propFile.exists()) { - throw new ConfigurationException("Missing configuration properties file : " + propFile); - } - - try { - props.load(new FileInputStream(propFile)); - } catch (Exception e) { - throw new ConfigurationException("Could not load properties file " + propPath, e); - - } - - synchronized (SvcLogicActivator.class) { - if (registrations == null) { - registrations = new LinkedList<>(); - } - // Advertise SvcLogicService - svcLogicServiceImpl = new SvcLogicServiceImpl(); - } - - LOG.info("SLI: Registering service {} in bundle {}", SvcLogicService.NAME, ctx.getBundle().getSymbolicName()); - ServiceRegistration reg = ctx.registerService(SvcLogicService.NAME, svcLogicServiceImpl, null); - registrations.add(reg); - - // Initialize SvcLogicStore - try { - SvcLogicStore store = getStore(); - } catch (ConfigurationException e) { - LOG.warn("Could not initialize SvcLogicScore", e); - } - - LOG.info("SLI - done registering services"); - } - - @Override - public void stop(BundleContext ctx) throws Exception { - - if (registrations != null) { - for (ServiceRegistration reg : registrations) { - ServiceReference regRef = reg.getReference(); - reg.unregister(); - } - synchronized (SvcLogicActivator.class) { - registrations = null; - } - } - } - - public static SvcLogicStore getStore() throws SvcLogicException { - // Create and initialize SvcLogicStore object - used to access - // saved service logic. - - SvcLogicStore store; - - try { - store = SvcLogicStoreFactory.getSvcLogicStore(props); - } catch (Exception e) { - throw new ConfigurationException("Could not get service logic store", e); - - } - - try { - store.init(props); - } catch (Exception e) { - throw new ConfigurationException("Could not get service logic store", e); - } - - return(store); - } - - -} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java index 43296c6cd..951536b50 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicNodeExecutor.java @@ -8,9 +8,9 @@ * 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. @@ -36,7 +36,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class SvcLogicNodeExecutor { - + public abstract SvcLogicNode execute(SvcLogicServiceImpl svc, SvcLogicNode node, SvcLogicContext ctx) throws SvcLogicException; private static final Logger LOG = LoggerFactory.getLogger(SvcLogicNodeExecutor.class); @@ -51,15 +51,12 @@ public abstract class SvcLogicNodeExecutor { node, ctx)); } - - protected SvcLogicStore getStore() throws SvcLogicException { - return SvcLogicActivator.getStore(); - } - + + protected SvcLogicAdaptor getAdaptor(String adaptorName) { return SvcLogicAdaptorFactory.getInstance(adaptorName); } - + protected SvcLogicResource getSvcLogicResource(String plugin) { BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); @@ -75,7 +72,7 @@ public abstract class SvcLogicNodeExecutor { return null; } } - + protected SvcLogicRecorder getSvcLogicRecorder(String plugin) { BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); @@ -90,7 +87,7 @@ public abstract class SvcLogicNodeExecutor { return null; } } - + protected SvcLogicJavaPlugin getSvcLogicJavaPlugin(String pluginName){ BundleContext bctx = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); @@ -106,5 +103,5 @@ public abstract class SvcLogicNodeExecutor { return plugin; } } - + } diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicPropertiesProvider.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicPropertiesProvider.java new file mode 100644 index 000000000..6e8597210 --- /dev/null +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicPropertiesProvider.java @@ -0,0 +1,188 @@ +/*- + * ============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.sli.provider; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Optional; +import java.util.Properties; +import java.util.Vector; + +import org.onap.ccsdk.sli.core.dblib.DblibConfigurationException; +import org.onap.ccsdk.sli.core.sli.ConfigurationException; +import org.onap.ccsdk.sli.core.utils.JREFileResolver; +import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; +import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; +import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; +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 SvcLogicPropertiesProvider { + + private static final Logger LOG = LoggerFactory.getLogger(SvcLogicPropertiesProvider.class); + + /** + * The name of the properties file for database configuration + */ + private static final String SVCLOGIC_PROP_FILE_NAME = "svclogic.properties"; + + /** + * A prioritized list of strategies for resolving dblib properties files. + */ + private Vector sliPropertiesFileResolvers = 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 SvcLogicPropertiesProvider() { + sliPropertiesFileResolvers + .add(new SdncConfigEnvVarFileResolver("Using property file (1) from environment variable")); + sliPropertiesFileResolvers.add(new CoreDefaultFileResolver("Using property file (2) from default directory")); + + sliPropertiesFileResolvers.add( + new JREFileResolver("Using property file (3) from JRE argument", SvcLogicPropertiesProvider.class)); + sliPropertiesFileResolvers.add(new KarafRootFileResolver("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 (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 ConfigurationException("Failed to load properties for file: " + propertiesFile.toString(), + e)); + } + } else { + // Try to read properties as resource + + InputStream propStr = getClass().getResourceAsStream("/" + SVCLOGIC_PROP_FILE_NAME); + if (propStr != null) { + properties = new Properties(); + try { + properties.load(propStr); + propStr.close(); + } catch (IOException e) { + properties = null; + } + } + + } + + if (properties == null) { + reportFailure("Missing configuration properties resource(3)", new ConfigurationException( + "Missing configuration properties resource(3): " + SVCLOGIC_PROP_FILE_NAME)); + } + } + + /** + * Extract svclogic config properties. + * + * @return the svclogic 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) { + if (fileOptional.isPresent()) { + final File file = fileOptional.get(); + LOG.info("{} {}", message, file.getPath()); + return file; + } + return null; + } + + /** + * Reports fatal errors. This is the case in which no properties file could be + * found. + * + * @param message + * An appropriate fatal error message + * @param configurationException + * An exception describing what went wrong during resolution + */ + private static void reportFailure(final String message, final ConfigurationException configurationException) { + + LOG.error("{}", message, configurationException); + } + + /** + * 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. + *
    + */ + File determinePropertiesFile(final SvcLogicPropertiesProvider resourceProvider) { + + for (final PropertiesFileResolver sliPropertiesFileResolver : sliPropertiesFileResolvers) { + final Optional fileOptional = sliPropertiesFileResolver.resolveFile(SVCLOGIC_PROP_FILE_NAME); + if (fileOptional.isPresent()) { + return reportSuccess(sliPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional); + } + } + + return null; + } +} diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java index 5f4d3653e..53875b35a 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/SvcLogicServiceImpl.java @@ -8,9 +8,9 @@ * 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. @@ -24,12 +24,16 @@ package org.onap.ccsdk.sli.core.sli.provider; import java.util.HashMap; import java.util.Properties; +import org.onap.ccsdk.sli.core.dblib.DbLibService; +import org.onap.ccsdk.sli.core.sli.ConfigurationException; import org.onap.ccsdk.sli.core.sli.MetricLogger; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicDblibStore; import org.onap.ccsdk.sli.core.sli.SvcLogicException; import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; import org.onap.ccsdk.sli.core.sli.SvcLogicNode; import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; @@ -51,6 +55,25 @@ public class SvcLogicServiceImpl implements SvcLogicService { private BundleContext bctx = null; + private Properties properties; + + private SvcLogicStore store; + + public SvcLogicServiceImpl(SvcLogicPropertiesProvider resourceProvider) throws SvcLogicException{ + + properties = resourceProvider.getProperties(); + + getStore(); + } + + public SvcLogicServiceImpl(SvcLogicPropertiesProvider resourceProvider, DbLibService dbSvc) throws SvcLogicException{ + + properties = resourceProvider.getProperties(); + store = new SvcLogicDblibStore(dbSvc); +} + + + private void registerExecutors() { LOG.info("Entered register executors"); @@ -210,8 +233,6 @@ public class SvcLogicServiceImpl implements SvcLogicService { @Override public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { - SvcLogicStore store = SvcLogicActivator.getStore(); - return (store.hasGraph(module, rpc, version, mode)); } @@ -226,8 +247,6 @@ public class SvcLogicServiceImpl implements SvcLogicService { public Properties execute(String module, String rpc, String version, String mode, Properties props, DOMDataBroker domDataBroker) throws SvcLogicException { - // See if there is a service logic defined - SvcLogicStore store = SvcLogicActivator.getStore(); LOG.info("Fetching service logic from data store"); SvcLogicGraph graph = store.fetch(module, rpc, version, mode); @@ -249,4 +268,28 @@ public class SvcLogicServiceImpl implements SvcLogicService { return(ctx.toProperties()); } + + public SvcLogicStore getStore() throws SvcLogicException { + // Create and initialize SvcLogicStore object - used to access + // saved service logic. + + if (store != null) { + return store; + } + + try { + store = SvcLogicStoreFactory.getSvcLogicStore(properties); + } catch (Exception e) { + throw new ConfigurationException("Could not get service logic store", e); + + } + + try { + store.init(properties); + } catch (SvcLogicException e) { + throw new ConfigurationException("Could not get service logic store", e); + } + + return store; + } } diff --git a/sli/provider/src/main/resources/org/opendaylight/blueprint/sli-blueprint.xml b/sli/provider/src/main/resources/org/opendaylight/blueprint/sli-blueprint.xml new file mode 100755 index 000000000..829057426 --- /dev/null +++ b/sli/provider/src/main/resources/org/opendaylight/blueprint/sli-blueprint.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + org.onap.ccsdk.sli.core.sli.provider.SvcLogicService + + + + \ No newline at end of file diff --git a/sli/provider/src/main/resources/svclogic.properties b/sli/provider/src/main/resources/svclogic.properties new file mode 100644 index 000000000..49d39ab40 --- /dev/null +++ b/sli/provider/src/main/resources/svclogic.properties @@ -0,0 +1,25 @@ +### +# ============LICENSE_START======================================================= +# ONAP : CCSDK +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +org.onap.ccsdk.sli.dbtype = dblib +org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true +org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver +org.onap.ccsdk.sli.jdbc.database = sdnctl diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java index 48e49f812..eccbfc9e8 100644 --- a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ExecuteNodeExecutorTest.java @@ -8,9 +8,9 @@ * 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. @@ -53,7 +53,8 @@ public class ExecuteNodeExecutorTest extends TestCase { MockExecuteNodeExecutor execute = new MockExecuteNodeExecutor(); SvcLogicNode node = new SvcLogicNode(0, "", "", new SvcLogicGraph()); node.setAttribute("method", "selectLunch"); - execute.execute(new SvcLogicServiceImpl(), new SvcLogicNode(0, "", "", new SvcLogicGraph()), new SvcLogicContext()); + SvcLogicPropertiesProvider resourceProvider = new SvcLogicPropertiesProvider(); + execute.execute(new SvcLogicServiceImpl(resourceProvider), new SvcLogicNode(0, "", "", new SvcLogicGraph()), new SvcLogicContext()); } } diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java index 724e946d5..18f044b30 100644 --- a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java @@ -102,8 +102,8 @@ public class ITCaseSvcLogicGraphExecutor { SvcLogicParser parser = new SvcLogicParser(); // Loop through executor tests - - SvcLogicServiceImpl svc = new SvcLogicServiceImpl(); + SvcLogicPropertiesProvider resourceProvider = new SvcLogicPropertiesProvider(); + SvcLogicServiceImpl svc = new SvcLogicServiceImpl(resourceProvider); for (String nodeType : BUILTIN_NODES.keySet()) { LOG.info("SLI - registering node executor for node type " + nodeType); @@ -156,8 +156,9 @@ public class ITCaseSvcLogicGraphExecutor { SvcLogicParser parser = new SvcLogicParser(); // Loop through executor tests + SvcLogicPropertiesProvider resourceProvider = new SvcLogicPropertiesProvider(); - SvcLogicServiceImpl svc = new SvcLogicServiceImpl(); + SvcLogicServiceImpl svc = new SvcLogicServiceImpl(resourceProvider); for (String nodeType : BUILTIN_NODES.keySet()) { diff --git a/sli/provider/src/test/resources/svclogic.properties b/sli/provider/src/test/resources/svclogic.properties index 25eb3bd47..49d39ab40 100644 --- a/sli/provider/src/test/resources/svclogic.properties +++ b/sli/provider/src/test/resources/svclogic.properties @@ -8,9 +8,9 @@ # 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. @@ -19,8 +19,7 @@ # ============LICENSE_END========================================================= ### -org.onap.ccsdk.sli.dbtype = jdbc -org.onap.ccsdk.sli.jdbc.url = jdbc:mysql://localhost:3306/sdnctl +org.onap.ccsdk.sli.dbtype = dblib +org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true +org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver org.onap.ccsdk.sli.jdbc.database = sdnctl -org.onap.ccsdk.sli.jdbc.user = sdnctl -org.onap.ccsdk.sli.jdbc.password = gamma diff --git a/sli/recording/pom.xml b/sli/recording/pom.xml index b571cfbb9..e8b136fdd 100755 --- a/sli/recording/pom.xml +++ b/sli/recording/pom.xml @@ -1,24 +1,38 @@ 4.0.0 + - org.onap.ccsdk.sli.core - sli - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core sli-recording + 0.2.1-SNAPSHOT bundle - SLI - Recording + + ccsdk-sli-core :: sli :: ${project.artifactId} + SLI Recording is an OSGi bundle that implements recording service for the service logic record node. + UTF-8 + + + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + - - junit - junit - ${junit.version} - test - org.onap.ccsdk.sli.core sli-common @@ -48,28 +62,23 @@ compile - - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.onap.ccsdk.sli.core.sli.recording;version=${project.version} - true - - - - + + org.opendaylight.controller + sal-binding-api + - + + + junit + junit + test + + + org.mockito + mockito-core + test + - - - SLI Recording is an OSGi bundle that implements recording service for the service logic record node. + diff --git a/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml b/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml new file mode 100644 index 000000000..8ea5ca86e --- /dev/null +++ b/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + single-feature-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + ccsdk-sliPluginUtils + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} + + + + + org.opendaylight.mdsal.model + mdsal-model-artifacts + 0.11.1 + pom + import + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.opendaylight.controller + odl-mdsal-broker + xml + features + + + + ${project.groupId} + ccsdk-sli + ${project.version} + xml + features + + + + ${project.groupId} + sliPluginUtils-provider + ${project.version} + + + equinoxSDK381 + org.eclipse.osgi + ${equinox.osgi.version} + provided + + + diff --git a/sliPluginUtils/features/features-sliPluginUtils/pom.xml b/sliPluginUtils/features/features-sliPluginUtils/pom.xml new file mode 100644 index 000000000..004277dd3 --- /dev/null +++ b/sliPluginUtils/features/features-sliPluginUtils/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + feature-repo-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + features-sliPluginUtils + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} + + + + ${project.groupId} + ccsdk-sliPluginUtils + ${project.version} + xml + features + + + + diff --git a/sliPluginUtils/features/pom.xml b/sliPluginUtils/features/pom.xml index 19d32f7a2..4a1f89947 100755 --- a/sliPluginUtils/features/pom.xml +++ b/sliPluginUtils/features/pom.xml @@ -1,127 +1,23 @@ - - sliPluginUtils-features - jar 4.0.0 - sliPluginUtils - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - SliPluginUtils Plugin - Features - - - - org.onap.ccsdk.sli.core - sliPluginUtils-provider - ${project.version} - - - commons-lang - commons-lang - ${commons.lang.version} - compile - - - org.opendaylight.mdsal - features-mdsal - ${odl.mdsal.features.version} - features - xml - runtime - - - - org.opendaylight.odlparent - opendaylight-karaf-empty - ${odl.karaf.empty.distro.version} - zip - - - - org.opendaylight.odlparent - features-test - ${odl.commons.opendaylight.version} - test - - - org.opendaylight.yangtools - features-yangtools - ${odl.yangtools.version} - features - xml - runtime - - - - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - + org.onap.ccsdk.sli.core + sliPluginUtils-features + 0.2.1-SNAPSHOT + pom - + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - + + features-sliPluginUtils + ccsdk-sliPluginUtils + diff --git a/sliPluginUtils/features/src/main/resources/features.xml b/sliPluginUtils/features/src/main/resources/features.xml deleted file mode 100644 index f59cea423..000000000 --- a/sliPluginUtils/features/src/main/resources/features.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features - - - - - odl-mdsal-broker - sdnc-sli - mvn:org.onap.ccsdk.sli.core/sliPluginUtils-provider/${project.version} - - - diff --git a/sliPluginUtils/installer/pom.xml b/sliPluginUtils/installer/pom.xml index 736d22202..1c0704af6 100755 --- a/sliPluginUtils/installer/pom.xml +++ b/sliPluginUtils/installer/pom.xml @@ -1,18 +1,24 @@ 4.0.0 + - sliPluginUtils - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + org.onap.ccsdl.sli.core sliPluginUtils-installer - SLI Plugin Utilities - Karaf Installer + 0.2.1-SNAPSHOT pom + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} + - sdnc-sliPluginUtils - sdnc-sliPluginUtils + ccsdk-sliPluginUtils + ${application.name} mvn:org.onap.ccsdk.sli.core/sliPluginUtils-features/${project.version}/xml/features false @@ -21,10 +27,10 @@ org.onap.ccsdk.sli.core - sliPluginUtils-features + ${application.name} ${project.version} - features xml + features * @@ -134,5 +140,4 @@ - diff --git a/sliPluginUtils/pom.xml b/sliPluginUtils/pom.xml index 21efb170b..45be684f7 100755 --- a/sliPluginUtils/pom.xml +++ b/sliPluginUtils/pom.xml @@ -1,38 +1,22 @@ - + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + org.onap.ccsdk.sli.core sliPluginUtils - 0.2.0-SNAPSHOT + 0.2.1-SNAPSHOT pom - 4.0.0 - - - org.onap.ccsdk.sli.core - ccsdk-sli-core - 0.2.0-SNAPSHOT - - Service Logic Interface Plugin Utilities + ccsdk-sli-core :: sliPluginUtils A package of static utility functions to be used when developing SLI plugins - - - - org.onap.ccsdk.sli.core - SliPluginUtils-features - features - xml - ${project.version} - - - org.onap.ccsdk.sli.core - SliPluginUtils-provider - ${project.version} - - - - provider features diff --git a/sliPluginUtils/provider/pom.xml b/sliPluginUtils/provider/pom.xml index 61b5e958f..0a274edd0 100755 --- a/sliPluginUtils/provider/pom.xml +++ b/sliPluginUtils/provider/pom.xml @@ -1,17 +1,20 @@ - - sliPluginUtils-provider - bundle 4.0.0 - org.onap.ccsdk.sli.core - sliPluginUtils - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + - SliPluginUtils Plugin - Provider + org.onap.ccsdk.sli.core + sliPluginUtils-provider + 0.2.1-SNAPSHOT + bundle + + ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} http://maven.apache.org @@ -22,11 +25,10 @@ junit junit - ${junit.version} test - org.onap.ccsdk.sli.core + ${project.groupId} sli-common ${project.version} compile @@ -34,22 +36,18 @@ equinoxSDK381 org.eclipse.osgi - ${equinox.osgi.version} org.slf4j slf4j-api - ${slf4j.version} org.slf4j jcl-over-slf4j - ${slf4j.version} org.apache.commons commons-lang3 - 3.1 org.hamcrest @@ -68,27 +66,4 @@ 1.1 - - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.onap.ccsdk.sli.core.slipluginutils - org.onap.ccsdk.sli.core.slipluginutils - org.onap.ccsdk.sli.core.*,org.osgi.framework.*,org.slf4j.*,java.net.* - *;scope=compile|runtime;artifactId=!sli-common|org.eclipse.osgi|mariadb-java-client|slf4j-api|jcl-over-slf4j - true - - - - - - - diff --git a/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/Dme2PropertiesProvider.java b/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/Dme2PropertiesProvider.java index 07c84c66f..6802c9a8b 100644 --- a/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/Dme2PropertiesProvider.java +++ b/sliPluginUtils/provider/src/main/java/org/onap/ccsdk/sli/core/slipluginutils/Dme2PropertiesProvider.java @@ -8,9 +8,9 @@ * 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. @@ -31,193 +31,248 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; +import java.util.Vector; +import org.onap.ccsdk.sli.core.utils.JREFileResolver; +import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; +import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; +import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Immutable properties container for dme2 properties. Since the initial design decision was made to - * utilize Properties instead of an OSGi ManagedService, it was decided - * to make these properties immutable. + * Immutable properties container for dme2 properties. Since the initial design + * decision was made to utilize Properties instead of an OSGi + * ManagedService, it was decided to make these properties + * immutable. */ public final class Dme2PropertiesProvider { - private static final Logger LOG = LoggerFactory.getLogger(Dme2PropertiesProvider.class); - - /** - * The name of the environment variable to specify the configuration directory. - */ - private static final String SDNC_ROOT_DIR_ENV_VAR_KEY = "SDNC_CONFIG_DIR"; - - /** - * the dme2 properties file name. - */ - private static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties"; - - /** - * the key for proxyUrl, which represents a CSV list of urls - */ - static final String PROXY_URL_KEY = "proxyUrl"; - - /** - * indicates that proxy urls are separated by commas - */ - private static final String PROXY_URLS_VALUE_SEPARATOR = ","; - - /** - * the key for aafUserName - */ - static final String AAF_USERNAME_KEY = "aafUserName"; - - /** - * the key for aafPassword - */ - static final String AAF_PASSWORD_KEY = "aafPassword"; - - /** - * the key for envContext - */ - static final String ENV_CONTEXT_KEY = "envContext"; - - /** - * the key for routeOffer - */ - static final String ROUTE_OFFER_KEY = "routeOffer"; - - /** - * the key for commonServiceVersion - */ - static final String COMMON_SERVICE_VERSION_KEY = "commonServiceVersion"; - - /** - * the key for partner - */ - static final String PARTNER_KEY = "partner"; - - private Optional proxyUrls = Optional.empty(); - - private Optional aafUsername = Optional.empty(); - - private Optional aafPassword = Optional.empty(); - - private Optional envContext = Optional.empty(); - - private Optional routeOffer = Optional.empty(); - - private Optional commonServiceVersion = Optional.empty(); - - private Optional partner = Optional.empty(); - - - /** - * Instantiates the properties provider, which involves loading the appropriate properties for dme2. - */ - public Dme2PropertiesProvider() { - this(getDme2Path(SDNC_ROOT_DIR_ENV_VAR_KEY, DME2_PROPERTIES_FILE_NAME).toString()); - } - - /** - * Instantiates the properties provider, which involves loading the appropriate properties for dme2. - * - * @param dme2Path location of the dme2.properties file - */ - @VisibleForTesting - Dme2PropertiesProvider(final String dme2Path) { - final Properties properties; - try { - properties = getProperties(dme2Path); - this.proxyUrls = getProxyUrls(properties); - this.aafUsername = getAafUsername(properties); - this.aafPassword = getAafPassword(properties); - this.envContext = getEnvContext(properties); - this.routeOffer = getRouteOffer(properties); - this.commonServiceVersion = getCommonServiceVersion(properties); - this.partner = getPartner(properties); - } catch (final FileNotFoundException e) { - LOG.error("dme2.properties file could not be found at path: {}", dme2Path, e); - } catch (final IOException e) { - LOG.error("fatal error reading dme2.properties at path: {}", dme2Path, e); - } - } - - private static Path getDme2Path(final String sdncRootDirectory, final String dme2Filename) { - return Paths.get(sdncRootDirectory, dme2Filename); - } - - private static Properties getProperties(final String dme2Path) throws IOException { - final File dme2File = new File(dme2Path); - final Properties properties = new Properties(); - properties.load(new FileReader(dme2File)); - return properties; - } - - private String getProxyUrl(final Properties properties) { - return properties.getProperty(PROXY_URL_KEY); - } - - private Optional getProxyUrls(final Properties properties) { - final String proxyUrlsValue = getProxyUrl(properties); - if (!Strings.isNullOrEmpty(proxyUrlsValue)) { - return Optional.ofNullable(proxyUrlsValue.split(PROXY_URLS_VALUE_SEPARATOR)); - } - return Optional.empty(); - } - - public Optional getProxyUrls() { - return this.proxyUrls; - } - - private Optional getAafUsername(final Properties properties) { - final String aafUsernameValue = properties.getProperty(AAF_USERNAME_KEY); - return Optional.ofNullable(aafUsernameValue); - } - - Optional getAafUsername() { - return this.aafUsername; - } - - private Optional getAafPassword(final Properties properties) { - final String aafPassword = properties.getProperty(AAF_PASSWORD_KEY); - return Optional.ofNullable(aafPassword); - } - - Optional getAafPassword() { - return this.aafPassword; - } - - private Optional getEnvContext(final Properties properties) { - final String envContext = properties.getProperty(ENV_CONTEXT_KEY); - return Optional.ofNullable(envContext); - } - - Optional getEnvContext() { - return this.envContext; - } - - private Optional getRouteOffer(final Properties properties) { - final String routeOffer = properties.getProperty(ROUTE_OFFER_KEY); - return Optional.ofNullable(routeOffer); - } - - Optional getRouteOffer() { - return this.routeOffer; - } - - private Optional getCommonServiceVersion(final Properties properties) { - final String commonServiceVersion = properties.getProperty(COMMON_SERVICE_VERSION_KEY); - return Optional.ofNullable(commonServiceVersion); - } - - Optional getCommonServiceVersion() { - return this.commonServiceVersion; - } - - private Optional getPartner(final Properties properties) { - final String partner = properties.getProperty(PARTNER_KEY); - return Optional.ofNullable(partner); - } - - Optional getPartner() { - return this.partner; - } + private static final Logger LOG = LoggerFactory.getLogger(Dme2PropertiesProvider.class); + + /** + * The name of the environment variable to specify the configuration directory. + */ + private static final String SDNC_ROOT_DIR_ENV_VAR_KEY = "SDNC_CONFIG_DIR"; + + /** + * the dme2 properties file name. + */ + private static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties"; + + /** + * the key for proxyUrl, which represents a CSV list of urls + */ + static final String PROXY_URL_KEY = "proxyUrl"; + + /** + * indicates that proxy urls are separated by commas + */ + private static final String PROXY_URLS_VALUE_SEPARATOR = ","; + + /** + * the key for aafUserName + */ + static final String AAF_USERNAME_KEY = "aafUserName"; + + /** + * the key for aafPassword + */ + static final String AAF_PASSWORD_KEY = "aafPassword"; + + /** + * the key for envContext + */ + static final String ENV_CONTEXT_KEY = "envContext"; + + /** + * the key for routeOffer + */ + static final String ROUTE_OFFER_KEY = "routeOffer"; + + /** + * the key for commonServiceVersion + */ + static final String COMMON_SERVICE_VERSION_KEY = "commonServiceVersion"; + + /** + * the key for partner + */ + static final String PARTNER_KEY = "partner"; + + private Optional proxyUrls = Optional.empty(); + + private Optional aafUsername = Optional.empty(); + + private Optional aafPassword = Optional.empty(); + + private Optional envContext = Optional.empty(); + + private Optional routeOffer = Optional.empty(); + + private Optional commonServiceVersion = Optional.empty(); + + private Optional partner = Optional.empty(); + + /** + * A prioritized list of strategies for resolving dme2 properties files. + */ + private Vector dme2PropertiesFileResolvers = new Vector<>(); + + /** + * Instantiates the properties provider, which involves loading the appropriate + * properties for dme2. + */ + public Dme2PropertiesProvider() { + this(DME2_PROPERTIES_FILE_NAME); + } + + /** + * Instantiates the properties provider, which involves loading the appropriate + * properties for dme2. + * + * @param dme2Path + * location of the dme2.properties file + */ + @VisibleForTesting + Dme2PropertiesProvider(final String dme2FileName) { + dme2PropertiesFileResolvers + .add(new SdncConfigEnvVarFileResolver("Using property file (1) from environment variable")); + dme2PropertiesFileResolvers.add(new CoreDefaultFileResolver("Using property file (2) from default directory")); + + dme2PropertiesFileResolvers + .add(new JREFileResolver("Using property file (3) from JRE argument", Dme2PropertiesProvider.class)); + dme2PropertiesFileResolvers.add(new KarafRootFileResolver("Using property file (4) from karaf root", this)); + + File dme2File = getDme2File(dme2FileName); + + init(dme2File); + } + + private void init(final File dme2Path) { + final Properties properties; + try { + properties = getProperties(dme2Path); + this.proxyUrls = getProxyUrls(properties); + this.aafUsername = getAafUsername(properties); + this.aafPassword = getAafPassword(properties); + this.envContext = getEnvContext(properties); + this.routeOffer = getRouteOffer(properties); + this.commonServiceVersion = getCommonServiceVersion(properties); + this.partner = getPartner(properties); + } catch (final FileNotFoundException e) { + + LOG.error("dme2.properties file could not be found at path: {}", dme2Path, e); + } catch (final IOException e) { + LOG.error("fatal error reading dme2.properties at path: {}", dme2Path, e); + } + } + + /** + * 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) { + if (fileOptional.isPresent()) { + final File file = fileOptional.get(); + LOG.info("{} {}", message, file.getPath()); + return file; + } + return null; + } + + private File getDme2File(final String dme2Filename) { + + for (final PropertiesFileResolver dblibPropertiesFileResolver : dme2PropertiesFileResolvers) { + final Optional fileOptional = dblibPropertiesFileResolver.resolveFile(dme2Filename); + if (fileOptional.isPresent()) { + return reportSuccess(dblibPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional); + } + } + return (new File(dme2Filename)); + } + + private static Properties getProperties(final File dme2File) throws IOException { + + final Properties properties = new Properties(); + properties.load(new FileReader(dme2File)); + return properties; + } + + private String getProxyUrl(final Properties properties) { + return properties.getProperty(PROXY_URL_KEY); + } + + private Optional getProxyUrls(final Properties properties) { + final String proxyUrlsValue = getProxyUrl(properties); + if (!Strings.isNullOrEmpty(proxyUrlsValue)) { + return Optional.ofNullable(proxyUrlsValue.split(PROXY_URLS_VALUE_SEPARATOR)); + } + return Optional.empty(); + } + + public Optional getProxyUrls() { + return this.proxyUrls; + } + + private Optional getAafUsername(final Properties properties) { + final String aafUsernameValue = properties.getProperty(AAF_USERNAME_KEY); + return Optional.ofNullable(aafUsernameValue); + } + + Optional getAafUsername() { + return this.aafUsername; + } + + private Optional getAafPassword(final Properties properties) { + final String aafPassword = properties.getProperty(AAF_PASSWORD_KEY); + return Optional.ofNullable(aafPassword); + } + + Optional getAafPassword() { + return this.aafPassword; + } + + private Optional getEnvContext(final Properties properties) { + final String envContext = properties.getProperty(ENV_CONTEXT_KEY); + return Optional.ofNullable(envContext); + } + + Optional getEnvContext() { + return this.envContext; + } + + private Optional getRouteOffer(final Properties properties) { + final String routeOffer = properties.getProperty(ROUTE_OFFER_KEY); + return Optional.ofNullable(routeOffer); + } + + Optional getRouteOffer() { + return this.routeOffer; + } + + private Optional getCommonServiceVersion(final Properties properties) { + final String commonServiceVersion = properties.getProperty(COMMON_SERVICE_VERSION_KEY); + return Optional.ofNullable(commonServiceVersion); + } + + Optional getCommonServiceVersion() { + return this.commonServiceVersion; + } + + private Optional getPartner(final Properties properties) { + final String partner = properties.getProperty(PARTNER_KEY); + return Optional.ofNullable(partner); + } + + Optional getPartner() { + return this.partner; + } } diff --git a/sliPluginUtils/provider/src/main/resources/dme2.properties b/sliPluginUtils/provider/src/main/resources/dme2.properties new file mode 100644 index 000000000..373448447 --- /dev/null +++ b/sliPluginUtils/provider/src/main/resources/dme2.properties @@ -0,0 +1,7 @@ +aafUserName=user@sample.com +aafPassword=fake +envContext=UAT +routeOffer=UAT +proxyUrl=http://sample.com:25055,http://sample.com:25055 +commonServiceVersion=1702.0 +partner= \ No newline at end of file diff --git a/sliapi/features/ccsdk-sliapi/pom.xml b/sliapi/features/ccsdk-sliapi/pom.xml new file mode 100644 index 000000000..be4025b4a --- /dev/null +++ b/sliapi/features/ccsdk-sliapi/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + single-feature-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + ccsdk-sliapi + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: sliapi :: ${project.artifactId} + + + + + org.opendaylight.mdsal.model + mdsal-model-artifacts + 0.11.1 + pom + import + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.opendaylight.controller + odl-mdsal-broker + xml + features + + + + ${project.groupId} + ccsdk-sli + ${project.version} + xml + features + + + + ${project.groupId} + sliapi-provider + ${project.version} + + + + diff --git a/sliapi/features/features-sliapi/pom.xml b/sliapi/features/features-sliapi/pom.xml new file mode 100644 index 000000000..f3481cba8 --- /dev/null +++ b/sliapi/features/features-sliapi/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + feature-repo-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + features-sliapi + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: sliapi :: ${project.artifactId} + + + + ${project.groupId} + ccsdk-sliapi + ${project.version} + xml + features + + + + diff --git a/sliapi/features/pom.xml b/sliapi/features/pom.xml index 78bfb89a4..17fa8fb41 100755 --- a/sliapi/features/pom.xml +++ b/sliapi/features/pom.xml @@ -1,134 +1,23 @@ 4.0.0 + - sliapi - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - sliapi-features - - jar - - - - org.onap.ccsdk.sli.core - sliapi-model - - - org.onap.ccsdk.sli.core - sliapi-provider - config - xml - - - org.onap.ccsdk.sli.core - sliapi-provider - - - - org.opendaylight.mdsal - features-mdsal - ${odl.mdsal.features.version} - features - xml - - runtime - - - - - - - org.opendaylight.odlparent - opendaylight-karaf-empty - ${odl.karaf.empty.distro.version} - zip - - - - - - org.opendaylight.odlparent - features-test - test - ${odl.commons.opendaylight.version} - - - org.opendaylight.yangtools - features-yangtools - ${odl.yangtools.version} - features - xml - runtime - - + org.onap.ccsdk.sli.core + sliapi-feature-aggregator + 0.2.1-SNAPSHOT + pom - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - + + features-sliapi + ccsdk-sliapi + diff --git a/sliapi/features/src/main/resources/features.xml b/sliapi/features/src/main/resources/features.xml deleted file mode 100644 index c5df348fa..000000000 --- a/sliapi/features/src/main/resources/features.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features - - - - odl-mdsal-broker - sdnc-sli - mvn:org.onap.ccsdk.sli.core/sliapi-model/${project.version} - mvn:org.onap.ccsdk.sli.core/sliapi-provider/${project.version} - mvn:org.onap.ccsdk.sli.core/sliapi-provider/${project.version}/xml/config - - - diff --git a/sliapi/installer/pom.xml b/sliapi/installer/pom.xml index cddcf6dd7..290524e32 100755 --- a/sliapi/installer/pom.xml +++ b/sliapi/installer/pom.xml @@ -1,18 +1,25 @@ 4.0.0 + - sliapi - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core sliapi-installer + 0.2.1-SNAPSHOT pom + ccsdk-sli-core :: sliapi :: ${project.artifactId} + - sdnc-sliapi - sdnc-sliapi - mvn:org.onap.ccsdk.sli.core/sliapi-features/${project.version}/xml/features + ccsdk-sliapi + ${application.name} + mvn:org.onap.ccsdk.sli.core/${features.boot}/${project.version}/xml/features false @@ -20,10 +27,10 @@ org.onap.ccsdk.sli.core - sliapi-features + ${application.name} ${project.version} - features xml + features * @@ -133,5 +140,4 @@ - diff --git a/sliapi/installer/src/assembly/assemble_mvnrepo_zip.xml b/sliapi/installer/src/assembly/assemble_mvnrepo_zip.xml index e22c6f567..5f3e3af31 100644 --- a/sliapi/installer/src/assembly/assemble_mvnrepo_zip.xml +++ b/sliapi/installer/src/assembly/assemble_mvnrepo_zip.xml @@ -8,9 +8,9 @@ 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. @@ -44,12 +44,6 @@ - - - ../provider/src/main/resources/initial/${feature-name}-provider.xml - ./etc/opendaylight/karaf/200-${feature-name}provider.xml - - diff --git a/sliapi/model/pom.xml b/sliapi/model/pom.xml index 4ea88516a..bbdcea051 100755 --- a/sliapi/model/pom.xml +++ b/sliapi/model/pom.xml @@ -1,89 +1,29 @@ 4.0.0 + - sliapi - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core sliapi-model + 0.2.1-SNAPSHOT bundle - + ccsdk-sli-core :: sliapi :: ${project.artifactId} - - - org.apache.felix - maven-bundle-plugin - true - - - * - - - - - org.opendaylight.yangtools - yang-maven-plugin - ${odl.yangtools.yang.maven.plugin.version} - - - org.opendaylight.mdsal - maven-sal-api-gen-plugin - ${odl.sal.api.gen.plugin.version} - jar - - - org.opendaylight.netconf - sal-rest-docgen-maven - ${odl.restconf.version} - jar - - - - - - generate-sources - - - ${yang.file.directory} - - - org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl - ${salGeneratorPath} - - - org.opendaylight.netconf.sal.rest.doc.maven.StaticDocGenerator - target/swagger - - - true - - - - - - - - org.opendaylight.mdsal - yang-binding - ${odl.mdsal.yang.binding.version} - - - org.opendaylight.yangtools - yang-common - ${odl.yangtools.version} - org.opendaylight.mdsal.model ietf-inet-types - ${odl.ietf-inet-types.version} org.opendaylight.mdsal.model ietf-yang-types - ${odl.ietf-yang-types.version} diff --git a/sliapi/pom.xml b/sliapi/pom.xml index a08d8fcb8..46057da0f 100755 --- a/sliapi/pom.xml +++ b/sliapi/pom.xml @@ -1,56 +1,20 @@ - + 4.0.0 - - org.onap.ccsdk.sli.core - ccsdk-sli-core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + - pom org.onap.ccsdk.sli.core sliapi - 0.2.0-SNAPSHOT - - - sliapi - - - - - - - - org.onap.ccsdk.sli.core - sliapi-features - features - xml - ${project.version} - - - - org.onap.ccsdk.sli.core - sliapi-model - ${project.version} - - - org.onap.ccsdk.sli.core - sliapi-provider - ${project.version} - config - xml - - - org.onap.ccsdk.sli.core - sliapi-provider - ${project.version} - - - + 0.2.1-SNAPSHOT + pom - + ccsdk-sli-core :: sliapi model @@ -58,4 +22,8 @@ provider installer + + + sliapi + diff --git a/sliapi/provider/pom.xml b/sliapi/provider/pom.xml index 5db9671d6..cb4dfc898 100755 --- a/sliapi/provider/pom.xml +++ b/sliapi/provider/pom.xml @@ -1,125 +1,53 @@ 4.0.0 + - sliapi - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core sliapi-provider + 0.2.1-SNAPSHOT bundle - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.config.yang.config.sliapi.impl - * - - - - - org.opendaylight.yangtools - yang-maven-plugin - ${odl.yangtools.yang.maven.plugin.version} - - - config - - generate-sources - - - - - org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - ${jmxGeneratorPath} - - urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang - - - - - org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl - ${salGeneratorPath} - - - true - - - - - - org.opendaylight.mdsal - maven-sal-api-gen-plugin - ${odl.sal.api.gen.plugin.version} - jar - - - org.opendaylight.controller - yang-jmx-generator-plugin - ${odl.yang.jmx.generator.version} - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/initial/sliapi-provider.xml - xml - config - - - - - - - - + ccsdk-sli-core :: sliapi :: ${project.artifactId} + + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + org.onap.ccsdk.sli.core sliapi-model - - - org.opendaylight.controller - config-api - ${odl.controller.config.api.version} + ${project.version} org.opendaylight.controller sal-binding-config - ${odl.mdsal.version} org.opendaylight.controller sal-binding-api - ${odl.mdsal.version} org.opendaylight.controller sal-common-util - ${odl.mdsal.version} @@ -136,12 +64,10 @@ org.opendaylight.controller sal-core-api - ${odl.mdsal.version} org.opendaylight.yangtools yang-data-impl - ${odl.yangtools.version} diff --git a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java index 82e660083..c3ad4ed60 100644 --- a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java +++ b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java @@ -31,6 +31,7 @@ import java.util.Properties; import java.util.concurrent.Future; import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService; import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; import org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedDataBroker; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; @@ -118,7 +119,7 @@ public class sliapiProvider implements AutoCloseable, SLIAPIService{ protected DataBroker dataBroker; protected DOMDataBroker domDataBroker; - protected NotificationProviderService notificationService; + protected NotificationPublishService notificationService; protected RpcProviderRegistry rpcRegistry; protected BindingAwareBroker.RpcRegistration rpcRegistration; @@ -142,16 +143,24 @@ public class sliapiProvider implements AutoCloseable, SLIAPIService{ } - public sliapiProvider() { + public sliapiProvider( + DataBroker dataBroker, + NotificationPublishService notificationPublishService, + RpcProviderRegistry rpcProviderRegistry) { this.LOG.info( "Creating provider for " + appName ); + this.dataBroker = dataBroker; + this.notificationService = notificationPublishService; + this.rpcRegistry = rpcProviderRegistry; + initialize(); } + + public void initialize(){ LOG.info( "Initializing provider for " + appName ); //initialization code goes here. sdncStatusFile = System.getenv(SDNC_STATUS_FILE); LOG.info( "SDNC STATUS FILE = " + sdncStatusFile ); - rpcRegistration = rpcRegistry.addRpcImplementation(SLIAPIService.class, this); LOG.info( "Initialization complete for " + appName ); } @@ -179,7 +188,7 @@ public class sliapiProvider implements AutoCloseable, SLIAPIService{ } public void setNotificationService( - NotificationProviderService notificationService) { + NotificationPublishService notificationService) { this.notificationService = notificationService; if( LOG.isDebugEnabled() ){ LOG.debug( "Notification Service set to " + (notificationService==null?"null":"non-null") + "." ); diff --git a/sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModule.java b/sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModule.java deleted file mode 100644 index e7444e318..000000000 --- a/sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModule.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : CCSDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.provider.impl.rev140523; - -import org.onap.ccsdk.sli.core.sliapi.sliapiProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SliapiProviderModule extends org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.provider.impl.rev140523.AbstractSliapiProviderModule { - private final Logger LOG = LoggerFactory.getLogger( SliapiProviderModule.class ); - - public SliapiProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { - super(identifier, dependencyResolver); - } - - public SliapiProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.provider.impl.rev140523.SliapiProviderModule oldModule, java.lang.AutoCloseable oldInstance) { - super(identifier, dependencyResolver, oldModule, oldInstance); - } - - @Override - public void customValidation() { - // add custom validation form module attributes here. - } - - @Override - public java.lang.AutoCloseable createInstance() { - - LOG.info("Calling SliapiProviderModule.createInstance"); - final sliapiProvider provider = new sliapiProvider(); - provider.setDataBroker( getDataBrokerDependency() ); - provider.setNotificationService( getNotificationServiceDependency() ); - provider.setRpcRegistry( getRpcRegistryDependency() ); - provider.initialize(); - return new AutoCloseable() { - - @Override - public void close() throws Exception { - //TODO: CLOSE ANY REGISTRATION OBJECTS CREATED USING ABOVE BROKER/NOTIFICATION - //SERVIE/RPC REGISTRY - provider.close(); - } - }; - } - -} diff --git a/sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModuleFactory.java b/sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModuleFactory.java deleted file mode 100644 index 6454d17c4..000000000 --- a/sliapi/provider/src/main/java/org/opendaylight/yang/gen/v1/org/onap/ccsdk/sli/core/sliapi/provider/impl/rev140523/SliapiProviderModuleFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : CCSDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/* -* Generated file -* -* Generated from: yang module name: sliapi-provider-impl yang module local name: sliapi-provider-impl -* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator -* Generated at: Thu Aug 03 16:10:18 EDT 2017 -* -* Do not modify this file unless it is present under src/main directory -*/ -package org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.provider.impl.rev140523; -public class SliapiProviderModuleFactory extends org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.provider.impl.rev140523.AbstractSliapiProviderModuleFactory { - -} diff --git a/sliapi/provider/src/main/resources/initial/sliapi-provider.xml b/sliapi/provider/src/main/resources/initial/sliapi-provider.xml deleted file mode 100644 index 47d31d0ab..000000000 --- a/sliapi/provider/src/main/resources/initial/sliapi-provider.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - prefix:sliapi-provider-impl - - sliapi-provider-impl - - - - binding:binding-rpc-registry - binding-rpc-broker - - - - binding:binding-async-data-broker - binding-data-broker - - - - - binding:binding-notification-service - - binding-notification-broker - - - - - - - - - - - org:onap:ccsdk:sli:core:sliapi:provider:impl?module=sliapi-provider-impl&revision=2014-05-23 - - - diff --git a/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml b/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml new file mode 100644 index 000000000..761b014a0 --- /dev/null +++ b/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/utils/features/features-util/pom.xml b/utils/features/features-util/pom.xml new file mode 100644 index 000000000..9a4cd43c5 --- /dev/null +++ b/utils/features/features-util/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + feature-repo-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + features-util + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: utils :: ${project.artifactId} + + + + ${project.groupId} + ccsdk-slicore-utils + ${project.version} + xml + features + + + + diff --git a/utils/features/features3-util/pom.xml b/utils/features/features3-util/pom.xml new file mode 100755 index 000000000..5cc0d8995 --- /dev/null +++ b/utils/features/features3-util/pom.xml @@ -0,0 +1,141 @@ + + + 4.0.0 + + utils + org.onap.ccsdk.sli.core + 0.2.0-SNAPSHOT + + + org.onap.ccsdk.sli.core + utils-features + ccsdk-sli-core :: utils :: ${project.artifactId} + DBLIB Adaptor - Features + + jar + + + + + + org.onap.ccsdk.sli.core + utils-provider + ${project.version} + + + + commons-lang + commons-lang + ${commons.lang.version} + compile + + + + org.opendaylight.mdsal + features-mdsal + ${odl.mdsal.features.version} + features + xml + + runtime + + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + + + org.opendaylight.odlparent + opendaylight-karaf-empty + ${odl.karaf.empty.distro.version} + zip + + + + + org.opendaylight.odlparent + features-test + ${odl.commons.opendaylight.version} + test + + + + org.opendaylight.yangtools + features-yangtools + ${odl.yangtools.version} + features + xml + runtime + + + + + + + true + src/main/resources + + + + + org.apache.maven.plugins + maven-resources-plugin + + + filter + + resources + + generate-resources + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + + attach-artifact + + package + + + + ${project.build.directory}/classes/${features.file} + xml + features + + + + + + + + + diff --git a/utils/features/features3-util/src/main/resources/features.xml b/utils/features/features3-util/src/main/resources/features.xml new file mode 100755 index 000000000..547832ba6 --- /dev/null +++ b/utils/features/features3-util/src/main/resources/features.xml @@ -0,0 +1,16 @@ + + + + + mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features + + + + + odl-mdsal-broker + mvn:org.onap.ccsdk.sli.core/utils-provider/${project.version} + + + diff --git a/utils/features/pom.xml b/utils/features/pom.xml index be6227d7e..8bc1cd8a8 100755 --- a/utils/features/pom.xml +++ b/utils/features/pom.xml @@ -1,138 +1,22 @@ - 4.0.0 - - utils - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT - - utils-features - DBLIB Adaptor - Features + 4.0.0 - jar + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + - + org.onap.ccsdk.sli.core + utils-features-aggregator + pom + ccsdk-sli-core :: utils :: ${project.artifactId} - - org.onap.ccsdk.sli.core - utils-provider - ${project.version} - - - - commons-lang - commons-lang - ${commons.lang.version} - compile - - - - org.opendaylight.mdsal - features-mdsal - ${odl.mdsal.features.version} - features - xml - - runtime - - - - org.apache.tomcat - tomcat-jdbc - ${tomcat-jdbc.version} - - - - - org.opendaylight.odlparent - opendaylight-karaf-empty - ${odl.karaf.empty.distro.version} - zip - - - - - org.opendaylight.odlparent - features-test - ${odl.commons.opendaylight.version} - test - - - - org.opendaylight.yangtools - features-yangtools - ${odl.yangtools.version} - features - xml - runtime - - - - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - + + features-util + sdnc-slicore-utils + diff --git a/utils/features/sdnc-slicore-utils/pom.xml b/utils/features/sdnc-slicore-utils/pom.xml new file mode 100644 index 000000000..85c81ff67 --- /dev/null +++ b/utils/features/sdnc-slicore-utils/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + + org.onap.ccsdk.parent + single-feature-parent + 1.0.1-SNAPSHOT + + + + org.onap.ccsdk.sli.core + ccsdk-slicore-utils + 0.2.1-SNAPSHOT + feature + + ccsdk-sli-core :: utils :: ${project.artifactId} + + + + + org.opendaylight.mdsal.model + mdsal-model-artifacts + 0.11.1 + pom + import + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.opendaylight.controller + odl-mdsal-broker + xml + features + + + + ${project.groupId} + utils-provider + ${project.version} + + + + diff --git a/utils/features/src/main/resources/features.xml b/utils/features/src/main/resources/features.xml deleted file mode 100755 index 547832ba6..000000000 --- a/utils/features/src/main/resources/features.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features - - - - - odl-mdsal-broker - mvn:org.onap.ccsdk.sli.core/utils-provider/${project.version} - - - diff --git a/utils/installer/pom.xml b/utils/installer/pom.xml index df7fc0de8..c19ac8c67 100755 --- a/utils/installer/pom.xml +++ b/utils/installer/pom.xml @@ -1,19 +1,25 @@ 4.0.0 + - utils - org.onap.ccsdk.sli.core - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + + org.onap.ccsdk.sli.core utils-installer - SLI core utils - Karaf Installer + 0.2.1-SNAPSHOT pom + ccsdk-sli-core :: utils :: ${project.artifactId} + - sdnc-slicore-utils - sdnc-slicore-utils - mvn:org.onap.ccsdk.sli.core/utils-features/${project.version}/xml/features + ccsdk-slicore-utils + ${application.name} + mvn:org.onap.ccsdk.sli.core/${features.boot}/${project.version}/xml/features false @@ -21,10 +27,10 @@ org.onap.ccsdk.sli.core - utils-features + ${application.name} ${project.version} - features xml + features * @@ -134,5 +140,4 @@ - diff --git a/utils/pom.xml b/utils/pom.xml index 17a0f6b6e..cd342f774 100755 --- a/utils/pom.xml +++ b/utils/pom.xml @@ -1,77 +1,26 @@ - - - org.onap.ccsdk.sli.core - ccsdk-sli-core - 0.2.0-SNAPSHOT + + 4.0.0 + + + org.onap.ccsdk.parent + odlparent-lite + 1.0.1-SNAPSHOT + + org.onap.ccsdk.sli.core + utils + 0.2.1-SNAPSHOT + pom - 4.0.0 - pom - org.onap.ccsdk.sli.core - utils - - - SLI Utils - Utilities used across sli-core - - 0.2.0-SNAPSHOT - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compile.plugin.version} - - ${java.version.source} - ${java.version.target} - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10 - - - - aggregate - - aggregate - - site - - - - - - maven-source-plugin - 2.1.1 - - - bundle-sources - package - - - jar-no-fork - - - test-jar-no-fork - - - - - - - - - - AT&T + ccsdk-sli-core :: utils + Utilities used across sli-core + + ONAP - + + provider features installer diff --git a/utils/provider/pom.xml b/utils/provider/pom.xml index b0adc7d46..7a4e8c9ed 100644 --- a/utils/provider/pom.xml +++ b/utils/provider/pom.xml @@ -1,21 +1,26 @@ - + + 4.0.0 - org.onap.ccsdk.sli.core - utils - 0.2.0-SNAPSHOT + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + - 4.0.0 - bundle + org.onap.ccsdk.sli.core utils-provider - SLI Core Utilities Package + 0.2.1-SNAPSHOT + bundle + ccsdk-sli-core :: utils :: ${project.artifactId} The SLI Core Utilities Package provides common functionality for setting up SLI connectivity. + + ONAP + @@ -26,6 +31,7 @@ equinoxSDK381 org.eclipse.osgi ${equinox.osgi.version} + provided @@ -41,17 +47,4 @@ test - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - - - - - Inocybe Technologies and Others - diff --git a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java index 8da9b7ef0..cc164d042 100755 --- a/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java +++ b/utils/provider/src/main/java/org/onap/ccsdk/sli/core/utils/JREFileResolver.java @@ -7,9 +7,9 @@ * 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. @@ -54,9 +54,11 @@ public class JREFileResolver implements PropertiesFileResolver { */ @Override public Optional resolveFile(final String filename) { + final Bundle bundle = FrameworkUtil.getBundle(this.clazz); final File dataFile; + try { if (bundle == null) { return Optional.empty(); @@ -67,6 +69,7 @@ public class JREFileResolver implements PropertiesFileResolver { return Optional.empty(); } + dataFile = bundle.getDataFile(filename); if(dataFile.exists()) { dataFile.delete(); -- cgit 1.2.3-korg From 650bf0cbd81be4af3203103188e69f68fdca3a01 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Wed, 14 Feb 2018 14:17:50 +0000 Subject: Fixed Java Code Conventions issue Changes made: * corrected sonar related issue in CachedDataSource class Change-Id: If84b9abcd115ad042f2cc0527b5ab8c8e12cae5a Issue-ID: CCSDK-151 Signed-off-by: Rich Tabedzki --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 1023 ++++++++++---------- 1 file changed, 511 insertions(+), 512 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 8dac33611..e5eff24a5 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -56,516 +56,515 @@ import org.slf4j.LoggerFactory; public abstract class CachedDataSource implements DataSource, SQLExecutionMonitorObserver { - private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); - - private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; - private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; - private static final String WITH_ARGUMENTS = " with arguments: "; - private static final String WITH_NO_ARGUMENTS = " with no arguments. "; - private static final String SQL_DATA_SOURCE = "SQL DataSource <"; - - protected long connReqTimeout = 30L; - protected long dataReqTimeout = 100L; - - private final SQLExecutionMonitor monitor; - protected DataSource ds = null; - protected String connectionName = null; - protected boolean initialized = false; - - private long interval = 1000; - private long initialDelay = 5000; - private long expectedCompletionTime = 50L; - private boolean canTakeOffLine = true; - private long unprocessedFailoverThreshold = 3L; - - private long nextErrorReportTime = 0L; - - private String globalHostName = null; - - private boolean isDerby = false; - - public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { - configure(jdbcElem); - - if ("org.apache.derby.jdbc.EmbeddedDriver".equals(jdbcElem.getDriverName())) { - isDerby = true; - } - monitor = new SQLExecutionMonitor(this); - } - - protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; - - /* - * (non-Javadoc) - * - * @see javax.sql.DataSource#getConnection() - */ - @Override - public Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - public CachedRowSet getData(String statement, List arguments) throws SQLException { - TestObject testObject = monitor.registerRequest(); - - try (Connection connection = this.getConnection()) { - if (connection == null) { - throw new SQLException("Connection invalid"); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); - } - return executePreparedStatement(connection, statement, arguments, true); - } finally { - monitor.deregisterRequest(testObject); - } - } - - public boolean writeData(String statement, List arguments) throws SQLException { - TestObject testObject = monitor.registerRequest(); - - try (Connection connection = this.getConnection()) { - if (connection == null) { - throw new SQLException("Connection invalid"); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); - } - return executeUpdatePreparedStatement(connection, statement, arguments, true); - } finally { - monitor.deregisterRequest(testObject); - } - } - - CachedRowSet executePreparedStatement(Connection conn, String statement, List arguments, boolean close) - throws SQLException { - long time = System.currentTimeMillis(); - - CachedRowSet data = null; - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL Statement: {}", statement); - if (arguments != null && !arguments.isEmpty()) { - LOGGER.debug("Argunments: {}", arguments); - } - } - - ResultSet rs = null; - try (PreparedStatement ps = conn.prepareStatement(statement)) { - data = RowSetProvider.newFactory().createCachedRowSet(); - if (arguments != null) { - for (int i = 0, max = arguments.size(); i < max; i++) { - ps.setObject(i + 1, arguments.get(i)); - } - } - rs = ps.executeQuery(); - data.populate(rs); - // Point the rowset Cursor to the start - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), - (System.currentTimeMillis() - time)); - } - } catch (SQLException exc) { - handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); - } finally { - handleFinallyBlockForExecutePreparedStatement(rs, conn, close); - } - - return data; - } - - private void handleSqlExceptionForExecuteStatement(Connection conn, String statement, List arguments, - SQLException exc, long time) throws SQLException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(SQL_FAILURE + (System.currentTimeMillis() - time)); - } - try { - conn.rollback(); - } catch (Exception thr) { - LOGGER.error(thr.getLocalizedMessage(), thr); - } - if (arguments != null && !arguments.isEmpty()) { - LOGGER.error(String.format("<%s%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_ARGUMENTS, - arguments), exc); - } else { - LOGGER.error(String.format("<%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_NO_ARGUMENTS), - exc); - } - throw exc; - } - - private void handleFinallyBlockForExecutePreparedStatement(ResultSet rs, Connection conn, boolean close) { - try { - if (rs != null) { - rs.close(); - } - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } - try { - if (conn != null && close) { - conn.close(); - } - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } - } - - boolean executeUpdatePreparedStatement(Connection conn, String statement, List arguments, boolean close) - throws SQLException { - long time = System.currentTimeMillis(); - - CachedRowSet data; - - try (PreparedStatement ps = conn.prepareStatement(statement)) { - data = RowSetProvider.newFactory().createCachedRowSet(); - if (arguments != null) { - prepareStatementForExecuteUpdate(arguments, ps); - } - ps.executeUpdate(); - // Point the rowset Cursor to the start - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), - (System.currentTimeMillis() - time)); - } - ps.close(); - } catch (SQLException exc) { - handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); - } finally { - try { - if (close) { - conn.close(); - } - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } - } - - return true; - } - - private void prepareStatementForExecuteUpdate(List arguments, PreparedStatement ps) throws SQLException { - for (int i = 0, max = arguments.size(); i < max; i++) { - Object value = arguments.get(i); - if (value instanceof Blob) { - ps.setBlob(i + 1, (Blob) value); - } else if (value instanceof Timestamp) { - ps.setTimestamp(i + 1, (Timestamp) value); - } else if (value instanceof Integer) { - ps.setInt(i + 1, (Integer) value); - } else if (value instanceof Long) { - ps.setLong(i + 1, (Long) value); - } else if (value instanceof Date) { - ps.setDate(i + 1, (Date) value); - } else { - ps.setObject(i + 1, value); - } - } - } - - /* - * (non-Javadoc) - * - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ - @Override - public Connection getConnection(String username, String password) throws SQLException { - return ds.getConnection(username, password); - } - - /* - * (non-Javadoc) - * - * @see javax.sql.DataSource#getLogWriter() - */ - @Override - public PrintWriter getLogWriter() throws SQLException { - return ds.getLogWriter(); - } - - /* - * (non-Javadoc) - * - * @see javax.sql.DataSource#getLoginTimeout() - */ - @Override - public int getLoginTimeout() throws SQLException { - return ds.getLoginTimeout(); - } - - /* - * (non-Javadoc) - * - * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) - */ - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - ds.setLogWriter(out); - } - - /* - * (non-Javadoc) - * - * @see javax.sql.DataSource#setLoginTimeout(int) - */ - @Override - public void setLoginTimeout(int seconds) throws SQLException { - ds.setLoginTimeout(seconds); - } - - @Override - public final String getDbConnectionName() { - return connectionName; - } - - protected final void setDbConnectionName(String name) { - this.connectionName = name; - } - - public void cleanUp() { - if (ds != null && ds instanceof Closeable) { - try { - ((Closeable) ds).close(); - } catch (IOException e) { - LOGGER.warn(e.getMessage()); - } - } - ds = null; - monitor.deleteObservers(); - monitor.cleanup(); - } - - public boolean isInitialized() { - return initialized; - } - - protected boolean testConnection() { - return testConnection(false); - } - - protected boolean testConnection(boolean errorLevel) { - ResultSet rs = null; - try (Connection conn = this.getConnection(); Statement stmt = conn.createStatement()) { - Boolean readOnly; - String hostname; - rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); // ("SELECT 1 FROM DUAL"); //"select - // BANNER from SYS.V_$VERSION" - while (rs.next()) { - readOnly = rs.getBoolean(1); - hostname = rs.getString(2); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(SQL_DATA_SOURCE + getDbConnectionName() + "> connected to " + hostname - + ", read-only is " + readOnly + ", tested successfully "); - } - } - } catch (Exception exc) { - if (errorLevel) { - LOGGER.error( - SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } else { - LOGGER.info( - SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); - } - return false; - } finally { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - LOGGER.error(e.getLocalizedMessage(), e); - } - } - } - return true; - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - @SuppressWarnings("deprecation") - public void setConnectionCachingEnabled(boolean state) { - // if(ds != null && ds instanceof OracleDataSource) - // try { - // ((OracleDataSource)ds).setConnectionCachingEnabled(true); - // } catch (SQLException exc) { - // LOGGER.warn("", exc); - // } - } - - public void addObserver(Observer observer) { - monitor.addObserver(observer); - } - - public void deleteObserver(Observer observer) { - monitor.deleteObserver(observer); - } - - @Override - public long getInterval() { - return interval; - } - - @Override - public long getInitialDelay() { - return initialDelay; - } - - @Override - public void setInterval(long value) { - interval = value; - } - - @Override - public void setInitialDelay(long value) { - initialDelay = value; - } - - @Override - public long getExpectedCompletionTime() { - return expectedCompletionTime; - } - - @Override - public void setExpectedCompletionTime(long value) { - expectedCompletionTime = value; - } - - @Override - public long getUnprocessedFailoverThreshold() { - return unprocessedFailoverThreshold; - } - - @Override - public void setUnprocessedFailoverThreshold(long value) { - this.unprocessedFailoverThreshold = value; - } - - public boolean canTakeOffLine() { - return canTakeOffLine; - } - - public void blockImmediateOffLine() { - canTakeOffLine = false; - final Thread offLineTimer = new Thread(() -> { - try { - Thread.sleep(30000L); - } catch (Exception exc) { - LOGGER.error(exc.getLocalizedMessage(), exc); - } finally { - canTakeOffLine = true; - } - }); - offLineTimer.setDaemon(true); - offLineTimer.start(); - } - - /** - * @return the monitor - */ - final SQLExecutionMonitor getMonitor() { - return monitor; - } - - protected boolean isSlave() throws PoolExhaustedException { - - // If using Apache derby, just return false - if (isDerby) { - return false; - } - CachedRowSet rs; - boolean isSlave; - String hostname = "UNDETERMINED"; - try { - boolean localSlave = true; - rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList<>()); - while (rs.next()) { - localSlave = rs.getBoolean(1); - hostname = rs.getString(2); - } - isSlave = localSlave; - } catch (PoolExhaustedException peexc) { - throw peexc; - } catch (Exception e) { - LOGGER.error("", e); - isSlave = true; - } - if (isSlave) { - LOGGER.debug("SQL SLAVE : {} on server {}", connectionName, hostname); - } else { - LOGGER.debug("SQL MASTER : {} on server {}", connectionName, hostname); - } - return isSlave; - } - - public boolean isFabric() { - return false; - } - - protected boolean lockTable(Connection conn, String tableName) { - boolean retValue = false; - String query = "LOCK TABLES " + tableName + " WRITE"; - try (Statement preStmt = conn.createStatement(); - Statement lock = conn.prepareStatement(query); - ResultSet rs = preStmt.executeQuery("GETDATE()")) { - if (tableName != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); - if ("SVC_LOGIC".equals(tableName)) { - Exception e = new Exception(); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - LOGGER.debug(sw.toString()); - } - } - lock.execute(query); - retValue = true; - } - } catch (Exception exc) { - LOGGER.error("", exc); - retValue = false; - } - return retValue; - } - - protected boolean unlockTable(Connection conn) { - boolean retValue; - try (Statement lock = conn.createStatement()) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Executing 'UNLOCK TABLES' on connection {}", conn); - } - retValue = lock.execute("UNLOCK TABLES"); - } catch (Exception exc) { - LOGGER.error("", exc); - retValue = false; - } - return retValue; - } - - public void getPoolInfo(boolean allocation) { - - } - - public long getNextErrorReportTime() { - return nextErrorReportTime; - } - - public void setNextErrorReportTime(long nextTime) { - this.nextErrorReportTime = nextTime; - } - - public void setGlobalHostName(String hostname) { - this.globalHostName = hostname; - } - - public String getGlobalHostName() { - return globalHostName; - } + private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); + + private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; + private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; + private static final String WITH_ARGUMENTS = " with arguments: "; + private static final String WITH_NO_ARGUMENTS = " with no arguments. "; + private static final String SQL_DATA_SOURCE = "SQL DataSource <"; + + protected long connReqTimeout = 30L; + protected long dataReqTimeout = 100L; + + private final SQLExecutionMonitor monitor; + protected DataSource ds = null; + protected String connectionName = null; + protected boolean initialized = false; + + private long interval = 1000; + private long initialDelay = 5000; + private long expectedCompletionTime = 50L; + private boolean canTakeOffLine = true; + private long unprocessedFailoverThreshold = 3L; + + private long nextErrorReportTime = 0L; + + private String globalHostName = null; + + private boolean isDerby = false; + + public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { + configure(jdbcElem); + + if ("org.apache.derby.jdbc.EmbeddedDriver".equals(jdbcElem.getDriverName())) { + isDerby = true; + } + monitor = new SQLExecutionMonitor(this); + } + + protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getConnection() + */ + @Override + public Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + public CachedRowSet getData(String statement, List arguments) throws SQLException { + TestObject testObject = monitor.registerRequest(); + + try (Connection connection = this.getConnection()) { + if (connection == null) { + throw new SQLException("Connection invalid"); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); + } + return executePreparedStatement(connection, statement, arguments, true); + } finally { + monitor.deregisterRequest(testObject); + } + } + + public boolean writeData(String statement, List arguments) throws SQLException { + TestObject testObject = monitor.registerRequest(); + + try (Connection connection = this.getConnection()) { + if (connection == null) { + throw new SQLException("Connection invalid"); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Obtained connection <{}>: {}", connectionName, connection); + } + return executeUpdatePreparedStatement(connection, statement, arguments, true); + } finally { + monitor.deregisterRequest(testObject); + } + } + + CachedRowSet executePreparedStatement(Connection conn, String statement, List arguments, boolean close) + throws SQLException { + long time = System.currentTimeMillis(); + + CachedRowSet data = null; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL Statement: {}", statement); + if (arguments != null && !arguments.isEmpty()) { + LOGGER.debug("Argunments: {}", arguments); + } + } + + ResultSet rs = null; + try (PreparedStatement ps = conn.prepareStatement(statement)) { + data = RowSetProvider.newFactory().createCachedRowSet(); + if (arguments != null) { + for (int i = 0, max = arguments.size(); i < max; i++) { + ps.setObject(i + 1, arguments.get(i)); + } + } + rs = ps.executeQuery(); + data.populate(rs); + // Point the rowset Cursor to the start + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), + (System.currentTimeMillis() - time)); + } + } catch (SQLException exc) { + handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); + } finally { + handleFinallyBlockForExecutePreparedStatement(rs, conn, close); + } + + return data; + } + + private void handleSqlExceptionForExecuteStatement(Connection conn, String statement, List arguments, + SQLException exc, long time) throws SQLException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(SQL_FAILURE + (System.currentTimeMillis() - time)); + } + try { + conn.rollback(); + } catch (Exception thr) { + LOGGER.error(thr.getLocalizedMessage(), thr); + } + if (arguments != null && !arguments.isEmpty()) { + LOGGER.error(String.format("<%s%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_ARGUMENTS, + arguments), exc); + } else { + LOGGER.error(String.format("<%s%s%s%s", connectionName, FAILED_TO_EXECUTE, statement, WITH_NO_ARGUMENTS), + exc); + } + throw exc; + } + + private void handleFinallyBlockForExecutePreparedStatement(ResultSet rs, Connection conn, boolean close) { + try { + if (rs != null) { + rs.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + try { + if (conn != null && close) { + conn.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + } + + boolean executeUpdatePreparedStatement(Connection conn, String statement, List arguments, boolean close) + throws SQLException { + long time = System.currentTimeMillis(); + + CachedRowSet data; + + try (PreparedStatement ps = conn.prepareStatement(statement)) { + data = RowSetProvider.newFactory().createCachedRowSet(); + if (arguments != null) { + prepareStatementForExecuteUpdate(arguments, ps); + } + ps.executeUpdate(); + // Point the rowset Cursor to the start + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), + (System.currentTimeMillis() - time)); + } + ps.close(); + } catch (SQLException exc) { + handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); + } finally { + try { + if (close) { + conn.close(); + } + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } + } + + return true; + } + + private void prepareStatementForExecuteUpdate(List arguments, PreparedStatement ps) throws SQLException { + for (int i = 0, max = arguments.size(); i < max; i++) { + Object value = arguments.get(i); + if (value instanceof Blob) { + ps.setBlob(i + 1, (Blob) value); + } else if (value instanceof Timestamp) { + ps.setTimestamp(i + 1, (Timestamp) value); + } else if (value instanceof Integer) { + ps.setInt(i + 1, (Integer) value); + } else if (value instanceof Long) { + ps.setLong(i + 1, (Long) value); + } else if (value instanceof Date) { + ps.setDate(i + 1, (Date) value); + } else { + ps.setObject(i + 1, value); + } + } + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) + */ + @Override + public Connection getConnection(String username, String password) throws SQLException { + return ds.getConnection(username, password); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getLogWriter() + */ + @Override + public PrintWriter getLogWriter() throws SQLException { + return ds.getLogWriter(); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#getLoginTimeout() + */ + @Override + public int getLoginTimeout() throws SQLException { + return ds.getLoginTimeout(); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) + */ + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + ds.setLogWriter(out); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.DataSource#setLoginTimeout(int) + */ + @Override + public void setLoginTimeout(int seconds) throws SQLException { + ds.setLoginTimeout(seconds); + } + + @Override + public final String getDbConnectionName() { + return connectionName; + } + + protected final void setDbConnectionName(String name) { + this.connectionName = name; + } + + public void cleanUp() { + if (ds != null && ds instanceof Closeable) { + try { + ((Closeable) ds).close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage()); + } + } + ds = null; + monitor.deleteObservers(); + monitor.cleanup(); + } + + public boolean isInitialized() { + return initialized; + } + + protected boolean testConnection() { + return testConnection(false); + } + + protected boolean testConnection(boolean errorLevel) { + ResultSet rs = null; + try (Connection conn = this.getConnection(); Statement stmt = conn.createStatement()) { + Boolean readOnly; + String hostname; + rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); // ("SELECT 1 FROM DUAL"); //"select + // BANNER from SYS.V_$VERSION" + while (rs.next()) { + readOnly = rs.getBoolean(1); + hostname = rs.getString(2); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(SQL_DATA_SOURCE + getDbConnectionName() + "> connected to " + hostname + + ", read-only is " + readOnly + ", tested successfully "); + } + } + } catch (Exception exc) { + if (errorLevel) { + LOGGER.error( + SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } else { + LOGGER.info( + SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + } + return false; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + LOGGER.error(e.getLocalizedMessage(), e); + } + } + } + return true; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @SuppressWarnings("deprecation") + public void setConnectionCachingEnabled(boolean state) { + // if(ds != null && ds instanceof OracleDataSource) + // try { + // ((OracleDataSource)ds).setConnectionCachingEnabled(true); + // } catch (SQLException exc) { + // LOGGER.warn("", exc); + // } + } + + public void addObserver(Observer observer) { + monitor.addObserver(observer); + } + + public void deleteObserver(Observer observer) { + monitor.deleteObserver(observer); + } + + @Override + public long getInterval() { + return interval; + } + + @Override + public long getInitialDelay() { + return initialDelay; + } + + @Override + public void setInterval(long value) { + interval = value; + } + + @Override + public void setInitialDelay(long value) { + initialDelay = value; + } + + @Override + public long getExpectedCompletionTime() { + return expectedCompletionTime; + } + + @Override + public void setExpectedCompletionTime(long value) { + expectedCompletionTime = value; + } + + @Override + public long getUnprocessedFailoverThreshold() { + return unprocessedFailoverThreshold; + } + + @Override + public void setUnprocessedFailoverThreshold(long value) { + this.unprocessedFailoverThreshold = value; + } + + public boolean canTakeOffLine() { + return canTakeOffLine; + } + + public void blockImmediateOffLine() { + canTakeOffLine = false; + final Thread offLineTimer = new Thread(() -> { + try { + Thread.sleep(30000L); + } catch (Exception exc) { + LOGGER.error(exc.getLocalizedMessage(), exc); + } finally { + canTakeOffLine = true; + } + }); + offLineTimer.setDaemon(true); + offLineTimer.start(); + } + + /** + * @return the monitor + */ + final SQLExecutionMonitor getMonitor() { + return monitor; + } + + protected boolean isSlave() throws PoolExhaustedException { + + // If using Apache derby, just return false + if (isDerby) { + return false; + } + CachedRowSet rs; + boolean isSlave; + String hostname = "UNDETERMINED"; + try { + boolean localSlave = true; + rs = this.getData("SELECT @@global.read_only, @@global.hostname", new ArrayList<>()); + while (rs.next()) { + localSlave = rs.getBoolean(1); + hostname = rs.getString(2); + } + isSlave = localSlave; + } catch (PoolExhaustedException peexc) { + throw peexc; + } catch (Exception e) { + LOGGER.error("", e); + isSlave = true; + } + if (isSlave) { + LOGGER.debug("SQL SLAVE : {} on server {}", connectionName, hostname); + } else { + LOGGER.debug("SQL MASTER : {} on server {}", connectionName, hostname); + } + return isSlave; + } + + public boolean isFabric() { + return false; + } + + protected boolean lockTable(Connection conn, String tableName) { + boolean retValue = false; + String query = "LOCK TABLES " + tableName + " WRITE"; + try (Statement preStmt = conn.createStatement(); + Statement lock = conn.prepareStatement(query)) { + if (tableName != null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'LOCK TABLES " + tableName + " WRITE' on connection " + conn.toString()); + if ("SVC_LOGIC".equals(tableName)) { + Exception e = new Exception(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + LOGGER.debug(sw.toString()); + } + } + lock.execute(query); + retValue = true; + } + } catch (Exception exc) { + LOGGER.error("", exc); + retValue = false; + } + return retValue; + } + + protected boolean unlockTable(Connection conn) { + boolean retValue; + try (Statement lock = conn.createStatement()) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Executing 'UNLOCK TABLES' on connection {}", conn); + } + retValue = lock.execute("UNLOCK TABLES"); + } catch (Exception exc) { + LOGGER.error("", exc); + retValue = false; + } + return retValue; + } + + public void getPoolInfo(boolean allocation) { + + } + + public long getNextErrorReportTime() { + return nextErrorReportTime; + } + + public void setNextErrorReportTime(long nextTime) { + this.nextErrorReportTime = nextTime; + } + + public void setGlobalHostName(String hostname) { + this.globalHostName = hostname; + } + + public String getGlobalHostName() { + return globalHostName; + } } -- cgit 1.2.3-korg From e69c6e3320f27d31d6dcd86a1ab40960758b59cb Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Fri, 2 Mar 2018 04:42:45 +0000 Subject: Updated master database detection algorithm Changes made: * updated algorithm in DBResourceManager * Updated CachedDataSource, JdbcDBCachedDataSource * added new unit tests Change-Id: I4f6bbeb3839f55d183d7e762743fbc9171b63b1a Issue-ID: CCSDK-192 Signed-off-by: Rich Tabedzki --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 19 +- .../ccsdk/sli/core/dblib/DBResourceManager.java | 279 +++++++++------------ .../onap/ccsdk/sli/core/dblib/DataAccessor.java | 1 + .../core/dblib/TerminatingCachedDataSource.java | 120 ++++----- .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 29 ++- .../ccsdk/sli/core/dblib/DBLibExceptionTest.java | 14 ++ .../dblib/NoAvailableConnectionsExceptionTest.java | 16 ++ .../org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 | 2 +- 8 files changed, 227 insertions(+), 253 deletions(-) mode change 100644 => 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsExceptionTest.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index e5eff24a5..02cce3cf1 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -47,7 +47,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * @version $Revision: 1.13 $ + * @version $Revision: 1.14 $ * Change Log * Author Date Comments * ============== ======== ==================================================== @@ -68,7 +68,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito protected long dataReqTimeout = 100L; private final SQLExecutionMonitor monitor; - protected DataSource ds = null; + protected final DataSource ds; protected String connectionName = null; protected boolean initialized = false; @@ -85,7 +85,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito private boolean isDerby = false; public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { - configure(jdbcElem); + ds = configure(jdbcElem); if ("org.apache.derby.jdbc.EmbeddedDriver".equals(jdbcElem.getDriverName())) { isDerby = true; @@ -93,7 +93,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito monitor = new SQLExecutionMonitor(this); } - protected abstract void configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + protected abstract DataSource configure(BaseDBConfiguration jdbcElem) throws DBConfigException; /* * (non-Javadoc) @@ -329,7 +329,6 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito LOGGER.warn(e.getMessage()); } } - ds = null; monitor.deleteObservers(); monitor.cleanup(); } @@ -389,16 +388,6 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito return null; } - @SuppressWarnings("deprecation") - public void setConnectionCachingEnabled(boolean state) { - // if(ds != null && ds instanceof OracleDataSource) - // try { - // ((OracleDataSource)ds).setConnectionCachingEnabled(true); - // } catch (SQLException exc) { - // LOGGER.warn("", exc); - // } - } - public void addObserver(Observer observer) { monitor.addObserver(observer); } 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 b31645d41..27c14d2a4 100755 --- 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 @@ -20,39 +20,39 @@ package org.onap.ccsdk.sli.core.dblib; -import org.apache.tomcat.jdbc.pool.PoolExhaustedException; -import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; -import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; -import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; -import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.sql.DataSource; -import javax.sql.rowset.CachedRowSet; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLDataException; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; import java.sql.SQLSyntaxErrorException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; -import java.util.LinkedList; import java.util.Observable; -import java.util.PriorityQueue; import java.util.Properties; -import java.util.Queue; import java.util.Set; +import java.util.SortedSet; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ConcurrentSkipListSet; + +import javax.sql.DataSource; +import javax.sql.rowset.CachedRowSet; +import org.apache.tomcat.jdbc.pool.PoolExhaustedException; +import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; +import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; +import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @version $Revision: 1.15 $ @@ -68,31 +68,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb transient protected long retryInterval = 10000L; transient boolean recoveryMode = true; - protected final AtomicBoolean dsSelector = new AtomicBoolean(); - - Queue dsQueue = new PriorityQueue<>(4, new Comparator() { - @Override - public int compare(CachedDataSource left, CachedDataSource right) { - try { - if (left == null) { - return 1; - } - if (right == null) { - return -1; - } - - if (!left.isSlave()) { - return -1; - } - if (!right.isSlave()) { - return 1; - } - } catch (Throwable e) { - LOGGER.warn("", e); - } - return 0; - } -}); + SortedSet dsQueue = new ConcurrentSkipListSet(new DataSourceComparator()); protected final Set broken = Collections.synchronizedSet(new HashSet()); protected final Object monitor = new Object(); protected final Properties configProps; @@ -174,7 +150,6 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb cachedDS[i].addObserver(DBResourceManager.this); } -// CachedDataSource[] cachedDS = factory.initDBResourceManager(dbConfig, DBResourceManager.this, semaphore); DataSourceTester[] tester = new DataSourceTester[config.length]; for(int i=0; i { + @Override + public int compare(CachedDataSource left, CachedDataSource right) { + if(LOGGER.isTraceEnabled()) + LOGGER.trace("----------SORTING-------- () : ()", left.getDbConnectionName(), right.getDbConnectionName()); + try { + if(left == right) { + return 0; + } + if(left == null){ + return 1; + } + if(right == null){ + return -1; + } + + if(!left.isSlave()) + return -1; + if(!right.isSlave()) + return 1; + + } catch (Throwable e) { + LOGGER.warn("", e); + } + return -1; + } + } + class DataSourceTester extends Thread { private final CachedDataSource ds; @@ -224,7 +227,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } if(!slave) { - LOGGER.info(String.format("Adding MASTER (%s) to active queue", ds.getDbConnectionName())); + LOGGER.info("Adding MASTER {} to active queue", ds.getDbConnectionName()); try { synchronized (semaphoreQ) { semaphoreQ.notifyAll(); @@ -245,7 +248,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } catch(Exception exc) { LOGGER.warn("", exc); } - LOGGER.info(String.format("Thread DataSourceTester terminated %s for %s", this.getName(), ds.getDbConnectionName())); + LOGGER.info("Thread DataSourceTester terminated {} for {}", this.getName(), ds.getDbConnectionName()); } } @@ -300,7 +303,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb if(monitor.getParent() instanceof CachedDataSource) { CachedDataSource dataSource = (CachedDataSource)monitor.getParent(); - if(dataSource == dsQueue.peek()) + if(dataSource == dsQueue.first()) { if(recoveryMode && dsQueue.size() > 1){ handleGetConnectionException(dataSource, new Exception(data.toString())); @@ -312,7 +315,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public void testForceRecovery() { - CachedDataSource active = this.dsQueue.peek(); + CachedDataSource active = this.dsQueue.first(); handleGetConnectionException(active, new Exception("test")); } @@ -386,51 +389,45 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb private CachedRowSet requestDataWithRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { Throwable lastException = null; - CachedDataSource active = null; // test if there are any connection pools available - LinkedList sources = new LinkedList<>(this.dsQueue); - if(sources.isEmpty()){ + if(this.dsQueue.isEmpty()){ LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); } - if(preferredDS != null && !sources.peek().getDbConnectionName().equals(preferredDS)) { - Collections.reverse(sources); - } - // loop through available data sources to retrieve data. - while(!sources.isEmpty()) + for(int i=0; i< 2; i++) { - active = sources.peek(); + CachedDataSource active = this.dsQueue.first(); long time = System.currentTimeMillis(); try { if(!active.isFabric()) { + if(this.dsQueue.size() > 1 && active.isSlave()) { CachedDataSource master = findMaster(); if(master != null) { active = master; - master = null; } } - sources.remove(active); + } + return active.getData(statement, arguments); } catch(SQLDataException | SQLSyntaxErrorException | SQLIntegrityConstraintViolationException exc){ throw exc; } catch(Throwable exc){ - lastException = exc; - String message = exc.getMessage(); - if(message == null) { - if(exc.getCause() != null) { - message = exc.getCause().getMessage(); + if(exc instanceof SQLException) { + SQLException sqlExc = (SQLException)exc; + int code = sqlExc.getErrorCode(); + String state = sqlExc.getSQLState(); + LOGGER.debug("SQLException code: {} state: {}", code, state); + if("07001".equals(sqlExc.getSQLState())) { + throw sqlExc; } - if(message == null) - message = exc.getClass().getName(); } - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + lastException = exc; + LOGGER.error("Generated alarm: "+active.getDbConnectionName(), exc); handleGetConnectionException(active, exc); - if(sources.contains(active)) - sources.remove(active); } finally { if(LOGGER.isDebugEnabled()){ time = System.currentTimeMillis() - time; @@ -462,13 +459,16 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); } - CachedDataSource active = this.dsQueue.peek(); + CachedDataSource active = this.dsQueue.first(); long time = System.currentTimeMillis(); try { if(!active.isFabric()) { + if(this.dsQueue.size() > 1 && active.isSlave()) { CachedDataSource master = findMaster(); - if(master != null) + if(master != null) { active = master; + } + } } return active.getData(statement, arguments); // } catch(SQLDataException exc){ @@ -508,17 +508,21 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb return writeDataNoRecovery(statement, newList, preferredDS); } - CachedDataSource findMaster() throws PoolExhaustedException { - CachedDataSource master = null; - CachedDataSource[] dss = this.dsQueue.toArray(new CachedDataSource[0]); - for(int i=0; i 1 && active.isSlave()) { CachedDataSource master = findMaster(); if(master != null) { active = master; } } + } return active.writeData(statement, arguments); } catch(Throwable exc){ @@ -557,8 +563,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb // handle read-only exception if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { LOGGER.warn("retrying due to: " + sqlExc.getMessage()); - dsQueue.remove(active); - dsQueue.add(active); + this.findMaster(); if(retryAllowed){ retryAllowed = false; initialRequest = true; @@ -604,10 +609,15 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } try { - active = dsQueue.peek(); - CachedDataSource tmpActive = findMaster(); - if(tmpActive != null) { - active = tmpActive; + active = dsQueue.first(); + + if(!active.isFabric()) { + if(this.dsQueue.size() > 1 && active.isSlave()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + } + } } return new DBLibConnection(active.getConnection(), active); } catch(javax.sql.rowset.spi.SyncFactoryException exc){ @@ -616,6 +626,8 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb lastException = exc; } catch(PoolExhaustedException exc) { throw new NoAvailableConnectionsException(exc); + } catch(SQLNonTransientConnectionException exc){ + throw new NoAvailableConnectionsException(exc); } catch(Exception exc){ lastException = exc; if(recoveryMode){ @@ -667,10 +679,14 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb try { - active = dsQueue.peek(); - CachedDataSource tmpActive = findMaster(); - if(tmpActive != null) { - active = tmpActive; + active = dsQueue.first(); + if(!active.isFabric()) { + if(this.dsQueue.size() > 1 && active.isSlave()) { + CachedDataSource master = findMaster(); + if(master != null) { + active = master; + } + } } return active.getConnection(username, password); } catch(Throwable exc){ @@ -691,7 +707,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb throw new DBLibException("No connections available in DBResourceManager in GetConnection call."); } - private void handleGetConnectionException(CachedDataSource source, Throwable exc) { + private void handleGetConnectionException(final CachedDataSource source, Throwable exc) { try { if(!source.canTakeOffLine()) { @@ -715,7 +731,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb { if(!dsQueue.isEmpty()) { - LOGGER.warn("DB DataSource <" + dsQueue.peek().getDbConnectionName() + "> became active"); + LOGGER.warn("DB DataSource <" + dsQueue.first().getDbConnectionName() + "> became active"); } } } catch (Exception e) { @@ -749,28 +765,28 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb @Override public PrintWriter getLogWriter() throws SQLException { - return this.dsQueue.peek().getLogWriter(); + return this.dsQueue.first().getLogWriter(); } @Override public int getLoginTimeout() throws SQLException { - return this.dsQueue.peek().getLoginTimeout(); + return this.dsQueue.first().getLoginTimeout(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { - this.dsQueue.peek().setLogWriter(out); + this.dsQueue.first().setLogWriter(out); } @Override public void setLoginTimeout(int seconds) throws SQLException { - this.dsQueue.peek().setLoginTimeout(seconds); + this.dsQueue.first().setLoginTimeout(seconds); } public void displayState(){ if(LOGGER.isDebugEnabled()){ LOGGER.debug("POOLS : Active = "+dsQueue.size() + ";\t Broken = "+broken.size()); - CachedDataSource current = dsQueue.peek(); + CachedDataSource current = dsQueue.first(); if(current != null) { LOGGER.debug("POOL : Active name = \'"+current.getDbConnectionName()+ "\'"); } @@ -811,7 +827,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb buffer.append("in recovery"); } if (dsQueue.contains(list.get(i))) { - if (dsQueue.peek() == list.get(i)) + if (dsQueue.first() == list.get(i)) buffer.append("active"); else buffer.append("standby"); @@ -827,7 +843,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb buffer.append("in recovery"); } else if (dsQueue.contains(list.get(i))) { - if (dsQueue.peek() == list.get(i)) + if (dsQueue.first() == list.get(i)) buffer.append("active"); else buffer.append("standby"); @@ -859,7 +875,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } public void test(){ - CachedDataSource obj = dsQueue.peek(); + CachedDataSource obj = dsQueue.first(); Exception ption = new Exception(); try { for(int i=0; i<5; i++) @@ -871,77 +887,16 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } - public String getPreferredDSName(){ - if(isActive()){ - return getPreferredDataSourceName(dsSelector); - } - return ""; - } - - public String getPreferredDataSourceName(AtomicBoolean flipper) { - - LinkedList snapshot = new LinkedList<>(dsQueue); - if(snapshot.size() > 1){ - CachedDataSource first = snapshot.getFirst(); - CachedDataSource last = snapshot.getLast(); - - int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); - if(delta < 0) { - flipper.set(false); - } else if(delta > 0) { - flipper.set(true); - } else { - // check the last value and return !last - flipper.getAndSet(!flipper.get()); - } - - if (flipper.get()) - Collections.reverse(snapshot); - } - return snapshot.peek().getDbConnectionName(); - } - @Override public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } - public String getMasterName() { - if(isActive()){ - return getMasterDataSourceName(dsSelector); - } - return ""; - } - - - private String getMasterDataSourceName(AtomicBoolean flipper) { - - LinkedList snapshot = new LinkedList<>(dsQueue); - if(snapshot.size() > 1){ - CachedDataSource first = snapshot.getFirst(); - CachedDataSource last = snapshot.getLast(); - - int delta = first.getMonitor().getProcessedConnectionsCount() - last.getMonitor().getProcessedConnectionsCount(); - if(delta < 0) { - flipper.set(false); - } else if(delta > 0) { - flipper.set(true); - } else { - // check the last value and return !last - flipper.getAndSet(!flipper.get()); - } - - if (flipper.get()) - Collections.reverse(snapshot); - } - return snapshot.peek().getDbConnectionName(); - } - class RemindTask extends TimerTask { @Override public void run() { - CachedDataSource ds = dsQueue.peek(); + CachedDataSource ds = dsQueue.first(); if(ds != null) ds.getPoolInfo(false); } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java index fdfb47bca..93d8b6bf5 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DataAccessor.java @@ -25,6 +25,7 @@ import java.util.ArrayList; import javax.sql.rowset.CachedRowSet; +@FunctionalInterface public interface DataAccessor { CachedRowSet getData(String statement, ArrayList arguments, String preferredDS) diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java old mode 100644 new mode 100755 index b4d1ef679..92b31470e --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java @@ -22,71 +22,71 @@ package org.onap.ccsdk.sli.core.dblib; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; - +import javax.sql.DataSource; import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; public class TerminatingCachedDataSource extends CachedDataSource implements SQLExecutionMonitorObserver { - public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { - super(jdbcElem); - } - - @Override - protected void configure(BaseDBConfiguration jdbcElem) throws DBConfigException { - // no action - } - - @Override - public long getInterval() { - return 1000; - } - - @Override - public long getInitialDelay() { - return 1000; - } - - @Override - public long getExpectedCompletionTime() { - return 50; - } - - @Override - public void setExpectedCompletionTime(long value) { - - } - - @Override - public void setInterval(long value) { - - } - - @Override - public void setInitialDelay(long value) { - - } - - @Override - public long getUnprocessedFailoverThreshold() { - return 3; - } - - @Override - public void setUnprocessedFailoverThreshold(long value) { - - } - - public int compareTo(CachedDataSource ods) - { - return 0; - } - - @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub - return null; - } + public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { + super(jdbcElem); + } + + @Override + protected DataSource configure(BaseDBConfiguration jdbcElem) throws DBConfigException { + return null; + } + + @Override + public long getInterval() { + return 1000; + } + + @Override + public long getInitialDelay() { + return 1000; + } + + @Override + public long getExpectedCompletionTime() { + return 50; + } + + @Override + public void setExpectedCompletionTime(long value) { + + } + + @Override + public void setInterval(long value) { + + } + + @Override + public void setInitialDelay(long value) { + + } + + @Override + public long getUnprocessedFailoverThreshold() { + return 3; + } + + @Override + public void setUnprocessedFailoverThreshold(long value) { + + } + + public int compareTo(CachedDataSource ods) + { + return 0; + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + // TODO Auto-generated method stub + return null; + } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java index ca16834c4..a6582b9e7 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -53,7 +53,7 @@ public class JdbcDBCachedDataSource extends CachedDataSource { } @Override - protected void configure(BaseDBConfiguration xmlElem) throws DBConfigException { + protected DataSource configure(BaseDBConfiguration xmlElem) throws DBConfigException { BaseDBConfiguration jdbcConfig = xmlElem; if (jdbcConfig.getConnTimeout() > 0) { this.connReqTimeout = jdbcConfig.getConnTimeout(); @@ -90,23 +90,23 @@ public class JdbcDBCachedDataSource extends CachedDataSource { minLimit = jdbcConfig.getDbMinLimit(); // if (minLimit == null) // { -// String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); +// String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); // } maxLimit = jdbcConfig.getDbMaxLimit(); // if (maxLimit == null) // { -// String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); +// String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); // } initialLimit = jdbcConfig.getDbInitialLimit(); // if (initialLimit == null) // { -// String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); +// String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; +// LOGGER.error(AS_CONF_ERROR + errorMsg); +// throw new DBConfigException(errorMsg); // } dbUrl = jdbcConfig.getDbUrl(); @@ -142,20 +142,19 @@ public class JdbcDBCachedDataSource extends CachedDataSource { p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); - DataSource dataSource = new DataSource(p); + final DataSource dataSource = new DataSource(p); synchronized (this) { - this.ds = dataSource; - initialized = true; + } LOGGER.info(String.format("JdbcDBCachedDataSource <%s> configured successfully. Using URL: %s", dbConnectionName, dbUrl)); - } + return dataSource; } catch (Exception exc) { initialized = false; LOGGER.error(String.format("AS_CONF_ERROR: Failed to initialize MySQLCachedDataSource <%s>. Reason: %s", dbConnectionName, exc.getMessage())); -// throw new DBConfigException(e.getMessage()); + return null; } } diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java new file mode 100644 index 000000000..cab24042c --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java @@ -0,0 +1,14 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class DBLibExceptionTest { + + @Test + public void testDBLibException() { + assertNotNull(new DBLibException("test")); + } + +} diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsExceptionTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsExceptionTest.java new file mode 100644 index 000000000..2fdacb922 --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/NoAvailableConnectionsExceptionTest.java @@ -0,0 +1,16 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class NoAvailableConnectionsExceptionTest { + + @Test + public void testNoAvailableConnectionsException() { + assertNotNull(new NoAvailableConnectionsException(new Exception("test"))); + } + +} diff --git a/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 b/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 index 1b026bb1a..42563168c 100755 --- a/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 +++ b/sli/common/src/main/antlr4/org/onap/ccsdk/sli/core/sli/ExprGrammar.g4 @@ -16,7 +16,7 @@ MULTOP : '/' | '*'; NUMBER : ('0'..'9')+; -STRING : '\'' ~[\']* '\''; +STRING : '\'' ~[']* '\''; IDENTIFIER : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'-')*; -- cgit 1.2.3-korg From a9e89cccc344b5f1aecbe3936f6bb917cfe7b20f Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Thu, 8 Mar 2018 14:50:22 +0000 Subject: Fix sonar related items Changes made: * Optimized TerminatingCachedDataSource * Added additional unit tests Change-Id: I0a83c993898e2bee11b8d3c5df8f95b4b216e9b8 Issue-ID: CCSDK-151 Signed-off-by: Rich Tabedzki --- .../ccsdk/sli/core/dblib/DBResourceManager.java | 3 +- .../core/dblib/TerminatingCachedDataSource.java | 46 ----------- .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 1 - .../ccsdk/sli/core/dblib/CachedDataSourceTest.java | 94 ++++++++++++++++++++++ .../sli/core/dblib/DBConfigExceptionTest.java | 19 +++++ .../dblib/DblibConfigurationExceptionTest.java | 24 ++++++ .../dblib/TerminatingCachedDataSourceTest.java | 94 ++++++++++++++++++++++ 7 files changed, 233 insertions(+), 48 deletions(-) create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBConfigExceptionTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationExceptionTest.java create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSourceTest.java (limited to 'dblib/provider/src') 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 27c14d2a4..9acae340b 100755 --- 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 @@ -248,7 +248,8 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } catch(Exception exc) { LOGGER.warn("", exc); } - LOGGER.info("Thread DataSourceTester terminated {} for {}", this.getName(), ds.getDbConnectionName()); + if(ds != null) + LOGGER.info("Thread DataSourceTester terminated {} for {}", this.getName(), ds.getDbConnectionName()); } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java index 92b31470e..e1afcc22e 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java @@ -38,54 +38,8 @@ public class TerminatingCachedDataSource extends CachedDataSource implements SQL return null; } - @Override - public long getInterval() { - return 1000; - } - - @Override - public long getInitialDelay() { - return 1000; - } - - @Override - public long getExpectedCompletionTime() { - return 50; - } - - @Override - public void setExpectedCompletionTime(long value) { - - } - - @Override - public void setInterval(long value) { - - } - - @Override - public void setInitialDelay(long value) { - - } - - @Override - public long getUnprocessedFailoverThreshold() { - return 3; - } - - @Override - public void setUnprocessedFailoverThreshold(long value) { - - } - - public int compareTo(CachedDataSource ods) - { - return 0; - } - @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub return null; } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java index a6582b9e7..80ca577cf 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -180,7 +180,6 @@ public class JdbcDBCachedDataSource extends CachedDataSource { public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { - // TODO Auto-generated method stub return null; } diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java new file mode 100644 index 000000000..6385c1b57 --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java @@ -0,0 +1,94 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import java.sql.SQLFeatureNotSupportedException; +import java.util.Properties; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.onap.ccsdk.sli.core.dblib.jdbc.JdbcDBCachedDataSource; +import org.slf4j.LoggerFactory; + +public class CachedDataSourceTest { + + private static final Properties props = new Properties(); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + props.setProperty("org.onap.ccsdk.sli.dbtype", "jdbc"); + props.setProperty("org.onap.ccsdk.sli.jdbc.hosts", "localhost"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", "jdbc:mysql://dbhost:3306/test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.driver", "org.mariadb.jdbc.Driver"); + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.user", "dbuser"); + props.setProperty("org.onap.ccsdk.sli.jdbc.password", "passw0rd"); + props.setProperty("org.onap.ccsdk.sli.jdbc.connection.name", "testdb01"); + props.setProperty("org.onap.ccsdk.sli.jdbc.connection.timeout", "50"); + props.setProperty("org.onap.ccsdk.sli.jdbc.request.timeout", "100"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.init", "10"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.min", "10"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.max", "20"); + props.setProperty("org.onap.dblib.connection.recovery", "false"); + } + + @Test + public void testCachedDataSource() { + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new JdbcDBCachedDataSource(config); + assertNotNull(ds); + } + + @Test + public void testConfigure() { + BaseDBConfiguration config = new JDBCConfiguration(props); + + CachedDataSource ds = new JdbcDBCachedDataSource(config); + assertNotNull(ds.configure(config)); + } + + @Test + public void testSetInitialDelay() { + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new JdbcDBCachedDataSource(config); + ds.setInitialDelay(1000L); + assertTrue(ds.getInitialDelay() == 1000L); + } + + @Test + public void testSetInterval() { + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new JdbcDBCachedDataSource(config); + ds.setInterval(1000L); + assertTrue(ds.getInterval() == 1000L); + } + + @Test + public void testSetExpectedCompletionTime() { + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new JdbcDBCachedDataSource(config); + ds.setExpectedCompletionTime(100L); + assertTrue(ds.getExpectedCompletionTime() == 100L); + } + + @Test + public void testSetUnprocessedFailoverThreshold() { + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new JdbcDBCachedDataSource(config); + ds.setUnprocessedFailoverThreshold(100L); + assertTrue(ds.getUnprocessedFailoverThreshold() == 100L); + } + + @Test + public void testGetParentLogger() { + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new JdbcDBCachedDataSource(config); + try { + assertNull(ds.getParentLogger()); + } catch (SQLFeatureNotSupportedException e) { + LoggerFactory.getLogger(CachedDataSourceTest.class).warn("Test Failure", e); + } + } +} \ No newline at end of file diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBConfigExceptionTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBConfigExceptionTest.java new file mode 100644 index 000000000..2a5b65c7a --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBConfigExceptionTest.java @@ -0,0 +1,19 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class DBConfigExceptionTest { + + @Test + public void testDBConfigExceptionException() { + assertNotNull(new DBConfigException("JUnit Test")); + } + + @Test + public void testDBConfigExceptionString() { + assertNotNull(new DBConfigException(new Exception("JUnit Test"))); + } + +} diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationExceptionTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationExceptionTest.java new file mode 100644 index 000000000..7becd1ae4 --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DblibConfigurationExceptionTest.java @@ -0,0 +1,24 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class DblibConfigurationExceptionTest { + + @Test + public void testDblibConfigurationException() { + assertNotNull(new DblibConfigurationException()); + } + + @Test + public void testDblibConfigurationExceptionString() { + assertNotNull(new DblibConfigurationException("JUnit Test")); + } + + @Test + public void testDblibConfigurationExceptionStringThrowable() { + assertNotNull(new DblibConfigurationException("JUnit Test", new Exception("JUnit Test"))); + } + +} diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSourceTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSourceTest.java new file mode 100644 index 000000000..160a3d4ae --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSourceTest.java @@ -0,0 +1,94 @@ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import java.sql.SQLFeatureNotSupportedException; +import java.util.Properties; + +import org.junit.Test; +import org.onap.ccsdk.sli.core.dblib.config.BaseDBConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.slf4j.LoggerFactory; + +public class TerminatingCachedDataSourceTest { + + @Test + public void testTerminatingCachedDataSource() { + Properties props = new Properties(); + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new TerminatingCachedDataSource(config); + assertNotNull(ds); + } + + @Test + public void testConfigure() { + Properties props = new Properties(); + props.setProperty("org.onap.ccsdk.sli.dbtype", "jdbc"); + props.setProperty("org.onap.ccsdk.sli.jdbc.hosts", "localhost"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", "jdbc:mysql://dbhost:3306/test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.driver", "org.mariadb.jdbc.Driver"); + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.user", "dbuser"); + props.setProperty("org.onap.ccsdk.sli.jdbc.password", "passw0rd"); + props.setProperty("org.onap.ccsdk.sli.jdbc.connection.name", "testdb01"); + props.setProperty("org.onap.ccsdk.sli.jdbc.connection.timeout", "50"); + props.setProperty("org.onap.ccsdk.sli.jdbc.request.timeout", "100"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.init", "10"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.min", "10"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.max", "20"); + props.setProperty("org.onap.dblib.connection.recovery", "false"); + BaseDBConfiguration config = new JDBCConfiguration(props); + + CachedDataSource ds = new TerminatingCachedDataSource(config); + assertNull(ds.configure(config)); + } + + @Test + public void testSetInitialDelay() { + Properties props = new Properties(); + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new TerminatingCachedDataSource(config); + ds.setInitialDelay(1000L); + assertTrue(ds.getInitialDelay() == 1000L); + } + + @Test + public void testSetInterval() { + Properties props = new Properties(); + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new TerminatingCachedDataSource(config); + ds.setInterval(1000L); + assertTrue(ds.getInterval() == 1000L); + } + + @Test + public void testSetExpectedCompletionTime() { + Properties props = new Properties(); + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new TerminatingCachedDataSource(config); + ds.setExpectedCompletionTime(100L); + assertTrue(ds.getExpectedCompletionTime() == 100L); + } + + @Test + public void testSetUnprocessedFailoverThreshold() { + Properties props = new Properties(); + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new TerminatingCachedDataSource(config); + ds.setUnprocessedFailoverThreshold(100L); + assertTrue(ds.getUnprocessedFailoverThreshold() == 100L); + } + + @Test + public void testGetParentLogger() { + Properties props = new Properties(); + BaseDBConfiguration config = new JDBCConfiguration(props); + CachedDataSource ds = new TerminatingCachedDataSource(config); + ds.setInterval(100L); + try { + assertNull(ds.getParentLogger()); + } catch (SQLFeatureNotSupportedException e) { + LoggerFactory.getLogger(TerminatingCachedDataSourceTest.class).warn("Test Failure", e); + } + } +} \ No newline at end of file -- cgit 1.2.3-korg From a0ab49e6c1ea41af18656d6e9efb3377051f2528 Mon Sep 17 00:00:00 2001 From: "Timoney, Dan (dt5972)" Date: Sat, 24 Mar 2018 19:11:10 -0400 Subject: Add unit tests for sli Added unit tests for ccsdk/sli/core/sli Change-Id: I0d2408c43b9e56a78f3e01e87985aedb6cad5953 Issue-ID: CCSDK-213 Signed-off-by: Timoney, Dan (dt5972) --- .gitignore | 2 + .../ccsdk/sli/core/dblib/CachedDataSource.java | 7 +- filters/provider/pom.xml | 8 + .../filters/RequestResponseDbLoggingFilter.java | 5 +- .../onap/ccsdk/sli/core/filters/TestLogFilter.java | 71 +++++++ .../filters/TestRequestResponseLoggingFilter.java | 129 +++++++++++++ sli/common/pom.xml | 12 +- .../org/onap/ccsdk/sli/core/sli/MessageWriter.java | 6 +- .../ccsdk/sli/core/sli/SvcLogicDblibStore.java | 13 ++ .../onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java | 1 - .../onap/ccsdk/sli/core/sli/SvcLogicParser.java | 6 +- .../ccsdk/sli/core/sli/ITCaseSvcLogicParser.java | 139 ++++++++++++-- .../ccsdk/sli/core/sli/PrintYangToPropTest.java | 22 +++ .../onap/ccsdk/sli/core/sli/TestMetricLogger.java | 135 +++++++++++++ .../ccsdk/sli/core/sli/TestSvcLogicLoader.java | 38 ++++ sli/common/src/test/resources/dblib.properties | 14 ++ .../test/resources/graphs/sliapi/graph.versions | 1 + .../resources/graphs/sliapi/sli_healthcheck.xml | 27 +++ sli/common/src/test/resources/l3sdn_logic_v10.xml | 208 +++++++++++++++++++++ sli/common/src/test/resources/parser-good.tests | 1 + sli/common/src/test/resources/svclogic.properties | 7 +- sli/common/src/test/resources/svclogic.xsd | 11 ++ sli/provider/pom.xml | 96 +++++----- .../src/main/resources/svclogic.properties | 25 --- .../sli/provider/ITCaseSvcLogicGraphExecutor.java | 29 +-- sli/provider/src/test/resources/executor.tests | 4 +- .../src/test/resources/l3sdn_logic_v10.xml | 23 +++ .../src/test/resources/svclogic.properties | 4 +- sliapi/provider/pom.xml | 143 ++++++++------ .../onap/ccsdk/sli/core/sliapi/sliapiProvider.java | 23 ++- .../ccsdk/sli/core/sliapi/TestSliapiProvider.java | 171 +++++++++++++++++ .../src/test/resources/sli_healthcheck.xml | 27 +++ .../src/test/resources/svclogic.properties | 27 +++ 33 files changed, 1241 insertions(+), 194 deletions(-) create mode 100644 filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestLogFilter.java create mode 100644 filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestRequestResponseLoggingFilter.java create mode 100644 sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestMetricLogger.java create mode 100644 sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestSvcLogicLoader.java create mode 100755 sli/common/src/test/resources/dblib.properties create mode 100644 sli/common/src/test/resources/graphs/sliapi/graph.versions create mode 100644 sli/common/src/test/resources/graphs/sliapi/sli_healthcheck.xml create mode 100644 sli/common/src/test/resources/l3sdn_logic_v10.xml delete mode 100644 sli/provider/src/main/resources/svclogic.properties create mode 100644 sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java create mode 100644 sliapi/provider/src/test/resources/sli_healthcheck.xml create mode 100644 sliapi/provider/src/test/resources/svclogic.properties (limited to 'dblib/provider/src') diff --git a/.gitignore b/.gitignore index a36bed326..a5a0d80e3 100755 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,5 @@ sdnc-core_bdio.jsonld blackDuckHubProjectName.txt blackDuckHubProjectVersionName.txt +# Derby log +derby.log diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 02cce3cf1..97380f58d 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -342,11 +342,16 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } protected boolean testConnection(boolean errorLevel) { + + String testQuery = "SELECT @@global.read_only, @@global.hostname"; + if (isDerby) { + testQuery = "SELECT 'false', 'localhost' FROM SYSIBM.SYSDUMMY1"; + } ResultSet rs = null; try (Connection conn = this.getConnection(); Statement stmt = conn.createStatement()) { Boolean readOnly; String hostname; - rs = stmt.executeQuery("SELECT @@global.read_only, @@global.hostname"); // ("SELECT 1 FROM DUAL"); //"select + rs = stmt.executeQuery(testQuery); // ("SELECT 1 FROM DUAL"); //"select // BANNER from SYS.V_$VERSION" while (rs.next()) { readOnly = rs.getBoolean(1); diff --git a/filters/provider/pom.xml b/filters/provider/pom.xml index 4fdd83280..a60c0be05 100755 --- a/filters/provider/pom.xml +++ b/filters/provider/pom.xml @@ -19,6 +19,8 @@ UTF-8 + + **/RequestResponseDbLoggingFilter.java @@ -28,6 +30,12 @@ ${junit.version} test + + + org.mockito + mockito-core + test + javax.servlet javax.servlet-api diff --git a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java index 8b67276b0..359136565 100644 --- a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java +++ b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseDbLoggingFilter.java @@ -8,9 +8,9 @@ * 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. @@ -47,6 +47,7 @@ import org.onap.ccsdk.sli.core.sli.MessageWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@Deprecated public class RequestResponseDbLoggingFilter implements Filter { private static Logger log = LoggerFactory.getLogger(RequestResponseDbLoggingFilter.class); diff --git a/filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestLogFilter.java b/filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestLogFilter.java new file mode 100644 index 000000000..a900b246c --- /dev/null +++ b/filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestLogFilter.java @@ -0,0 +1,71 @@ +/** + * + */ +package org.onap.ccsdk.sli.core.filters; + +import static org.junit.Assert.*; +import org.apache.commons.codec.binary.Base64; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.mockito.Mockito.*; +import java.io.IOException; +import java.util.UUID; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author dt5972 + * + */ +public class TestLogFilter { + + LogFilter logFilter; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + logFilter = new LogFilter(); + logFilter.init(null); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + logFilter.destroy(); + } + + /** + * Test method for {@link org.onap.ccsdk.sli.core.filters.LogFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)}. + * @throws ServletException + * @throws IOException + */ + @Test + public void testDoFilter() throws IOException, ServletException { + + // Test failed request with minimal headers + HttpServletRequest servletReq = mock(HttpServletRequest.class); + when(servletReq.getRequestURL()).thenReturn(new StringBuffer("SLI-API:healthcheck")); + when(servletReq.getPathInfo()).thenReturn("/hello:world"); + HttpServletResponse servletResp = mock(HttpServletResponse.class); + when(servletResp.getStatus()).thenReturn(400); + FilterChain filterChain = mock(FilterChain.class); + logFilter.doFilter(servletReq, servletResp, filterChain); + + // Test successful request with valid header + when(servletReq.getHeader(LogFilter.REQUEST_ID)).thenReturn(UUID.randomUUID().toString()); + when(servletReq.getHeader("Authorization")).thenReturn("Basic "+Base64.encodeBase64String("username:password".getBytes())); + when(servletResp.getStatus()).thenReturn(200); + logFilter.doFilter(servletReq, servletResp, filterChain); + + + } + +} diff --git a/filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestRequestResponseLoggingFilter.java b/filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestRequestResponseLoggingFilter.java new file mode 100644 index 000000000..9f36fe11e --- /dev/null +++ b/filters/provider/src/test/java/org/onap/ccsdk/sli/core/filters/TestRequestResponseLoggingFilter.java @@ -0,0 +1,129 @@ +/** + * + */ +package org.onap.ccsdk.sli.core.filters; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringBufferInputStream; +import java.io.StringReader; +import java.util.LinkedList; +import java.util.UUID; +import java.util.Vector; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.codec.binary.Base64; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author dt5972 + * + */ +public class TestRequestResponseLoggingFilter { + + RequestResponseLoggingFilter filter; + + private class DummyServletInputStream extends ServletInputStream { + + InputStream stream; + + public DummyServletInputStream(InputStream stream) { + this.stream = stream; + } + + + @Override + public void close() throws IOException { + super.close(); + stream.close(); + } + + + @Override + public int read() throws IOException { + return stream.read(); + } + + + + } + + private class DummyServletOutputStream extends ServletOutputStream { + + OutputStream ostr; + + public DummyServletOutputStream(OutputStream ostr) { + this.ostr = ostr; + } + + @Override + public void write(int b) throws IOException { + ostr.write(b); + } + + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + filter = new RequestResponseLoggingFilter(); + filter.init(null); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + /** + * Test method for {@link org.onap.ccsdk.sli.core.filters.RequestResponseLoggingFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)}. + * @throws IOException + * @throws ServletException + */ + @Test + public void testDoFilter() throws IOException, ServletException { + + HttpServletRequest request = mock(HttpServletRequest.class); + String msgBody = "hello world"; + InputStream reqInputStream = new ByteArrayInputStream(msgBody.getBytes()); + when(request.getInputStream()).thenReturn(new DummyServletInputStream(reqInputStream)); + when(request.getMethod()).thenReturn("POST"); + when(request.getRequestURL()).thenReturn(new StringBuffer("/HELLO:world")); + when(request.getPathInfo()).thenReturn("/hello:world"); + Vector headerList = new Vector<>(); + headerList.add(LogFilter.REQUEST_ID); + headerList.add("Authorization"); + when(request.getHeaderNames()).thenReturn(headerList.elements()); + + when(request.getHeader(LogFilter.REQUEST_ID)).thenReturn(UUID.randomUUID().toString()); + when(request.getHeader("Authorization")).thenReturn("Basic "+Base64.encodeBase64String("username:password".getBytes())); + + HttpServletResponse response = mock(HttpServletResponse.class); + OutputStream outStr = new ByteArrayOutputStream(); + when(response.getOutputStream()).thenReturn(new DummyServletOutputStream(outStr)); + + FilterChain filterChain = mock(FilterChain.class); + + filter.doFilter(request, response, filterChain); + + + + } + +} diff --git a/sli/common/pom.xml b/sli/common/pom.xml index 1d35dfb1b..c22c1ae69 100755 --- a/sli/common/pom.xml +++ b/sli/common/pom.xml @@ -18,6 +18,12 @@ ccsdk-sli-core :: sli :: ${project.artifactId} The SLI Common package includes common classes used by the various SLI subcomponents, as well as classes used by clients to interface with the service logic interpreter + + + **/MessageWriter.java + + + @@ -31,9 +37,9 @@ - ch.vorburger.mariaDB4j - mariaDB4j - 2.2.3 + org.apache.derby + derby + 10.11.1.1 test diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java index c75873eb6..0e39896e0 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/MessageWriter.java @@ -8,9 +8,9 @@ * 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. @@ -38,7 +38,7 @@ import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - +@Deprecated public class MessageWriter { private static final Logger LOG = LoggerFactory.getLogger(MessageWriter.class); 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 ee3bcca5c..864652b40 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 @@ -66,6 +66,19 @@ public class SvcLogicDblibStore implements SvcLogicStore { this.dbSvc = dbsvc; } + public SvcLogicDblibStore(Properties props) { + try { + dbSvc = new DBResourceManager(props); + JavaSingleton.setInstance(dbSvc); + } catch (Exception e) { + LOG.warn("Caught exception trying to create DBResourceManager", e); + } + } + + public Connection getConnection() throws SQLException { + return(dbSvc.getConnection()); + } + @Override public void init(Properties props) throws ConfigurationException { diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java index e2fbdf726..0e7d05a6e 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicJdbcStore.java @@ -38,7 +38,6 @@ import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class SvcLogicJdbcStore implements SvcLogicStore { private static final Logger LOG = LoggerFactory.getLogger(SvcLogicJdbcStore.class); diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java index 3d9caffbd..2804f6205 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicParser.java @@ -437,7 +437,7 @@ public class SvcLogicParser { } - + public static void load(String xmlfile, SvcLogicStore store) throws SvcLogicException { File xmlFile = new File(xmlfile); if (!xmlFile.canRead()) { @@ -531,7 +531,7 @@ public class SvcLogicParser { } - private static void activate(String module, String rpc, String version, String mode, SvcLogicStore store) { + public static void activate(String module, String rpc, String version, String mode, SvcLogicStore store) { String details = "(module:" + module + ", rpc:" + rpc + ", version:" + version + ", mode:" + mode + ")"; try { @@ -560,7 +560,7 @@ public class SvcLogicParser { System.exit(1); } - + protected SAXParser initParser() throws ParserConfigurationException, SAXException { URL xsdUrl = null; Schema schema = null; diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java index 368d9f95d..6ee18e922 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ITCaseSvcLogicParser.java @@ -32,11 +32,13 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.util.Properties; -import ch.vorburger.mariadb4j.DB; -import ch.vorburger.mariadb4j.DBConfigurationBuilder; - import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -67,17 +69,9 @@ public class ITCaseSvcLogicParser { props.load(propStr); + store = SvcLogicStoreFactory.getSvcLogicStore(props); - // Start MariaDB4j database - DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); - config.setPort(0); // 0 => autom. detect free port - DB db = DB.newEmbeddedDB(config.build()); - db.start(); - - - // Override jdbc URL and database name - props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); - props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + assertNotNull(store); } @@ -120,8 +114,123 @@ public class ITCaseSvcLogicParser { } try { - SvcLogicParser.validate(testCaseUrl.getPath(), store); + SvcLogicParser.load(testCaseUrl.getPath(), store); } catch (Exception e) { + + fail("Validation failure [" + e.getMessage() + "]"); + } + } + } + } catch (SvcLogicParserException e) { + fail("Parser error : " + e.getMessage()); + } catch (Exception e) { + LOG.error("", e); + fail("Caught exception processing test cases"); + } + } + + @Test + public void testDblibLoadValidXml() throws IOException, SQLException, ConfigurationException { + + URL propUrl = ITCaseSvcLogicParser.class.getResource("/dblib.properties"); + + InputStream propStr = ITCaseSvcLogicParser.class.getResourceAsStream("/dblib.properties"); + + Properties props = new Properties(); + + props.load(propStr); + + SvcLogicDblibStore dblibStore = new SvcLogicDblibStore(props); + + Connection dbConn = dblibStore.getConnection(); + + String dbName = props.getProperty("org.onap.ccsdk.sli.jdbc.database", "sdnctl"); + + DatabaseMetaData dbm; + + try { + dbm = dbConn.getMetaData(); + } catch (SQLException e) { + + throw new ConfigurationException("could not get databse metadata", e); + } + + // See if table SVC_LOGIC exists. If not, create it. + Statement stmt = null; + try { + + ResultSet tables = dbm.getTables(null, null, "SVC_LOGIC", null); + if (tables.next()) { + LOG.debug("SVC_LOGIC table already exists"); + } else { + String crTableCmd = "CREATE TABLE " + dbName + ".SVC_LOGIC (" + "module varchar(80) NOT NULL," + + "rpc varchar(80) NOT NULL," + "version varchar(40) NOT NULL," + "mode varchar(5) NOT NULL," + + "active varchar(1) NOT NULL," + "graph BLOB," + + "CONSTRAINT P_SVC_LOGIC PRIMARY KEY(module, rpc, version, mode))"; + + stmt = dbConn.createStatement(); + stmt.executeUpdate(crTableCmd); + } + } catch (Exception e) { + throw new ConfigurationException("could not create SVC_LOGIC table", e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + LOG.error("Statement close error ", e); + } + } + } + + // See if NODE_TYPES table exists and, if not, create it + stmt = null; + try { + + ResultSet tables = dbm.getTables(null, null, "NODE_TYPES", null); + if (tables.next()) { + LOG.debug("NODE_TYPES table already exists"); + } else { + String crTableCmd = "CREATE TABLE " + dbName + ".NODE_TYPES (" + "nodetype varchar(80) NOT NULL," + + "CONSTRAINT P_NODE_TYPES PRIMARY KEY(nodetype))"; + + stmt = dbConn.createStatement(); + + stmt.executeUpdate(crTableCmd); + } + } catch (Exception e) { + throw new ConfigurationException("could not create SVC_LOGIC table", e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + LOG.error("Statement close error ", e); + } + } + } + + try { + InputStream testStr = getClass().getResourceAsStream("/parser-good.tests"); + BufferedReader testsReader = new BufferedReader(new InputStreamReader(testStr)); + String testCaseFile = null; + while ((testCaseFile = testsReader.readLine()) != null) { + + testCaseFile = testCaseFile.trim(); + + if (testCaseFile.length() > 0) { + if (!testCaseFile.startsWith("/")) { + testCaseFile = "/" + testCaseFile; + } + URL testCaseUrl = getClass().getResource(testCaseFile); + if (testCaseUrl == null) { + fail("Could not resolve test case file " + testCaseFile); + } + + try { + SvcLogicParser.load(testCaseUrl.getPath(), dblibStore); + } catch (Exception e) { + fail("Validation failure [" + e.getMessage() + "]"); } } @@ -152,7 +261,7 @@ public class ITCaseSvcLogicParser { if (testCaseUrl == null) { fail("Could not resolve test case file " + testCaseFile); } - SvcLogicParser.load(testCaseUrl.getPath(), store); + SvcLogicParser.validate(testCaseUrl.getPath(), store); } } } diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java index 21d3e59c3..fb6eaf70b 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java @@ -15,6 +15,9 @@ import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.Exe import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInputBuilder; import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameter; import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameterBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddressBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefixBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,6 +53,22 @@ public class PrintYangToPropTest { pBuilder.setIntValue(null); pBuilder.setBooleanValue(true); pList.add(pBuilder.build()); + pBuilder.setParameterName("ipaddress-value1"); + pBuilder.setBooleanValue(null); + pBuilder.setIpaddressValue(IpAddressBuilder.getDefaultInstance("127.0.0.1")); + pList.add(pBuilder.build()); + pBuilder.setParameterName("ipaddress-value1"); + pBuilder.setIpaddressValue(IpAddressBuilder.getDefaultInstance("::1")); + pList.add(pBuilder.build()); + pBuilder.setParameterName("ipprefix-value1"); + pBuilder.setIpaddressValue(null); + pBuilder.setIpprefixValue(IpPrefixBuilder.getDefaultInstance("192.168.0.0/16")); + pList.add(pBuilder.build()); + pBuilder.setParameterName("ipprefix-value2"); + pBuilder.setIpprefixValue(IpPrefixBuilder.getDefaultInstance("2001:db8:3c4d::/48")); + pList.add(pBuilder.build()); + + egBuilder.setSliParameter(pList); @@ -64,6 +83,9 @@ public class PrintYangToPropTest { LOG.info("Property {} = {}", propName, props.getProperty(propName)); } + // Generate builder from properties just generated + PrintYangToProp.toBuilder(props, pBuilder); + } } diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestMetricLogger.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestMetricLogger.java new file mode 100644 index 000000000..31a419bb1 --- /dev/null +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestMetricLogger.java @@ -0,0 +1,135 @@ +package org.onap.ccsdk.sli.core.sli; + +import static org.junit.Assert.*; +import java.util.Date; +import org.junit.Before; +import org.junit.Test; + +public class TestMetricLogger { + + MetricLogger logger; + + @Before + public void setUp() throws Exception { + + logger = new MetricLogger(); + logger.resetContext(); + logger.logRequest("svcInstance1", "svcName", "svcPartner", "targetEntity", "targetServiceName", "targetVirtualEntity", "hello-world"); + logger.logResponse("200", "200", "SUCCESS"); + + } + + @Test + public final void testGetBeginTimestamp() { + logger.getBeginTimestamp(); + } + + @Test + public final void testGetEndTimestamp() { + logger.getEndTimestamp(); + } + + @Test + public final void testGetRequestID() { + logger.getRequestID(); + } + + @Test + public final void testGetServiceInstanceID() { + logger.getServiceInstanceID(); + } + + @Test + public final void testGetServiceName() { + logger.getServiceName(); + } + + @Test + public final void testGetPartnerName() { + logger.getPartnerName(); + } + + @Test + public final void testGetTargetEntity() { + logger.getTargetEntity(); + } + + @Test + public final void testGetTargetServiceName() { + logger.getTargetServiceName(); + } + + @Test + public final void testGetStatusCode() { + logger.getStatusCode(); + } + + @Test + public final void testGetResponseCode() { + logger.getResponseCode(); + } + + @Test + public final void testGetResponseDescription() { + logger.getResponseDescription(); + } + + @Test + public final void testGetInstanceUUID() { + logger.getInstanceUUID(); + } + + @Test + public final void testGetCategoryLogLevel() { + logger.getCategoryLogLevel(); + } + + @Test + public final void testGetSeverity() { + logger.getSeverity(); + } + + @Test + public final void testGetServerIpAddress() { + logger.getServerIpAddress(); + } + + @Test + public final void testGetElapsedTime() { + logger.getElapsedTime(); + } + + @Test + public final void testGetServer() { + logger.getServer(); + } + + @Test + public final void testGetClientIp() { + logger.getClientIp(); + } + + @Test + public final void testGetClassName() { + logger.getClassName(); + } + + @Test + public final void testGetTargetVirtualEntity() { + logger.getTargetVirtualEntity(); + } + + @Test + public final void testAsIso8601Date() { + logger.asIso8601(new Date()); + } + + @Test + public final void testAsIso8601Long() { + logger.asIso8601(System.currentTimeMillis()); + } + + + + +} diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestSvcLogicLoader.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestSvcLogicLoader.java new file mode 100644 index 000000000..8998382ec --- /dev/null +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/TestSvcLogicLoader.java @@ -0,0 +1,38 @@ +package org.onap.ccsdk.sli.core.sli; + +import static org.junit.Assert.*; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Properties; +import org.junit.Test; + +public class TestSvcLogicLoader { + + @Test + public void testLoadAndActivate() throws IOException, SvcLogicException { + URL propUrl = ITCaseSvcLogicParser.class.getResource("/svclogic.properties"); + + InputStream propStr = ITCaseSvcLogicParser.class.getResourceAsStream("/svclogic.properties"); + + Properties props = new Properties(); + + props.load(propStr); + + SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(props); + + URL graphUrl = TestSvcLogicLoader.class.getClassLoader().getResource("graphs"); + + if (graphUrl == null) { + fail("Cannot find graphs directory"); + } + + SvcLogicLoader loader = new SvcLogicLoader(graphUrl.getPath(), store); + loader.loadAndActivate(); + + + } + + + +} diff --git a/sli/common/src/test/resources/dblib.properties b/sli/common/src/test/resources/dblib.properties new file mode 100755 index 000000000..f08dce7a0 --- /dev/null +++ b/sli/common/src/test/resources/dblib.properties @@ -0,0 +1,14 @@ +org.onap.ccsdk.sli.dbtype=jdbc +org.onap.ccsdk.sli.jdbc.hosts=sdnctldb01,sdnctldb02 +org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:test;create=true +org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver +org.onap.ccsdk.sli.jdbc.database=test +org.onap.ccsdk.sli.jdbc.user=test +org.onap.ccsdk.sli.jdbc.password=test +org.onap.ccsdk.sli.jdbc.connection.name=sdnctldb01 + +org.onap.ccsdk.sli.jdbc.connection.timeout=50 +org.onap.ccsdk.sli.jdbc.request.timeout=100 +org.onap.ccsdk.sli.jdbc.limit.init=10 +org.onap.ccsdk.sli.jdbc.limit.min=10 +org.onap.ccsdk.sli.jdbc.limit.max=20 diff --git a/sli/common/src/test/resources/graphs/sliapi/graph.versions b/sli/common/src/test/resources/graphs/sliapi/graph.versions new file mode 100644 index 000000000..d72920a43 --- /dev/null +++ b/sli/common/src/test/resources/graphs/sliapi/graph.versions @@ -0,0 +1 @@ +sli healthcheck 1.0.0 sync diff --git a/sli/common/src/test/resources/graphs/sliapi/sli_healthcheck.xml b/sli/common/src/test/resources/graphs/sliapi/sli_healthcheck.xml new file mode 100644 index 000000000..d512f546f --- /dev/null +++ b/sli/common/src/test/resources/graphs/sliapi/sli_healthcheck.xml @@ -0,0 +1,27 @@ + + + + + + + + diff --git a/sli/common/src/test/resources/l3sdn_logic_v10.xml b/sli/common/src/test/resources/l3sdn_logic_v10.xml new file mode 100644 index 000000000..58a420f9e --- /dev/null +++ b/sli/common/src/test/resources/l3sdn_logic_v10.xml @@ -0,0 +1,208 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sli/common/src/test/resources/parser-good.tests b/sli/common/src/test/resources/parser-good.tests index 06543126f..4147fdb62 100755 --- a/sli/common/src/test/resources/parser-good.tests +++ b/sli/common/src/test/resources/parser-good.tests @@ -1,2 +1,3 @@ ReleasePortSvcLogic_v101.xml neutron_logic_v10.xml +l3sdn_logic_v10.xml diff --git a/sli/common/src/test/resources/svclogic.properties b/sli/common/src/test/resources/svclogic.properties index 33d7ae6e4..426960f76 100644 --- a/sli/common/src/test/resources/svclogic.properties +++ b/sli/common/src/test/resources/svclogic.properties @@ -20,7 +20,8 @@ ### org.onap.ccsdk.sli.dbtype = jdbc -org.onap.ccsdk.sli.jdbc.url = jdbc:mysql://localhost:3306/test -org.onap.ccsdk.sli.jdbc.database = test +org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true +org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver +org.onap.ccsdk.sli.jdbc.database = sdnctl org.onap.ccsdk.sli.jdbc.user = test -org.onap.ccsdk.sli.jdbc.password = test123 +org.onap.ccsdk.sli.jdbc.password = test diff --git a/sli/common/src/test/resources/svclogic.xsd b/sli/common/src/test/resources/svclogic.xsd index a63758f7c..2704de88e 100755 --- a/sli/common/src/test/resources/svclogic.xsd +++ b/sli/common/src/test/resources/svclogic.xsd @@ -30,6 +30,7 @@ + @@ -320,4 +321,14 @@ + + + + + + + + + + diff --git a/sli/provider/pom.xml b/sli/provider/pom.xml index 4a90ae005..1b21b0020 100755 --- a/sli/provider/pom.xml +++ b/sli/provider/pom.xml @@ -1,44 +1,40 @@ - - 4.0.0 + + 4.0.0 - + org.onap.ccsdk.parent binding-parent 1.0.1-SNAPSHOT - + - org.onap.ccsdk.sli.core - sli-provider - 0.2.1-SNAPSHOT - bundle + org.onap.ccsdk.sli.core + sli-provider + 0.2.1-SNAPSHOT + bundle - ccsdk-sli-core :: sli :: ${project.artifactId} - SLI Provider is the OSGi bundle that exposes the service logic interpreter as a service. + ccsdk-sli-core :: sli :: ${project.artifactId} + SLI Provider is the OSGi bundle that exposes the service logic interpreter as a service. - + UTF-8 - - - - org.opendaylight.controller - mdsal-artifacts - 1.6.1 - pom - import - - - - - - ch.vorburger.mariaDB4j - mariaDB4j - 2.2.3 - test - + + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + org.onap.ccsdk.sli.core sli-model @@ -61,11 +57,6 @@ slf4j-api ${slf4j.version} - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - commons-lang commons-lang @@ -74,23 +65,28 @@ - - org.opendaylight.controller - sal-binding-api - - - - - junit - junit - test - + + org.opendaylight.controller + sal-binding-api + - - org.mockito - mockito-core - test - + + + junit + junit + test + + + org.mockito + mockito-core + test + + + org.apache.derby + derby + 10.11.1.1 + test + diff --git a/sli/provider/src/main/resources/svclogic.properties b/sli/provider/src/main/resources/svclogic.properties deleted file mode 100644 index 49d39ab40..000000000 --- a/sli/provider/src/main/resources/svclogic.properties +++ /dev/null @@ -1,25 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP : CCSDK -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights -# reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= -### - -org.onap.ccsdk.sli.dbtype = dblib -org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true -org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver -org.onap.ccsdk.sli.jdbc.database = sdnctl diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java index 4c112ab25..0a8bf71ac 100644 --- a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/ITCaseSvcLogicGraphExecutor.java @@ -24,8 +24,7 @@ package org.onap.ccsdk.sli.core.sli.provider; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; -import ch.vorburger.mariadb4j.DB; -import ch.vorburger.mariadb4j.DBConfigurationBuilder; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -40,6 +39,7 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.ccsdk.sli.core.dblib.DBResourceManager; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicGraph; import org.onap.ccsdk.sli.core.sli.SvcLogicParser; @@ -74,6 +74,7 @@ public class ITCaseSvcLogicGraphExecutor { put("set", new SetNodeExecutor()); put("switch", new SwitchNodeExecutor()); put("update", new UpdateNodeExecutor()); + put("while", new WhileNodeExecutor()); } }; @@ -88,16 +89,6 @@ public class ITCaseSvcLogicGraphExecutor { Properties svcprops = new Properties(); svcprops.load(propStr); - // Start MariaDB4j database - DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); - config.setPort(0); // 0 => autom. detect free port - DB db = DB.newEmbeddedDB(config.build()); - db.start(); - - // Override jdbc URL and database name - svcprops.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); - svcprops.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); - SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(svcprops); assertNotNull(store); @@ -144,18 +135,9 @@ public class ITCaseSvcLogicGraphExecutor { Properties svcprops = new Properties(); svcprops.load(propStr); - // Start MariaDB4j database - DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); - config.setPort(0); // 0 => autom. detect free port - DB db = DB.newEmbeddedDB(config.build()); - db.start(); - - // Override jdbc URL and database name - svcprops.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); - svcprops.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); - SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(svcprops); + assertNotNull(store); @@ -214,10 +196,13 @@ public class ITCaseSvcLogicGraphExecutor { fail("Could not resolve test case file " + testCaseFile); } + LinkedList graphs = parser.parse(testCaseUrl.getPath()); assertNotNull(graphs); + // Load grqphs into db to support call node + parser.load(testCaseUrl.getPath(), store); for (SvcLogicGraph graph : graphs) { if (graph.getRpc().equals(testCaseMethod)) { Properties props = ctx.toProperties(); diff --git a/sli/provider/src/test/resources/executor.tests b/sli/provider/src/test/resources/executor.tests index e4e60208a..5468c8d60 100755 --- a/sli/provider/src/test/resources/executor.tests +++ b/sli/provider/src/test/resources/executor.tests @@ -1,6 +1,8 @@ l3sdn_logic_v10.xml:switchTester:test-value="" l3sdn_logic_v10.xml:switchTester:test-value="hi" l3sdn_logic_v10.xml:forRecordTester +l3sdn_logic_v10.xml:whileNodeTester l3sdn_logic_v10.xml:resourceTester l3sdn_logic_v10.xml:configureTester -l3sdn_logic_v10.xml:javaPluginTester \ No newline at end of file +l3sdn_logic_v10.xml:javaPluginTester +l3sdn_logic_v10.xml:allNodesTester \ No newline at end of file diff --git a/sli/provider/src/test/resources/l3sdn_logic_v10.xml b/sli/provider/src/test/resources/l3sdn_logic_v10.xml index 1386df10d..cbb5db1ba 100644 --- a/sli/provider/src/test/resources/l3sdn_logic_v10.xml +++ b/sli/provider/src/test/resources/l3sdn_logic_v10.xml @@ -49,6 +49,27 @@ + + + + + + + + + + + + + + + + + + + + + @@ -167,6 +188,8 @@ + + diff --git a/sli/provider/src/test/resources/svclogic.properties b/sli/provider/src/test/resources/svclogic.properties index 49d39ab40..426960f76 100644 --- a/sli/provider/src/test/resources/svclogic.properties +++ b/sli/provider/src/test/resources/svclogic.properties @@ -19,7 +19,9 @@ # ============LICENSE_END========================================================= ### -org.onap.ccsdk.sli.dbtype = dblib +org.onap.ccsdk.sli.dbtype = jdbc org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver org.onap.ccsdk.sli.jdbc.database = sdnctl +org.onap.ccsdk.sli.jdbc.user = test +org.onap.ccsdk.sli.jdbc.password = test diff --git a/sliapi/provider/pom.xml b/sliapi/provider/pom.xml index cb4dfc898..5650416df 100755 --- a/sliapi/provider/pom.xml +++ b/sliapi/provider/pom.xml @@ -1,73 +1,94 @@ - - 4.0.0 + + 4.0.0 - - org.onap.ccsdk.parent - binding-parent - 1.0.1-SNAPSHOT - - + + org.onap.ccsdk.parent + binding-parent + 1.0.1-SNAPSHOT + + - org.onap.ccsdk.sli.core - sliapi-provider - 0.2.1-SNAPSHOT - bundle + org.onap.ccsdk.sli.core + sliapi-provider + 0.2.1-SNAPSHOT + bundle - ccsdk-sli-core :: sliapi :: ${project.artifactId} + ccsdk-sli-core :: sliapi :: ${project.artifactId} - - - - org.opendaylight.controller - mdsal-artifacts - 1.6.1 - pom - import - - - - - - org.onap.ccsdk.sli.core - sliapi-model - ${project.version} - + + + + org.opendaylight.controller + mdsal-artifacts + 1.6.1 + pom + import + + + + + + org.onap.ccsdk.sli.core + sliapi-model + ${project.version} + - - org.opendaylight.controller - sal-binding-config - + + org.opendaylight.controller + sal-binding-config + - - org.opendaylight.controller - sal-binding-api - + + org.opendaylight.controller + sal-binding-api + - - org.opendaylight.controller - sal-common-util - + + org.opendaylight.controller + sal-common-util + - - org.onap.ccsdk.sli.core - sli-common - ${project.version} - - - org.onap.ccsdk.sli.core - sli-provider - ${project.version} - - - org.opendaylight.controller - sal-core-api - - - org.opendaylight.yangtools - yang-data-impl - - + + org.onap.ccsdk.sli.core + sli-common + ${project.version} + + + org.onap.ccsdk.sli.core + sli-provider + ${project.version} + + + org.opendaylight.controller + sal-core-api + + + org.opendaylight.yangtools + yang-data-impl + + + + junit + junit + ${junit.version} + test + + + + org.mockito + mockito-core + test + + + + org.apache.derby + derby + 10.11.1.1 + test + + diff --git a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java index 3ff2f52d4..e9a2b8eb2 100644 --- a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java +++ b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java @@ -114,14 +114,16 @@ import com.google.common.util.concurrent.Futures; */ public class sliapiProvider implements AutoCloseable, SLIAPIService{ - private final Logger LOG = LoggerFactory.getLogger( sliapiProvider.class ); - private final String appName = "slitester"; + private static final Logger LOG = LoggerFactory.getLogger( sliapiProvider.class ); + private static final String appName = "slitester"; protected DataBroker dataBroker; protected DOMDataBroker domDataBroker; protected NotificationPublishService notificationService; protected RpcProviderRegistry rpcRegistry; + private SvcLogicService svcLogic; + protected BindingAwareBroker.RpcRegistration rpcRegistration; private static String SLIAPI_NAMESPACE = "org:onap:ccsdk:sli:core:sliapi"; @@ -142,15 +144,23 @@ public class sliapiProvider implements AutoCloseable, SLIAPIService{ RESULTS_QNAME = QName.create(TEST_RESULT_QNAME, "results"); } + public sliapiProvider( + DataBroker dataBroker, + NotificationPublishService notificationPublishService, + RpcProviderRegistry rpcProviderRegistry) { + this(dataBroker, notificationPublishService, rpcProviderRegistry, findSvcLogicService()); + } public sliapiProvider( DataBroker dataBroker, NotificationPublishService notificationPublishService, - RpcProviderRegistry rpcProviderRegistry) { + RpcProviderRegistry rpcProviderRegistry, + SvcLogicService svcLogic) { this.LOG.info( "Creating provider for " + appName ); this.dataBroker = dataBroker; this.notificationService = notificationPublishService; this.rpcRegistry = rpcProviderRegistry; + this.svcLogic = svcLogic; initialize(); } @@ -357,6 +367,13 @@ public class sliapiProvider implements AutoCloseable, SLIAPIService{ private SvcLogicService getSvcLogicService() { + if (svcLogic == null) { + svcLogic = findSvcLogicService(); + } + + return(svcLogic); + } + private static SvcLogicService findSvcLogicService() { BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class).getBundleContext(); SvcLogicService svcLogic = null; diff --git a/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java b/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java new file mode 100644 index 000000000..38cbd40c9 --- /dev/null +++ b/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java @@ -0,0 +1,171 @@ +/** + * + */ +package org.onap.ccsdk.sli.core.sliapi; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.*; +import java.io.InputStream; +import java.net.URL; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.core.sli.SvcLogicParser; +import org.onap.ccsdk.sli.core.sli.SvcLogicStore; +import org.onap.ccsdk.sli.core.sli.SvcLogicStoreFactory; +import org.onap.ccsdk.sli.core.sli.provider.BlockNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.CallNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ConfigureNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.DeleteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ExecuteNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ExistsNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ForNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.GetResourceNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.IsAvailableNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.NotifyNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.RecordNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ReleaseNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ReserveNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.ReturnNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SaveNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SetNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicPropertiesProviderImpl; +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicServiceImpl; +import org.onap.ccsdk.sli.core.sli.provider.SwitchNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.UpdateNodeExecutor; +import org.onap.ccsdk.sli.core.sli.provider.WhileNodeExecutor; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.SLIAPIService; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameter; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameterBuilder; + +/** + * @author dt5972 + * + */ +public class TestSliapiProvider { + + private sliapiProvider provider; + + private static final String HEALTHCHECK_DG = "sli_healthcheck.xml"; + + private static final Map BUILTIN_NODES = new HashMap() { + { + put("block", new BlockNodeExecutor()); + put("call", new CallNodeExecutor()); + put("configure", new ConfigureNodeExecutor()); + put("delete", new DeleteNodeExecutor()); + put("execute", new ExecuteNodeExecutor()); + put("exists", new ExistsNodeExecutor()); + put("for", new ForNodeExecutor()); + put("get-resource", new GetResourceNodeExecutor()); + put("is-available", new IsAvailableNodeExecutor()); + put("notify", new NotifyNodeExecutor()); + put("record", new RecordNodeExecutor()); + put("release", new ReleaseNodeExecutor()); + put("reserve", new ReserveNodeExecutor()); + put("return", new ReturnNodeExecutor()); + put("save", new SaveNodeExecutor()); + put("set", new SetNodeExecutor()); + put("switch", new SwitchNodeExecutor()); + put("update", new UpdateNodeExecutor()); + put("while", new WhileNodeExecutor()); + + } + }; + + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + DataBroker dataBroker = mock(DataBroker.class); + NotificationPublishService notifyService = mock(NotificationPublishService.class); + RpcProviderRegistry rpcRegistry = mock(RpcProviderRegistry.class); + BindingAwareBroker.RpcRegistration rpcRegistration = (BindingAwareBroker.RpcRegistration) mock(BindingAwareBroker.RpcRegistration.class); + when(rpcRegistry.addRpcImplementation(any(Class.class), any(SLIAPIService.class))).thenReturn(rpcRegistration); + + + // Load svclogic.properties and get a SvcLogicStore + InputStream propStr = TestSliapiProvider.class.getResourceAsStream("/svclogic.properties"); + Properties svcprops = new Properties(); + svcprops.load(propStr); + + SvcLogicStore store = SvcLogicStoreFactory.getSvcLogicStore(svcprops); + + assertNotNull(store); + + // Load the DG for the healthcheck api + URL testCaseUrl = TestSliapiProvider.class.getClassLoader().getResource(HEALTHCHECK_DG); + if (testCaseUrl == null) { + fail("Cannot find "+HEALTHCHECK_DG); + } + SvcLogicParser.load(testCaseUrl.getPath(), store); + SvcLogicParser.activate("sli", "healthcheck", "1.0.0", "sync", store); + + // Create a ServiceLogicService and initialize it + SvcLogicServiceImpl svc = new SvcLogicServiceImpl(new SvcLogicPropertiesProviderImpl()); + for (String nodeType : BUILTIN_NODES.keySet()) { + svc.registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); + } + + // Finally ready to create sliapiProvider + provider = new sliapiProvider(dataBroker, notifyService, rpcRegistry, svc); + provider.setDataBroker(dataBroker); + provider.setNotificationService(notifyService); + provider.setRpcRegistry(rpcRegistry); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + provider.close(); + } + + /** + * Test method for {@link org.onap.ccsdk.sli.core.sliapi.sliapiProvider#executeGraph(org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput)}. + */ + @Test + public void testExecuteGraph() { + ExecuteGraphInputBuilder inputBuilder = new ExecuteGraphInputBuilder(); + + inputBuilder.setMode(ExecuteGraphInput.Mode.Sync); + inputBuilder.setModuleName("sli"); + inputBuilder.setRpcName("healthcheck"); + List pList = new LinkedList<>(); + SliParameterBuilder pBuilder = new SliParameterBuilder(); + pBuilder.setParameterName("int-parameter"); + pBuilder.setIntValue(1); + pList.add(pBuilder.build()); + inputBuilder.setSliParameter(pList); + + + + + provider.executeGraph(inputBuilder.build()); + } + + /** + * Test method for {@link org.onap.ccsdk.sli.core.sliapi.sliapiProvider#healthcheck()}. + */ + @Test + public void testHealthcheck() { + provider.healthcheck(); + } + +} diff --git a/sliapi/provider/src/test/resources/sli_healthcheck.xml b/sliapi/provider/src/test/resources/sli_healthcheck.xml new file mode 100644 index 000000000..d512f546f --- /dev/null +++ b/sliapi/provider/src/test/resources/sli_healthcheck.xml @@ -0,0 +1,27 @@ + + + + + + + + diff --git a/sliapi/provider/src/test/resources/svclogic.properties b/sliapi/provider/src/test/resources/svclogic.properties new file mode 100644 index 000000000..426960f76 --- /dev/null +++ b/sliapi/provider/src/test/resources/svclogic.properties @@ -0,0 +1,27 @@ +### +# ============LICENSE_START======================================================= +# ONAP : CCSDK +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +org.onap.ccsdk.sli.dbtype = jdbc +org.onap.ccsdk.sli.jdbc.url=jdbc:derby:memory:sdnctl;create=true +org.onap.ccsdk.sli.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver +org.onap.ccsdk.sli.jdbc.database = sdnctl +org.onap.ccsdk.sli.jdbc.user = test +org.onap.ccsdk.sli.jdbc.password = test -- cgit 1.2.3-korg From 972b25417e2851486940ca93d73763026eaa13b6 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Tue, 8 May 2018 11:27:50 -0400 Subject: Provide support for properties encryption Changes made: * Implemented code to decrypt password field in property file Change-Id: I97e5f93fd1f8383c1e2a1e6170489dc1db9d6337 Issue-ID: CCSDK-182 Signed-off-by: Rich Tabedzki --- dblib/provider/pom.xml | 5 ++ .../sli/core/dblib/DBLIBResourceProvider.java | 56 ++++++++++++++++++++++ .../onap/ccsdk/sli/core/dblib/EncShellCommand.java | 48 +++++++++++++++++++ .../org/opendaylight/blueprint/dblib-blueprint.xml | 6 +++ 4 files changed, 115 insertions(+) mode change 100644 => 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/DBLIBResourceProvider.java create mode 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index 3eaefd067..9bf898f51 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -82,5 +82,10 @@ mockito-core test + + org.apache.karaf.shell + org.apache.karaf.shell.console + 3.0.8 + 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 old mode 100644 new mode 100755 index ddfb73316..6d36d6389 --- 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 @@ -23,6 +23,7 @@ package org.onap.ccsdk.sli.core.dblib; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.lang.reflect.Method; import java.util.Optional; import java.util.Properties; import java.util.Vector; @@ -32,6 +33,9 @@ import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,6 +49,12 @@ import org.slf4j.LoggerFactory; *
  • A directory identified by the JRE argument dblib.properties
  • *
  • A dblib.properties file located in the karaf root directory
  • * + * + * Encryption Support + *
      + *
    1. Uses ecryption provided by AAAEncryptionService
    2. + *
    3. AAA Configuration file is aaa-cert-config.xml
    4. + *
    */ public class DBLIBResourceProvider { @@ -55,6 +65,8 @@ public class DBLIBResourceProvider { */ private static final String DBLIB_PROP_FILE_NAME = "dblib.properties"; + private static final String DBLIB_PROPERTY_NAME = "org.onap.ccsdk.sli.jdbc.password"; + /** * A prioritized list of strategies for resolving dblib properties files. */ @@ -87,6 +99,20 @@ public class DBLIBResourceProvider { try(FileInputStream fileInputStream = new FileInputStream(propertiesFile)) { properties = new Properties(); properties.load(fileInputStream); + + if(properties.containsKey(DBLIB_PROPERTY_NAME)) { + String sensitive = properties.getProperty(DBLIB_PROPERTY_NAME); + if(sensitive != null && sensitive.startsWith("ENC:")) { + try { + sensitive = sensitive.substring(4); + String postsense = decrypt(sensitive); + properties.setProperty(DBLIB_PROPERTY_NAME, postsense); + } catch(Exception exc) { + LOG.error("Failed to translate property", exc); + } + } + } + } catch (final IOException e) { LOG.error("Failed to load properties for file: {}", propertiesFile.toString(), new DblibConfigurationException("Failed to load properties for file: " @@ -95,6 +121,36 @@ public class DBLIBResourceProvider { } } + /** + * + * @param value + * @return decrypted string if successful or the original value if unsuccessful + */ + private String decrypt(String value) { + try { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + + ServiceReference sref = bctx.getServiceReference("org.opendaylight.aaa.encrypt.AAAEncryptionService"); + if(sref == null) { + LOG.warn("Could not acquire service reference for 'org.opendaylight.aaa.encrypt.AAAEncryptionService'"); + return value; + } + Object encrSvc = bctx.getService(sref); + if(encrSvc == null) { + LOG.warn("Could not access service for 'org.opendaylight.aaa.encrypt.AAAEncryptionService'"); + return value; + } + + Method gs2Method = encrSvc.getClass().getMethod("decrypt", new Class[] { "".getClass() }); + Object unmasked = gs2Method.invoke(encrSvc, new Object[] { value }); + return unmasked.toString(); + + } catch (Exception exc) { + LOG.error("Failure", exc); + return value; + } + } + /** * Extract db config properties. * diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java new file mode 100755 index 000000000..eaa5700c9 --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java @@ -0,0 +1,48 @@ +package org.onap.ccsdk.sli.core.dblib; + +import java.lang.reflect.Method; + +/** + * https://karaf.apache.org/manual/latest-2.x/developers-guide/extending-console.html + * https://github.com/apache/karaf/tree/master/shell/console/src/main/java/org/apache/felix/gogo/commands + */ +import org.apache.karaf.shell.commands.Argument; +import org.apache.karaf.shell.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Command(scope = "dblib", name = "encode", description="Says hello") +public class EncShellCommand extends OsgiCommandSupport { + private static Logger LOGGER = LoggerFactory.getLogger(EncShellCommand.class); + + @Argument(index = 0, name = "arg", description = "The command argument", required = true, multiValued = false) + String arg = null; + + @Override + protected Object doExecute() throws Exception { + System.out.println(String.format("Original value: %s", arg)); + System.out.println(String.format("Encrypted value: %s", encrypt(arg))); + return null; + } + + private String encrypt(String value) { + try { + BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); + + ServiceReference sref = bctx.getServiceReference("org.opendaylight.aaa.encrypt.AAAEncryptionService"); + Object encrSvc = bctx.getService(sref); + + Method gs2Method = encrSvc.getClass().getMethod("encrypt", new Class[] { "".getClass() }); + Object unmasked = gs2Method.invoke(encrSvc, new Object[] { value }); + return String.format("ENC:%s", unmasked.toString()); + + } catch (Exception exc) { + LOGGER.error("Failure", exc); + return value; + } + } +} \ No newline at end of file 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 index f1d5166db..d9bb99c07 100755 --- a/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml +++ b/dblib/provider/src/main/resources/org/opendaylight/blueprint/dblib-blueprint.xml @@ -15,4 +15,10 @@ + + + + + + \ No newline at end of file -- cgit 1.2.3-korg From 47099b56dcecba622e574b37c0167a061d6f667b Mon Sep 17 00:00:00 2001 From: Parshad Patel Date: Tue, 24 Jul 2018 19:15:27 +0900 Subject: Fix sonar issues Fix sonar issues in ccsdk/sli/core Issue-ID: CCSDK-332 Change-Id: I2aee69cf410d8f9cb63f3a22aeb793a99e27d2c7 Signed-off-by: Parshad Patel --- .../java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java | 7 ++----- .../ccsdk/sli/core/filters/RequestResponseLoggingFilter.java | 2 +- .../onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java | 2 +- .../onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java | 2 +- .../org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java | 12 +++++++----- 5 files changed, 12 insertions(+), 13 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 97380f58d..f3ecfa279 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -214,10 +214,8 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito throws SQLException { long time = System.currentTimeMillis(); - CachedRowSet data; - - try (PreparedStatement ps = conn.prepareStatement(statement)) { - data = RowSetProvider.newFactory().createCachedRowSet(); + try (PreparedStatement ps = conn.prepareStatement(statement); + CachedRowSet data = RowSetProvider.newFactory().createCachedRowSet()) { if (arguments != null) { prepareStatementForExecuteUpdate(arguments, ps); } @@ -227,7 +225,6 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito LOGGER.debug("SQL SUCCESS. rows returned: {}, time(ms): {}", data.size(), (System.currentTimeMillis() - time)); } - ps.close(); } catch (SQLException exc) { handleSqlExceptionForExecuteStatement(conn, statement, arguments, exc, time); } finally { diff --git a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java index ffe6d71d6..f5510b9ab 100644 --- a/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java +++ b/filters/provider/src/main/java/org/onap/ccsdk/sli/core/filters/RequestResponseLoggingFilter.java @@ -166,7 +166,7 @@ public class RequestResponseLoggingFilter implements Filter { bais = new ByteArrayInputStream(buffer); bsis = new BufferedServletInputStream(bais); } catch (Exception ex) { - ex.printStackTrace(); + log.error("Exception in getInputStream",ex); } return bsis; diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java index c229cf59f..d275e9703 100644 --- a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicExpressionFactory.java @@ -93,7 +93,7 @@ public class SvcLogicExpressionFactory { try { SvcLogicExpressionFactory.parse(sbuff.toString()); } catch (IOException e) { - e.printStackTrace(); + LOG.error("Exception in SvcLogicExpressionFactory.parse",e); } } } diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java index 6c6b4ca27..a73fadcfc 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/ForNodeExecutor.java @@ -101,7 +101,7 @@ public class ForNodeExecutor extends SvcLogicNodeExecutor { } } } catch (BreakNodeException br) { - LOG.debug("ForNodeExecutor caught break"); + LOG.error("ForNodeExecutor caught break",br); } return (null); } diff --git a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java index e50b99742..f7a229d5d 100644 --- a/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java +++ b/sli/provider/src/main/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelper.java @@ -1117,8 +1117,11 @@ public class MdsalHelper { Class returnClass = m.getReturnType(); String fieldName = toLowerHyphen(m.getName().substring(3)); - fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); - + if(fieldName!=null) { + fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); + }else { + fieldName=""; + } String propName = propNamePfx + "." + fieldName; // Is the return type a yang generated class? @@ -1182,11 +1185,10 @@ public class MdsalHelper { } public static boolean isYangGenerated(Class c) { - if (c == null) { - return (false); - } else { + if (c != null) { return (c.getName().startsWith("org.opendaylight.yang.gen.")); } + return false; } public static boolean isIpPrefix(Class c) { -- cgit 1.2.3-korg From f029e358bf9318ac03ba1be27912f52d296feacd Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Mon, 24 Sep 2018 01:03:37 +0530 Subject: formatted code and added test case to increase code coverage in CachedDataSourceTest Issue-ID: CCSDK-595 Change-Id: I10c2fec758bfb93587b4f5b096828a43a64039b0 Signed-off-by: Sandeep J --- .../ccsdk/sli/core/dblib/CachedDataSourceTest.java | 159 +++++++++++---------- 1 file changed, 81 insertions(+), 78 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java index 6385c1b57..c463f38bb 100644 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java @@ -1,6 +1,9 @@ package org.onap.ccsdk.sli.core.dblib; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; @@ -14,81 +17,81 @@ import org.slf4j.LoggerFactory; public class CachedDataSourceTest { - private static final Properties props = new Properties(); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - props.setProperty("org.onap.ccsdk.sli.dbtype", "jdbc"); - props.setProperty("org.onap.ccsdk.sli.jdbc.hosts", "localhost"); - props.setProperty("org.onap.ccsdk.sli.jdbc.url", "jdbc:mysql://dbhost:3306/test"); - props.setProperty("org.onap.ccsdk.sli.jdbc.driver", "org.mariadb.jdbc.Driver"); - props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); - props.setProperty("org.onap.ccsdk.sli.jdbc.user", "dbuser"); - props.setProperty("org.onap.ccsdk.sli.jdbc.password", "passw0rd"); - props.setProperty("org.onap.ccsdk.sli.jdbc.connection.name", "testdb01"); - props.setProperty("org.onap.ccsdk.sli.jdbc.connection.timeout", "50"); - props.setProperty("org.onap.ccsdk.sli.jdbc.request.timeout", "100"); - props.setProperty("org.onap.ccsdk.sli.jdbc.limit.init", "10"); - props.setProperty("org.onap.ccsdk.sli.jdbc.limit.min", "10"); - props.setProperty("org.onap.ccsdk.sli.jdbc.limit.max", "20"); - props.setProperty("org.onap.dblib.connection.recovery", "false"); - } - - @Test - public void testCachedDataSource() { - BaseDBConfiguration config = new JDBCConfiguration(props); - CachedDataSource ds = new JdbcDBCachedDataSource(config); - assertNotNull(ds); - } - - @Test - public void testConfigure() { - BaseDBConfiguration config = new JDBCConfiguration(props); - - CachedDataSource ds = new JdbcDBCachedDataSource(config); - assertNotNull(ds.configure(config)); - } - - @Test - public void testSetInitialDelay() { - BaseDBConfiguration config = new JDBCConfiguration(props); - CachedDataSource ds = new JdbcDBCachedDataSource(config); - ds.setInitialDelay(1000L); - assertTrue(ds.getInitialDelay() == 1000L); - } - - @Test - public void testSetInterval() { - BaseDBConfiguration config = new JDBCConfiguration(props); - CachedDataSource ds = new JdbcDBCachedDataSource(config); - ds.setInterval(1000L); - assertTrue(ds.getInterval() == 1000L); - } - - @Test - public void testSetExpectedCompletionTime() { - BaseDBConfiguration config = new JDBCConfiguration(props); - CachedDataSource ds = new JdbcDBCachedDataSource(config); - ds.setExpectedCompletionTime(100L); - assertTrue(ds.getExpectedCompletionTime() == 100L); - } - - @Test - public void testSetUnprocessedFailoverThreshold() { - BaseDBConfiguration config = new JDBCConfiguration(props); - CachedDataSource ds = new JdbcDBCachedDataSource(config); - ds.setUnprocessedFailoverThreshold(100L); - assertTrue(ds.getUnprocessedFailoverThreshold() == 100L); - } - - @Test - public void testGetParentLogger() { - BaseDBConfiguration config = new JDBCConfiguration(props); - CachedDataSource ds = new JdbcDBCachedDataSource(config); - try { - assertNull(ds.getParentLogger()); - } catch (SQLFeatureNotSupportedException e) { - LoggerFactory.getLogger(CachedDataSourceTest.class).warn("Test Failure", e); - } - } + private static final Properties props = new Properties(); + private static BaseDBConfiguration config; + private static CachedDataSource ds; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + props.setProperty("org.onap.ccsdk.sli.dbtype", "jdbc"); + props.setProperty("org.onap.ccsdk.sli.jdbc.hosts", "localhost"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", "jdbc:mysql://dbhost:3306/test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.driver", "org.mariadb.jdbc.Driver"); + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.user", "dbuser"); + props.setProperty("org.onap.ccsdk.sli.jdbc.password", "passw0rd"); + props.setProperty("org.onap.ccsdk.sli.jdbc.connection.name", "testdb01"); + props.setProperty("org.onap.ccsdk.sli.jdbc.connection.timeout", "50"); + props.setProperty("org.onap.ccsdk.sli.jdbc.request.timeout", "100"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.init", "10"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.min", "10"); + props.setProperty("org.onap.ccsdk.sli.jdbc.limit.max", "20"); + props.setProperty("org.onap.dblib.connection.recovery", "false"); + + config = new JDBCConfiguration(props); + ds = new JdbcDBCachedDataSource(config); + } + + @Test + public void testCachedDataSource() { + assertNotNull(ds); + } + + @Test + public void testConfigure() { + + assertNotNull(ds.configure(config)); + } + + @Test + public void testSetInitialDelay() { + ds.setInitialDelay(1000L); + assertTrue(ds.getInitialDelay() == 1000L); + } + + @Test + public void testSetInterval() { + ds.setInterval(1000L); + assertTrue(ds.getInterval() == 1000L); + } + + @Test + public void testSetExpectedCompletionTime() { + ds.setExpectedCompletionTime(100L); + assertTrue(ds.getExpectedCompletionTime() == 100L); + } + + @Test + public void testSetUnprocessedFailoverThreshold() { + ds.setUnprocessedFailoverThreshold(100L); + assertTrue(ds.getUnprocessedFailoverThreshold() == 100L); + } + + @Test + public void testGetParentLogger() { + try { + assertNull(ds.getParentLogger()); + } catch (SQLFeatureNotSupportedException e) { + LoggerFactory.getLogger(CachedDataSourceTest.class).warn("Test Failure", e); + } + } + + @Test + public void testGettersForJdbcDBCachedDataSource() { + + assertEquals("jdbc:mysql://dbhost:3306/test", ((JdbcDBCachedDataSource) ds).getDbUrl()); + assertEquals("dbuser", ((JdbcDBCachedDataSource) ds).getDbUserId()); + assertEquals("passw0rd", ((JdbcDBCachedDataSource) ds).getDbPasswd()); + assertEquals("testdb01", ((JdbcDBCachedDataSource) ds).toString()); + } } \ No newline at end of file -- cgit 1.2.3-korg From cdd9c11b89444735350eed52d412caf3f6d85c16 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Mon, 24 Sep 2018 01:28:16 +0530 Subject: added test cases to TestDBResourceManager to increase code coverage Issue-ID: CCSDK-595 Change-Id: I8def1aa2e4108f48bc549e63e533f8a63e7a0377 Signed-off-by: Sandeep J --- .../sli/core/dblib/TestDBResourceManager.java | 63 +++++++++++++--------- 1 file changed, 39 insertions(+), 24 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java index dca07921b..8d7d34324 100644 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager.java @@ -4,6 +4,7 @@ import static org.junit.Assert.*; import java.io.InputStream; import java.net.URL; +import java.sql.SQLException; import java.util.Properties; import org.junit.Before; @@ -14,42 +15,56 @@ import ch.vorburger.mariadb4j.DBConfigurationBuilder; public class TestDBResourceManager { - DbLibService dblibSvc; + DbLibService dblibSvc; + DBResourceManager dbm; - @Before - public void setUp() throws Exception { - URL propUrl = getClass().getResource("/dblib.properties"); + @Before + public void setUp() throws Exception { + URL propUrl = getClass().getResource("/dblib.properties"); - InputStream propStr = getClass().getResourceAsStream("/dblib.properties"); + InputStream propStr = getClass().getResourceAsStream("/dblib.properties"); - Properties props = new Properties(); + Properties props = new Properties(); - props.load(propStr); + props.load(propStr); + // Start MariaDB4j database + DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); + config.setPort(0); // 0 => autom. detect free port + DB db = DB.newEmbeddedDB(config.build()); + db.start(); - // Start MariaDB4j database - DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); - config.setPort(0); // 0 => autom. detect free port - DB db = DB.newEmbeddedDB(config.build()); - db.start(); + // Override jdbc URL and database name + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + dblibSvc = new DBResourceManager(props); + dbm = new DBResourceManager(props); + dblibSvc.writeData("CREATE TABLE DBLIB_TEST (name varchar(20));", null, null); + dblibSvc.getData("SELECT * FROM DBLIB_TEST", null, null); - // Override jdbc URL and database name - props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); - props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + } + @Test + public void testForceRecovery() { + dbm.testForceRecovery(); + } - dblibSvc = new DBResourceManager(props); + @Test + public void testGetConnection() throws SQLException { + assertNotNull(dbm.getConnection()); + assertNotNull(dbm.getConnection("testUser", "testPaswd")); + } - dblibSvc.writeData("CREATE TABLE DBLIB_TEST (name varchar(20));", null, null); - dblibSvc.getData("SELECT * FROM DBLIB_TEST", null, null); + @Test + public void testCleanup() { + dbm.cleanUp(); - } + } - @Test - public void test() { - - - } + @Test + public void testGetLogWriter() throws SQLException { + assertNull(dbm.getLogWriter()); + } } -- cgit 1.2.3-korg From 2f5bc084af648187c9fcffb8ff6472f8755c034d Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Tue, 2 Oct 2018 01:10:21 +0530 Subject: added test cases to CachedDataSource to increase code coverage Issue-ID: CCSDK-595 Change-Id: I7d5a5ed59538e7d6e1a7d00dfba690eedc7c2e22 Signed-off-by: Sandeep J --- .../ccsdk/sli/core/dblib/CachedDataSourceTest.java | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java index c463f38bb..45268107e 100644 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceTest.java @@ -1,10 +1,12 @@ package org.onap.ccsdk.sli.core.dblib; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; @@ -94,4 +96,26 @@ public class CachedDataSourceTest { assertEquals("passw0rd", ((JdbcDBCachedDataSource) ds).getDbPasswd()); assertEquals("testdb01", ((JdbcDBCachedDataSource) ds).toString()); } + + @Test + public void testIsInitialised() { + assertTrue(ds.isInitialized()); + } + + @Test + public void testIsWrapperFor() throws SQLException { + assertFalse(ds.isWrapperFor(CachedDataSource.class)); + } + + @Test + public void testGetSetNextErrorReportTime() throws SQLException { + ds.setNextErrorReportTime(1L); + assertEquals(1L, ds.getNextErrorReportTime()); + } + + @Test + public void testGetSetGlobalHostName() throws SQLException { + ds.setGlobalHostName("hostName"); + assertEquals("hostName", ds.getGlobalHostName()); + } } \ No newline at end of file -- cgit 1.2.3-korg From 959f2e22cf3f794e040dde4d687712cfefd3b00a Mon Sep 17 00:00:00 2001 From: ezhil Date: Fri, 30 Nov 2018 17:02:27 +0530 Subject: Fixed Sonar issue in BaseDBConfiguration.java Logged exception in Logger Issue-ID: CCSDK-774 Change-Id: I28d10215daafd9f0dcaf7e0d765afbe72c184053 Signed-off-by: ezhil --- .../onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java index a8bc58b8b..5f0209b67 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java @@ -3,6 +3,7 @@ * onap * ================================================================================ * Copyright (C) 2016 - 2017 ONAP + * Modifications Copyright (C) 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +22,14 @@ package org.onap.ccsdk.sli.core.dblib.config; import java.util.Properties; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Base class responsible for parsing business logic for database configuration from given Properties. */ public abstract class BaseDBConfiguration { + private Logger logger = LoggerFactory.getLogger(BaseDBConfiguration.class); /** * Property key within a properties configuration File for db type */ @@ -45,7 +48,7 @@ public abstract class BaseDBConfiguration { /** * Property key with a properties configuration File for jdbc driver */ - public static final String DRIVER_NAME = "org.onap.ccsdk.sli.jdbc.driver"; + public static final String DRIVER_NAME = "org.onap.ccsdk.sli.jdbc.driver"; /** * Property key with a properties configuration File for db database connection name @@ -131,6 +134,7 @@ public abstract class BaseDBConfiguration { String value = properties.getProperty(CONNECTION_TIMEOUT, DEFAULT_REJECT_CHANGE_VALUE); return Integer.parseInt(value); } catch (Exception exc) { + logger.error("Exception",exc); return Integer.parseInt(DEFAULT_REJECT_CHANGE_VALUE); } } @@ -146,6 +150,7 @@ public abstract class BaseDBConfiguration { String value = properties.getProperty(REQUEST_TIMEOUT, DEFAULT_REJECT_CHANGE_VALUE); return Integer.parseInt(value); } catch (Exception exc) { + logger.error("Exception",exc); return Integer.parseInt(DEFAULT_REJECT_CHANGE_VALUE); } } -- cgit 1.2.3-korg From c09ec873586ca6870dd2764d64a04482197e9759 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Wed, 5 Dec 2018 16:16:59 +0530 Subject: fixed sonar issues in CachedDataSourceFactory removed unnecessary cast to object Issue-ID: CCSDK-525 Change-Id: Iccd4430cdbbadfabbdc21820c1f0f962b7635444 Signed-off-by: Sandeep J --- .../java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java index 296fe70f1..15aa7a1d0 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSourceFactory.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2016 - 2017 ONAP * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ * 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 @@ -38,7 +40,7 @@ public class CachedDataSourceFactory { if(config instanceof JDBCConfiguration) return JdbcDBCachedDataSource.createInstance(config); - return (CachedDataSource)null; + return null; } } -- cgit 1.2.3-korg From 291194ce7f32d15bc37b10fe926ac07189c9c7d4 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Wed, 5 Dec 2018 16:29:35 +0530 Subject: fixed sonar issues in DBResourceManager.java fixed sonar issue Issue-ID: CCSDK-525 Change-Id: I29b85aa6066c6a940818443602e3e0e02fad59ab Signed-off-by: Sandeep J --- .../java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'dblib/provider/src') 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 9acae340b..047fa297e 100755 --- 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 @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2016 - 2017 ONAP * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ * 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 @@ -68,7 +70,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb transient protected long retryInterval = 10000L; transient boolean recoveryMode = true; - SortedSet dsQueue = new ConcurrentSkipListSet(new DataSourceComparator()); + SortedSet dsQueue = new ConcurrentSkipListSet<>(new DataSourceComparator()); protected final Set broken = Collections.synchronizedSet(new HashSet()); protected final Object monitor = new Object(); protected final Properties configProps; @@ -80,6 +82,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb protected final long monitoringInitialDelay; protected final long expectedCompletionTime; protected final long unprocessedFailoverThreshold; + private static final String LOGGER_ALARM_MSG="Generated alarm: DBResourceManager.getData - No active DB connection pools are available."; public DBResourceManager(final DBLIBResourceProvider configuration) { this(configuration.getProperties()); @@ -393,7 +396,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb // test if there are any connection pools available if(this.dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + LOGGER.error(LOGGER_ALARM_MSG); throw new DBLibException("No active DB connection pools are available in RequestDataWithRecovery call."); } @@ -457,7 +460,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb private CachedRowSet requestDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { if(dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + LOGGER.error(LOGGER_ALARM_MSG); throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); } CachedDataSource active = this.dsQueue.first(); @@ -533,7 +536,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb private boolean writeDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { if(dsQueue.isEmpty()){ - LOGGER.error("Generated alarm: DBResourceManager.getData - No active DB connection pools are available."); + LOGGER.error(LOGGER_ALARM_MSG); throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); } -- cgit 1.2.3-korg From e232a5607bb89cad0a52524e430b44633c64e270 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Wed, 5 Dec 2018 16:34:19 +0530 Subject: fixed sonar issues in DbConfigPool.java fixed sonar issue Issue-ID: CCSDK-525 Change-Id: Ibf082dc71b49b8d657dfbb79ac0ef396eb3f4aa8 Signed-off-by: Sandeep J --- .../main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java index 21fdab245..fb94ea0e7 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2016 - 2017 ONAP * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ * 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 @@ -30,7 +32,7 @@ public class DbConfigPool { private final String type; - private ArrayList configurations = new ArrayList(); + private ArrayList configurations = new ArrayList<>(); public DbConfigPool(Properties properties) { LOGGER.debug("Initializing DbConfigType"); @@ -38,7 +40,6 @@ public class DbConfigPool { } public int getTimeout() { - // TODO Auto-generated method stub return 0; } -- cgit 1.2.3-korg From 53e0e685052653bda628dfb316642be35d316c61 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Wed, 5 Dec 2018 16:37:42 +0530 Subject: fixed sonar issue in DBConfigFactory fixed sonar issue Issue-ID: CCSDK-525 Change-Id: I64adc9bc11c7e4fcac2c1caec614745ebe6887be Signed-off-by: Sandeep J --- .../java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java index c3503576e..1aa907837 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/factory/DBConfigFactory.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2016 - 2017 ONAP * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ * 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 @@ -44,7 +46,7 @@ public class DBConfigFactory { static DbConfigPool getConfigparams(Properties properties) { DbConfigPool xmlConfig = new DbConfigPool(properties); - ArrayList propertySets = new ArrayList(); + ArrayList propertySets = new ArrayList<>(); if ("JDBC".equalsIgnoreCase(xmlConfig.getType())) { String hosts = properties.getProperty(BaseDBConfiguration.DATABASE_HOSTS); -- cgit 1.2.3-korg From 72504e5853929bd0d649fc3bc42d3e91fc60c079 Mon Sep 17 00:00:00 2001 From: ezhil Date: Wed, 5 Dec 2018 20:33:08 +0530 Subject: Fixed sonar issues in PollingWorker.java Fixed logger issues Issue-ID: CCSDK-791 Change-Id: Ie1759c8778ff896b2cff3e187308e6a10265e966 Signed-off-by: ezhil --- .../ccsdk/sli/core/dblib/pm/PollingWorker.java | 29 ++++++++++++---------- 1 file changed, 16 insertions(+), 13 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java index 4bfa058a8..b44e2f89d 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java @@ -35,7 +35,7 @@ import java.util.concurrent.atomic.AtomicLong; public class PollingWorker implements Runnable { - private Logger LOGGER = LoggerFactory.getLogger(PollingWorker.class); + private Logger logger = LoggerFactory.getLogger(PollingWorker.class); private static PollingWorker self = null; @@ -47,17 +47,6 @@ public class PollingWorker implements Runnable { private static boolean enabled = false; private Timer timer = null; - public static void post(long starttime){ - PollingWorker temp = self; - if(temp != null && enabled) { - temp.register(new TestSample(starttime)); - } - } - - public static void createInistance(Properties props){ - self = new PollingWorker(props); - } - private PollingWorker(Properties ctxprops){ if(ctxprops==null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm") == null){ enabled = false; @@ -89,6 +78,18 @@ public class PollingWorker implements Runnable { timer.schedule(new MyTimerTask(), interval*1000L, interval*1000L); } } + public static void post(long starttime){ + PollingWorker temp = self; + if(temp != null && enabled) { + temp.register(new TestSample(starttime)); + } + } + + public static void createInistance(Properties props){ + self = new PollingWorker(props); + } + + private void register(TestSample object){ try { @@ -113,12 +114,14 @@ public class PollingWorker implements Runnable { consume((TestSample)next); } else { System.out.println(next.getClass().getName()); + logger.error(next.getClass().getName()); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); + } } @@ -146,7 +149,7 @@ public class PollingWorker implements Runnable { } sb.append(tmp2[i].get()).append("\t"); } - LOGGER.info(sb.toString()); + logger.info(sb.toString()); } class MyTimerTask extends TimerTask{ -- cgit 1.2.3-korg From 05102065e87889d6d4a8b8690d9ee6cdd4faf61d Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Thu, 13 Dec 2018 17:31:51 -0500 Subject: fixed sonar issue in JdbcCachedDataSource Changes made: * fixed sonar issue Change-Id: I2112b202f8b7eb628fc21c3a972e35704dc827f9 Issue-ID: CCSDK-525 Signed-off-by: Rich Tabedzki --- .../sli/core/dblib/config/BaseDBConfiguration.java | 6 ++-- .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 39 ++++++++++++---------- 2 files changed, 24 insertions(+), 21 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java index 5f0209b67..967059a31 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java @@ -209,7 +209,7 @@ public abstract class BaseDBConfiguration { * Integer. */ public int getDbMinLimit() throws NumberFormatException { - String value = properties.getProperty(MIN_LIMIT); + String value = properties.getProperty(MIN_LIMIT, "-1"); return Integer.parseInt(value); } @@ -222,7 +222,7 @@ public abstract class BaseDBConfiguration { * Integer. */ public int getDbMaxLimit() throws NumberFormatException { - String value = properties.getProperty(MAX_LIMIT); + String value = properties.getProperty(MAX_LIMIT, "-1"); return Integer.parseInt(value); } @@ -235,7 +235,7 @@ public abstract class BaseDBConfiguration { * Integer. */ public int getDbInitialLimit() throws NumberFormatException { - String value = properties.getProperty(INIT_LIMIT); + String value = properties.getProperty(INIT_LIMIT, "-1"); return Integer.parseInt(value); } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java index 80ca577cf..09c1c202b 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -42,6 +42,9 @@ public class JdbcDBCachedDataSource extends CachedDataSource { private int initialLimit; private static final String AS_CONF_ERROR = "AS_CONF_ERROR: "; + private static final int MIN_LIMIT = 5; + private static final int MAX_LIMIT = 10; + private static final int INITIAL_LIMIT = 10; private static final Logger LOGGER = LoggerFactory.getLogger(JdbcDBCachedDataSource.class); @@ -88,26 +91,26 @@ public class JdbcDBCachedDataSource extends CachedDataSource { } minLimit = jdbcConfig.getDbMinLimit(); -// if (minLimit == null) -// { -// String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); -// } + if (minLimit == -1) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing minLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + minLimit = MIN_LIMIT; + } maxLimit = jdbcConfig.getDbMaxLimit(); -// if (maxLimit == null) -// { -// String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); -// } + if (maxLimit == -1) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing maxLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + maxLimit = MAX_LIMIT; + } initialLimit = jdbcConfig.getDbInitialLimit(); -// if (initialLimit == null) -// { -// String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; -// LOGGER.error(AS_CONF_ERROR + errorMsg); -// throw new DBConfigException(errorMsg); -// } + if (initialLimit == -1) + { + String errorMsg = "Invalid XML contents: JDBC Connection missing initialLimit attribute"; + LOGGER.error(AS_CONF_ERROR + errorMsg); + initialLimit = INITIAL_LIMIT; + } dbUrl = jdbcConfig.getDbUrl(); if (dbUrl == null) { -- cgit 1.2.3-korg From c157d989c9e8634ad7d2d4456a235fa8ce34da81 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Tue, 18 Dec 2018 14:56:29 +0530 Subject: fixed sonar issues and formatted code formatted code and added equals and hashcode method as per sonar standards Issue-ID: CCSDK-525 Change-Id: Idaa0a6a0a82315189a9365064d4f196e4689ee57 Signed-off-by: Sandeep J --- .../ccsdk/sli/core/dblib/pm/PollingWorker.java | 127 +++++++++++++-------- 1 file changed, 78 insertions(+), 49 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java index b44e2f89d..905944b1c 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2016 - 2017 ONAP * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ * 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 @@ -26,13 +28,12 @@ import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicLong; - public class PollingWorker implements Runnable { private Logger logger = LoggerFactory.getLogger(PollingWorker.class); @@ -47,71 +48,72 @@ public class PollingWorker implements Runnable { private static boolean enabled = false; private Timer timer = null; - private PollingWorker(Properties ctxprops){ - if(ctxprops==null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm") == null){ + private PollingWorker(Properties ctxprops) { + if (ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm") == null) { enabled = false; } else { - if("true".equalsIgnoreCase((String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm"))){ + if ("true".equalsIgnoreCase((String) ctxprops.getProperty("org.onap.ccsdk.dblib.pm"))) { enabled = true; } else { enabled = false; } } - interval = Long.parseLong(( ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval") == null) ? "60" : (String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval")); + interval = Long.parseLong((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval") == null) + ? "60" : (String) ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval")); // '0' bucket is to count exceptions - String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")==null) ? "0,2,5,10,20,50,100" : (String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")).split(","); + String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling") == null) + ? "0,2,5,10,20,50,100" : (String) ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")).split(","); - if(enabled){ + if (enabled) { bucketUnit = new int[sampling.length]; - for(int i=0, max = bucketUnit.length; i arguments, String preferredDS) throws SQLException { if(dsQueue.isEmpty()){ LOGGER.error(LOGGER_ALARM_MSG); - throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + throw new DBLibException(EXCEPTION_MSG); } CachedDataSource active = this.dsQueue.first(); long time = System.currentTimeMillis(); @@ -475,8 +476,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } return active.getData(statement, arguments); -// } catch(SQLDataException exc){ -// throw exc; + } catch(Throwable exc){ String message = exc.getMessage(); if(message == null) @@ -537,7 +537,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb private boolean writeDataNoRecovery(String statement, ArrayList arguments, String preferredDS) throws SQLException { if(dsQueue.isEmpty()){ LOGGER.error(LOGGER_ALARM_MSG); - throw new DBLibException("No active DB connection pools are available in RequestDataNoRecovery call."); + throw new DBLibException(EXCEPTION_MSG); } boolean initialRequest = true; @@ -665,7 +665,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb SQLException exception = new DBLibException(lastException.getMessage()); exception.setStackTrace(lastException.getStackTrace()); if(lastException.getCause() instanceof SQLException) { -// exception.setNextException((SQLException)lastException.getCause()); + throw (SQLException)lastException.getCause(); } throw exception; -- cgit 1.2.3-korg From 93a61abf96ac8f4432a19f99ca5ab7a92e22d368 Mon Sep 17 00:00:00 2001 From: Sandeep J Date: Thu, 20 Dec 2018 12:59:36 +0530 Subject: fixed sonar issue in PollingWorker.java fixed sonar issue Issue-ID: CCSDK-525 Change-Id: If242b9995469c0b0a25b1285db1536ff52adce2c Signed-off-by: Sandeep J --- .../src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java index 905944b1c..454af02bb 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java @@ -62,7 +62,7 @@ public class PollingWorker implements Runnable { interval = Long.parseLong((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval") == null) ? "60" : (String) ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval")); // '0' bucket is to count exceptions - String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling") == null) + String[] sampling = ((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling") == null) ? "0,2,5,10,20,50,100" : (String) ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")).split(","); if (enabled) { -- cgit 1.2.3-korg From b264dee1ac60671ce6174bdd6d4e067219dc48b3 Mon Sep 17 00:00:00 2001 From: ezhil Date: Wed, 26 Dec 2018 16:49:07 +0530 Subject: Fixed sonar fix in DbConfigPool.java Fixed major sonar issue Issue-ID: CCSDK-796 Change-Id: Id8a655875c972bb3df1f12f211b6a0068922b21d Signed-off-by: ezhil --- .../java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java index fb94ea0e7..6cb1d9c33 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java @@ -28,19 +28,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DbConfigPool { - private static Logger LOGGER = LoggerFactory.getLogger(DbConfigPool.class); - + private static Logger log = LoggerFactory.getLogger(DbConfigPool.class); private final String type; - + private static final int timeOut=0; private ArrayList configurations = new ArrayList<>(); public DbConfigPool(Properties properties) { - LOGGER.debug("Initializing DbConfigType"); + log.debug("Initializing DbConfigType"); type = properties.getProperty(BaseDBConfiguration.DATABASE_TYPE, "JDBC").toUpperCase(); } public int getTimeout() { - return 0; + return timeOut; } public String getType() { -- cgit 1.2.3-korg From c62fdd3be263bdb4543aba980780df642af67313 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Mon, 7 Jan 2019 15:10:11 -0500 Subject: fixed sonar issue in JdbcCachedDataSource Changes made: * updated cleanup code * added TerminatingConfiguration class Change-Id: Iee16116a5fc419065915b9f84488874dd192af7c Issue-ID: CCSDK-913 Signed-off-by: Rich Tabedzki --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 5 ++-- .../core/dblib/TerminatingCachedDataSource.java | 10 +++++-- .../sli/core/dblib/config/BaseDBConfiguration.java | 14 +++++++-- .../dblib/config/TerminatingConfiguration.java | 33 ++++++++++++++++++++++ .../core/dblib/jdbc/JdbcDBCachedDataSource.java | 5 ++++ 5 files changed, 60 insertions(+), 7 deletions(-) create mode 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/TerminatingConfiguration.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index f3ecfa279..0f1674f90 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -94,6 +94,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito } protected abstract DataSource configure(BaseDBConfiguration jdbcElem) throws DBConfigException; + protected abstract int getAvailableConnections(); /* * (non-Javadoc) @@ -488,9 +489,9 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito isSlave = true; } if (isSlave) { - LOGGER.debug("SQL SLAVE : {} on server {}", connectionName, hostname); + LOGGER.debug("SQL SLAVE : {} on server {}, pool {}", connectionName, getDbConnectionName(), getAvailableConnections()); } else { - LOGGER.debug("SQL MASTER : {} on server {}", connectionName, hostname); + LOGGER.debug("SQL MASTER : {} on server {}, pool {}", connectionName, getDbConnectionName(), getAvailableConnections()); } return isSlave; } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java index e1afcc22e..884f88825 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java @@ -7,9 +7,9 @@ * 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. @@ -29,6 +29,8 @@ import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; public class TerminatingCachedDataSource extends CachedDataSource implements SQLExecutionMonitorObserver { + private static final int DEFAULT_AVAILABLE_CONNECTIONS = 0; + public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { super(jdbcElem); } @@ -43,4 +45,8 @@ public class TerminatingCachedDataSource extends CachedDataSource implements SQL return null; } + @Override + protected int getAvailableConnections() { + return DEFAULT_AVAILABLE_CONNECTIONS; + } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java index 967059a31..ea6bc450d 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/BaseDBConfiguration.java @@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory; */ public abstract class BaseDBConfiguration { - private Logger logger = LoggerFactory.getLogger(BaseDBConfiguration.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BaseDBConfiguration.class); /** * Property key within a properties configuration File for db type */ @@ -134,7 +134,7 @@ public abstract class BaseDBConfiguration { String value = properties.getProperty(CONNECTION_TIMEOUT, DEFAULT_REJECT_CHANGE_VALUE); return Integer.parseInt(value); } catch (Exception exc) { - logger.error("Exception",exc); + LOGGER.error("Exception",exc); return Integer.parseInt(DEFAULT_REJECT_CHANGE_VALUE); } } @@ -150,7 +150,7 @@ public abstract class BaseDBConfiguration { String value = properties.getProperty(REQUEST_TIMEOUT, DEFAULT_REJECT_CHANGE_VALUE); return Integer.parseInt(value); } catch (Exception exc) { - logger.error("Exception",exc); + LOGGER.error("Exception",exc); return Integer.parseInt(DEFAULT_REJECT_CHANGE_VALUE); } } @@ -247,4 +247,12 @@ public abstract class BaseDBConfiguration { public String getDbUrl() { return properties.getProperty(DATABASE_URL); } + + public boolean containsKey(String propertyname) { + return properties.containsKey(propertyname); + } + + public String getProperty(String propertyname) { + return properties.getProperty(propertyname); + } } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/TerminatingConfiguration.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/TerminatingConfiguration.java new file mode 100755 index 000000000..1ebd1441f --- /dev/null +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/TerminatingConfiguration.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ + * 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.config; + +import java.util.Properties; + +public class TerminatingConfiguration extends BaseDBConfiguration { + + public TerminatingConfiguration() { + super(new Properties()); + } + +} diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java index 09c1c202b..a53d18639 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/jdbc/JdbcDBCachedDataSource.java @@ -193,4 +193,9 @@ public class JdbcDBCachedDataSource extends CachedDataSource { dataSource.close(true); super.cleanUp(); } + + @Override + protected int getAvailableConnections() { + return org.apache.tomcat.jdbc.pool.DataSource.class.cast(ds).getSize(); + } } -- cgit 1.2.3-korg From 742aa5d00edbb6bee2ed6c2e710a1f5203305354 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Tue, 8 Jan 2019 12:21:23 -0500 Subject: Fix sonar issues in ccsdk-sli-core Changes made: * Updated message template handling in CachedDataSource Change-Id: I9a082753d80f790b77448a5b3de957b404d737fb Issue-ID: CCSDK-647 Signed-off-by: Rich Tabedzki --- .../onap/ccsdk/sli/core/dblib/CachedDataSource.java | 18 ++++++++---------- .../onap/ccsdk/sli/core/dblib/DBResourceManager.java | 3 ++- 2 files changed, 10 insertions(+), 11 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index 0f1674f90..bc466d931 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -59,10 +59,11 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; - private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; + private static final String FAILED_TO_EXECUTE = "> failed to execute: "; private static final String WITH_ARGUMENTS = " with arguments: "; private static final String WITH_NO_ARGUMENTS = " with no arguments. "; - private static final String SQL_DATA_SOURCE = "SQL DataSource <"; + private static final String DATA_SOURCE_CONNECT_SUCCESS = "SQL DataSource < {} > connected to {}, read-only is {}, tested successfully"; + private static final String DATA_SOURCE_CONNECT_FAILURE = "SQL DataSource < {} > test failed. Cause : {}> test failed. Cause : {}"; protected long connReqTimeout = 30L; protected long dataReqTimeout = 100L; @@ -356,17 +357,14 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito hostname = rs.getString(2); if (LOGGER.isDebugEnabled()) { - LOGGER.debug(SQL_DATA_SOURCE + getDbConnectionName() + "> connected to " + hostname - + ", read-only is " + readOnly + ", tested successfully "); + LOGGER.debug(DATA_SOURCE_CONNECT_SUCCESS,getDbConnectionName(),hostname,readOnly); } } } catch (Exception exc) { if (errorLevel) { - LOGGER.error( - SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + LOGGER.error(DATA_SOURCE_CONNECT_FAILURE, this.getDbConnectionName(),exc.getMessage()); } else { - LOGGER.info( - SQL_DATA_SOURCE + this.getDbConnectionName() + "> test failed. Cause : " + exc.getMessage()); + LOGGER.info(DATA_SOURCE_CONNECT_FAILURE, this.getDbConnectionName(),exc.getMessage()); } return false; } finally { @@ -489,9 +487,9 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito isSlave = true; } if (isSlave) { - LOGGER.debug("SQL SLAVE : {} on server {}, pool {}", connectionName, getDbConnectionName(), getAvailableConnections()); + LOGGER.debug("SQL SLAVE : {} on server {}, pool {}", connectionName, hostname, getAvailableConnections()); } else { - LOGGER.debug("SQL MASTER : {} on server {}, pool {}", connectionName, getDbConnectionName(), getAvailableConnections()); + LOGGER.debug("SQL MASTER : {} on server {}, pool {}", connectionName, hostname, getAvailableConnections()); } return isSlave; } 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 85acd272b..9d797d096 100755 --- 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 @@ -50,6 +50,7 @@ import javax.sql.rowset.CachedRowSet; import org.apache.tomcat.jdbc.pool.PoolExhaustedException; import org.onap.ccsdk.sli.core.dblib.config.DbConfigPool; import org.onap.ccsdk.sli.core.dblib.config.JDBCConfiguration; +import org.onap.ccsdk.sli.core.dblib.config.TerminatingConfiguration; import org.onap.ccsdk.sli.core.dblib.factory.DBConfigFactory; import org.onap.ccsdk.sli.core.dblib.pm.PollingWorker; import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitor; @@ -755,7 +756,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb if(broken != null) { try { - broken.add( new TerminatingCachedDataSource(null)); + broken.add( new TerminatingCachedDataSource(new TerminatingConfiguration())); } catch(Exception exc){ LOGGER.error("Waiting for Worker to stop", exc); } -- cgit 1.2.3-korg From 58982ce3d08ed1510daada7d0ecb0792990248d6 Mon Sep 17 00:00:00 2001 From: Driptaroop Das Date: Fri, 1 Feb 2019 12:42:36 +0530 Subject: Junit for EncShellCommand.java Junit for EncShellCommand.java Issue-ID: CCSDK-1016 Change-Id: I7cbdb49b6e04ce6a69a48f9a507c7db959698140 Signed-off-by: Driptaroop Das --- .../ccsdk/sli/core/dblib/EncShellCommandTest.java | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java new file mode 100644 index 000000000..740e69dba --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java @@ -0,0 +1,41 @@ +package org.onap.ccsdk.sli.core.dblib; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; + +import static org.junit.Assert.*; + +public class EncShellCommandTest { + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + private final PrintStream originalOut = System.out; + private final PrintStream originalErr = System.err; + + @Before + public void setUp() { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + } + + @After + public void tearDown() { + System.setOut(originalOut); + System.setErr(originalErr); + } + + @Test + public void testDoExecute() throws Exception { + String expected = "Original value: test" + System.getProperty("line.separator") + + "Encrypted value: test"; + EncShellCommand encShellCommand = new EncShellCommand(); + encShellCommand.arg = "test"; + encShellCommand.doExecute(); + assertEquals(expected.trim(), outContent.toString().trim()); + } +} \ No newline at end of file -- cgit 1.2.3-korg From 66879d0c4c73b9cd371cdffec3a56f25c340a100 Mon Sep 17 00:00:00 2001 From: "Timoney, Dan (dt5972)" Date: Fri, 1 Feb 2019 15:45:52 -0500 Subject: Hack to force classloader t find mariadb driver Container is not coming up because dblib is getting ClassNotFoundException for mariadb driver, even though it is installed. To correct this temporarily, updated code to explicitly create a driver object. Change-Id: I210d042be2c71a4392781ad26f858c916dbd7364 Issue-ID: CCSDK-489 Signed-off-by: Timoney, Dan (dt5972) --- .../main/java/org/onap/ccsdk/sli/core/dblib/DBResourceManager.java | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'dblib/provider/src') 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 9d797d096..0b8c565f1 100755 --- 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 @@ -24,6 +24,7 @@ package org.onap.ccsdk.sli.core.dblib; import java.io.PrintWriter; import java.sql.Connection; +import java.sql.Driver; import java.sql.SQLDataException; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; @@ -92,6 +93,12 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb public DBResourceManager(final Properties properties) { this.configProps = properties; + + // TODO : hack to force classloader to cache mariadb driver. This shouldnt be necessary, + // but for some reason it is (without this, dblib throws ClassNotFound on mariadb driver + // and fails to load). + Driver dvr = new org.mariadb.jdbc.Driver(); + dvr = null; // get retry interval value retryInterval = getLongFromProperties(properties, "org.onap.dblib.connection.retry", 10000L); -- cgit 1.2.3-korg From 484f1b32f1ef9cfcf74189b701ebb9078ddb0ab8 Mon Sep 17 00:00:00 2001 From: "Timoney, Dan (dt5972)" Date: Tue, 5 Feb 2019 11:17:44 -0500 Subject: Add dummy input Fluorine version of restconf does not handle RPCs with no input correctly. So, need to work around that by defining dummy input for SLI-API vlbcheck and healthcheck APIs Change-Id: I6a78a899937e1bb9bd7674530166a493875ca3bf Issue-ID: CCSDK-1035 Signed-off-by: Timoney, Dan (dt5972) --- .../org/onap/ccsdk/sli/core/dblib/DBResourceManager.java | 1 + sliapi/model/src/main/yang/sliapi.yang | 13 +++++++++++++ 2 files changed, 14 insertions(+) (limited to 'dblib/provider/src') 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 0b8c565f1..236bce6e3 100755 --- 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 @@ -97,6 +97,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb // TODO : hack to force classloader to cache mariadb driver. This shouldnt be necessary, // but for some reason it is (without this, dblib throws ClassNotFound on mariadb driver // and fails to load). + LOGGER.info("Creating dummy instance of org.mariadb.jdbc.Driver"); Driver dvr = new org.mariadb.jdbc.Driver(); dvr = null; diff --git a/sliapi/model/src/main/yang/sliapi.yang b/sliapi/model/src/main/yang/sliapi.yang index 98cbb2aa7..b3272be80 100755 --- a/sliapi/model/src/main/yang/sliapi.yang +++ b/sliapi/model/src/main/yang/sliapi.yang @@ -103,12 +103,25 @@ module SLI-API { } rpc healthcheck { + // OpenDaylight Fluorine version of restconf cannot handle RPCs with no input + input { + leaf dummy { + type string; + } + } output { uses response-fields; } } rpc vlbcheck { + // OpenDaylight Fluorine version of restconf cannot handle RPCs with no input + input { + leaf dummy + { + type string; + } + } output { uses response-fields; } -- cgit 1.2.3-korg From 23ff887d1e61e490b48f735a49c434d50efa1639 Mon Sep 17 00:00:00 2001 From: "Timoney, Dan (dt5972)" Date: Wed, 20 Feb 2019 20:10:35 -0500 Subject: Increase code coverage Added junit test cases, and updated jacoco config in provider/base to include provider tests as well Change-Id: I8f384b3a4dd7362f004eaa959cd0c634edf0ddbe Issue-ID: CCSDK-1096 Signed-off-by: Timoney, Dan (dt5972) --- .../sli/core/dblib/TestDBResourceManager2.java | 95 ++++++++++++++++++++++ .../ccsdk/sli/core/sli/PrintYangToPropTest.java | 59 +++++++++++++- sli/model/src/main/yang/sliapi.yang | 6 ++ sli/provider-base/pom.xml | 7 +- .../sli/core/sli/provider/MdsalHelperTest.java | 15 ++++ 5 files changed, 178 insertions(+), 4 deletions(-) create mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager2.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager2.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager2.java new file mode 100644 index 000000000..a3cb8d914 --- /dev/null +++ b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/TestDBResourceManager2.java @@ -0,0 +1,95 @@ +/*- + 2 * ============LICENSE_START======================================================= + 3 * ONAP CCSDK + 4 * ================================================================================ + 5 * Copyright (C) 2019 AT&T Intellectual Property. All rights + 6 * reserved. + 7 * ================================================================================ + 8 * Licensed under the Apache License, Version 2.0 (the "License"); + 9 * you may not use this file except in compliance with the License. + 10 * You may obtain a copy of the License at + 11 * + 12 * http://www.apache.org/licenses/LICENSE-2.0 + 13 * + 14 * Unless required by applicable law or agreed to in writing, software + 15 * distributed under the License is distributed on an "AS IS" BASIS, + 16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + 17 * See the License for the specific language governing permissions and + 18 * limitations under the License. + 19 * ============LICENSE_END============================================ + 20 * =================================================================== + 21 * + 22 */ +package org.onap.ccsdk.sli.core.dblib; + +import static org.junit.Assert.*; + +import java.io.InputStream; +import java.net.URL; +import java.sql.SQLException; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +import ch.vorburger.mariadb4j.DB; +import ch.vorburger.mariadb4j.DBConfigurationBuilder; + +public class TestDBResourceManager2 { + + DbLibService dblibSvc; + DBResourceManager dbm; + + @Before + public void setUp() throws Exception { + URL propUrl = getClass().getResource("/dblib.properties"); + + InputStream propStr = getClass().getResourceAsStream("/dblib.properties"); + + Properties props = new Properties(); + + props.load(propStr); + + // Start MariaDB4j database + DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); + config.setPort(0); // 0 => autom. detect free port + DB db = DB.newEmbeddedDB(config.build()); + db.start(); + + // Override jdbc URL, database name, and recovery + props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); + props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); + props.setProperty("org.onap.dblib.connection.recovery", "true"); + + + dblibSvc = new DBResourceManager(props); + dbm = new DBResourceManager(props); + dblibSvc.writeData("CREATE TABLE DBLIB_TEST2 (name varchar(20));", null, null); + dblibSvc.getData("SELECT * FROM DBLIB_TEST2", null, null); + + + } + + @Test + public void testForceRecovery() { + dbm.testForceRecovery(); + } + + @Test + public void testGetConnection() throws SQLException { + assertNotNull(dbm.getConnection()); + assertNotNull(dbm.getConnection("testUser", "testPaswd")); + } + + @Test + public void testCleanup() { + dbm.cleanUp(); + + } + + @Test + public void testGetLogWriter() throws SQLException { + assertNull(dbm.getLogWriter()); + } + +} diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java index d639c28dc..14b4dcb76 100644 --- a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/PrintYangToPropTest.java @@ -1,6 +1,25 @@ -/** - * - */ +/*- + 2 * ============LICENSE_START======================================================= + 3 * ONAP CCSDK + 4 * ================================================================================ + 5 * Copyright (C) 2019 AT&T Intellectual Property. All rights + 6 * reserved. + 7 * ================================================================================ + 8 * Licensed under the Apache License, Version 2.0 (the "License"); + 9 * you may not use this file except in compliance with the License. + 10 * You may obtain a copy of the License at + 11 * + 12 * http://www.apache.org/licenses/LICENSE-2.0 + 13 * + 14 * Unless required by applicable law or agreed to in writing, software + 15 * distributed under the License is distributed on an "AS IS" BASIS, + 16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + 17 * See the License for the specific language governing permissions and + 18 * limitations under the License. + 19 * ============LICENSE_END============================================ + 20 * =================================================================== + 21 * + 22 */ package org.onap.ccsdk.sli.core.sli; import java.util.Enumeration; @@ -11,8 +30,11 @@ import java.util.Properties; import org.junit.Test; import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput.Mode; import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.TestResultsBuilder; import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameter; import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameterBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.test.results.TestResult; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.test.results.TestResultBuilder; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefixBuilder; import org.slf4j.Logger; @@ -82,7 +104,38 @@ public class PrintYangToPropTest { // Generate builder from properties just generated PrintYangToProp.toBuilder(props, pBuilder); + } + + @Test + public void testWithList() { + TestResultsBuilder resultsBuilder = new TestResultsBuilder(); + TestResultBuilder resultBuilder = new TestResultBuilder(); + + // Set builder with values + List resultList = new LinkedList<>(); + resultBuilder.setTestIdentifier("test1"); + List results = new LinkedList<>(); + results.add("pass"); + resultBuilder.setResults(results); + resultList.add(resultBuilder.build()); + resultsBuilder.setTestResult(resultList); + + // Generate properties + Properties props = new Properties(); + props = PrintYangToProp.toProperties(props, resultsBuilder); + + Enumeration propNames = props.propertyNames(); + + while (propNames.hasMoreElements()) { + String propName = (String) propNames.nextElement(); + LOG.info("Property {} = {}", propName, props.getProperty(propName)); + } + + // Generate builder from properties just generated + PrintYangToProp.toBuilder(props, resultsBuilder); + + } } diff --git a/sli/model/src/main/yang/sliapi.yang b/sli/model/src/main/yang/sliapi.yang index 19adecca9..a7d52928b 100755 --- a/sli/model/src/main/yang/sliapi.yang +++ b/sli/model/src/main/yang/sliapi.yang @@ -45,6 +45,12 @@ module SLI-API { leaf ipprefix-value { type inet:ip-prefix; } + leaf port-number { + type inet:port-number; + } + leaf dscp { + type inet:dscp; + } } grouping response-fields { diff --git a/sli/provider-base/pom.xml b/sli/provider-base/pom.xml index 0b6dfff44..856ee238a 100644 --- a/sli/provider-base/pom.xml +++ b/sli/provider-base/pom.xml @@ -12,6 +12,11 @@ org.onap.ccsdk.sli.core sli-provider-base 0.4.1-SNAPSHOT + + + + target/code-coverage/jacoco-ut.exec,target/code-coverage/jacoco-it.exec,../provider/target/code-coverage/jacoco-ut.exec,../provider/target/code-coverage/jacoco-it.exec + @@ -30,7 +35,6 @@ ${project.version} compile - org.slf4j slf4j-api @@ -56,4 +60,5 @@ + diff --git a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java index 939777597..56d0369e2 100755 --- a/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java +++ b/sli/provider/src/test/java/org/onap/ccsdk/sli/core/sli/provider/MdsalHelperTest.java @@ -94,6 +94,21 @@ public class MdsalHelperTest extends TestCase { parmBuilder.setParameterName("ipaddress6-parm"); parmBuilder.setIpaddressValue(IpAddressBuilder.getDefaultInstance("ef::1")); params.add(parmBuilder.build()); + + parmBuilder.setParameterName("ipprefix-parm"); + parmBuilder.setIpaddressValue(null); + parmBuilder.setIpprefixValue(IpPrefixBuilder.getDefaultInstance("10.0.0.0/24")); + params.add(parmBuilder.build()); + + parmBuilder.setParameterName("portnumber-parm"); + parmBuilder.setIpprefixValue(null); + parmBuilder.setPortNumber(PortNumber.getDefaultInstance("8080")); + params.add(parmBuilder.build()); + + parmBuilder.setParameterName("dcsp-parm"); + parmBuilder.setPortNumber(null); + parmBuilder.setDscp(Dscp.getDefaultInstance("57")); + params.add(parmBuilder.build()); execBuilder.setMode(Mode.Sync); execBuilder.setModuleName("my-module"); -- cgit 1.2.3-korg From 88c5e41c5d3115521b24800b7be4e8bd77a27fc1 Mon Sep 17 00:00:00 2001 From: Rich Tabedzki Date: Fri, 22 Mar 2019 11:01:50 -0400 Subject: Support system variables in property values Changes made: * Added code in DBResourceManager to replace with its value * Expanded debug statement by adding processing time Change-Id: I22748daed50063e8e0ac7201e88d69a2609c1788 Issue-ID: CCSDK-1133 Signed-off-by: Rich Tabedzki --- .../ccsdk/sli/core/dblib/CachedDataSource.java | 41 +++++++- .../ccsdk/sli/core/dblib/DBResourceManager.java | 104 ++++++++++++++++----- .../core/dblib/TerminatingCachedDataSource.java | 7 ++ 3 files changed, 127 insertions(+), 25 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java index bc466d931..b9a0f071b 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/CachedDataSource.java @@ -33,6 +33,7 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Observer; import javax.sql.DataSource; @@ -59,7 +60,7 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito private static final Logger LOGGER = LoggerFactory.getLogger(CachedDataSource.class); private static final String SQL_FAILURE = "SQL FAILURE. time(ms): "; - private static final String FAILED_TO_EXECUTE = "> failed to execute: "; + private static final String FAILED_TO_EXECUTE = "> Failed to execute: "; private static final String WITH_ARGUMENTS = " with arguments: "; private static final String WITH_NO_ARGUMENTS = " with no arguments. "; private static final String DATA_SOURCE_CONNECT_SUCCESS = "SQL DataSource < {} > connected to {}, read-only is {}, tested successfully"; @@ -82,12 +83,13 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito private long nextErrorReportTime = 0L; private String globalHostName = null; + private final int index; private boolean isDerby = false; public CachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { ds = configure(jdbcElem); - + index = initializeIndex(jdbcElem); if ("org.apache.derby.jdbc.EmbeddedDriver".equals(jdbcElem.getDriverName())) { isDerby = true; } @@ -97,6 +99,16 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito protected abstract DataSource configure(BaseDBConfiguration jdbcElem) throws DBConfigException; protected abstract int getAvailableConnections(); + protected int initializeIndex(BaseDBConfiguration jdbcElem) { + if(jdbcElem.containsKey(BaseDBConfiguration.DATABASE_HOSTS)) { + String hosts = jdbcElem.getProperty(BaseDBConfiguration.DATABASE_HOSTS); + String name = jdbcElem.getProperty(BaseDBConfiguration.CONNECTION_NAME); + List numbers = Arrays.asList(hosts.split(",")); + return numbers.indexOf(name); + } else + return -1; + } + /* * (non-Javadoc) * @@ -104,7 +116,14 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito */ @Override public Connection getConnection() throws SQLException { + LapsedTimer lt = new LapsedTimer(); + try { return ds.getConnection(); + } finally { + if(LOGGER.isTraceEnabled()) { + LOGGER.trace(String.format("SQL Connection aquisition time : %s", lt.lapsedTime())); + } + } } public CachedRowSet getData(String statement, List arguments) throws SQLException { @@ -397,6 +416,10 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito monitor.deleteObserver(observer); } + public int getIndex() { + return index; + } + @Override public long getInterval() { return interval; @@ -487,9 +510,9 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito isSlave = true; } if (isSlave) { - LOGGER.debug("SQL SLAVE : {} on server {}, pool {}", connectionName, hostname, getAvailableConnections()); + LOGGER.debug("SQL SLAVE : {} on server {}, pool {}", connectionName, getDbConnectionName(), getAvailableConnections()); } else { - LOGGER.debug("SQL MASTER : {} on server {}, pool {}", connectionName, hostname, getAvailableConnections()); + LOGGER.debug("SQL MASTER : {} on server {}, pool {}", connectionName, getDbConnectionName(), getAvailableConnections()); } return isSlave; } @@ -557,4 +580,14 @@ public abstract class CachedDataSource implements DataSource, SQLExecutionMonito public String getGlobalHostName() { return globalHostName; } + + static class LapsedTimer { + private final long msTime = System.currentTimeMillis(); + + public String lapsedTime() { + double timediff = System.currentTimeMillis() - msTime; + timediff = timediff/1000; + return String.valueOf( timediff)+"s"; + } + } } 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 236bce6e3..7c71bcc81 100755 --- 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 @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; +import java.util.Map; import java.util.HashSet; import java.util.Iterator; import java.util.Observable; @@ -44,6 +45,7 @@ import java.util.SortedSet; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListSet; +import java.util.stream.Collectors; import javax.sql.DataSource; import javax.sql.rowset.CachedRowSet; @@ -66,7 +68,8 @@ import org.slf4j.LoggerFactory; * Rich Tabedzki */ public class DBResourceManager implements DataSource, DataAccessor, DBResourceObserver, DbLibService { - private static Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DBResourceManager.class); + private static final String DATABASE_URL = "org.onap.ccsdk.sli.jdbc.url"; transient boolean terminating = false; transient protected long retryInterval = 10000L; @@ -92,8 +95,8 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } public DBResourceManager(final Properties properties) { - this.configProps = properties; - + this.configProps = processSystemVariables(properties); + // TODO : hack to force classloader to cache mariadb driver. This shouldnt be necessary, // but for some reason it is (without this, dblib throws ClassNotFound on mariadb driver // and fails to load). @@ -102,26 +105,26 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb dvr = null; // get retry interval value - retryInterval = getLongFromProperties(properties, "org.onap.dblib.connection.retry", 10000L); + retryInterval = getLongFromProperties(configProps, "org.onap.dblib.connection.retry", 10000L); // get recovery mode flag - recoveryMode = getBooleanFromProperties(properties, "org.onap.dblib.connection.recovery", true); + recoveryMode = getBooleanFromProperties(configProps, "org.onap.dblib.connection.recovery", true); if(!recoveryMode) { recoveryMode = false; LOGGER.info("Recovery Mode disabled"); } // get time out value for thread cleanup - terminationTimeOut = getLongFromProperties(properties, "org.onap.dblib.termination.timeout", 300000L); + terminationTimeOut = getLongFromProperties(configProps, "org.onap.dblib.termination.timeout", 300000L); // get properties for monitoring - 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); + monitorDbResponse = getBooleanFromProperties(configProps, "org.onap.dblib.connection.monitor", false); + monitoringInterval = getLongFromProperties(configProps, "org.onap.dblib.connection.monitor.interval", 1000L); + monitoringInitialDelay = getLongFromProperties(configProps, "org.onap.dblib.connection.monitor.startdelay", 5000L); + expectedCompletionTime = getLongFromProperties(configProps, "org.onap.dblib.connection.monitor.expectedcompletiontime", 5000L); + unprocessedFailoverThreshold = getLongFromProperties(configProps, "org.onap.dblib.connection.monitor.unprocessedfailoverthreshold", 3L); // initialize performance monitor - PollingWorker.createInistance(properties); + PollingWorker.createInistance(configProps); // initialize recovery thread worker = new RecoveryMgr(); @@ -130,13 +133,49 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb worker.start(); try { - this.config(properties); + this.config(configProps); } 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); } } + public static Properties processSystemVariables(Properties properties) { + Map hmap = new Properties(); + hmap.putAll(properties); + + Map result = hmap.entrySet().stream() + .filter(map -> map.getValue().toString().startsWith("${")) + .filter(map -> map.getValue().toString().endsWith("}")) + .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); + + result.forEach((name, propEntries) -> { + hmap.put(name, replace(propEntries.toString())); + }); + + if(hmap.containsKey(DATABASE_URL) && hmap.get(DATABASE_URL).toString().contains("${")) { + String url = hmap.get(DATABASE_URL).toString(); + String[] innerChunks = url.split("\\$\\{"); + for(String chunk : innerChunks) { + if(chunk.contains("}")) { + String subChunk = chunk.substring(0, chunk.indexOf("}")); + String varValue = System.getenv(subChunk); + url = url.replace("${"+subChunk+"}", varValue); + } + } + hmap.put(DATABASE_URL, url); + } + return Properties.class.cast(hmap); + } + + + private static String replace(String value) { + String globalVariable = value.substring(2, value.length() -1); + String varValue = System.getenv(globalVariable); + return (varValue != null) ? varValue : value; + } + + private void config(Properties configProps) throws Exception { final ConcurrentLinkedQueue semaphore = new ConcurrentLinkedQueue<>(); final DbConfigPool dbConfig = DBConfigFactory.createConfig(configProps); @@ -204,11 +243,33 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb return -1; } - if(!left.isSlave()) + boolean leftMaster = !left.isSlave(); + if(leftMaster) { + if(left.getIndex() <= right.getIndex()) + return -1; + else { + boolean rightMaster = !right.isSlave(); + if(rightMaster) { + if(left.getIndex() <= right.getIndex()) + return -1; +// if(left.getIndex() > right.getIndex()) + else { + return 1; + } + } else { return -1; + } + } + } if(!right.isSlave()) return 1; + if(left.getIndex() <= right.getIndex()) + return -1; + if(left.getIndex() > right.getIndex()) + return 1; + + } catch (Throwable e) { LOGGER.warn("", e); } @@ -440,12 +501,12 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } } lastException = exc; - LOGGER.error("Generated alarm: "+active.getDbConnectionName(), exc); + LOGGER.error("Generated alarm: {}", active.getDbConnectionName(), exc); handleGetConnectionException(active, exc); } finally { if(LOGGER.isDebugEnabled()){ time = System.currentTimeMillis() - time; - LOGGER.debug("getData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + LOGGER.debug("getData processing time : {} {} miliseconds.", active.getDbConnectionName(), time); } } } @@ -490,7 +551,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb String message = exc.getMessage(); if(message == null) message = exc.getClass().getName(); - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + LOGGER.error("Generated alarm: {} - {}",active.getDbConnectionName(), message); if(exc instanceof SQLException) throw (SQLException)exc; else { @@ -501,7 +562,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } finally { if(LOGGER.isDebugEnabled()){ time = System.currentTimeMillis() - time; - LOGGER.debug(">> getData : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + LOGGER.debug(">> getData : {} {} miliseconds.", active.getDbConnectionName(), time); } } } @@ -570,12 +631,12 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb String message = exc.getMessage(); if(message == null) message = exc.getClass().getName(); - LOGGER.error("Generated alarm: "+active.getDbConnectionName()+" - "+message); + LOGGER.error("Generated alarm: {} - {}", active.getDbConnectionName(), message); if(exc instanceof SQLException) { SQLException sqlExc = SQLException.class.cast(exc); // handle read-only exception if(sqlExc.getErrorCode() == 1290 && "HY000".equals(sqlExc.getSQLState())) { - LOGGER.warn("retrying due to: " + sqlExc.getMessage()); + LOGGER.warn("retrying due to: {}", sqlExc.getMessage()); this.findMaster(); if(retryAllowed){ retryAllowed = false; @@ -592,7 +653,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb } finally { if(LOGGER.isDebugEnabled()){ time = System.currentTimeMillis() - time; - LOGGER.debug("writeData processing time : "+ active.getDbConnectionName()+" "+time+" miliseconds."); + LOGGER.debug("writeData processing time : {} {} miliseconds.", active.getDbConnectionName(), time); } } } @@ -626,6 +687,7 @@ public class DBResourceManager implements DataSource, DataAccessor, DBResourceOb if(!active.isFabric()) { if(this.dsQueue.size() > 1 && active.isSlave()) { + LOGGER.debug("Forcing reorder on: {}", dsQueue.toString()); CachedDataSource master = findMaster(); if(master != null) { active = master; diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java index 884f88825..852dda3c7 100755 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/TerminatingCachedDataSource.java @@ -30,6 +30,7 @@ import org.onap.ccsdk.sli.core.dblib.pm.SQLExecutionMonitorObserver; public class TerminatingCachedDataSource extends CachedDataSource implements SQLExecutionMonitorObserver { private static final int DEFAULT_AVAILABLE_CONNECTIONS = 0; + private static final int DEFAULT_INDEX = -1; public TerminatingCachedDataSource(BaseDBConfiguration jdbcElem) throws DBConfigException { super(jdbcElem); @@ -49,4 +50,10 @@ public class TerminatingCachedDataSource extends CachedDataSource implements SQL protected int getAvailableConnections() { return DEFAULT_AVAILABLE_CONNECTIONS; } + + @Override + protected int initializeIndex(BaseDBConfiguration jdbcElem) { + return DEFAULT_INDEX; + } + } -- cgit 1.2.3-korg From 46c7c43043d8f48dc866e73c752248f4d466b3a0 Mon Sep 17 00:00:00 2001 From: anushadasari Date: Tue, 23 Jul 2019 23:06:04 +0530 Subject: JUNIT-ConfigurationException.java JUNIT for ConfigurationException.java Issue-ID: CCSDK-1520 Change-Id: I64e50083b9b0fe40fa0ba32723e30adb0dbce08e Signed-off-by: anushadasari --- .../ccsdk/sli/core/dblib/DBLibExceptionTest.java | 14 ---------- .../sli/core/sli/ConfigurationExceptionTestt.java | 30 ++++++++++++++++++++++ sli/features/features-sli/pom.xml | 2 +- 3 files changed, 31 insertions(+), 15 deletions(-) delete mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java create mode 100644 sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ConfigurationExceptionTestt.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java deleted file mode 100644 index cab24042c..000000000 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/DBLibExceptionTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.onap.ccsdk.sli.core.dblib; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class DBLibExceptionTest { - - @Test - public void testDBLibException() { - assertNotNull(new DBLibException("test")); - } - -} diff --git a/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ConfigurationExceptionTestt.java b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ConfigurationExceptionTestt.java new file mode 100644 index 000000000..ef7492366 --- /dev/null +++ b/sli/common/src/test/java/org/onap/ccsdk/sli/core/sli/ConfigurationExceptionTestt.java @@ -0,0 +1,30 @@ +package org.onap.ccsdk.sli.core.sli; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ConfigurationExceptionTestt { + + + @Test + public void ConfigurationExceptionTest() { + assertNotNull(new ConfigurationException()); + + } + + @Test + public void ConfigurationExceptionTestString() { + assertNotNull(new ConfigurationException("JUnit Test")); + + } + + @Test + public void ConfigurationExceptionTestStringThrowable() { + assertNotNull(new ConfigurationException("JUnit Test", new Exception("JUnit Test"))); + + } + + + +} diff --git a/sli/features/features-sli/pom.xml b/sli/features/features-sli/pom.xml index 128d49758..c16347968 100644 --- a/sli/features/features-sli/pom.xml +++ b/sli/features/features-sli/pom.xml @@ -24,6 +24,6 @@ xml features - + -- cgit 1.2.3-korg From 06877cb9a30c4ea3e7e95c230f214a78fb4db9e1 Mon Sep 17 00:00:00 2001 From: "Timoney, Dan (dt5972)" Date: Wed, 3 Jul 2019 13:53:18 -0400 Subject: Code changes for OpenDaylight Neon Updated code for OpenDaylight Neon (using ccsdk/parent/tools/fluorine2neon.sh) Change-Id: Ic54b636f691cb2c9dd627dfc3b22b523c0f4f8da Issue-ID: CCSDK-1389 Signed-off-by: Timoney, Dan (dt5972) --- artifacts/pom.xml | 4 +- dblib/features/ccsdk-dblib/pom.xml | 4 +- dblib/features/features-dblib/pom.xml | 4 +- dblib/features/pom.xml | 4 +- dblib/installer/pom.xml | 4 +- dblib/pom.xml | 4 +- dblib/provider/pom.xml | 4 +- .../OSGI-INF/blueprint/dblib-blueprint.xml | 24 + features/ccsdk-sli-core-all/pom.xml | 4 +- features/features-sli-core/pom.xml | 4 +- features/installer/pom.xml | 4 +- features/pom.xml | 4 +- filters/features/ccsdk-filters/pom.xml | 4 +- filters/features/features-filters/pom.xml | 4 +- filters/features/pom.xml | 3 +- filters/installer/pom.xml | 4 +- filters/pom.xml | 4 +- filters/provider/pom.xml | 4 +- .../OSGI-INF/blueprint/filters-blueprint.xml | 9 + pom.xml | 4 +- sli/common/pom.xml | 14 +- sli/features/features-sli/pom.xml | 4 +- sli/features/odl-sli/pom.xml | 4 +- sli/features/pom.xml | 4 +- sli/installer/pom.xml | 4 +- sli/model/pom.xml | 16 +- sli/pom.xml | 4 +- sli/provider-base/pom.xml | 4 +- sli/provider/pom.xml | 4 +- .../resources/OSGI-INF/blueprint/sli-blueprint.xml | 21 + sli/recording/pom.xml | 4 +- .../OSGI-INF/blueprint/recording-blueprint.xml | 20 + .../features/ccsdk-sliPluginUtils/pom.xml | 4 +- .../features/features-sliPluginUtils/pom.xml | 4 +- sliPluginUtils/features/pom.xml | 4 +- sliPluginUtils/installer/pom.xml | 4 +- sliPluginUtils/pom.xml | 4 +- sliPluginUtils/provider/pom.xml | 4 +- .../blueprint/slipluginutils-blueprint.xml | 13 + sliapi/features/ccsdk-sliapi/pom.xml | 4 +- sliapi/features/features-sliapi/pom.xml | 4 +- sliapi/features/pom.xml | 4 +- sliapi/installer/pom.xml | 4 +- sliapi/model/pom.xml | 16 +- sliapi/pom.xml | 4 +- sliapi/provider/pom.xml | 4 +- .../onap/ccsdk/sli/core/sliapi/SliapiProvider.java | 676 ++++++++++++++++++++ .../onap/ccsdk/sli/core/sliapi/sliapiProvider.java | 677 --------------------- .../OSGI-INF/blueprint/sliapi-blueprint.xml | 28 + .../opendaylight/blueprint/sliapi-blueprint.xml | 2 +- .../ccsdk/sli/core/sliapi/TestSliapiProvider.java | 10 +- .../src/test/resources/simplelogger.properties | 2 +- utils/features/ccsdk-slicore-utils/pom.xml | 4 +- utils/features/features-util/pom.xml | 4 +- utils/features/pom.xml | 3 +- utils/installer/pom.xml | 4 +- utils/pom.xml | 4 +- utils/provider/pom.xml | 4 +- version.properties | 4 +- 59 files changed, 906 insertions(+), 800 deletions(-) create mode 100755 dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml create mode 100644 filters/provider/src/main/resources/OSGI-INF/blueprint/filters-blueprint.xml create mode 100644 sli/provider/src/main/resources/OSGI-INF/blueprint/sli-blueprint.xml create mode 100644 sli/recording/src/main/resources/OSGI-INF/blueprint/recording-blueprint.xml create mode 100644 sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml create mode 100644 sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/SliapiProvider.java delete mode 100644 sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java create mode 100644 sliapi/provider/src/main/resources/OSGI-INF/blueprint/sliapi-blueprint.xml (limited to 'dblib/provider/src') diff --git a/artifacts/pom.xml b/artifacts/pom.xml index 405a572b7..245077465 100755 --- a/artifacts/pom.xml +++ b/artifacts/pom.xml @@ -4,7 +4,7 @@ org.onap.ccsdk.sli.core sli-core-artifacts - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sli-core-artifacts @@ -17,7 +17,7 @@ org.onap.ccsdk.parent parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT diff --git a/dblib/features/ccsdk-dblib/pom.xml b/dblib/features/ccsdk-dblib/pom.xml index ef0c3ee07..d541bab9c 100644 --- a/dblib/features/ccsdk-dblib/pom.xml +++ b/dblib/features/ccsdk-dblib/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-dblib - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: dblib :: ${project.artifactId} diff --git a/dblib/features/features-dblib/pom.xml b/dblib/features/features-dblib/pom.xml index 87c7ed78b..462ca365b 100644 --- a/dblib/features/features-dblib/pom.xml +++ b/dblib/features/features-dblib/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-dblib - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: dblib :: ${project.artifactId} diff --git a/dblib/features/pom.xml b/dblib/features/pom.xml index 89c0c8b19..bac999f62 100755 --- a/dblib/features/pom.xml +++ b/dblib/features/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core dblib-feature-aggregator - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: dblib :: ${project.artifactId} diff --git a/dblib/installer/pom.xml b/dblib/installer/pom.xml index a283157eb..c02f6ee62 100755 --- a/dblib/installer/pom.xml +++ b/dblib/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core dblib-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: dblib :: ${project.artifactId} diff --git a/dblib/pom.xml b/dblib/pom.xml index 0d5d565a8..258a4307a 100755 --- a/dblib/pom.xml +++ b/dblib/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core dblib - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: dblib diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index d0b97afe0..52a39b8f9 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core dblib-provider - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: dblib :: ${project.artifactId} diff --git a/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml b/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml new file mode 100755 index 000000000..d9bb99c07 --- /dev/null +++ b/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + javax.sql.DataSource + org.onap.ccsdk.sli.core.dblib.DbLibService + + + + + + + + + + \ No newline at end of file diff --git a/features/ccsdk-sli-core-all/pom.xml b/features/ccsdk-sli-core-all/pom.xml index 3f9a272a2..a040c3687 100644 --- a/features/ccsdk-sli-core-all/pom.xml +++ b/features/ccsdk-sli-core-all/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-sli-core-all - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: features :: ${project.artifactId} diff --git a/features/features-sli-core/pom.xml b/features/features-sli-core/pom.xml index 8109a7a29..b90f020e8 100644 --- a/features/features-sli-core/pom.xml +++ b/features/features-sli-core/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-sli-core - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: features :: ${project.artifactId} diff --git a/features/installer/pom.xml b/features/installer/pom.xml index b15835444..76bd191b2 100755 --- a/features/installer/pom.xml +++ b/features/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core slicore-features-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: features :: ${project.artifactId} diff --git a/features/pom.xml b/features/pom.xml index 52f8a427e..f374be96b 100755 --- a/features/pom.xml +++ b/features/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core slicore-feature-aggregator - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: features diff --git a/filters/features/ccsdk-filters/pom.xml b/filters/features/ccsdk-filters/pom.xml index 952e8da11..390f1b34e 100644 --- a/filters/features/ccsdk-filters/pom.xml +++ b/filters/features/ccsdk-filters/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-filters - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: filters :: ${project.artifactId} diff --git a/filters/features/features-filters/pom.xml b/filters/features/features-filters/pom.xml index c130afe9c..d72f95a5f 100644 --- a/filters/features/features-filters/pom.xml +++ b/filters/features/features-filters/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-filters - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: filters :: ${project.artifactId} diff --git a/filters/features/pom.xml b/filters/features/pom.xml index 4daca915f..494f7f169 100755 --- a/filters/features/pom.xml +++ b/filters/features/pom.xml @@ -5,13 +5,12 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core filters-features-aggregator - 0.5.2-SNAPSHOT pom ccsdk-sli-core :: filters :: ${project.artifactId} diff --git a/filters/installer/pom.xml b/filters/installer/pom.xml index b980d5a58..42c39e9c3 100755 --- a/filters/installer/pom.xml +++ b/filters/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core filters-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: filters :: ${project.artifactId} diff --git a/filters/pom.xml b/filters/pom.xml index 2fee26b06..12f44bfeb 100644 --- a/filters/pom.xml +++ b/filters/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core filters - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: filters diff --git a/filters/provider/pom.xml b/filters/provider/pom.xml index bf28ad975..e7555aaf6 100755 --- a/filters/provider/pom.xml +++ b/filters/provider/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core filters-provider - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: filters :: ${project.artifactId} diff --git a/filters/provider/src/main/resources/OSGI-INF/blueprint/filters-blueprint.xml b/filters/provider/src/main/resources/OSGI-INF/blueprint/filters-blueprint.xml new file mode 100644 index 000000000..3bf8423e9 --- /dev/null +++ b/filters/provider/src/main/resources/OSGI-INF/blueprint/filters-blueprint.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/pom.xml b/pom.xml index c52876b93..711f3faea 100755 --- a/pom.xml +++ b/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-sli-core - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core diff --git a/sli/common/pom.xml b/sli/common/pom.xml index c35397f37..24e29b2ec 100755 --- a/sli/common/pom.xml +++ b/sli/common/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-common - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sli :: ${project.artifactId} @@ -70,13 +70,11 @@ test - org.opendaylight.mdsal.model - ietf-inet-types-2013-07-15 - - - org.opendaylight.mdsal.model - ietf-yang-types-20130715 + org.opendaylight.mdsal.binding.model.ietf + rfc6991 + + org.opendaylight.controller sal-core-api diff --git a/sli/features/features-sli/pom.xml b/sli/features/features-sli/pom.xml index ee93bab69..8597432e1 100644 --- a/sli/features/features-sli/pom.xml +++ b/sli/features/features-sli/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-sli - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: sli :: ${project.artifactId} diff --git a/sli/features/odl-sli/pom.xml b/sli/features/odl-sli/pom.xml index d53cb4498..8c46e8193 100644 --- a/sli/features/odl-sli/pom.xml +++ b/sli/features/odl-sli/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-sli - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: sli :: ${project.artifactId} diff --git a/sli/features/pom.xml b/sli/features/pom.xml index 5beb26338..871d41c37 100644 --- a/sli/features/pom.xml +++ b/sli/features/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-feature-aggregator - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sli :: ${project.artifactId} diff --git a/sli/installer/pom.xml b/sli/installer/pom.xml index 54e24d004..ad8a9200e 100755 --- a/sli/installer/pom.xml +++ b/sli/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sli :: ${project.artifactId} diff --git a/sli/model/pom.xml b/sli/model/pom.xml index 75befd35f..243223e17 100755 --- a/sli/model/pom.xml +++ b/sli/model/pom.xml @@ -5,25 +5,23 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-model - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sli :: ${project.artifactId} - org.opendaylight.mdsal.model - ietf-inet-types-2013-07-15 - - - org.opendaylight.mdsal.model - ietf-yang-types-20130715 - + org.opendaylight.mdsal.binding.model.ietf + rfc6991 + + + diff --git a/sli/pom.xml b/sli/pom.xml index bfb63846d..b9b60e9e3 100755 --- a/sli/pom.xml +++ b/sli/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sli diff --git a/sli/provider-base/pom.xml b/sli/provider-base/pom.xml index e31119377..d1dd62930 100644 --- a/sli/provider-base/pom.xml +++ b/sli/provider-base/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-provider-base - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT diff --git a/sli/provider/pom.xml b/sli/provider/pom.xml index aff9ca270..1326ef7aa 100755 --- a/sli/provider/pom.xml +++ b/sli/provider/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-provider - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sli :: ${project.artifactId} diff --git a/sli/provider/src/main/resources/OSGI-INF/blueprint/sli-blueprint.xml b/sli/provider/src/main/resources/OSGI-INF/blueprint/sli-blueprint.xml new file mode 100644 index 000000000..bb14477e4 --- /dev/null +++ b/sli/provider/src/main/resources/OSGI-INF/blueprint/sli-blueprint.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + org.onap.ccsdk.sli.core.sli.provider.SvcLogicService + + + + \ No newline at end of file diff --git a/sli/recording/pom.xml b/sli/recording/pom.xml index a4ec1b255..de8a56440 100755 --- a/sli/recording/pom.xml +++ b/sli/recording/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sli-recording - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sli :: ${project.artifactId} diff --git a/sli/recording/src/main/resources/OSGI-INF/blueprint/recording-blueprint.xml b/sli/recording/src/main/resources/OSGI-INF/blueprint/recording-blueprint.xml new file mode 100644 index 000000000..6786b955b --- /dev/null +++ b/sli/recording/src/main/resources/OSGI-INF/blueprint/recording-blueprint.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml b/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml index a0450630b..f55d3d47e 100644 --- a/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml +++ b/sliPluginUtils/features/ccsdk-sliPluginUtils/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-sliPluginUtils - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} diff --git a/sliPluginUtils/features/features-sliPluginUtils/pom.xml b/sliPluginUtils/features/features-sliPluginUtils/pom.xml index e639b1c64..3950c94ec 100644 --- a/sliPluginUtils/features/features-sliPluginUtils/pom.xml +++ b/sliPluginUtils/features/features-sliPluginUtils/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-sliPluginUtils - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} diff --git a/sliPluginUtils/features/pom.xml b/sliPluginUtils/features/pom.xml index 5c56b0174..d95b5fdf1 100755 --- a/sliPluginUtils/features/pom.xml +++ b/sliPluginUtils/features/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliPluginUtils-features - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} diff --git a/sliPluginUtils/installer/pom.xml b/sliPluginUtils/installer/pom.xml index fde893095..fdb245d62 100755 --- a/sliPluginUtils/installer/pom.xml +++ b/sliPluginUtils/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliPluginUtils-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} diff --git a/sliPluginUtils/pom.xml b/sliPluginUtils/pom.xml index 1ce7757c2..f9cdcec2e 100755 --- a/sliPluginUtils/pom.xml +++ b/sliPluginUtils/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliPluginUtils - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sliPluginUtils diff --git a/sliPluginUtils/provider/pom.xml b/sliPluginUtils/provider/pom.xml index 49a1210fd..1814a0085 100755 --- a/sliPluginUtils/provider/pom.xml +++ b/sliPluginUtils/provider/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliPluginUtils-provider - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sliPluginUtils :: ${project.artifactId} diff --git a/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml b/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml new file mode 100644 index 000000000..534b92c93 --- /dev/null +++ b/sliPluginUtils/provider/src/main/resources/OSGI-INF/blueprint/slipluginutils-blueprint.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/sliapi/features/ccsdk-sliapi/pom.xml b/sliapi/features/ccsdk-sliapi/pom.xml index 329d6ff7a..004ec95f4 100644 --- a/sliapi/features/ccsdk-sliapi/pom.xml +++ b/sliapi/features/ccsdk-sliapi/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-sliapi - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: sliapi :: ${project.artifactId} diff --git a/sliapi/features/features-sliapi/pom.xml b/sliapi/features/features-sliapi/pom.xml index c95311cc3..8765fb97f 100644 --- a/sliapi/features/features-sliapi/pom.xml +++ b/sliapi/features/features-sliapi/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-sliapi - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: sliapi :: ${project.artifactId} diff --git a/sliapi/features/pom.xml b/sliapi/features/pom.xml index 6e366e6e4..719aa1962 100755 --- a/sliapi/features/pom.xml +++ b/sliapi/features/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliapi-feature-aggregator - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sliapi :: ${project.artifactId} diff --git a/sliapi/installer/pom.xml b/sliapi/installer/pom.xml index eb69925b5..95fea32cd 100755 --- a/sliapi/installer/pom.xml +++ b/sliapi/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliapi-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sliapi :: ${project.artifactId} diff --git a/sliapi/model/pom.xml b/sliapi/model/pom.xml index a4faeae36..2b0f58717 100755 --- a/sliapi/model/pom.xml +++ b/sliapi/model/pom.xml @@ -5,25 +5,23 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliapi-model - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sliapi :: ${project.artifactId} - org.opendaylight.mdsal.model - ietf-inet-types-2013-07-15 - - - org.opendaylight.mdsal.model - ietf-yang-types-20130715 - + org.opendaylight.mdsal.binding.model.ietf + rfc6991 + + + diff --git a/sliapi/pom.xml b/sliapi/pom.xml index c5ed07a00..c9541ac22 100755 --- a/sliapi/pom.xml +++ b/sliapi/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliapi - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: sliapi diff --git a/sliapi/provider/pom.xml b/sliapi/provider/pom.xml index 8dd79432c..533b18e0c 100755 --- a/sliapi/provider/pom.xml +++ b/sliapi/provider/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core sliapi-provider - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: sliapi :: ${project.artifactId} diff --git a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/SliapiProvider.java b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/SliapiProvider.java new file mode 100644 index 000000000..449fc3822 --- /dev/null +++ b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/SliapiProvider.java @@ -0,0 +1,676 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.core.sliapi; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.LinkedList; +import java.util.Properties; + +import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService; +import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; +import org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedDataBroker; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; +import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; +import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput.Mode; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphOutput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.HealthcheckInput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.HealthcheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.HealthcheckOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.SLIAPIService; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.TestResults; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.VlbcheckInput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.VlbcheckOutput; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.VlbcheckOutputBuilder; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameter; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.test.results.TestResult; +import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.test.results.TestResultBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.common.RpcResultBuilder; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue; +import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; +import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Defines a base implementation for your provider. This class extends from a + * helper class which provides storage for the most commonly used components of + * the MD-SAL. Additionally the base class provides some basic logging and + * initialization / clean up methods. + * + * To use this, copy and paste (overwrite) the following method into the + * TestApplicationProviderModule class which is auto generated under + * src/main/java in this project (created only once during first compilation): + * + *
    + * 
    + * @Override
    + * public java.lang.AutoCloseable createInstance() {
    + * 
    + * 	final SliapiProvider provider = new SliapiProvider();
    + * 	provider.setDataBroker(getDataBrokerDependency());
    + * 	provider.setNotificationService(getNotificationServiceDependency());
    + * 	provider.setRpcRegistry(getRpcRegistryDependency());
    + * 	provider.initialize();
    + * 	return new AutoCloseable() {
    + * 
    + * 		@Override
    + * 		public void close() throws Exception {
    + * 			// TODO: CLOSE ANY REGISTRATION OBJECTS CREATED USING ABOVE
    + * 			// BROKER/NOTIFICATION
    + * 			// SERVIE/RPC REGISTRY
    + * 			provider.close();
    + * 		}
    + * 	};
    + * }
    + * 
    + * 
    + */ +public class SliapiProvider implements AutoCloseable, SLIAPIService { + + private static final Logger LOG = LoggerFactory.getLogger(SliapiProvider.class); + private static final String appName = "slitester"; + + protected DataBroker dataBroker; + protected DOMDataBroker domDataBroker; + protected NotificationPublishService notificationService; + protected RpcProviderRegistry rpcRegistry; + + private SvcLogicService svcLogic; + + protected BindingAwareBroker.RpcRegistration rpcRegistration; + + private static String SLIAPI_NAMESPACE = "org:onap:ccsdk:sli:core:sliapi"; + private static String SLIAPI_REVISION = "2016-11-10"; + private static String SDNC_STATUS_FILE = "SDNC_STATUS_FILE"; + private static String sdncStatusFile = null; + + private static QName TEST_RESULTS_QNAME = null; + private static QName TEST_RESULT_QNAME = null; + private static QName TEST_ID_QNAME = null; + private static QName RESULTS_QNAME = null; + private static final String NON_NULL = "non-null"; + + static { + + TEST_RESULTS_QNAME = QName.create(SLIAPI_NAMESPACE, SLIAPI_REVISION, "test-results"); + TEST_RESULT_QNAME = QName.create(TEST_RESULTS_QNAME, "test-result"); + TEST_ID_QNAME = QName.create(TEST_RESULT_QNAME, "test-identifier"); + RESULTS_QNAME = QName.create(TEST_RESULT_QNAME, "results"); + } + + public SliapiProvider(DataBroker dataBroker, NotificationPublishService notificationPublishService, + RpcProviderRegistry rpcProviderRegistry) { + this(dataBroker, notificationPublishService, rpcProviderRegistry, findSvcLogicService()); + } + + public SliapiProvider(DataBroker dataBroker, NotificationPublishService notificationPublishService, + RpcProviderRegistry rpcProviderRegistry, SvcLogicService svcLogic) { + this.LOG.info("Creating provider for " + appName); + this.dataBroker = dataBroker; + this.notificationService = notificationPublishService; + this.rpcRegistry = rpcProviderRegistry; + this.svcLogic = svcLogic; + initialize(); + } + + public void initialize() { + LOG.info("Initializing provider for " + appName); + // initialization code goes here. + rpcRegistration = rpcRegistry.addRpcImplementation(SLIAPIService.class, this); + + sdncStatusFile = System.getenv(SDNC_STATUS_FILE); + LOG.info("SDNC STATUS FILE = " + sdncStatusFile); + LOG.info("Initialization complete for " + appName); + } + + protected void initializeChild() { + // Override if you have custom initialization intelligence + } + + @Override + public void close() throws Exception { + LOG.info("Closing provider for " + appName); + // closing code goes here + + rpcRegistration.close(); + LOG.info("Successfully closed provider for " + appName); + } + + public void setDataBroker(DataBroker dataBroker) { + this.dataBroker = dataBroker; + if (dataBroker instanceof AbstractForwardedDataBroker) { + domDataBroker = ((AbstractForwardedDataBroker) dataBroker).getDelegate(); + } + if (LOG.isDebugEnabled()) { + LOG.debug("DataBroker set to " + (dataBroker == null ? "null" : NON_NULL) + "."); + } + } + + public void setNotificationService(NotificationPublishService notificationService) { + this.notificationService = notificationService; + if (LOG.isDebugEnabled()) { + LOG.debug("Notification Service set to " + (notificationService == null ? "null" : NON_NULL) + "."); + } + } + + public void setRpcRegistry(RpcProviderRegistry rpcRegistry) { + this.rpcRegistry = rpcRegistry; + if (LOG.isDebugEnabled()) { + LOG.debug("RpcRegistry set to " + (rpcRegistry == null ? "null" : NON_NULL) + "."); + } + } + + @Override + public ListenableFuture> executeGraph(ExecuteGraphInput input) { + RpcResult rpcResult = null; + + SvcLogicService svcLogic = getSvcLogicService(); + ExecuteGraphOutputBuilder respBuilder = new ExecuteGraphOutputBuilder(); + + String calledModule = input.getModuleName(); + String calledRpc = input.getRpcName(); + Mode calledMode = input.getMode(); + String modeStr = "sync"; + + if (calledMode == Mode.Async) { + modeStr = "async"; + } + + if (svcLogic == null) { + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Could not locate OSGi SvcLogicService service"); + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + try { + if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) { + respBuilder.setResponseCode("404"); + respBuilder.setResponseMessage( + "Directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr + " not found"); + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + } catch (Exception e) { + LOG.error( + "Caught exception looking for directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr, + e); + + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Internal error : could not determine if target graph exists"); + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + // Load properties + Properties parms = new Properties(); + + // Pass properties using names from sli-parameters + for (SliParameter sliParm : input.getSliParameter()) { + + String propValue = ""; + + Boolean boolval = sliParm.isBooleanValue(); + + if (boolval != null) { + propValue = boolval.toString(); + } else { + Integer intval = sliParm.getIntValue(); + if (intval != null) { + propValue = intval.toString(); + } else { + propValue = sliParm.getStringValue(); + if (propValue == null) { + propValue = ""; + } + } + } + parms.setProperty(sliParm.getParameterName(), propValue); + } + + // Also, pass "meta" properties (i.e. pass SliParameter objects themselves) + ExecuteGraphInputBuilder inputBuilder = new ExecuteGraphInputBuilder(input); + + SliapiHelper.toProperties(parms, "input", inputBuilder); + + try { + LOG.info("Calling directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr); + + if (LOG.isTraceEnabled()) { + StringBuffer argList = new StringBuffer(); + argList.append("Parameters : {"); + Enumeration e = parms.propertyNames(); + while (e.hasMoreElements()) { + String propName = (String) e.nextElement(); + argList.append(" (" + propName + "," + parms.getProperty(propName) + ") "); + } + argList.append("}"); + LOG.trace(argList.toString()); + argList = null; + } + + Properties respProps = svcLogic.execute(calledModule, calledRpc, null, modeStr, parms, domDataBroker); + + StringBuilder sb = new StringBuilder("{"); + + for (Object key : respProps.keySet()) { + String keyValue = (String) key; + if (keyValue != null && !"".equals(keyValue) && !keyValue.contains("input.sli-parameter")) { + sb.append("\"").append(keyValue).append("\": \"").append(respProps.getProperty(keyValue)) + .append("\","); + } + } + + sb.setLength(sb.length() - 1); + sb.append("}"); + + respBuilder.setResponseCode(respProps.getProperty("error-code", "0")); + respBuilder.setResponseMessage(respProps.getProperty("error-message", ""));// TODO change response-text to + // response-message to match + // other BVC APIs + respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y")); + respBuilder.setContextMemoryJson(sb.toString()); + + TestResultBuilder testResultBuilder = new TestResultBuilder(); + + SliapiHelper.toBuilder(respProps, testResultBuilder); + + String testIdentifier = testResultBuilder.getTestIdentifier(); + + if ((testIdentifier != null) && (testIdentifier.length() > 0)) { + + // Add test results to config tree + LOG.debug("Saving test results for test id " + testIdentifier); + + DomSaveTestResult(testResultBuilder.build(), true, LogicalDatastoreType.CONFIGURATION); + + } + + } catch (Exception e) { + LOG.error("Caught exception executing directed graph for" + calledModule + ":" + calledRpc + "," + modeStr + + ">", e); + + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Internal error : caught exception executing directed graph " + calledModule + + "/" + calledRpc + "/" + modeStr); + respBuilder.setAckFinalIndicator("Y"); + + } + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + private SvcLogicService getSvcLogicService() { + if (svcLogic == null) { + svcLogic = findSvcLogicService(); + } + + return (svcLogic); + } + + private static SvcLogicService findSvcLogicService() { + BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class).getBundleContext(); + + SvcLogicService svcLogic = null; + + // Get SvcLogicService reference + ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME); + if (sref != null) { + svcLogic = (SvcLogicService) bctx.getService(sref); + + } else { + LOG.warn("Cannot find service reference for " + SvcLogicService.NAME); + + } + + return (svcLogic); + } + + @Override + public ListenableFuture> healthcheck(HealthcheckInput healthcheckInput) { + + RpcResult rpcResult = null; + SvcLogicService svcLogic = getSvcLogicService(); + + HealthcheckOutputBuilder respBuilder = new HealthcheckOutputBuilder(); + + String calledModule = "sli"; + String calledRpc = "healthcheck"; + String modeStr = "sync"; + + if (svcLogic == null) { + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Could not locate OSGi SvcLogicService service"); + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.failed().withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + try { + if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) { + respBuilder.setResponseCode("404"); + respBuilder.setResponseMessage( + "Directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr + " not found"); + + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + } catch (Exception e) { + LOG.error( + "Caught exception looking for directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr, + e); + + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Internal error : could not determine if target graph exists"); + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.failed().withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + try { + LOG.info("Calling directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr); + + Properties parms = new Properties(); + + Properties respProps = svcLogic.execute(calledModule, calledRpc, null, modeStr, parms); + + respBuilder.setResponseCode(respProps.getProperty("error-code", "0")); + respBuilder.setResponseMessage(respProps.getProperty("error-message", "")); + respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y")); + + } catch (Exception e) { + LOG.error("Caught exception executing directed graph for" + calledModule + ":" + calledRpc + "," + modeStr + + ">", e); + + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Internal error : caught exception executing directed graph " + calledModule + + "/" + calledRpc + "/" + modeStr); + respBuilder.setAckFinalIndicator("Y"); + + } + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + public ListenableFuture> vlbcheck(VlbcheckInput vlbInput) { + + RpcResult rpcResult = null; + SvcLogicService svcLogic = getSvcLogicService(); + + VlbcheckOutputBuilder respBuilder = new VlbcheckOutputBuilder(); + + String calledModule = "sli"; + String calledRpc = "vlbcheck"; + String modeStr = "sync"; + + if (svcLogic == null) { + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Could not locate OSGi SvcLogicService service"); + respBuilder.setAckFinalIndicator("Y"); + + rpcResult = RpcResultBuilder.failed().withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } + + boolean dgExists = true; + try { + if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) { + dgExists = false; + } + } catch (Exception e) { + LOG.warn( + "Caught exception looking for directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr, + e); + + dgExists = false; + } + + if (dgExists) { + try { + LOG.info("Calling directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr); + + Properties parms = new Properties(); + + Properties respProps = svcLogic.execute(calledModule, calledRpc, null, modeStr, parms); + + respBuilder.setResponseCode(respProps.getProperty("error-code", "0")); + respBuilder.setResponseMessage(respProps.getProperty("error-message", "")); + respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y")); + + } catch (Exception e) { + LOG.error("Caught exception executing directed graph for" + calledModule + ":" + calledRpc + "," + + modeStr + ">", e); + + respBuilder.setResponseCode("500"); + respBuilder.setResponseMessage("Internal error : caught exception executing directed graph " + + calledModule + "/" + calledRpc + "/" + modeStr); + respBuilder.setAckFinalIndicator("Y"); + + } + + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + return (Futures.immediateFuture(rpcResult)); + } else { + // check the state based on the config file + + boolean suspended = false; + BufferedReader br = null; + String line = ""; + + if (sdncStatusFile != null) { + try { + br = new BufferedReader(new FileReader(sdncStatusFile)); + while ((line = br.readLine()) != null) { + if ("ODL_STATE=SUSPENDED".equals(line)) { + suspended = true; + LOG.debug("vlbcheck: server is suspended"); + } + } + br.close(); + } catch (FileNotFoundException e) { + LOG.trace("Caught File not found exception " + sdncStatusFile + "\n", e); + } catch (Exception e) { + LOG.trace("Failed to read status file " + sdncStatusFile + "\n", e); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + LOG.warn("Failed to close status file " + sdncStatusFile + "\n", e); + } + } + } + } + + if (suspended) { + rpcResult = RpcResultBuilder.failed() + .withError(ErrorType.APPLICATION, "resource-denied", "Server Suspended").build(); + } else { + respBuilder.setResponseMessage("server is normal"); + rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); + } + return (Futures.immediateFuture(rpcResult)); + } + } + + private void DomSaveTestResult(final TestResult entry, boolean merge, LogicalDatastoreType storeType) { + + if (domDataBroker == null) { + LOG.error("domDataBroker unset - cannot save test result using DOMDataBroker"); + return; + } + + MapEntryNode resultNode = null; + + try { + resultNode = toMapEntryNode(entry); + } catch (Exception e) { + LOG.error("Caught exception trying to create map entry node", e); + } + + if (resultNode == null) { + LOG.error("Could not convert entry to MapEntryNode"); + return; + } + + YangInstanceIdentifier testResultsPid = YangInstanceIdentifier.builder().node(TEST_RESULTS_QNAME) + .node(QName.create(TEST_RESULTS_QNAME, "test-result")).build(); + YangInstanceIdentifier testResultPid = testResultsPid + .node(new NodeIdentifierWithPredicates(TEST_RESULT_QNAME, resultNode.getIdentifier().getKeyValues())); + + int tries = 2; + while (true) { + try { + DOMDataWriteTransaction wtx = domDataBroker.newWriteOnlyTransaction(); + if (merge) { + LOG.info("Merging test identifier " + entry.getTestIdentifier()); + wtx.merge(storeType, testResultPid, resultNode); + } else { + LOG.info("Putting test identifier " + entry.getTestIdentifier()); + wtx.put(storeType, testResultPid, resultNode); + } + wtx.submit().checkedGet(); + LOG.trace("Update DataStore succeeded"); + break; + } catch (final TransactionCommitFailedException e) { + if (e instanceof OptimisticLockFailedException) { + if (--tries <= 0) { + LOG.trace("Got OptimisticLockFailedException on last try - failing "); + throw new IllegalStateException(e); + } + LOG.trace("Got OptimisticLockFailedException - trying again "); + } else { + LOG.trace("Update DataStore failed"); + throw new IllegalStateException(e); + } + } + } + + } + + private void SaveTestResult(final TestResult entry, boolean merge, LogicalDatastoreType storeType) + throws IllegalStateException { + // Each entry will be identifiable by a unique key, we have to create that + // identifier + + InstanceIdentifier.InstanceIdentifierBuilder testResultIdBuilder = InstanceIdentifier + .builder(TestResults.class).child(TestResult.class, entry.key()); + InstanceIdentifier path = testResultIdBuilder.build(); + int tries = 2; + while (true) { + try { + WriteTransaction tx = dataBroker.newWriteOnlyTransaction(); + if (merge) { + tx.merge(storeType, path, entry); + } else { + tx.put(storeType, path, entry); + } + tx.submit().checkedGet(); + LOG.trace("Update DataStore succeeded"); + break; + } catch (final TransactionCommitFailedException e) { + if (e instanceof OptimisticLockFailedException) { + if (--tries <= 0) { + LOG.trace("Got OptimisticLockFailedException on last try - failing "); + throw new IllegalStateException(e); + } + LOG.trace("Got OptimisticLockFailedException - trying again "); + } else { + LOG.trace("Update DataStore failed"); + throw new IllegalStateException(e); + } + } + } + } + + private MapEntryNode toMapEntryNode(TestResult testResult) { + + YangInstanceIdentifier testResultId = YangInstanceIdentifier.builder().node(TEST_RESULTS_QNAME) + .node(TEST_RESULT_QNAME).build(); + + // Construct results list + LinkedList> entryList = new LinkedList<>(); + for (String result : testResult.getResults()) { + LeafSetEntryNode leafSetEntryNode = ImmutableLeafSetEntryNodeBuilder.create() + .withNodeIdentifier(new NodeWithValue(RESULTS_QNAME, result)).withValue(result).build(); + entryList.add(leafSetEntryNode); + } + // Construct results LeafSetNode + LeafSetNode resultsNode = ImmutableLeafSetNodeBuilder.create() + .withNodeIdentifier(new NodeIdentifier(RESULTS_QNAME)).withValue(entryList).build(); + + // Construct test result ContainerNode with 2 children - test-identifier leaf + // and results leaf-set + MapEntryNode testResultNode = ImmutableNodes.mapEntryBuilder() + .withNodeIdentifier(new NodeIdentifierWithPredicates(TEST_RESULT_QNAME, TEST_ID_QNAME, + testResult.getTestIdentifier())) + .withChild(ImmutableNodes.leafNode(TEST_ID_QNAME, testResult.getTestIdentifier())) + .withChild(resultsNode).build(); + + return (testResultNode); + + } + +} diff --git a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java b/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java deleted file mode 100644 index 20cbc2e0f..000000000 --- a/sliapi/provider/src/main/java/org/onap/ccsdk/sli/core/sliapi/sliapiProvider.java +++ /dev/null @@ -1,677 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP : CCSDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.sli.core.sliapi; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.Properties; -import java.util.concurrent.Future; - -import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService; -import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; -import org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedDataBroker; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException; -import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; -import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; -import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput.Mode; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphOutput; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.HealthcheckInput; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.HealthcheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.HealthcheckOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.SLIAPIService; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.TestResults; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.VlbcheckInput; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.VlbcheckOutput; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.VlbcheckOutputBuilder; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.execute.graph.input.SliParameter; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.test.results.TestResult; -import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.test.results.TestResultBuilder; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue; -import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode; -import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -/** - * Defines a base implementation for your provider. This class extends from a - * helper class which provides storage for the most commonly used components of - * the MD-SAL. Additionally the base class provides some basic logging and - * initialization / clean up methods. - * - * To use this, copy and paste (overwrite) the following method into the - * TestApplicationProviderModule class which is auto generated under - * src/main/java in this project (created only once during first compilation): - * - *
    - * 
    - * @Override
    - * public java.lang.AutoCloseable createInstance() {
    - * 
    - * 	final sliapiProvider provider = new sliapiProvider();
    - * 	provider.setDataBroker(getDataBrokerDependency());
    - * 	provider.setNotificationService(getNotificationServiceDependency());
    - * 	provider.setRpcRegistry(getRpcRegistryDependency());
    - * 	provider.initialize();
    - * 	return new AutoCloseable() {
    - * 
    - * 		@Override
    - * 		public void close() throws Exception {
    - * 			// TODO: CLOSE ANY REGISTRATION OBJECTS CREATED USING ABOVE
    - * 			// BROKER/NOTIFICATION
    - * 			// SERVIE/RPC REGISTRY
    - * 			provider.close();
    - * 		}
    - * 	};
    - * }
    - * 
    - * 
    - */ -public class sliapiProvider implements AutoCloseable, SLIAPIService { - - private static final Logger LOG = LoggerFactory.getLogger(sliapiProvider.class); - private static final String appName = "slitester"; - - protected DataBroker dataBroker; - protected DOMDataBroker domDataBroker; - protected NotificationPublishService notificationService; - protected RpcProviderRegistry rpcRegistry; - - private SvcLogicService svcLogic; - - protected BindingAwareBroker.RpcRegistration rpcRegistration; - - private static String SLIAPI_NAMESPACE = "org:onap:ccsdk:sli:core:sliapi"; - private static String SLIAPI_REVISION = "2016-11-10"; - private static String SDNC_STATUS_FILE = "SDNC_STATUS_FILE"; - private static String sdncStatusFile = null; - - private static QName TEST_RESULTS_QNAME = null; - private static QName TEST_RESULT_QNAME = null; - private static QName TEST_ID_QNAME = null; - private static QName RESULTS_QNAME = null; - private static final String NON_NULL = "non-null"; - - static { - - TEST_RESULTS_QNAME = QName.create(SLIAPI_NAMESPACE, SLIAPI_REVISION, "test-results"); - TEST_RESULT_QNAME = QName.create(TEST_RESULTS_QNAME, "test-result"); - TEST_ID_QNAME = QName.create(TEST_RESULT_QNAME, "test-identifier"); - RESULTS_QNAME = QName.create(TEST_RESULT_QNAME, "results"); - } - - public sliapiProvider(DataBroker dataBroker, NotificationPublishService notificationPublishService, - RpcProviderRegistry rpcProviderRegistry) { - this(dataBroker, notificationPublishService, rpcProviderRegistry, findSvcLogicService()); - } - - public sliapiProvider(DataBroker dataBroker, NotificationPublishService notificationPublishService, - RpcProviderRegistry rpcProviderRegistry, SvcLogicService svcLogic) { - this.LOG.info("Creating provider for " + appName); - this.dataBroker = dataBroker; - this.notificationService = notificationPublishService; - this.rpcRegistry = rpcProviderRegistry; - this.svcLogic = svcLogic; - initialize(); - } - - public void initialize() { - LOG.info("Initializing provider for " + appName); - // initialization code goes here. - rpcRegistration = rpcRegistry.addRpcImplementation(SLIAPIService.class, this); - - sdncStatusFile = System.getenv(SDNC_STATUS_FILE); - LOG.info("SDNC STATUS FILE = " + sdncStatusFile); - LOG.info("Initialization complete for " + appName); - } - - protected void initializeChild() { - // Override if you have custom initialization intelligence - } - - @Override - public void close() throws Exception { - LOG.info("Closing provider for " + appName); - // closing code goes here - - rpcRegistration.close(); - LOG.info("Successfully closed provider for " + appName); - } - - public void setDataBroker(DataBroker dataBroker) { - this.dataBroker = dataBroker; - if (dataBroker instanceof AbstractForwardedDataBroker) { - domDataBroker = ((AbstractForwardedDataBroker) dataBroker).getDelegate(); - } - if (LOG.isDebugEnabled()) { - LOG.debug("DataBroker set to " + (dataBroker == null ? "null" : NON_NULL) + "."); - } - } - - public void setNotificationService(NotificationPublishService notificationService) { - this.notificationService = notificationService; - if (LOG.isDebugEnabled()) { - LOG.debug("Notification Service set to " + (notificationService == null ? "null" : NON_NULL) + "."); - } - } - - public void setRpcRegistry(RpcProviderRegistry rpcRegistry) { - this.rpcRegistry = rpcRegistry; - if (LOG.isDebugEnabled()) { - LOG.debug("RpcRegistry set to " + (rpcRegistry == null ? "null" : NON_NULL) + "."); - } - } - - @Override - public ListenableFuture> executeGraph(ExecuteGraphInput input) { - RpcResult rpcResult = null; - - SvcLogicService svcLogic = getSvcLogicService(); - ExecuteGraphOutputBuilder respBuilder = new ExecuteGraphOutputBuilder(); - - String calledModule = input.getModuleName(); - String calledRpc = input.getRpcName(); - Mode calledMode = input.getMode(); - String modeStr = "sync"; - - if (calledMode == Mode.Async) { - modeStr = "async"; - } - - if (svcLogic == null) { - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Could not locate OSGi SvcLogicService service"); - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - try { - if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) { - respBuilder.setResponseCode("404"); - respBuilder.setResponseMessage( - "Directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr + " not found"); - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - } catch (Exception e) { - LOG.error( - "Caught exception looking for directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr, - e); - - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Internal error : could not determine if target graph exists"); - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - // Load properties - Properties parms = new Properties(); - - // Pass properties using names from sli-parameters - for (SliParameter sliParm : input.getSliParameter()) { - - String propValue = ""; - - Boolean boolval = sliParm.isBooleanValue(); - - if (boolval != null) { - propValue = boolval.toString(); - } else { - Integer intval = sliParm.getIntValue(); - if (intval != null) { - propValue = intval.toString(); - } else { - propValue = sliParm.getStringValue(); - if (propValue == null) { - propValue = ""; - } - } - } - parms.setProperty(sliParm.getParameterName(), propValue); - } - - // Also, pass "meta" properties (i.e. pass SliParameter objects themselves) - ExecuteGraphInputBuilder inputBuilder = new ExecuteGraphInputBuilder(input); - - SliapiHelper.toProperties(parms, "input", inputBuilder); - - try { - LOG.info("Calling directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr); - - if (LOG.isTraceEnabled()) { - StringBuffer argList = new StringBuffer(); - argList.append("Parameters : {"); - Enumeration e = parms.propertyNames(); - while (e.hasMoreElements()) { - String propName = (String) e.nextElement(); - argList.append(" (" + propName + "," + parms.getProperty(propName) + ") "); - } - argList.append("}"); - LOG.trace(argList.toString()); - argList = null; - } - - Properties respProps = svcLogic.execute(calledModule, calledRpc, null, modeStr, parms, domDataBroker); - - StringBuilder sb = new StringBuilder("{"); - - for (Object key : respProps.keySet()) { - String keyValue = (String) key; - if (keyValue != null && !"".equals(keyValue) && !keyValue.contains("input.sli-parameter")) { - sb.append("\"").append(keyValue).append("\": \"").append(respProps.getProperty(keyValue)) - .append("\","); - } - } - - sb.setLength(sb.length() - 1); - sb.append("}"); - - respBuilder.setResponseCode(respProps.getProperty("error-code", "0")); - respBuilder.setResponseMessage(respProps.getProperty("error-message", ""));// TODO change response-text to - // response-message to match - // other BVC APIs - respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y")); - respBuilder.setContextMemoryJson(sb.toString()); - - TestResultBuilder testResultBuilder = new TestResultBuilder(); - - SliapiHelper.toBuilder(respProps, testResultBuilder); - - String testIdentifier = testResultBuilder.getTestIdentifier(); - - if ((testIdentifier != null) && (testIdentifier.length() > 0)) { - - // Add test results to config tree - LOG.debug("Saving test results for test id " + testIdentifier); - - DomSaveTestResult(testResultBuilder.build(), true, LogicalDatastoreType.CONFIGURATION); - - } - - } catch (Exception e) { - LOG.error("Caught exception executing directed graph for" + calledModule + ":" + calledRpc + "," + modeStr - + ">", e); - - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Internal error : caught exception executing directed graph " + calledModule - + "/" + calledRpc + "/" + modeStr); - respBuilder.setAckFinalIndicator("Y"); - - } - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - private SvcLogicService getSvcLogicService() { - if (svcLogic == null) { - svcLogic = findSvcLogicService(); - } - - return (svcLogic); - } - - private static SvcLogicService findSvcLogicService() { - BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class).getBundleContext(); - - SvcLogicService svcLogic = null; - - // Get SvcLogicService reference - ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME); - if (sref != null) { - svcLogic = (SvcLogicService) bctx.getService(sref); - - } else { - LOG.warn("Cannot find service reference for " + SvcLogicService.NAME); - - } - - return (svcLogic); - } - - @Override - public ListenableFuture> healthcheck(HealthcheckInput healthcheckInput) { - - RpcResult rpcResult = null; - SvcLogicService svcLogic = getSvcLogicService(); - - HealthcheckOutputBuilder respBuilder = new HealthcheckOutputBuilder(); - - String calledModule = "sli"; - String calledRpc = "healthcheck"; - String modeStr = "sync"; - - if (svcLogic == null) { - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Could not locate OSGi SvcLogicService service"); - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.failed().withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - try { - if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) { - respBuilder.setResponseCode("404"); - respBuilder.setResponseMessage( - "Directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr + " not found"); - - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - } catch (Exception e) { - LOG.error( - "Caught exception looking for directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr, - e); - - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Internal error : could not determine if target graph exists"); - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.failed().withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - try { - LOG.info("Calling directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr); - - Properties parms = new Properties(); - - Properties respProps = svcLogic.execute(calledModule, calledRpc, null, modeStr, parms); - - respBuilder.setResponseCode(respProps.getProperty("error-code", "0")); - respBuilder.setResponseMessage(respProps.getProperty("error-message", "")); - respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y")); - - } catch (Exception e) { - LOG.error("Caught exception executing directed graph for" + calledModule + ":" + calledRpc + "," + modeStr - + ">", e); - - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Internal error : caught exception executing directed graph " + calledModule - + "/" + calledRpc + "/" + modeStr); - respBuilder.setAckFinalIndicator("Y"); - - } - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - public ListenableFuture> vlbcheck(VlbcheckInput vlbInput) { - - RpcResult rpcResult = null; - SvcLogicService svcLogic = getSvcLogicService(); - - VlbcheckOutputBuilder respBuilder = new VlbcheckOutputBuilder(); - - String calledModule = "sli"; - String calledRpc = "vlbcheck"; - String modeStr = "sync"; - - if (svcLogic == null) { - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Could not locate OSGi SvcLogicService service"); - respBuilder.setAckFinalIndicator("Y"); - - rpcResult = RpcResultBuilder.failed().withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } - - boolean dgExists = true; - try { - if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) { - dgExists = false; - } - } catch (Exception e) { - LOG.warn( - "Caught exception looking for directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr, - e); - - dgExists = false; - } - - if (dgExists) { - try { - LOG.info("Calling directed graph for " + calledModule + "/" + calledRpc + "/" + modeStr); - - Properties parms = new Properties(); - - Properties respProps = svcLogic.execute(calledModule, calledRpc, null, modeStr, parms); - - respBuilder.setResponseCode(respProps.getProperty("error-code", "0")); - respBuilder.setResponseMessage(respProps.getProperty("error-message", "")); - respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y")); - - } catch (Exception e) { - LOG.error("Caught exception executing directed graph for" + calledModule + ":" + calledRpc + "," - + modeStr + ">", e); - - respBuilder.setResponseCode("500"); - respBuilder.setResponseMessage("Internal error : caught exception executing directed graph " - + calledModule + "/" + calledRpc + "/" + modeStr); - respBuilder.setAckFinalIndicator("Y"); - - } - - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - return (Futures.immediateFuture(rpcResult)); - } else { - // check the state based on the config file - - boolean suspended = false; - BufferedReader br = null; - String line = ""; - - if (sdncStatusFile != null) { - try { - br = new BufferedReader(new FileReader(sdncStatusFile)); - while ((line = br.readLine()) != null) { - if ("ODL_STATE=SUSPENDED".equals(line)) { - suspended = true; - LOG.debug("vlbcheck: server is suspended"); - } - } - br.close(); - } catch (FileNotFoundException e) { - LOG.trace("Caught File not found exception " + sdncStatusFile + "\n", e); - } catch (Exception e) { - LOG.trace("Failed to read status file " + sdncStatusFile + "\n", e); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - LOG.warn("Failed to close status file " + sdncStatusFile + "\n", e); - } - } - } - } - - if (suspended) { - rpcResult = RpcResultBuilder.failed() - .withError(ErrorType.APPLICATION, "resource-denied", "Server Suspended").build(); - } else { - respBuilder.setResponseMessage("server is normal"); - rpcResult = RpcResultBuilder.status(true).withResult(respBuilder.build()).build(); - } - return (Futures.immediateFuture(rpcResult)); - } - } - - private void DomSaveTestResult(final TestResult entry, boolean merge, LogicalDatastoreType storeType) { - - if (domDataBroker == null) { - LOG.error("domDataBroker unset - cannot save test result using DOMDataBroker"); - return; - } - - MapEntryNode resultNode = null; - - try { - resultNode = toMapEntryNode(entry); - } catch (Exception e) { - LOG.error("Caught exception trying to create map entry node", e); - } - - if (resultNode == null) { - LOG.error("Could not convert entry to MapEntryNode"); - return; - } - - YangInstanceIdentifier testResultsPid = YangInstanceIdentifier.builder().node(TEST_RESULTS_QNAME) - .node(QName.create(TEST_RESULTS_QNAME, "test-result")).build(); - YangInstanceIdentifier testResultPid = testResultsPid - .node(new NodeIdentifierWithPredicates(TEST_RESULT_QNAME, resultNode.getIdentifier().getKeyValues())); - - int tries = 2; - while (true) { - try { - DOMDataWriteTransaction wtx = domDataBroker.newWriteOnlyTransaction(); - if (merge) { - LOG.info("Merging test identifier " + entry.getTestIdentifier()); - wtx.merge(storeType, testResultPid, resultNode); - } else { - LOG.info("Putting test identifier " + entry.getTestIdentifier()); - wtx.put(storeType, testResultPid, resultNode); - } - wtx.submit().checkedGet(); - LOG.trace("Update DataStore succeeded"); - break; - } catch (final TransactionCommitFailedException e) { - if (e instanceof OptimisticLockFailedException) { - if (--tries <= 0) { - LOG.trace("Got OptimisticLockFailedException on last try - failing "); - throw new IllegalStateException(e); - } - LOG.trace("Got OptimisticLockFailedException - trying again "); - } else { - LOG.trace("Update DataStore failed"); - throw new IllegalStateException(e); - } - } - } - - } - - private void SaveTestResult(final TestResult entry, boolean merge, LogicalDatastoreType storeType) - throws IllegalStateException { - // Each entry will be identifiable by a unique key, we have to create that - // identifier - - InstanceIdentifier.InstanceIdentifierBuilder testResultIdBuilder = InstanceIdentifier - .builder(TestResults.class).child(TestResult.class, entry.key()); - InstanceIdentifier path = testResultIdBuilder.build(); - int tries = 2; - while (true) { - try { - WriteTransaction tx = dataBroker.newWriteOnlyTransaction(); - if (merge) { - tx.merge(storeType, path, entry); - } else { - tx.put(storeType, path, entry); - } - tx.submit().checkedGet(); - LOG.trace("Update DataStore succeeded"); - break; - } catch (final TransactionCommitFailedException e) { - if (e instanceof OptimisticLockFailedException) { - if (--tries <= 0) { - LOG.trace("Got OptimisticLockFailedException on last try - failing "); - throw new IllegalStateException(e); - } - LOG.trace("Got OptimisticLockFailedException - trying again "); - } else { - LOG.trace("Update DataStore failed"); - throw new IllegalStateException(e); - } - } - } - } - - private MapEntryNode toMapEntryNode(TestResult testResult) { - - YangInstanceIdentifier testResultId = YangInstanceIdentifier.builder().node(TEST_RESULTS_QNAME) - .node(TEST_RESULT_QNAME).build(); - - // Construct results list - LinkedList> entryList = new LinkedList<>(); - for (String result : testResult.getResults()) { - LeafSetEntryNode leafSetEntryNode = ImmutableLeafSetEntryNodeBuilder.create() - .withNodeIdentifier(new NodeWithValue(RESULTS_QNAME, result)).withValue(result).build(); - entryList.add(leafSetEntryNode); - } - // Construct results LeafSetNode - LeafSetNode resultsNode = ImmutableLeafSetNodeBuilder.create() - .withNodeIdentifier(new NodeIdentifier(RESULTS_QNAME)).withValue(entryList).build(); - - // Construct test result ContainerNode with 2 children - test-identifier leaf - // and results leaf-set - MapEntryNode testResultNode = ImmutableNodes.mapEntryBuilder() - .withNodeIdentifier(new NodeIdentifierWithPredicates(TEST_RESULT_QNAME, TEST_ID_QNAME, - testResult.getTestIdentifier())) - .withChild(ImmutableNodes.leafNode(TEST_ID_QNAME, testResult.getTestIdentifier())) - .withChild(resultsNode).build(); - - return (testResultNode); - - } - -} diff --git a/sliapi/provider/src/main/resources/OSGI-INF/blueprint/sliapi-blueprint.xml b/sliapi/provider/src/main/resources/OSGI-INF/blueprint/sliapi-blueprint.xml new file mode 100644 index 000000000..875027e63 --- /dev/null +++ b/sliapi/provider/src/main/resources/OSGI-INF/blueprint/sliapi-blueprint.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml b/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml index 761b014a0..875027e63 100644 --- a/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml +++ b/sliapi/provider/src/main/resources/org/opendaylight/blueprint/sliapi-blueprint.xml @@ -19,7 +19,7 @@ interface="org.opendaylight.controller.sal.binding.api.RpcProviderRegistry" odl:type="default" /> - + diff --git a/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java b/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java index 0326429c9..c898ffffe 100644 --- a/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java +++ b/sliapi/provider/src/test/java/org/onap/ccsdk/sli/core/sliapi/TestSliapiProvider.java @@ -65,7 +65,7 @@ import org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.exe */ public class TestSliapiProvider { - private sliapiProvider provider; + private SliapiProvider provider; private static final String HEALTHCHECK_DG = "sli_healthcheck.xml"; @@ -129,8 +129,8 @@ public class TestSliapiProvider { svc.registerExecutor(nodeType, BUILTIN_NODES.get(nodeType)); } - // Finally ready to create sliapiProvider - provider = new sliapiProvider(dataBroker, notifyService, rpcRegistry, svc); + // Finally ready to create SliapiProvider + provider = new SliapiProvider(dataBroker, notifyService, rpcRegistry, svc); provider.setDataBroker(dataBroker); provider.setNotificationService(notifyService); provider.setRpcRegistry(rpcRegistry); @@ -146,7 +146,7 @@ public class TestSliapiProvider { /** * Test method for - * {@link org.onap.ccsdk.sli.core.sliapi.sliapiProvider#executeGraph(org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput)}. + * {@link SliapiProvider#executeGraph(org.opendaylight.yang.gen.v1.org.onap.ccsdk.sli.core.sliapi.rev161110.ExecuteGraphInput)}. */ @Test public void testExecuteGraph() { @@ -198,7 +198,7 @@ public class TestSliapiProvider { /** * Test method for - * {@link org.onap.ccsdk.sli.core.sliapi.sliapiProvider#healthcheck()}. + * {@link SliapiProvider#healthcheck()}. */ @Test public void testHealthcheck() { diff --git a/sliapi/provider/src/test/resources/simplelogger.properties b/sliapi/provider/src/test/resources/simplelogger.properties index 417c4d143..2f7d8ea0b 100644 --- a/sliapi/provider/src/test/resources/simplelogger.properties +++ b/sliapi/provider/src/test/resources/simplelogger.properties @@ -20,4 +20,4 @@ ### org.slf4j.simpleLogger.defaultLogLevel=info -org.slf4j.simplelogger.log.org.onap.ccsdk.sli.core.sliapi.sliapiProvider=debug +org.slf4j.simplelogger.log.org.onap.ccsdk.sli.core.sliapi.SliapiProvider=debug diff --git a/utils/features/ccsdk-slicore-utils/pom.xml b/utils/features/ccsdk-slicore-utils/pom.xml index fdeeb4412..71110f6b6 100644 --- a/utils/features/ccsdk-slicore-utils/pom.xml +++ b/utils/features/ccsdk-slicore-utils/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent single-feature-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core ccsdk-slicore-utils - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: utils :: ${project.artifactId} diff --git a/utils/features/features-util/pom.xml b/utils/features/features-util/pom.xml index c1e60c647..cc52237da 100644 --- a/utils/features/features-util/pom.xml +++ b/utils/features/features-util/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent feature-repo-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core features-util - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT feature ccsdk-sli-core :: utils :: ${project.artifactId} diff --git a/utils/features/pom.xml b/utils/features/pom.xml index 19279b3ff..e1528efb3 100755 --- a/utils/features/pom.xml +++ b/utils/features/pom.xml @@ -5,13 +5,12 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core utils-features-aggregator - 0.5.2-SNAPSHOT pom ccsdk-sli-core :: utils :: ${project.artifactId} diff --git a/utils/installer/pom.xml b/utils/installer/pom.xml index db0c505d1..02b824013 100755 --- a/utils/installer/pom.xml +++ b/utils/installer/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core utils-installer - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: utils :: ${project.artifactId} diff --git a/utils/pom.xml b/utils/pom.xml index 2b42734e0..f2bb15ca0 100755 --- a/utils/pom.xml +++ b/utils/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent odlparent-lite - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core utils - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT pom ccsdk-sli-core :: utils diff --git a/utils/provider/pom.xml b/utils/provider/pom.xml index 2b7799741..d65fa253f 100644 --- a/utils/provider/pom.xml +++ b/utils/provider/pom.xml @@ -5,13 +5,13 @@ org.onap.ccsdk.parent binding-parent - 1.3.3-SNAPSHOT + 1.4.0-SNAPSHOT org.onap.ccsdk.sli.core utils-provider - 0.5.2-SNAPSHOT + 0.6.0-SNAPSHOT bundle ccsdk-sli-core :: utils :: ${project.artifactId} diff --git a/version.properties b/version.properties index 6a35b9035..50be578e4 100644 --- a/version.properties +++ b/version.properties @@ -5,8 +5,8 @@ release_name=0 -sprint_number=5 -feature_revision=2 +sprint_number=6 +feature_revision=0 base_version=${release_name}.${sprint_number}.${feature_revision} -- cgit 1.2.3-korg From c9bf82b628b7d3f5f21f153538f950ac9a7d1294 Mon Sep 17 00:00:00 2001 From: "Smokowski, Kevin (ks6305)" Date: Thu, 17 Oct 2019 19:15:42 +0000 Subject: remove EncShellCommand remove EncShellCommand to separate dblib from karaf and odl Issue-ID: CCSDK-1848 Signed-off-by: Smokowski, Kevin (ks6305) Change-Id: If43abeceb556b4075d2866a18b8c9e92765e14a2 --- dblib/provider/pom.xml | 18 -------- .../sli/core/dblib/DBLIBResourceProvider.java | 49 ---------------------- .../onap/ccsdk/sli/core/dblib/EncShellCommand.java | 48 --------------------- .../OSGI-INF/blueprint/dblib-blueprint.xml | 6 --- .../ccsdk/sli/core/dblib/EncShellCommandTest.java | 41 ------------------ 5 files changed, 162 deletions(-) delete mode 100755 dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java delete mode 100644 dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java (limited to 'dblib/provider/src') diff --git a/dblib/provider/pom.xml b/dblib/provider/pom.xml index a3bd00f3a..0af382506 100755 --- a/dblib/provider/pom.xml +++ b/dblib/provider/pom.xml @@ -15,11 +15,6 @@ bundle ccsdk-sli-core :: dblib :: ${project.artifactId} - http://maven.apache.org - - - UTF-8 - @@ -32,19 +27,10 @@ mariaDB4j test - - org.osgi - org.osgi.core - provided - org.slf4j slf4j-api - - org.slf4j - jcl-over-slf4j - org.slf4j slf4j-simple @@ -74,9 +60,5 @@ mockito-core test - - org.apache.karaf.shell - org.apache.karaf.shell.console - 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 index 6d36d6389..45e5a7870 100755 --- 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 @@ -23,19 +23,14 @@ package org.onap.ccsdk.sli.core.dblib; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.lang.reflect.Method; import java.util.Optional; import java.util.Properties; import java.util.Vector; - import org.onap.ccsdk.sli.core.utils.JREFileResolver; import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -99,20 +94,6 @@ public class DBLIBResourceProvider { try(FileInputStream fileInputStream = new FileInputStream(propertiesFile)) { properties = new Properties(); properties.load(fileInputStream); - - if(properties.containsKey(DBLIB_PROPERTY_NAME)) { - String sensitive = properties.getProperty(DBLIB_PROPERTY_NAME); - if(sensitive != null && sensitive.startsWith("ENC:")) { - try { - sensitive = sensitive.substring(4); - String postsense = decrypt(sensitive); - properties.setProperty(DBLIB_PROPERTY_NAME, postsense); - } catch(Exception exc) { - LOG.error("Failed to translate property", exc); - } - } - } - } catch (final IOException e) { LOG.error("Failed to load properties for file: {}", propertiesFile.toString(), new DblibConfigurationException("Failed to load properties for file: " @@ -121,36 +102,6 @@ public class DBLIBResourceProvider { } } - /** - * - * @param value - * @return decrypted string if successful or the original value if unsuccessful - */ - private String decrypt(String value) { - try { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - - ServiceReference sref = bctx.getServiceReference("org.opendaylight.aaa.encrypt.AAAEncryptionService"); - if(sref == null) { - LOG.warn("Could not acquire service reference for 'org.opendaylight.aaa.encrypt.AAAEncryptionService'"); - return value; - } - Object encrSvc = bctx.getService(sref); - if(encrSvc == null) { - LOG.warn("Could not access service for 'org.opendaylight.aaa.encrypt.AAAEncryptionService'"); - return value; - } - - Method gs2Method = encrSvc.getClass().getMethod("decrypt", new Class[] { "".getClass() }); - Object unmasked = gs2Method.invoke(encrSvc, new Object[] { value }); - return unmasked.toString(); - - } catch (Exception exc) { - LOG.error("Failure", exc); - return value; - } - } - /** * Extract db config properties. * diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java deleted file mode 100755 index eaa5700c9..000000000 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/EncShellCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.onap.ccsdk.sli.core.dblib; - -import java.lang.reflect.Method; - -/** - * https://karaf.apache.org/manual/latest-2.x/developers-guide/extending-console.html - * https://github.com/apache/karaf/tree/master/shell/console/src/main/java/org/apache/felix/gogo/commands - */ -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Command(scope = "dblib", name = "encode", description="Says hello") -public class EncShellCommand extends OsgiCommandSupport { - private static Logger LOGGER = LoggerFactory.getLogger(EncShellCommand.class); - - @Argument(index = 0, name = "arg", description = "The command argument", required = true, multiValued = false) - String arg = null; - - @Override - protected Object doExecute() throws Exception { - System.out.println(String.format("Original value: %s", arg)); - System.out.println(String.format("Encrypted value: %s", encrypt(arg))); - return null; - } - - private String encrypt(String value) { - try { - BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - - ServiceReference sref = bctx.getServiceReference("org.opendaylight.aaa.encrypt.AAAEncryptionService"); - Object encrSvc = bctx.getService(sref); - - Method gs2Method = encrSvc.getClass().getMethod("encrypt", new Class[] { "".getClass() }); - Object unmasked = gs2Method.invoke(encrSvc, new Object[] { value }); - return String.format("ENC:%s", unmasked.toString()); - - } catch (Exception exc) { - LOGGER.error("Failure", exc); - return value; - } - } -} \ No newline at end of file diff --git a/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml b/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml index d9bb99c07..f1d5166db 100755 --- a/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml +++ b/dblib/provider/src/main/resources/OSGI-INF/blueprint/dblib-blueprint.xml @@ -15,10 +15,4 @@ - - - - - - \ No newline at end of file diff --git a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java b/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java deleted file mode 100644 index 740e69dba..000000000 --- a/dblib/provider/src/test/java/org/onap/ccsdk/sli/core/dblib/EncShellCommandTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.onap.ccsdk.sli.core.dblib; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.Arrays; - -import static org.junit.Assert.*; - -public class EncShellCommandTest { - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - private final PrintStream originalOut = System.out; - private final PrintStream originalErr = System.err; - - @Before - public void setUp() { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - } - - @After - public void tearDown() { - System.setOut(originalOut); - System.setErr(originalErr); - } - - @Test - public void testDoExecute() throws Exception { - String expected = "Original value: test" + System.getProperty("line.separator") + - "Encrypted value: test"; - EncShellCommand encShellCommand = new EncShellCommand(); - encShellCommand.arg = "test"; - encShellCommand.doExecute(); - assertEquals(expected.trim(), outContent.toString().trim()); - } -} \ No newline at end of file -- cgit 1.2.3-korg From deac6fe2a23859c5cf9cf8c828045af5eff78868 Mon Sep 17 00:00:00 2001 From: "Agarwal, Ruchira (ra1926)" Date: Tue, 5 Nov 2019 19:50:30 +0000 Subject: minor updates to clean up code clean up code to sync with internal Issue-ID: CCSDK-1873 Signed-off-by: Agarwal, Ruchira (ra1926) Change-Id: I1043e3f34176aebf2531bf0581b207694264d6f2 --- .../onap/ccsdk/sli/core/dblib/config/DbConfigPool.java | 11 +++++++++-- .../org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java | 17 ++++++++++++----- 2 files changed, 21 insertions(+), 7 deletions(-) (limited to 'dblib/provider/src') diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java index 6cb1d9c33..ea7b3fdc8 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/config/DbConfigPool.java @@ -27,14 +27,21 @@ import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * @version $Revision: 1.15 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ public class DbConfigPool { - private static Logger log = LoggerFactory.getLogger(DbConfigPool.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DbConfigPool.class); private final String type; private static final int timeOut=0; private ArrayList configurations = new ArrayList<>(); public DbConfigPool(Properties properties) { - log.debug("Initializing DbConfigType"); + LOGGER.debug("Initializing DbConfigType"); type = properties.getProperty(BaseDBConfiguration.DATABASE_TYPE, "JDBC").toUpperCase(); } diff --git a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java index 454af02bb..f66250676 100644 --- a/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java +++ b/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java @@ -34,9 +34,16 @@ import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * @version $Revision: 1.15 $ + * Change Log + * Author Date Comments + * ============== ======== ==================================================== + * Rich Tabedzki + */ public class PollingWorker implements Runnable { - private Logger logger = LoggerFactory.getLogger(PollingWorker.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PollingWorker.class); private static PollingWorker self = null; @@ -116,7 +123,7 @@ public class PollingWorker implements Runnable { consume((TestSample) next); } else { System.out.println(next.getClass().getName()); - logger.error(next.getClass().getName()); + LOGGER.error(next.getClass().getName()); } } try { @@ -152,7 +159,7 @@ public class PollingWorker implements Runnable { } sb.append(tmp2[i].get()).append("\t"); } - logger.info(sb.toString()); + LOGGER.info(sb.toString()); } class MyTimerTask extends TimerTask { @@ -191,8 +198,8 @@ public class PollingWorker implements Runnable { } /** - * @author Rich Tabedzki A helper class to pass measured parameter to the - * counter. + * @author Rich Tabedzki + * A helper class to pass measured parameter to the counter. */ static class TestSample implements Comparable { private long starttime; -- cgit 1.2.3-korg