diff options
author | Michael DÜrre <michael.duerre@highstreet-technologies.com> | 2021-08-24 06:16:11 +0200 |
---|---|---|
committer | Michael DÜrre <michael.duerre@highstreet-technologies.com> | 2021-08-24 06:17:47 +0200 |
commit | c8f7e3f376992b202ba26464b9b329d6c4b2821d (patch) | |
tree | c61507b22b28ccc536485a8bf291826d0461b031 /sdnr/wt/data-provider/dblib/src/main/java | |
parent | 2a55fbf61c4450bfc2bb3f90b060c3aa65af91f3 (diff) |
fix some sdnr sonar bugs
sonar fixes for some sdnr components
Issue-ID: SDNC-1590
Change-Id: I02e44b6f5477bcd0490c3499caf20228eb9772ed
Signed-off-by: Michael DÜrre <michael.duerre@highstreet-technologies.com>
Diffstat (limited to 'sdnr/wt/data-provider/dblib/src/main/java')
9 files changed, 212 insertions, 113 deletions
diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/SqlDBClient.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/SqlDBClient.java index f16eadd01..ce9d4dcd1 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/SqlDBClient.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/SqlDBClient.java @@ -56,6 +56,7 @@ public class SqlDBClient { private static final String DBVERSION_REGEX = "^([\\d]+\\.[\\d]+\\.[\\d]+)"; private static final Pattern DBVERSION_PATTERN = Pattern.compile(DBVERSION_REGEX); private static final String SELECT_VERSION_QUERY = "SELECT @@version as version"; + private static final String LOG_PROBLEM_CLOSING_CONNECTION = "problem closing connection: "; private static final String DBNAME_DEFAULT = "sdnrdb"; private final String dbConnectionString; @@ -72,8 +73,8 @@ public class SqlDBClient { public SqlDBClient(String dbUrl, String username, String password) throws IllegalArgumentException { this.dbConnectionString = String.format("%s?user=%s&password=%s", dbUrl, username, password); final Matcher matcher = DBURL_PATTERN.matcher(dbUrl); - if(!matcher.find()) { - throw new IllegalArgumentException("unable to parse databaseUrl "+dbUrl); + if (!matcher.find()) { + throw new IllegalArgumentException("unable to parse databaseUrl " + dbUrl); } this.dbHost = matcher.group(2); this.dbPort = Integer.parseInt(matcher.group(3)); @@ -117,7 +118,7 @@ public class SqlDBClient { } public void waitForYellowStatus(long timeoutms) { - Portstatus.waitSecondsTillAvailable(timeoutms/1000, this.dbHost, this.dbPort); + Portstatus.waitSecondsTillAvailable(timeoutms / 1000, this.dbHost, this.dbPort); } public DatabaseVersion readActualVersion() throws SQLException, ParseException { @@ -136,7 +137,7 @@ public class SqlDBClient { } } } catch (SQLException e) { - LOG.warn("problem reading tables: ", e); + LOG.warn("problem reading actual version: ", e); } throw new SQLException("unable to read version from database"); } @@ -152,16 +153,26 @@ public class SqlDBClient { } public boolean createTable(String query) { + boolean result = false; + PreparedStatement stmt = null; try { Connection connection = this.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); + stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); stmt.execute(); connection.close(); - return true; + result = true; } catch (SQLException e) { LOG.warn("problem creating table:", e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + LOG.warn("problem closing stmt:", e); + } + } } - return false; + return result; } public boolean createView(String tableName, String viewName) throws SQLException { @@ -186,31 +197,81 @@ public class SqlDBClient { public boolean update(String query) throws SQLException { boolean result = false; - Connection connection = null; - connection = DriverManager.getConnection(this.dbConnectionString); - Statement stmt = connection.createStatement(); - result = stmt.execute(query); - return stmt.getUpdateCount() > 0 ? stmt.getUpdateCount() > 0 : result; + SQLException innerE = null; + Statement stmt = null; + try (Connection connection = this.getConnection()) { + stmt = connection.createStatement(); + result = stmt.execute(query); + result = stmt.getUpdateCount() > 0 ? stmt.getUpdateCount() > 0 : result; + } catch (SQLException e) { + innerE = e; + } finally { + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException e) { + LOG.warn(LOG_PROBLEM_CLOSING_CONNECTION, e); + } + } + if (innerE != null) { + throw innerE; + } + return result; } public boolean write(String query) throws SQLException { - Connection connection = this.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); - boolean result = stmt.execute(); - connection.close(); - return stmt.getUpdateCount() > 0 ? stmt.getUpdateCount() > 0 : result; + boolean result = false; + SQLException innerE = null; + PreparedStatement stmt = null; + try (Connection connection = this.getConnection()) { + stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); + result = stmt.execute(); + result = stmt.getUpdateCount() > 0 ? stmt.getUpdateCount() > 0 : result; + } catch (SQLException e) { + innerE = e; + } finally { + try { + if (stmt != null) { + stmt.close(); + } + } catch (SQLException e) { + LOG.warn(LOG_PROBLEM_CLOSING_CONNECTION, e); + } + } + if (innerE != null) { + throw innerE; + } + return result; } public String writeAndReturnId(String query) throws SQLException { - Connection connection = this.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); - stmt.execute(); - ResultSet generatedKeys = stmt.getGeneratedKeys(); - connection.close(); - if (generatedKeys.next()) { - return String.valueOf(generatedKeys.getLong(1)); + String result = null; + SQLException innerE = null; + PreparedStatement stmt = null; + try (Connection connection = this.getConnection()) { + stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); + stmt.execute(); + ResultSet generatedKeys = stmt.getGeneratedKeys(); + if (generatedKeys.next()) { + result = String.valueOf(generatedKeys.getLong(1)); + } + } catch (SQLException e) { + innerE = e; + } finally { + try { + if (stmt != null) { + stmt.close(); + } + + } catch (SQLException e) { + LOG.warn(LOG_PROBLEM_CLOSING_CONNECTION, e); + } } - return null; + if (innerE != null) { + throw innerE; + } + return result; } public boolean deleteTable(String tableName) throws SQLException { @@ -229,24 +290,21 @@ public class SqlDBClient { public ResultSet read(String query) { ResultSet data = null; - Connection connection = null; Statement stmt = null; - try { - connection = DriverManager.getConnection(this.dbConnectionString); + try (Connection connection = this.getConnection()) { stmt = connection.createStatement(); data = stmt.executeQuery(query); } catch (SQLException e) { - LOG.warn("problem reading tables: ", e); + LOG.warn("problem reading db for query '{}': ", query, e); } finally { try { - if (connection != null) { - connection.close(); + if (stmt != null) { + stmt.close(); } } catch (SQLException e) { - LOG.warn("problem closing connection: ", e); + LOG.warn(LOG_PROBLEM_CLOSING_CONNECTION, e); } } - return data; } @@ -258,7 +316,4 @@ public class SqlDBClient { this.write(query); return true; } - - - } diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/DatabaseIdGenerator.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/DatabaseIdGenerator.java index 5a9e58cef..2b07dfae2 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/DatabaseIdGenerator.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/DatabaseIdGenerator.java @@ -40,6 +40,13 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro public class DatabaseIdGenerator { private static final Pattern FAULTPATTERN = Pattern.compile(".*\\[layerProtocol=(.*)\\]"); + private static final String FORMAT_PMDATA_ID = "%s/%s/%s"; + private static final String FORMAT_FAULTDATA_ID = "%s/%s/%s"; + private static final String FORMAT_INVENTORYDATA_ID = "%s/%s"; + + private DatabaseIdGenerator(){ + + } public static String getMaintenanceId(String nodeId) { return nodeId; @@ -62,7 +69,7 @@ public class DatabaseIdGenerator { } else { uuId = objectId; } - return String.format("%s/%s/%s", nodeId, uuId, problemName); + return String.format(FORMAT_FAULTDATA_ID, nodeId, uuId, problemName); } public static String getFaultcurrentId(FaultcurrentEntity object) { @@ -78,7 +85,7 @@ public class DatabaseIdGenerator { } public static String getPmData15mId(String nodeId, String uuidInterface, String timestamp) { - return String.format("%s/%s/%s", nodeId, uuidInterface, timestamp); + return String.format(FORMAT_PMDATA_ID, nodeId, uuidInterface, timestamp); } public static String getPmData15mId(Pmdata15mEntity object) { @@ -86,7 +93,7 @@ public class DatabaseIdGenerator { : getPmData15mId(object.getNodeName(), object.getUuidInterface(), object.getTimeStamp().getValue()); } public static String getPmData24hId(String nodeId, String uuidInterface, String timestamp) { - return String.format("%s/%s/%s", nodeId, uuidInterface, timestamp); + return String.format(FORMAT_PMDATA_ID, nodeId, uuidInterface, timestamp); } public static String getPmData24hId(Pmdata24hEntity object) { @@ -99,6 +106,6 @@ public class DatabaseIdGenerator { } private static String getInventoryId(String nodeId, String uuid) { - return String.format("%s/%s", nodeId, uuid); + return String.format(FORMAT_INVENTORYDATA_ID, nodeId, uuid); } } diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/HtDatabaseMaintenanceService.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/HtDatabaseMaintenanceService.java index dbbb89c47..a17c6ae48 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/HtDatabaseMaintenanceService.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/data/entity/HtDatabaseMaintenanceService.java @@ -66,7 +66,7 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { .createMaintenance(new CreateMaintenanceInputBuilder().setNodeId(nodeId).build()); e = createResult.build(); } catch (IOException e1) { - LOG.warn("problem writing initial maintenance entry for {} : ", nodeId, e); + LOG.warn("problem writing initial maintenance entry for {} : ", nodeId, e1); } } return e; @@ -84,10 +84,12 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { ReadNetworkElementConnectionListOutput result = this.dbProvider.readNetworkElementConnectionList( new ReadNetworkElementConnectionListInputBuilder().setFilter(getFilterInput("node-id", nodeId)).build()) .build(); - if (result.getData() != null && result.getData().size() > 0) { + final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.read.network.element.connection.list.output.Data> data = + result.getData(); + if (data != null && !data.isEmpty()) { org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.read.network.element.connection.list.output.Data entry = - result.getData().get(0); - if (entry.isIsRequired()) { + data.get(0); + if (entry.getIsRequired()) { return; } @@ -111,8 +113,8 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { .readMaintenanceList( new ReadMaintenanceListInputBuilder().setFilter(getFilterInput("node-id", nodeId)).build()) .build(); - - return result.getData() != null ? result.getData().size() > 0 ? result.getData().get(0) : null : null; + final List<Data> data = result.getData(); + return data != null ? !data.isEmpty() ? data.get(0) : null : null; } @Override diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBMapper.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBMapper.java index 063fae622..c63d2f16b 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBMapper.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBMapper.java @@ -58,17 +58,23 @@ public class SqlDBMapper { private static final String ODLID_DBTYPE = "VARCHAR(40)"; private static final String STRING_DBTYPE = "VARCHAR(255)"; private static final String ENUM_DBTYPE = "VARCHAR(100)"; + private static final String BIGINT_DBTYPE = "BIGINT"; public static final String ODLID_DBCOL = "controller-id"; + private static final String ID_DBCOL = "id"; private static List<Class<?>> numericClasses = Arrays.asList(Byte.class, Integer.class, Long.class, BigInteger.class, Uint8.class, Uint16.class, Uint32.class, Uint64.class); private static final YangToolsMapper mapper = new YangToolsMapper(); public static final String TABLENAME_CONTROLLER = "controller"; private static final String DEFAULTID_DBTYPE = "int(11)"; + private SqlDBMapper() { + + } + public static String createTableOdl() { - return "CREATE TABLE IF NOT EXISTS " + TABLENAME_CONTROLLER + " (" + "`id` " + ODLID_DBTYPE + " " - + getColumnOptions("id", ODLID_DBTYPE) + "," + "`desc` " + STRING_DBTYPE + " " - + getColumnOptions("description", STRING_DBTYPE) + "," + "primary key(id))"; + return "CREATE TABLE IF NOT EXISTS " + TABLENAME_CONTROLLER + " (`" + ID_DBCOL + "` " + ODLID_DBTYPE + " " + + getColumnOptions(ID_DBCOL, ODLID_DBTYPE) + "," + "`desc` " + STRING_DBTYPE + " " + + getColumnOptions("description", STRING_DBTYPE) + "," + "primary key(" + ID_DBCOL + "))"; } public static <T> String createTable(Class<T> clazz, Entity e) throws UnableToMapClassException { @@ -88,23 +94,24 @@ public class SqlDBMapper { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE IF NOT EXISTS `" + e.getName() + suffix + "` (\n"); if (autoIndex) { - sb.append("`id` " + DEFAULTID_DBTYPE + " " + getColumnOptions("id", DEFAULTID_DBTYPE) + ",\n"); + sb.append("`" + ID_DBCOL + "` " + DEFAULTID_DBTYPE + " " + getColumnOptions(ID_DBCOL, DEFAULTID_DBTYPE) + + ",\n"); } else { - sb.append("`id` " + STRING_DBTYPE + " " + getColumnOptions("id", STRING_DBTYPE) + ",\n"); + sb.append("`" + ID_DBCOL + "` " + STRING_DBTYPE + " " + getColumnOptions(ID_DBCOL, STRING_DBTYPE) + ",\n"); } sb.append("`" + ODLID_DBCOL + "` " + ODLID_DBTYPE + " " + getColumnOptions(ODLID_DBCOL, ODLID_DBTYPE) + ",\n"); for (Method method : getFilteredMethods(clazz, true)) { Class<?> valueType = method.getReturnType(); String colName = getColumnName(method); - if (colName.equals("id")) { + if (ID_DBCOL.equals(colName)) { continue; } String dbType = getDBType(valueType); String options = getColumnOptions(colName, dbType); sb.append("`" + colName + "` " + dbType + " " + options + ",\n"); } - sb.append("primary key(id),"); - sb.append("foreign key(`" + ODLID_DBCOL + "`) references " + TABLENAME_CONTROLLER + "(id)"); + sb.append("primary key(" + ID_DBCOL + "),"); + sb.append("foreign key(`" + ODLID_DBCOL + "`) references " + TABLENAME_CONTROLLER + "(" + ID_DBCOL + ")"); sb.append(");"); return sb.toString(); @@ -115,7 +122,7 @@ public class SqlDBMapper { if (dbType.contains("VARCHAR")) { options.append("CHARACTER SET utf8 "); } - if (colName.equals("id") || colName.equals(ODLID_DBCOL)) { + if (ID_DBCOL.equals(colName) || ODLID_DBCOL.equals(colName)) { if (dbType.equals(DEFAULTID_DBTYPE)) { options.append("NOT NULL AUTO_INCREMENT"); } else { @@ -157,8 +164,8 @@ public class SqlDBMapper { map.put(BigInteger.class, "BIGINT"); map.put(Uint8.class, "SMALLINT"); map.put(Uint16.class, "INTEGER"); - map.put(Uint32.class, "BIGINT"); - map.put(Uint64.class, "BIGINT"); //???? + map.put(Uint32.class, BIGINT_DBTYPE); + map.put(Uint64.class, BIGINT_DBTYPE); //???? map.put(DateAndTime.class, "DATETIME(3)"); return map; } @@ -174,12 +181,10 @@ public class SqlDBMapper { //resolve conflict return !resolveConflict(method, cm, getterOrSetter); } - //silicon fix - if (method.getReturnType().equals(Boolean.class) && getterOrSetter) { - if (name.startsWith("get") && cm.getName().startsWith("is") - && cm.getName().endsWith(name.substring(3))) { - return true; - } + //silicon fix for deprecated is-... and getIs- methods for booleans + if (method.getReturnType().equals(Boolean.class) && getterOrSetter && name.startsWith("get") + && cm.getName().startsWith("is") && cm.getName().endsWith(name.substring(3))) { + return true; } } return false; @@ -336,20 +341,23 @@ public class SqlDBMapper { } public static <T extends DataObject> List<T> read(ResultSet data, Class<T> clazz) - throws JsonMappingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, - InstantiationException, SecurityException, NoSuchMethodException, JsonProcessingException, SQLException { + throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, + SecurityException, NoSuchMethodException, JsonProcessingException, SQLException { return read(data, clazz, null); } @SuppressWarnings("unchecked") - public static <T> List<T> read(ResultSet data, Class<T> clazz, String column) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, SQLException, InstantiationException, - SecurityException, NoSuchMethodException, JsonMappingException, JsonProcessingException { + public static <T> List<T> read(ResultSet data, Class<T> clazz, String column) + throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, + InstantiationException, SecurityException, NoSuchMethodException, JsonProcessingException { + Builder<T> builder = findPOJOBuilder(clazz); + if(builder==null && column==null) { + throw new InstantiationException("unable to find builder for class "+clazz.getName()); + } List<T> list = new ArrayList<>(); while (data.next()) { if (column == null) { - Builder<T> builder = findPOJOBuilder(clazz); Class<?> argType; String col; for (Method m : getFilteredMethods(builder.getClass(), false)) { @@ -409,7 +417,7 @@ public class SqlDBMapper { } else if (isComplex(dstType)) { String v = data.getString(col); - return (v == null || v.toLowerCase().equals("null")) ? null : mapper.readValue(v, dstType); + return (v == null || v.equalsIgnoreCase("null")) ? null : mapper.readValue(v, dstType); } return defaultValue; } @@ -436,14 +444,14 @@ public class SqlDBMapper { return Uint32.valueOf(value); } else if (dstType.equals(Uint16.class)) { return Uint16.valueOf(value); - } else if (dstType.equals(Uint16.class)) { + } else if (dstType.equals(Uint8.class)) { return Uint8.valueOf(value); } else if (dstType.equals(Long.class)) { - return Long.valueOf(value); + return value; } else if (dstType.equals(Integer.class)) { - return Long.valueOf(value).intValue(); + return (int)value; } else if (dstType.equals(Byte.class)) { - return Long.valueOf(value).byteValue(); + return (byte)value; } return null; } @@ -463,7 +471,7 @@ public class SqlDBMapper { } else { svalue = "'" + escape(value) + "'"; } - return new DBKeyValuePair<String>("`" + col + "`", svalue); + return new DBKeyValuePair<>("`" + col + "`", svalue); } private static String getDateTimeValue(DateAndTime value) { @@ -475,6 +483,4 @@ public class SqlDBMapper { } return s; } - - } diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriter.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriter.java index 6cc9e35d0..b5322d6ff 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriter.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriter.java @@ -30,6 +30,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Optional; import org.eclipse.jdt.annotation.Nullable; import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.SqlDBClient; @@ -44,6 +45,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EntityInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Filter; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterKey; import org.opendaylight.yangtools.yang.binding.DataObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -96,8 +98,8 @@ public class SqlDBReaderWriter<T extends DataObject> { list.remove(cFilter.get()); } if (controllerId != null) { - list.add(new FilterBuilder().setProperty(SqlDBMapper.ODLID_DBCOL).setFiltervalue(this.controllerId) - .build()); + list.add( + new FilterBuilder().setProperty(SqlDBMapper.ODLID_DBCOL).setFiltervalue(this.controllerId).build()); } return this.count(list); } @@ -108,8 +110,8 @@ public class SqlDBReaderWriter<T extends DataObject> { try { ResultSet data = this.dbService.read(query.toSql()); List<T> mappedData = SqlDBMapper.read(data, clazz); - long total = this.count(input.getFilter() != null ? new ArrayList<>(input.getFilter().values()) : null, - this.controllerId); + final Map<FilterKey, Filter> filter = input.getFilter(); + long total = this.count(filter != null ? new ArrayList<>(filter.values()) : null, this.controllerId); return new QueryResult<T>(mappedData, query.getPage(), query.getPageSize(), total); } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) { @@ -151,9 +153,10 @@ public class SqlDBReaderWriter<T extends DataObject> { UpdateQuery<S> query = new UpdateQuery<S>(this.entity, object, this.controllerId); query.setId(id); String insertedId = null; + PreparedStatement stmt = null; try { Connection connection = this.dbService.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query.toSql()); + stmt = connection.prepareStatement(query.toSql()); stmt.execute(); int affectedRows = stmt.getUpdateCount(); @@ -163,6 +166,14 @@ public class SqlDBReaderWriter<T extends DataObject> { } } catch (SQLException e) { LOG.warn("problem writing data into db: ", e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + LOG.warn("problem closing sql statement: ", e); + } + } } return insertedId; @@ -173,9 +184,10 @@ public class SqlDBReaderWriter<T extends DataObject> { query.setId(id); String insertedId = null; LOG.trace("query={}", query.toSql()); + PreparedStatement stmt = null; try { Connection connection = this.dbService.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query.toSql()); + stmt = connection.prepareStatement(query.toSql()); stmt.execute(); int affectedRows = stmt.getUpdateCount(); @@ -185,6 +197,14 @@ public class SqlDBReaderWriter<T extends DataObject> { } } catch (SQLException e) { LOG.warn("problem writing data into db: ", e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + LOG.warn("problem closing sql statement: ", e); + } + } } return insertedId; } @@ -202,14 +222,23 @@ public class SqlDBReaderWriter<T extends DataObject> { public int remove(List<Filter> filters) { DeleteQuery query = new DeleteQuery(this.entity, filters); int affectedRows = 0; + PreparedStatement stmt = null; try { Connection connection = this.dbService.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query.toSql()); + stmt = connection.prepareStatement(query.toSql()); stmt.execute(); affectedRows = stmt.getUpdateCount(); connection.close(); } catch (SQLException e) { LOG.warn("problem execute delete query: ", e); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + LOG.warn("problem closing sql statement: ", e); + } + } } return affectedRows; } @@ -226,7 +255,7 @@ public class SqlDBReaderWriter<T extends DataObject> { return mappedData; } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) { - LOG.warn("problem reading data {}: ", this.entity, e); + LOG.warn("problem reading all data{}: ", this.entity, e); } return null; } @@ -239,7 +268,7 @@ public class SqlDBReaderWriter<T extends DataObject> { return mappedData; } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) { - LOG.warn("problem reading data {}: ", this.entity, e); + LOG.warn("problem reading all data {} for key: ", this.entity, key, e); } return null; } diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriterPm.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriterPm.java index f0ce268db..021741bd8 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriterPm.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/database/SqlDBReaderWriterPm.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.SqlDBClient; +import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.entity.DatabaseIdGenerator; import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.rpctypehelper.QueryResult; import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SelectQuery; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; @@ -82,9 +83,9 @@ public class SqlDBReaderWriterPm<T extends DataObject> extends SqlDBReaderWriter try { ResultSet data = this.dbService.read(query.toSql()); List<String> mappedData = SqlDBMapper.read(data, String.class, UUID_KEY); - long total = this.count(input.getFilter() != null ? new ArrayList<>(input.getFilter().values()) : null, - this.controllerId); - return new QueryResult<String>(mappedData, query.getPage(), query.getPageSize(), total); + Map<FilterKey, Filter> inpFilter = input.getFilter(); + long total = this.count(inpFilter != null ? new ArrayList<>(inpFilter.values()) : null, this.controllerId); + return new QueryResult<>(mappedData, query.getPage(), query.getPageSize(), total); } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) { LOG.warn("problem reading ltp list: ", e); @@ -113,9 +114,9 @@ public class SqlDBReaderWriterPm<T extends DataObject> extends SqlDBReaderWriter try { ResultSet data = this.dbService.read(query.toSql()); List<String> mappedData = SqlDBMapper.read(data, String.class, NODE_KEY); - long total = this.count(input.getFilter() != null ? new ArrayList<>(input.getFilter().values()) : null, - this.controllerId); - return new QueryResult<String>(mappedData, query.getPage(), query.getPageSize(), total); + Map<FilterKey, Filter> inpFilter = input.getFilter(); + long total = this.count(inpFilter != null ? new ArrayList<>(inpFilter.values()) : null, this.controllerId); + return new QueryResult<>(mappedData, query.getPage(), query.getPageSize(), total); } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) { LOG.warn("problem reading device list: ", e); @@ -125,7 +126,7 @@ public class SqlDBReaderWriterPm<T extends DataObject> extends SqlDBReaderWriter public void write(PmdataEntity pmData) { DateAndTime date = pmData.getTimeStamp(); - final String id = String.format("%s/%s/%s", pmData.getNodeName(), pmData.getUuidInterface(), + final String id = DatabaseIdGenerator.getPmData15mId(pmData.getNodeName(), pmData.getUuidInterface(), date != null ? date.getValue() : "null"); this.updateOrInsert(pmData, id); } diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SelectQuery.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SelectQuery.java index e2cc2177d..6afcae077 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SelectQuery.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SelectQuery.java @@ -85,14 +85,13 @@ public class SelectQuery implements SqlQuery { this.addFilter(SqlDBMapper.ODLID_DBCOL, controllerId); } - Map<SortorderKey, Sortorder> so = input.getSortorder(); - if (so != null && so.size() > 0) { + Map<SortorderKey, Sortorder> so = input != null ? input.getSortorder() : null; + if (so != null && !so.isEmpty()) { for (Sortorder s : so.values()) { - this.addSortOrder(s.getProperty(), - s.getSortorder() == SortOrder.Ascending ? "ASC" : "DESC"); + this.addSortOrder(s.getProperty(), s.getSortorder() == SortOrder.Ascending ? "ASC" : "DESC"); } } - Pagination pagination = input.getPagination(); + Pagination pagination = input != null ? input.getPagination() : null; if (pagination != null) { this.setPagination(pagination.getPage().longValue(), pagination.getSize().longValue()); } else { @@ -118,11 +117,11 @@ public class SelectQuery implements SqlQuery { public void setPagination(@Nullable Pagination pagination) { long page = DEFAULT_PAGE; long pageSize = DEFAULT_PAGESIZE; - if(pagination!=null) { - if(pagination.getPage()!=null) { + if (pagination != null) { + if (pagination.getPage() != null) { page = pagination.getPage().longValue(); } - if(pagination.getSize()!=null) { + if (pagination.getSize() != null) { pageSize = pagination.getSize().longValue(); } } diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SqlQuery.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SqlQuery.java index 95e360540..82f10b1e5 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SqlQuery.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/SqlQuery.java @@ -52,7 +52,7 @@ public interface SqlQuery { return ""; } StringBuilder sb = new StringBuilder(); - if (filters.size() > 0) { + if (!filters.isEmpty()) { sb.append(" WHERE (" + getFilterExpression(filters.get(0)) + ")"); for (int i = 1; i < filters.size(); i++) { @@ -80,7 +80,7 @@ public interface SqlQuery { } public static String getFilterExpression(String property, String value) { - String filter = null;; + String filter = null; if (DbFilter.hasSearchParams(value)) { if (TIMESTAMPPROPERTYNAMES.contains(property.toLowerCase())) { if (DbFilter.isComparisonValid(value)) { @@ -224,12 +224,15 @@ public interface SqlQuery { netconfToMariaDBTimestamp(upperEnd), false); } - private static String netconfToMariaDBTimestamp(String ts) { - String v = ts.replace("T", " ").replace("Z", ""); - return v.length() > MARIADB_TIMESTAMP_REPLACER_MAX_LENGTH - ? v.substring(0, MARIADB_TIMESTAMP_REPLACER_MAX_LENGTH) - : v; + private static String netconfToMariaDBTimestamp(String ts) { + if(ts==null) { + return null; } + String v = ts.replace("T", " ").replace("Z", ""); + return v.length() > MARIADB_TIMESTAMP_REPLACER_MAX_LENGTH + ? v.substring(0, MARIADB_TIMESTAMP_REPLACER_MAX_LENGTH) + : v; + } private static String getTimestampUpperLimit(String lowerEnd, int idx) { @@ -244,7 +247,7 @@ public interface SqlQuery { if (dt == null) { return null; } - // property.substring(0,idx)+REPLACE.substring(idx+1); + Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTime(dt); int tmpvalue; diff --git a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/filters/DBKeyValuePair.java b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/filters/DBKeyValuePair.java index 2474e5227..1dd9516e6 100644 --- a/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/filters/DBKeyValuePair.java +++ b/sdnr/wt/data-provider/dblib/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/sqldb/query/filters/DBKeyValuePair.java @@ -47,10 +47,7 @@ public class DBKeyValuePair<T> implements SqlDBFilter { } protected boolean isNumericValue(T v) { - if ((v instanceof Long) || (v instanceof Integer) || (v instanceof Byte) || (v instanceof BigInteger)) { - return true; - } - return false; + return ((v instanceof Long) || (v instanceof Integer) || (v instanceof Byte) || (v instanceof BigInteger)); } @Override |