diff options
author | Dan Timoney <dtimoney@att.com> | 2017-12-05 11:50:42 -0500 |
---|---|---|
committer | Dan Timoney <dtimoney@att.com> | 2017-12-05 11:50:42 -0500 |
commit | 13cbc4e6633e4cef9cc33d10c11b9b177213acd9 (patch) | |
tree | 1ef5785a6355f9491d7f2f9cf8fcbfaea3e66d40 | |
parent | 7cb74a4e851ae85ffa8c7cd1ebe94007418b816c (diff) |
SLI parser improvements
Update SLI parser to remove validation based on NODE_TYPE table, which
is no longer needed (was introduced prior to use of XSD schema
validation). Also, use checksums to avoid needless recompilation
if version being loaded already exists in database.
Change-Id: Idfcba94de8fb71b17d5e0c5e69e04dee266988b1
Issue-ID: CCSDK-152
Signed-off-by: Dan Timoney <dtimoney@att.com>
13 files changed, 1170 insertions, 1189 deletions
diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ActivationEntry.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ActivationEntry.java new file mode 100644 index 00000000..a1c0eafe --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/ActivationEntry.java @@ -0,0 +1,41 @@ +/*- + * ============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.onap.ccsdk.sli.core.sli; + +public class ActivationEntry { + String module; + String rpc; + String version; + String mode; + + public ActivationEntry(String module, String rpc, String version, String mode) { + this.module = module; + this.rpc = rpc; + this.version = version; + this.mode = mode; + } + + @Override + public String toString() { + return "ActivationEntry [module=" + module + ", rpc=" + rpc + ", version=" + version + ", mode=" + mode + "]"; + } +} diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/CheckSumHelper.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/CheckSumHelper.java new file mode 100644 index 00000000..d6ad0742 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/CheckSumHelper.java @@ -0,0 +1,45 @@ +/*- + * ============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.onap.ccsdk.sli.core.sli; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +public class CheckSumHelper { + + public static String md5SumFromFile(String pathToFile) throws NoSuchAlgorithmException, IOException { + byte[] b = Files.readAllBytes(Paths.get(pathToFile)); + return md5SumFromByteArray(b); + } + + private static String md5SumFromByteArray(byte[] input) throws NoSuchAlgorithmException { + byte[] hash = MessageDigest.getInstance("MD5").digest(input); + String hexString = DatatypeConverter.printHexBinary(hash); + return hexString.toLowerCase(); + } + +} 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 index 0f6ae673..79989b51 100644 --- 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 @@ -295,7 +295,13 @@ public class MetricLogger { setResponseCode(responseCode); setResponseDescription(responseDescription); - METRIC.info(lastMsg); + METRIC.info(formatString(lastMsg)); } + + protected String formatString(String str) { + str = str.replaceAll("\\R",""); // this will strip all new line characters + str = str.replaceAll("\\|","%7C"); //log records should not contain a pipe, encode the pipe character + return str; + } } diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicCrawler.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicCrawler.java new file mode 100644 index 00000000..5ee138a3 --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicCrawler.java @@ -0,0 +1,90 @@ +/*- + * ============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.onap.ccsdk.sli.core.sli; + +import static java.nio.file.FileVisitResult.CONTINUE; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; + +public class SvcLogicCrawler extends SimpleFileVisitor<Path> { + + private List<Path> xmlGraphPathList; + private List<Path> activationFilePathList; + + public SvcLogicCrawler() { + xmlGraphPathList = new ArrayList<Path>(); + activationFilePathList = new ArrayList<Path>(); + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attr) { + if (attr.isRegularFile()) { + String fileName = file.getFileName().toString(); + if (!file.toString().contains(".git") && !fileName.equals("pom.xml") && !fileName.equals("assemble_zip.xml") && !fileName.equals("assemble_zip_less_config.xml") && !fileName.equals("descriptor.xml")) { + if (fileName.endsWith(".xml")) { + xmlGraphPathList.add(file); + } + else if (fileName.endsWith(".versions")) { + activationFilePathList.add(file); + } + } + } + return CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) { + return CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + System.err.println("Couldn't visitFile"); + System.err.println(exc.getMessage()); + return CONTINUE; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + String[] skipDirectories = {".git"}; + for (String str : skipDirectories) { + if (dir.endsWith(str)) { + return FileVisitResult.SKIP_SUBTREE; + } + } + return CONTINUE; + } + + public List<Path> getGraphPaths() { + return this.xmlGraphPathList; + } + + public List<Path> getActivationPaths() { + return this.activationFilePathList; + } +} 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 ab5773c0..74fa1dd6 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 @@ -326,80 +326,6 @@ public class SvcLogicDblibStore implements SvcLogicStore { } } - @Override - public void registerNodeType(String nodeType) throws SvcLogicException { - - String registerNodeSql = "INSERT INTO NODE_TYPES (nodetype) VALUES(?)"; - - if (isValidNodeType(nodeType)) { - return; - } - - DbLibService dbSvc = getDbLibService(); - ArrayList<String> 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<String> 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<String> args = new ArrayList<>(); - - args.add(nodeType); - - boolean isValid = false; - - try (CachedRowSet results = dbSvc.getData(validateNodeSql, args, null)) { - - if (results != null && 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); - } - - return isValid; - } - private DbLibService getDbLibService() { // Get DbLibService interface object. @@ -490,4 +416,31 @@ public class SvcLogicDblibStore implements SvcLogicStore { INSTANCE = dbresource; } } + + @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 = ?"; + + String activateSql = "UPDATE SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND mode = ? AND version = ?"; + + ArrayList<String> args = new ArrayList<String>(); + + args.add(module); + args.add(rpc); + args.add(mode); + + try { + + dbSvc.writeData(deactivateSql, args, null); + + args.add(version); + dbSvc.writeData(activateSql, args, null); + + } catch (Exception e) { + throw new SvcLogicException("Could not activate graph", e); + } + } + } 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 index 35486eba..cbac1544 100644 --- 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 @@ -37,7 +37,9 @@ public class SvcLogicGraph implements Serializable { private String rpc = null; private String mode = null; private String version = null; - + + private String md5sum = null; + private Map<String, Serializable> attributes; private Map<String, SvcLogicNode> namedNodes; private SvcLogicNode rootNode; @@ -48,6 +50,16 @@ public class SvcLogicGraph implements Serializable { namedNodes = new HashMap<String, SvcLogicNode>(); rootNode = null; } + + public String getMd5sum() { + return md5sum; + } + + + public void setMd5sum(String md5sum) { + this.md5sum = md5sum; + } + public String getModule() { @@ -178,7 +190,7 @@ public class SvcLogicGraph implements Serializable { @Override public String toString() { - return "SvcLogicGraph [module=" + module + ", rpc=" + rpc + ", mode=" + mode + ", version=" + version + "]"; + return "SvcLogicGraph [module=" + module + ", rpc=" + rpc + ", mode=" + mode + ", version=" + version + ", md5sum=" + md5sum + "]"; } } 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 1e4b71cd..e2fbdf72 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 @@ -35,109 +35,90 @@ 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 org.mariadb.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; - - 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. + 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 org.mariadb.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; + + 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 - { + try { - ResultSet tables = dbm.getTables(null, null, "SVC_LOGIC", null); - if (tables.next()) { + 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))"; + } 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 - { + } + } catch (Exception e) { + throw new ConfigurationException("could not create SVC_LOGIC table", e); + } finally { if (stmt != null) { try { stmt.close(); @@ -147,31 +128,24 @@ public class SvcLogicJdbcStore implements SvcLogicStore { } } - // See if NODE_TYPES table exists and, if not, create it + // See if NODE_TYPES table exists and, if not, create it stmt = null; - try - { + try { - ResultSet tables = dbm.getTables(null, null, "NODE_TYPES", null); - if (tables.next()) { + 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))"; + } 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 - { + } + } catch (Exception e) { + throw new ConfigurationException("could not create SVC_LOGIC table", e); + } finally { if (stmt != null) { try { stmt.close(); @@ -180,652 +154,444 @@ public class SvcLogicJdbcStore implements SvcLogicStore { } } } - } - - private void prepStatements() throws ConfigurationException - { - - // Prepare statements - String hasVersionGraphSql = CommonConstants.JDBC_SELECT_COUNT + dbName + CommonConstants.SVCLOGIC_TABLE - + CommonConstants.JDBC_GRAPH_QUERY; - - try - { - hasVersionGraphStmt = dbConn.prepareStatement(hasVersionGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + hasVersionGraphSql, e); - - } - - String hasActiveGraphSql = CommonConstants.JDBC_SELECT_COUNT + dbName + CommonConstants.SVCLOGIC_TABLE - + CommonConstants.JDBC_ACTIVE_GRAPH_QUERY; - - try - { - hasActiveGraphStmt = dbConn.prepareStatement(hasActiveGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + hasVersionGraphSql, e); - - } - - String fetchVersionGraphSql = CommonConstants.JDBC_SELECT_GRAPGH + dbName+CommonConstants.SVCLOGIC_TABLE - + CommonConstants.JDBC_GRAPH_QUERY; - - try - { - fetchVersionGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + fetchVersionGraphSql, e); - - } - - String fetchActiveGraphSql = CommonConstants.JDBC_SELECT_GRAPGH + dbName + CommonConstants.SVCLOGIC_TABLE - + CommonConstants.JDBC_ACTIVE_GRAPH_QUERY; - - try - { - fetchActiveGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + fetchVersionGraphSql, e); - - } - - String storeGraphSql = CommonConstants.JDBC_INSERT+dbName - + ".SVC_LOGIC (module, rpc, version, mode, active, graph) VALUES(?, ?, ?, ?, ?, ?)"; - - try - { - storeGraphStmt = dbConn.prepareStatement(storeGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + storeGraphSql, e); - } - - String deleteGraphSql = CommonConstants.JDBC_DELETE+dbName - + ".SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; - - try - { - deleteGraphStmt = dbConn.prepareStatement(deleteGraphSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + deleteGraphSql, e); - } - - String deactivateSql = CommonConstants.JDBC_UPDATE + dbName - +".SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; - - try - { - deactivateStmt = dbConn.prepareStatement(deactivateSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + deactivateSql, e); - } - - String activateSql = CommonConstants.JDBC_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(CommonConstants.JDBC_STATEMENT_ERR + activateSql, e); - } - - String registerNodeSql = CommonConstants.JDBC_INSERT + dbName + ".NODE_TYPES (nodetype) VALUES(?)"; - try - { - registerNodeStmt = dbConn.prepareStatement(registerNodeSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + registerNodeSql, e); - } - - String unregisterNodeSql = CommonConstants.JDBC_DELETE + dbName + ".NODE_TYPES WHERE nodetype = ?"; - try - { - unregisterNodeStmt = dbConn.prepareStatement(unregisterNodeSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + unregisterNodeSql, e); - } - - String validateNodeSql = CommonConstants.JDBC_SELECT_COUNT + dbName + ".NODE_TYPES WHERE nodetype = ?"; - try - { - validateNodeStmt = dbConn.prepareStatement(validateNodeSql); - } - catch (Exception e) - { - throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + 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(); - } - - - @Override - public void init(Properties props) throws ConfigurationException { - - - dbUrl = props.getProperty("org.onap.ccsdk.sli.jdbc.url"); - if ((dbUrl == null) || (dbUrl.length() == 0)) - { - throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.url unset"); - } - - dbName = props.getProperty("org.onap.ccsdk.sli.jdbc.database"); - if ((dbName == null) || (dbName.length() == 0)) - { - throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.database unset"); - } - - dbUser = props.getProperty("org.onap.ccsdk.sli.jdbc.user"); - if ((dbUser == null) || (dbUser.length() == 0)) - { - throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.user unset"); - } - - - dbPasswd = props.getProperty("org.onap.ccsdk.sli.jdbc.password"); - if ((dbPasswd == null) || (dbPasswd.length() == 0)) - { - throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.password unset"); - } - - dbDriver = props.getProperty("org.onap.ccsdk.sli.jdbc.driver"); - - - initDbResources(); - - } - - private boolean isDbConnValid() - { - - boolean isValid = false; - - try - { - if (dbConn != null) - { - isValid = dbConn.isValid(1); - } - } - catch (SQLException e) - { - LOG.error("Not a valid db connection: ", e); - } - - return isValid; - } - - @Override - public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); - } - } - - boolean retval = false; - ResultSet results = null; - - PreparedStatement hasGraphStmt; - 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) - { - LOG.error(CommonConstants.RESULTSET_CLOSE_ERR, x); - } - } - - } - - return retval; - - } - - @Override - public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException { - - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); - } - } - - SvcLogicGraph retval = null; - ResultSet results = null; - - PreparedStatement fetchGraphStmt; - 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()); - - } - } - - } - catch (Exception e) - { - throw new ConfigurationException("SQL query failed", e); - } - finally - { - if (results != null) - { - try - { - results.close(); - } - catch (SQLException x) - { - LOG.error(CommonConstants.RESULTSET_CLOSE_ERR, x); - } - } - - } - - return retval; - } - - public void store(SvcLogicGraph graph) throws SvcLogicException { - - - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); - } - } - - if (graph == null) - { - throw new SvcLogicException("graph cannot be null"); - } - - byte[] graphBytes; - - try (ByteArrayOutputStream byteStr = new ByteArrayOutputStream(); - ObjectOutputStream goutStr = new ObjectOutputStream(byteStr)) - { - - goutStr.writeObject(graph); - - graphBytes = byteStr.toByteArray(); - - } - catch (Exception e) - { - throw new SvcLogicException("could not serialize graph", 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); - } - } - - @Override - public void delete(String module, String rpc, String version, String mode) throws SvcLogicException - { - if (!isDbConnValid()) - { - - // Try reinitializing - initDbResources(); - - if (!isDbConnValid()) - { - throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); - } - } - - 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); - } - } - - @Override - 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(CommonConstants.JDBC_CONN_ERR); - } - } - - 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(CommonConstants.JDBC_CONN_ERR); - } - } - - 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(CommonConstants.JDBC_CONN_ERR); - } - } - - 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.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) - { - LOG.error(CommonConstants.RESULTSET_CLOSE_ERR, x); - } - } - - } - - return(isValid); - } + } + + private void prepStatements() throws ConfigurationException { + + // Prepare statements + String hasVersionGraphSql = CommonConstants.JDBC_SELECT_COUNT + dbName + CommonConstants.SVCLOGIC_TABLE + + CommonConstants.JDBC_GRAPH_QUERY; + + try { + hasVersionGraphStmt = dbConn.prepareStatement(hasVersionGraphSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + hasVersionGraphSql, e); + + } + + String hasActiveGraphSql = CommonConstants.JDBC_SELECT_COUNT + dbName + CommonConstants.SVCLOGIC_TABLE + + CommonConstants.JDBC_ACTIVE_GRAPH_QUERY; + + try { + hasActiveGraphStmt = dbConn.prepareStatement(hasActiveGraphSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + hasVersionGraphSql, e); + + } + + String fetchVersionGraphSql = CommonConstants.JDBC_SELECT_GRAPGH + dbName + CommonConstants.SVCLOGIC_TABLE + + CommonConstants.JDBC_GRAPH_QUERY; + + try { + fetchVersionGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + fetchVersionGraphSql, e); + + } + + String fetchActiveGraphSql = CommonConstants.JDBC_SELECT_GRAPGH + dbName + CommonConstants.SVCLOGIC_TABLE + + CommonConstants.JDBC_ACTIVE_GRAPH_QUERY; + + try { + fetchActiveGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + fetchVersionGraphSql, e); + + } + + String storeGraphSql = CommonConstants.JDBC_INSERT + dbName + + ".SVC_LOGIC (module, rpc, version, mode, active, graph) VALUES(?, ?, ?, ?, ?, ?)"; + + try { + storeGraphStmt = dbConn.prepareStatement(storeGraphSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + storeGraphSql, e); + } + + String deleteGraphSql = CommonConstants.JDBC_DELETE + dbName + + ".SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?"; + + try { + deleteGraphStmt = dbConn.prepareStatement(deleteGraphSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + deleteGraphSql, e); + } + + String deactivateSql = CommonConstants.JDBC_UPDATE + dbName + + ".SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?"; + + try { + deactivateStmt = dbConn.prepareStatement(deactivateSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + deactivateSql, e); + } + + String activateSql = CommonConstants.JDBC_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(CommonConstants.JDBC_STATEMENT_ERR + activateSql, e); + } + + String registerNodeSql = CommonConstants.JDBC_INSERT + dbName + ".NODE_TYPES (nodetype) VALUES(?)"; + try { + registerNodeStmt = dbConn.prepareStatement(registerNodeSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + registerNodeSql, e); + } + + String unregisterNodeSql = CommonConstants.JDBC_DELETE + dbName + ".NODE_TYPES WHERE nodetype = ?"; + try { + unregisterNodeStmt = dbConn.prepareStatement(unregisterNodeSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + unregisterNodeSql, e); + } + + String validateNodeSql = CommonConstants.JDBC_SELECT_COUNT + dbName + ".NODE_TYPES WHERE nodetype = ?"; + try { + validateNodeStmt = dbConn.prepareStatement(validateNodeSql); + } catch (Exception e) { + throw new ConfigurationException(CommonConstants.JDBC_STATEMENT_ERR + 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(); + } + + + @Override + public void init(Properties props) throws ConfigurationException { + + + dbUrl = props.getProperty("org.onap.ccsdk.sli.jdbc.url"); + if ((dbUrl == null) || (dbUrl.length() == 0)) { + throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.url unset"); + } + + dbName = props.getProperty("org.onap.ccsdk.sli.jdbc.database"); + if ((dbName == null) || (dbName.length() == 0)) { + throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.database unset"); + } + + dbUser = props.getProperty("org.onap.ccsdk.sli.jdbc.user"); + if ((dbUser == null) || (dbUser.length() == 0)) { + throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.user unset"); + } + + + dbPasswd = props.getProperty("org.onap.ccsdk.sli.jdbc.password"); + if ((dbPasswd == null) || (dbPasswd.length() == 0)) { + throw new ConfigurationException("property org.onap.ccsdk.sli.jdbc.password unset"); + } + + dbDriver = props.getProperty("org.onap.ccsdk.sli.jdbc.driver"); + + + initDbResources(); + + } + + private boolean isDbConnValid() { + + boolean isValid = false; + + try { + if (dbConn != null) { + isValid = dbConn.isValid(1); + } + } catch (SQLException e) { + LOG.error("Not a valid db connection: ", e); + } + + return isValid; + } + + @Override + public boolean hasGraph(String module, String rpc, String version, String mode) throws SvcLogicException { + + if (!isDbConnValid()) { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) { + throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); + } + } + + boolean retval = false; + ResultSet results = null; + + PreparedStatement hasGraphStmt; + 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) { + LOG.error(CommonConstants.RESULTSET_CLOSE_ERR, x); + } + } + + } + + return retval; + + } + + @Override + public SvcLogicGraph fetch(String module, String rpc, String version, String mode) throws SvcLogicException { + + + if (!isDbConnValid()) { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) { + throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); + } + } + + SvcLogicGraph retval = null; + ResultSet results = null; + + PreparedStatement fetchGraphStmt; + 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()); + + } + } + + } catch (Exception e) { + throw new ConfigurationException("SQL query failed", e); + } finally { + if (results != null) { + try { + results.close(); + } catch (SQLException x) { + LOG.error(CommonConstants.RESULTSET_CLOSE_ERR, x); + } + } + + } + + return retval; + } + + public void store(SvcLogicGraph graph) throws SvcLogicException { + + + if (!isDbConnValid()) { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) { + throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); + } + } + + if (graph == null) { + throw new SvcLogicException("graph cannot be null"); + } + + byte[] graphBytes; + + try (ByteArrayOutputStream byteStr = new ByteArrayOutputStream(); + ObjectOutputStream goutStr = new ObjectOutputStream(byteStr)) { + + goutStr.writeObject(graph); + + graphBytes = byteStr.toByteArray(); + + } catch (Exception e) { + throw new SvcLogicException("could not serialize graph", 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); + } + } + + @Override + public void delete(String module, String rpc, String version, String mode) throws SvcLogicException { + if (!isDbConnValid()) { + + // Try reinitializing + initDbResources(); + + if (!isDbConnValid()) { + throw new ConfigurationException(CommonConstants.JDBC_CONN_ERR); + } + } + + 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); + } + } + + @Override + 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 activate(String module, String rpc, String version, String mode) throws SvcLogicException { + try { + boolean oldAutoCommit = dbConn.getAutoCommit(); + + dbConn.setAutoCommit(false); + + // Deactivate any current active version + deactivateStmt.setString(1, module); + deactivateStmt.setString(2, rpc); + deactivateStmt.setString(3, mode); + deactivateStmt.executeUpdate(); + + // Activate this version + activateStmt.setString(1, module); + activateStmt.setString(2, rpc); + activateStmt.setString(3, version); + activateStmt.setString(4, mode); + activateStmt.executeUpdate(); + + dbConn.commit(); + + dbConn.setAutoCommit(oldAutoCommit); + + } catch (Exception e) { + throw new SvcLogicException("Could not activate graph", e); + } + } + } diff --git a/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicLoader.java b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicLoader.java new file mode 100644 index 00000000..bc8c1bdf --- /dev/null +++ b/sli/common/src/main/java/org/onap/ccsdk/sli/core/sli/SvcLogicLoader.java @@ -0,0 +1,168 @@ +/*- + * ============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.onap.ccsdk.sli.core.sli; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SvcLogicLoader { + private static final Logger LOGGER = LoggerFactory.getLogger(SvcLogicLoader.class); + SvcLogicStore store; + String directoryRoot; + String propFile; + + public SvcLogicLoader(String directoryRoot, String propFile) { + store = SvcLogicParser.getStore(propFile); + this.directoryRoot = directoryRoot; + this.propFile = propFile; + } + + public void loadAndActivate() throws IOException { + SvcLogicCrawler slc = new SvcLogicCrawler(); + Files.walkFileTree(Paths.get(this.directoryRoot), slc); + + loadGraphs(slc.getGraphPaths(), directoryRoot); + + List<ActivationEntry> activationEntries = processActivationFiles(slc.getActivationPaths()); + activateGraphs(activationEntries); + } + + private List<ActivationEntry> processActivationFiles(List<Path> activationPaths) { + List<ActivationEntry> activationEntries = new ArrayList<ActivationEntry>(); + for (Path activationFile : activationPaths) { + activationEntries.addAll(getActivationEntries(activationFile)); + } + return activationEntries; + + } + + private void activateGraphs(List<ActivationEntry> activationEntries) { + for (ActivationEntry entry : activationEntries) { + try { + if (store.hasGraph(entry.module, entry.rpc, entry.version, entry.mode)) { + store.activate(entry.module, entry.rpc, entry.version, entry.mode); + } else { + LOGGER.error("hasGraph returned false for " + entry.toString()); + } + } catch (SvcLogicException e) { + LOGGER.error("Failed to call hasGraph for " + entry.toString(), e); + } + } + } + + protected List<ActivationEntry> getActivationEntries(Path activationFilePath) { + List<ActivationEntry> activationEntries = new ArrayList<>(); + int lineNumber = 1; + try (BufferedReader br = Files.newBufferedReader(activationFilePath, StandardCharsets.US_ASCII)) { + String fileRead = br.readLine(); + while (fileRead != null) { + String[] fields = fileRead.split("\\s"); + if (fields.length == 4) { + activationEntries.add(parseActivationEntry(fields)); + } else { + LOGGER.error("Activation entry [" + fileRead + "] is declared at line number " + lineNumber + " in the file " + activationFilePath + " and is invalid."); + } + fileRead = br.readLine(); + lineNumber++; + } + return activationEntries; + } catch (IOException ioe) { + LOGGER.error("Couldn't read the activation file at " + activationFilePath, ioe); + return null; + } + } + + protected void loadGraphs(List<Path> graphPaths, String directoryRoot) { + for (Path graphPath : graphPaths) { + try { + saveGraph(graphPath.toString()); + } catch (Exception e) { + LOGGER.error("Couldn't load graph at " + graphPath, e); + } + } + } + + private void saveGraph(String xmlFile) throws SvcLogicException { + File f = new File(xmlFile); + if (!f.canRead()) { + throw new ConfigurationException("Cannot read xml file (" + xmlFile + ")"); + } + + SvcLogicParser parser = new SvcLogicParser(); + LinkedList<SvcLogicGraph> 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 (Iterator<SvcLogicGraph> iter = graphs.iterator(); iter.hasNext();) { + + SvcLogicGraph graph = iter.next(); + + try { + LOGGER.info("Saving " + graph.toString() + " to database"); + store.store(graph); + } catch (Exception e) { + throw new SvcLogicException(e.getMessage(), e); + } + + } + } + + protected ActivationEntry parseActivationEntry(String[] fileInput) { + return new ActivationEntry(fileInput[0], fileInput[1], fileInput[2], fileInput[3]); + } + + protected String getValue(String raw, String attributeName) { + raw = raw.substring(attributeName.length() + 1); + if (raw.contains(">")) { + raw = raw.substring(0, raw.lastIndexOf('>')); + } + if (raw.endsWith("'")) { + raw = raw.substring(0, raw.lastIndexOf('\'')); + } + if (raw.endsWith("\"")) { + raw = raw.substring(0, raw.lastIndexOf('"')); + } + return raw; + } + + +} 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 a33ba476..ee260433 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 @@ -21,32 +21,29 @@ package org.onap.ccsdk.sli.core.sli; +import java.io.File; +import java.io.IOException; +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; -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 java.io.File; -import java.io.InputStream; -import java.net.URL; -import java.util.LinkedList; - /** * @author dt5972 * */ public class SvcLogicParser { - private 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"; @@ -64,282 +61,247 @@ public class SvcLogicParser { 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<SvcLogicGraph> graphs = null; - private SvcLogicGraph curGraph = null; - private SvcLogicNode curNode = null; - private LinkedList<SvcLogicNode> nodeStack = null; - private int curNodeId = 0; - private String outcomeValue = null; - private LinkedList<String> outcomeStack = null; - private SvcLogicStore svcLogicStore = null; - - public SvcLogicHandler(LinkedList<SvcLogicGraph> 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; + private Locator locator = null; + private String module = null; + private String version = null; + private LinkedList<SvcLogicGraph> graphs = null; + private SvcLogicGraph curGraph = null; + private SvcLogicNode curNode = null; + private LinkedList<SvcLogicNode> nodeStack = null; + private int curNodeId = 0; + private String outcomeValue = null; + private LinkedList<String> outcomeStack = null; + + public SvcLogicHandler(LinkedList<SvcLogicGraph> graphs) { + this.graphs = graphs; + this.curNode = null; + this.nodeStack = new LinkedList<>(); + this.outcomeStack = new LinkedList<>(); + this.curNodeId = 1; + this.outcomeValue = null; + } - } + @Override + public void setDocumentLocator(Locator locator) { + this.locator = locator; + } - @Override - public void setDocumentLocator(Locator locator) { - this.locator = locator; - } + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) + throws SAXException { - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + // Handle service-logic (graph) tag + if ("service-logic".equalsIgnoreCase(qName)) { - // 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"); + } - 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"); + } - 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; } - return; - } + if ("method".equalsIgnoreCase(qName)) { - if ("method".equalsIgnoreCase(qName)) { + if (curGraph != null) { + throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + + "Cannot nest module tags"); + } - 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; - 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); - 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); - attrValue = attributes.getValue("mode"); - if (attrValue == null || attrValue.length() == 0) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + "Missing 'mode' attribute for method tag"); + return; } - 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"); - // Handle outcome (edge) tag - if ("outcome".equalsIgnoreCase(qName)) { - String refValue = attributes.getValue("ref"); + return; + } - if (refValue != null) { - SvcLogicNode refNode = curGraph.getNamedNode(refValue); + // Handle parameter tag + if ("parameter".equalsIgnoreCase(qName)) { + String parmName = attributes.getValue("name"); + String parmValue = attributes.getValue("value"); - if (refNode != null) { + if (parmName != null && parmName.length() > 0 && parmValue != null) { try { - curNode.addOutcome(attributes.getValue("value"), refNode); - } catch (SvcLogicException e) { + + curNode.mapParameter(parmName, parmValue); + } catch (Exception e) { throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + "Cannot add outcome", e); + + " cannot set parameter " + parmName + " to " + parmValue + " [" + e.getMessage() + + "]"); } - } else { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + "ref to unknown node " + refValue); } - return; - } - if (outcomeValue != null) { - outcomeStack.push(outcomeValue); + return; } - outcomeValue = attributes.getValue("value"); - return; - } + // Handle node tags + String nodeName = attributes.getValue("name"); + SvcLogicNode thisNode; - // 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 { + try { + if (nodeName != null && nodeName.length() > 0) { + thisNode = new SvcLogicNode(curNodeId++, qName, nodeName, curGraph); + } else { + thisNode = new SvcLogicNode(curNodeId++, qName, curGraph); + } - curNode.mapParameter(parmName, parmValue); - } catch (Exception e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + " cannot set parameter " + parmName + " to " + parmValue + " [" + e.getMessage() + "]"); + if (curGraph.getRootNode() == null) { + curGraph.setRootNode(thisNode); } - } + } catch (SvcLogicException e) { + throw new SAXException( + "line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + e.getMessage()); - return; - } + } - // Handle node tags - String nodeName = attributes.getValue("name"); - SvcLogicNode thisNode; + int numAttributes = attributes.getLength(); - 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); - } + for (int i = 0; i < numAttributes; i++) { + String attrName = attributes.getQName(i); + if (!"name".equalsIgnoreCase(attrName)) { + try { - try { - if (nodeName != null && nodeName.length() > 0) { - thisNode = new SvcLogicNode(curNodeId++, qName, nodeName, curGraph); - } else { - thisNode = new SvcLogicNode(curNodeId++, qName, curGraph); + String attrValueStr = attributes.getValue(i); + SvcLogicExpression attrValue; + 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 (curGraph.getRootNode() == null) { - curGraph.setRootNode(thisNode); + if (curNode != null) { + try { + if ("block".equalsIgnoreCase(curNode.getNodeType()) || "for".equalsIgnoreCase(curNode.getNodeType()) + || "while".equalsIgnoreCase(curNode.getNodeType())) { + curNode.addOutcome(Integer.toString(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); } - } catch (SvcLogicException e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + e.getMessage()); + curNode = thisNode; } - 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; - if (attrValueStr.trim().startsWith("`")) { - int lastParen = attrValueStr.lastIndexOf('`'); - String evalExpr = attrValueStr.trim().substring(1, lastParen); - attrValue = SvcLogicExpressionFactory.parse(evalExpr); + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { - } else { - if (Character.isDigit(attrValueStr.charAt(0))) { - attrValue = new SvcLogicAtom("NUMBER", attrValueStr); - } else { - attrValue = new SvcLogicAtom("STRING", attrValueStr); - } + // Handle close of service-logic tag + if ("service-logic".equalsIgnoreCase(qName)) { + // Nothing more to do + return; } - thisNode.setAttribute(attrName, attrValue); - } catch (Exception e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + "Cannot set attribute " + attrName, e); + + // Handle close of method tag + if ("method".equalsIgnoreCase(qName)) { + graphs.add(curGraph); + curGraph = null; + return; } - } - } - if (curNode != null) { - try { - if ("block".equalsIgnoreCase(curNode.getNodeType()) || "for".equalsIgnoreCase(curNode.getNodeType()) - || "while".equalsIgnoreCase(curNode.getNodeType())) { - curNode.addOutcome(Integer.toString(curNode.getNumOutcomes() + 1), thisNode); + // Handle close of outcome tag + if ("outcome".equalsIgnoreCase(qName)) { + // Finished this outcome - pop the outcome stack + if (outcomeStack.isEmpty()) { + outcomeValue = null; } 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); + outcomeValue = outcomeStack.pop(); } - } catch (SvcLogicException e) { - throw new SAXException("line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " - + e.getMessage()); + return; } - 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 parameter tag - do nothing + if ("parameter".equalsIgnoreCase(qName)) { + return; + } - // Handle close of outcome tag - if ("outcome".equalsIgnoreCase(qName)) { - // Finished this outcome - pop the outcome stack - if (outcomeStack.isEmpty()) { - outcomeValue = null; + // Handle close of a node tag + if (nodeStack.isEmpty()) { + curNode = null; } else { - outcomeValue = outcomeStack.pop(); + curNode = nodeStack.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); - + @Override + public void error(SAXParseException arg0) throws SAXException { + throw new SAXException( + "line " + locator.getLineNumber() + ":" + locator.getColumnNumber() + " " + arg0.getMessage()); } } @@ -382,7 +344,15 @@ public class SvcLogicParser { graphs = new LinkedList<>(); - saxParser.parse(fileName, new SvcLogicHandler(graphs, store)); + saxParser.parse(fileName, new SvcLogicHandler(graphs)); + + try { + for (SvcLogicGraph graph : graphs) { + graph.setMd5sum(CheckSumHelper.md5SumFromFile(fileName)); + } + } catch (Exception exc) { + LOGGER.error("Couldn't set md5sum on graphs", exc); + } } catch (Exception e) { LOGGER.error("Parsing failed ", e); @@ -422,18 +392,18 @@ public class SvcLogicParser { 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(); + 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])) { @@ -445,32 +415,43 @@ public class SvcLogicParser { } } 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); + SvcLogicStore store = SvcLogicParser.getStore(argv[5]); + SvcLogicParser.activate(argv[1], argv[2], argv[3], argv[4], store); } else { - SvcLogicParser.usage(); + SvcLogicParser.usage(); } } else if ("validate".equalsIgnoreCase(argv[0])) { if (argv.length == 3) { - String xmlfile = argv[1]; - String propfile = argv[2]; + 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("Validate failed", e); + System.setProperty(SLI_VALIDATING_PARSER, "true"); + SvcLogicStore store = SvcLogicParser.getStore(propfile); + try { + SvcLogicParser.validate(xmlfile, store); + } catch (Exception e) { + LOGGER.error("Validate failed", e); + } + } else { + SvcLogicParser.usage(); } + } else if ("install".equalsIgnoreCase(argv[0])) { + if (argv.length == 3) { + SvcLogicLoader loader = new SvcLogicLoader(argv[1], argv[2]); + try { + loader.loadAndActivate(); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + } } else { - SvcLogicParser.usage(); + SvcLogicParser.usage(); } } System.exit(0); } - private static SvcLogicStore getStore(String propfile) { + protected static SvcLogicStore getStore(String propfile) { SvcLogicStore store = null; @@ -491,7 +472,7 @@ public class SvcLogicParser { throw new ConfigurationException("Cannot read xml file (" + xmlfile + ")"); } - SvcLogicParser parser = new SvcLogicParser(store); + SvcLogicParser parser = new SvcLogicParser(); LinkedList<SvcLogicGraph> graphs; try { LOGGER.info("Loading {}", xmlfile); @@ -511,8 +492,8 @@ public class SvcLogicParser { String version = graph.getVersion(); String mode = graph.getMode(); try { - LOGGER.info("Saving SvcLogicGraph to database (module:{},rpc:{},mode:{},version:{})", module, rpc, - mode, version); + LOGGER.info("Saving SvcLogicGraph to database (module:{},rpc:{},mode:{},version:{})", module, rpc, mode, + version); store.store(graph); } catch (Exception e) { throw new SvcLogicException(e.getMessage(), e); @@ -528,7 +509,7 @@ public class SvcLogicParser { throw new ConfigurationException("Cannot read xml file (" + xmlfile + ")"); } - SvcLogicParser parser = new SvcLogicParser(store); + SvcLogicParser parser = new SvcLogicParser(); LinkedList<SvcLogicGraph> graphs; try { LOGGER.info("Validating {}", xmlfile); @@ -607,6 +588,9 @@ public class SvcLogicParser { System.err.println(" OR SvcLogicParser print <module> <rpc> <mode> [<version>] <prop-file>"); System.err.println(" OR SvcLogicParser get-source <module> <rpc> <mode> <version> <prop-file>"); System.err.println(" OR SvcLogicParser activate <module> <rpc> <version> <mode>"); + System.err.println(" OR SvcLogicParser validate <file path to graph> <prop-file>"); + System.err.println(" OR SvcLogicParser install <service-logic directory path> <prop-file>"); + System.exit(1); } 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 index 3a3f9288..2eda67f1 100644 --- 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 @@ -26,12 +26,11 @@ 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; + public void activate(String module, String rpc, String version, String mode) throws SvcLogicException; + } 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 0912ee9f..368d9f95 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 @@ -79,31 +79,6 @@ public class ITCaseSvcLogicParser { props.setProperty("org.onap.ccsdk.sli.jdbc.database", "test"); props.setProperty("org.onap.ccsdk.sli.jdbc.url", config.getURL("test")); - - store = SvcLogicStoreFactory.getSvcLogicStore(props); - - 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"); - store.registerNodeType("call"); - store.registerNodeType("delete"); - store.registerNodeType("execute"); - store.registerNodeType("notify"); - store.registerNodeType("save"); - store.registerNodeType("update"); - store.registerNodeType("break"); } @AfterClass 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 7c1fa8e4..cbde44d6 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 @@ -134,7 +134,6 @@ public class SvcLogicActivator implements BundleActivator { // Initialize SvcLogicStore try { SvcLogicStore store = getStore(); - registerNodeTypes(store); } catch (ConfigurationException e) { LOG.warn("Could not initialize SvcLogicScore", e); } @@ -148,13 +147,6 @@ public class SvcLogicActivator implements BundleActivator { 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(); } synchronized (SvcLogicActivator.class) { @@ -185,30 +177,5 @@ public class SvcLogicActivator implements BundleActivator { 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/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 0a0e28c4..724e946d 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 @@ -99,20 +99,7 @@ public class ITCaseSvcLogicGraphExecutor { 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); + SvcLogicParser parser = new SvcLogicParser(); // Loop through executor tests @@ -165,20 +152,8 @@ public class ITCaseSvcLogicGraphExecutor { 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); + + SvcLogicParser parser = new SvcLogicParser(); // Loop through executor tests |