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 | |
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>
34 files changed, 486 insertions, 341 deletions
diff --git a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java index 66cbd02e9..560330f85 100644 --- a/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java +++ b/sdnr/wt/apigateway/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/apigateway/MyProperties.java @@ -150,7 +150,7 @@ public class MyProperties { in.close(); this.aaiBase = getProperty(defaultProps,"aai", DEFAULT_AAI); - this.aaiHeaders = _parseHeadersMap(getProperty(defaultProps,"aaiHeaders", DEFAULT_AAI_HEADERS)); + this.aaiHeaders = parseHeadersMap(getProperty(defaultProps,"aaiHeaders", DEFAULT_AAI_HEADERS)); this.esBase = getProperty(defaultProps,"database", DEFAULT_ESDATABASE); this.tilesBase = getProperty(defaultProps,"tiles", DEFAULT_TILES, DEFAULT_URL_OFF); this.topologyBase = getProperty(defaultProps,"topology", DEFAULT_TOPOLOGY, DEFAULT_URL_OFF); @@ -187,12 +187,12 @@ public class MyProperties { } value = tmp; } - if((value==null || value == "") && valueIfEmpty!=null) { + if((value==null || value.isEmpty()) && valueIfEmpty!=null) { value = valueIfEmpty; } return value; } - private static Map<String, String> _parseHeadersMap(String s) { + private static Map<String, String> parseHeadersMap(String s) { Map<String, String> r = new HashMap<>(); try { JSONArray a = new JSONArray(s); diff --git a/sdnr/wt/common-yang/utils/src/main/java/org/onap/ccsdk/features/sdnr/wt/yang/mapper/YangToolsMapperHelper.java b/sdnr/wt/common-yang/utils/src/main/java/org/onap/ccsdk/features/sdnr/wt/yang/mapper/YangToolsMapperHelper.java index c50e3210e..f443fd615 100644 --- a/sdnr/wt/common-yang/utils/src/main/java/org/onap/ccsdk/features/sdnr/wt/yang/mapper/YangToolsMapperHelper.java +++ b/sdnr/wt/common-yang/utils/src/main/java/org/onap/ccsdk/features/sdnr/wt/yang/mapper/YangToolsMapperHelper.java @@ -87,7 +87,7 @@ public class YangToolsMapperHelper { } } // really not found in any bundle - throw new ClassNotFoundException("Can not find class '"+name+"'"); + throw new ClassNotFoundException("Can not find class '" + name + "'"); } private static Class<?> loadClass(Bundle b, String name) throws ClassNotFoundException { @@ -126,11 +126,13 @@ public class YangToolsMapperHelper { } @SuppressWarnings("unchecked") - public static <B extends Builder<?>> Class<B> findBuilderClass(DeserializationContext ctxt, Class<?> clazz) throws ClassNotFoundException { + public static <B extends Builder<?>> Class<B> findBuilderClass(DeserializationContext ctxt, Class<?> clazz) + throws ClassNotFoundException { return (Class<B>) findClass(getBuilderClassName(clazz)); } - public static <B extends Builder<?>> Optional<Class<B>> findBuilderClassOptional(DeserializationContext ctxt, Class<?> clazz) { + public static <B extends Builder<?>> Optional<Class<B>> findBuilderClassOptional(DeserializationContext ctxt, + Class<?> clazz) { try { return Optional.of(findBuilderClass(ctxt, clazz)); } catch (ClassNotFoundException e) { @@ -149,7 +151,9 @@ public class YangToolsMapperHelper { } @SuppressWarnings("unchecked") - public static <T> Optional<T> getInstanceByConstructor(Class<?> clazz, String arg) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + public static <T> Optional<T> getInstanceByConstructor(Class<?> clazz, String arg) + throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, + NoSuchMethodException, SecurityException { List<Class<?>> ctypes = getConstructorParameterTypes(clazz, String.class); Optional<Object> oObj; for (Class<?> ctype : ctypes) { @@ -167,17 +171,16 @@ public class YangToolsMapperHelper { } @SuppressWarnings("unchecked") - public static <T> Optional<T> getDefaultInstance(@Nullable Class<?> clazz, String arg) - throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException { - LOG.trace("arg:'{}' clazz '{}'", arg, clazz.getName()); + public static <T> Optional<T> getDefaultInstance(@Nullable Class<?> clazz, String arg) throws NoSuchMethodException, + SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + LOG.trace("arg:'{}' clazz '{}'", arg, clazz != null ? clazz.getName() : "null"); if (clazz != null) { Method[] methods = clazz.getDeclaredMethods(); for (Method m : methods) { //TODO Verify argument type to avoid exception if (m.getName().equals(TYPEOBJECT_INSTANCE_METHOD)) { Method method = clazz.getDeclaredMethod(TYPEOBJECT_INSTANCE_METHOD, String.class); - LOG.trace("Invoke {} available {}",TYPEOBJECT_INSTANCE_METHOD, method != null); + LOG.trace("Invoke {} available {}", TYPEOBJECT_INSTANCE_METHOD, method != null); return Optional.of((T) method.invoke(null, arg)); } } @@ -212,7 +215,7 @@ public class YangToolsMapperHelper { } public static boolean implementsInterface(Class<?> clz, Class<?> ifToImplement) { - if(clz.equals(ifToImplement)) { + if (clz.equals(ifToImplement)) { return true; } Class<?>[] ifs = clz.getInterfaces(); @@ -240,6 +243,7 @@ public class YangToolsMapperHelper { ret.append(toCamelCase(name)); return ret.toString(); } + public static String toCamelCase(final String name) { int start = 0; final StringBuilder ret = new StringBuilder(name.length()); @@ -255,20 +259,25 @@ public class YangToolsMapperHelper { } return ret.toString(); } + public static String toCamelCaseClassName(final String name) { final String clsName = toCamelCase(name); - return clsName.substring(0,1).toUpperCase()+clsName.substring(1); + return clsName.substring(0, 1).toUpperCase() + clsName.substring(1); } + private static BundleContext getBundleContext() { Bundle bundle = FrameworkUtil.getBundle(YangToolsMapperHelper.class); return bundle != null ? bundle.getBundleContext() : null; } + public static boolean hasTime(Notification notification) { return notification instanceof EventInstantAware; } + public static boolean hasTime(DOMNotification notification) { return notification instanceof DOMEvent; } + public static DateAndTime getTime(Notification notification, Instant defaultValue) { Instant time; if (hasTime(notification)) { // If notification class extends/implements the EventInstantAware diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java index 54a5172a3..9ca985d4d 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java @@ -49,6 +49,8 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { public static final String SECTIONNAME_ROOT = ""; private static final String LR = "\n"; private static final String EMPTY = ""; + + private static final String LOG_UNKNWON_CONFIG_SECTION = "Unknown configuration section {}"; // end of constants // variables @@ -70,8 +72,12 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { if (!this.mFile.createNewFile()) { LOG.error("Can not create file {}", f.getAbsolutePath()); } - this.mFile.setReadable(true, false); - this.mFile.setWritable(true, false); + if (!this.mFile.setReadable(true, false)) { + LOG.warn("unable to set file as readable"); + } + if (!this.mFile.setWritable(true, false)) { + LOG.warn("unable to set file as writable"); + } } reLoad(); @@ -106,9 +112,7 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { String curSectionName = SECTIONNAME_ROOT; Optional<Section> sectionOptional = this.getSection(curSectionName); Section curSection = sectionOptional.isPresent() ? sectionOptional.get() : this.addSection(curSectionName); - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(this.mFile)); + try (BufferedReader br = new BufferedReader(new FileReader(this.mFile))) { for (String line; (line = br.readLine()) != null;) { line = line.trim(); if (line.isEmpty()) { @@ -124,13 +128,6 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { } catch (Exception e) { LOG.info("Problem loading configuration file. {} {}", getMFileName(), e); - } finally { - try { - if (br != null) { - br.close(); - } - } catch (IOException e) { - } } LOG.debug("finished loading file"); LOG.debug("start parsing sections"); @@ -164,9 +161,8 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { bw.write(String.join(LR, section.toLines()) + LR + LR); } } - bw.close(); } catch (Exception e) { - LOG.warn("problem saving value: " + e.getMessage()); + LOG.warn("problem saving value: {}", e.getMessage()); } } @@ -194,7 +190,6 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { if (this.fileObserver != null) { this.fileObserver.interrupt(); } - super.finalize(); } /* @@ -206,7 +201,7 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { os.get().setProperty(key, value == null ? "null" : value.toString()); save(); } else { - LOG.info("Unknown configuration section {}", section); + LOG.info(LOG_UNKNWON_CONFIG_SECTION, section); } } @@ -215,7 +210,7 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { if (os.isPresent()) { return os.get().getProperty(propertyKey); } else { - LOG.debug("Unknown configuration section {}", section); + LOG.debug(LOG_UNKNWON_CONFIG_SECTION, section); return EMPTY; } } @@ -225,7 +220,7 @@ public class ConfigurationFileRepresentation implements IConfigChangedListener { if (os.isPresent()) { return os.get().getLong(propertyKey); } else { - LOG.debug("Unknown configuration section {}", section); + LOG.debug(LOG_UNKNWON_CONFIG_SECTION, section); return Optional.empty(); } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java index c6b121ae3..55e329ebc 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java @@ -29,7 +29,6 @@ import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.eclipse.jdt.annotation.NonNull; import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -266,7 +265,7 @@ public class Section { } // static methods - public static void setEnvGetter(@NonNull EnvGetter newEnvGetter) { + public static void setEnvGetter(EnvGetter newEnvGetter) { if (Objects.nonNull(newEnvGetter)) { envGetter = newEnvGetter; } else { 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 diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/YangHelper2.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/YangHelper2.java index dd90d29c8..423ebab0b 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/YangHelper2.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/YangHelper2.java @@ -29,7 +29,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jdt.annotation.NonNull; -import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.yangtools.yang.binding.Identifiable; import org.opendaylight.yangtools.yang.binding.Identifier; import org.opendaylight.yangtools.yang.common.Uint16; @@ -38,43 +37,47 @@ import org.opendaylight.yangtools.yang.common.Uint64; public class YangHelper2 { - static public @NonNull Uint64 getUint64(@NonNull BigInteger val) { + private YangHelper2() { + + } + + public static @NonNull Uint64 getUint64(@NonNull BigInteger val) { return Uint64.valueOf(val); } - static public @NonNull Uint64 getUint64(@NonNull Uint64 val) { + public static @NonNull Uint64 getUint64(@NonNull Uint64 val) { return val; } - static public @NonNull Uint32 getUint32(@NonNull Long val) { + public static @NonNull Uint32 getUint32(@NonNull Long val) { return Uint32.valueOf(val); } - static public @NonNull Uint32 getUint32(@NonNull Uint32 val) { + public static @NonNull Uint32 getUint32(@NonNull Uint32 val) { return val; } - public static @NonNull Uint16 getUint16(@Nullable Integer val) { + public static @NonNull Uint16 getUint16(@NonNull Integer val) { return Uint16.valueOf(val); } - public static @NonNull Uint16 getUint16(@Nullable Uint16 val) { + public static @NonNull Uint16 getUint16(@NonNull Uint16 val) { return val; } - public static @NonNull Integer getInteger(@Nullable Integer val) { + public static @NonNull Integer getInteger(@NonNull Integer val) { return val; } - public static @NonNull Integer getInteger(@Nullable Uint16 val) { + public static @NonNull Integer getInteger(@NonNull Uint16 val) { return val.intValue(); } - public static @NonNull Long getInteger(@Nullable Long val) { + public static @NonNull Long getInteger(@NonNull Long val) { return val; } - public static @NonNull Long getInteger(@Nullable Uint32 val) { + public static @NonNull Long getInteger(@NonNull Uint32 val) { return val.longValue(); } /** diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/EsDataObjectReaderWriter2.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/EsDataObjectReaderWriter2.java index a86ecdde1..cb0f22da1 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/EsDataObjectReaderWriter2.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/EsDataObjectReaderWriter2.java @@ -53,7 +53,7 @@ import org.slf4j.LoggerFactory; */ public class EsDataObjectReaderWriter2<T extends DataObject> { - private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter2.class); + private static final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter2.class); /** Typename for elastic search data schema **/ private String dataTypeName; @@ -202,7 +202,7 @@ public class EsDataObjectReaderWriter2<T extends DataObject> { * * @param writeInterfaceClazz */ - public EsDataObjectReaderWriter2<T> setWriteInterface(@Nonnull Class<? extends DataObject> writeInterfaceClazz) { + public EsDataObjectReaderWriter2<T> setWriteInterface(Class<? extends DataObject> writeInterfaceClazz) { LOG.debug("Set write interface to {}", writeInterfaceClazz); if (writeInterfaceClazz == null) { throw new IllegalArgumentException("Null not allowed here."); @@ -359,7 +359,7 @@ public class EsDataObjectReaderWriter2<T extends DataObject> { if(this.doFullsizeRequest) { query.doFullsizeRequest(); } - SearchResult<T> res = new SearchResult<T>(); + SearchResult<T> res = new SearchResult<>(); SearchResult<SearchHit> result; List<SearchHit> hits; if (query != null) { diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/data/rpctypehelper/QueryByFilter.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/data/rpctypehelper/QueryByFilter.java index eef61e09c..69f9bcc29 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/data/rpctypehelper/QueryByFilter.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/elasticsearch/data/rpctypehelper/QueryByFilter.java @@ -96,10 +96,10 @@ public class QueryByFilter { if (fromPage < 0 || pageSize > 10000) throw new IllegalArgumentException("mismatching input parameters. From:" + fromPage + " size:" + pageSize); - filterList = YangHelper.getList(input.getFilter()); + filterList = input == null ? null : YangHelper.getList(input.getFilter()); if (filterList == null) filterList = emptyFilterList; - sortOrder = YangHelper.getList(input.getSortorder()); + sortOrder = input == null ? null : YangHelper.getList(input.getSortorder()); if (sortOrder == null) sortOrder = emptySortOrderList; @@ -167,7 +167,7 @@ public class QueryByFilter { * Private and static implementations */ private static QueryBuilder setSortOrder(QueryBuilder query, @Nullable List<Sortorder> sortorder, String prefix) { - if (sortorder != null && sortorder.size() > 0) { + if (sortorder != null && !sortorder.isEmpty()) { for (Sortorder so : sortorder) { query.sort(handlePrefix(prefix, so.getProperty()), convert(so.getSortorder())); } @@ -179,7 +179,7 @@ public class QueryByFilter { return sortOrder == SortOrder.Ascending ? org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder.ASCENDING : org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder.DESCENDING; - }; + } private static Sortorder getSortOrder(@Nullable List<Sortorder> list, String prop) { if (list == null) { @@ -353,7 +353,7 @@ public class QueryByFilter { } private static List<String> collectValues(Filter filter) { - List<String> values = new ArrayList<String>(); + List<String> values = new ArrayList<>(); if (filter.getFiltervalue() != null) { values.add(filter.getFiltervalue()); } @@ -364,7 +364,7 @@ public class QueryByFilter { } private static QueryBuilder fromFilter(@Nullable List<Filter> filters, String prefix) { - if (filters == null || filters.size() == 0) { + if (filters == null || filters.isEmpty()) { return QueryBuilders.matchAllQuery(); } else if (filters.size() == 1) { @@ -399,7 +399,6 @@ public class QueryByFilter { tmpQuery.should(getSinglePropertyQuery(p, v, prefix)); } query.must(tmpQuery); - tmpQuery = QueryBuilders.boolQuery(); } } LOG.trace("Query result. {}", query.toJSON()); diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/DataTreeHttpServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/DataTreeHttpServlet.java index 115ff4f40..3c4a7621b 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/DataTreeHttpServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/DataTreeHttpServlet.java @@ -29,6 +29,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; @@ -70,9 +71,9 @@ public class DataTreeHttpServlet extends HttpServlet { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; + IOException toThrow = null; + try (InputStream inputStream = request.getInputStream()) { - try { - InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; @@ -84,17 +85,20 @@ public class DataTreeHttpServlet extends HttpServlet { stringBuilder.append(""); } } catch (IOException ex) { - throw ex; + toThrow = ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { - throw ex; + LOG.debug("problem closing reader:", ex); + toThrow = ex; } } } - + if (toThrow != null) { + throw toThrow; + } body = stringBuilder.toString(); return body; } @@ -164,13 +168,16 @@ public class DataTreeHttpServlet extends HttpServlet { final String regex = "^\\/tree\\/read-(.*)-tree\\/?(.*)$"; final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(uri); - Entity e = null; if (matcher.find() && matcher.groupCount() > 0) { try { - e = Entity.forName(matcher.group(1)).get(); - return new EntityWithTree(e, matcher.groupCount() > 1 ? matcher.group(2) : null); + Optional<Entity> oe = Entity.forName(matcher.group(1)); + if (oe.isPresent()) { + return new EntityWithTree(oe.get(), matcher.groupCount() > 1 ? matcher.group(2) : null); + } else { + LOG.warn("unable to find entity for name {}", matcher.group(1)); + } } catch (Exception e2) { - LOG.warn("unable to parse {} into entity: {}", matcher.group(2), e2); + LOG.warn("unable to parse {} into entity: ", matcher.group(2), e2); } } return null; @@ -182,7 +189,7 @@ public class DataTreeHttpServlet extends HttpServlet { try { resp.getWriter().write(data.toJSON()); } catch (IOException e) { - LOG.warn("problem sending response: {}", e); + LOG.warn("problem sending response: ", e); } } @@ -196,14 +203,14 @@ public class DataTreeHttpServlet extends HttpServlet { } /** - * - * @param e database enttity to access - * @param tree tree description - * e.g. nodeA => tree entry for node-id=nodeA - * nodeA/key0 => tree entry for node-id=nodeA and uuid=key0 and tree-level=0 - * nodeA/key0/key1 => tree entry for node-id=nodeA and uuid=key1 and tree-level=1 - * - */ + * + * @param e database enttity to access + * @param tree tree description + * e.g. nodeA => tree entry for node-id=nodeA + * nodeA/key0 => tree entry for node-id=nodeA and uuid=key0 and tree-level=0 + * nodeA/key0/key1 => tree entry for node-id=nodeA and uuid=key1 and tree-level=1 + * + */ public EntityWithTree(Entity e, String tree) { this.entity = e; if (tree != null) { diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/UserdataHttpServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/UserdataHttpServlet.java index 09a81c381..b51d2a6df 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/UserdataHttpServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/UserdataHttpServlet.java @@ -43,7 +43,7 @@ public class UserdataHttpServlet extends HttpServlet { private static final String REGEX = "^\\/userdata[\\/]?([a-zA-Z0-9]+)?$"; private static final Pattern PATTERN = Pattern.compile(REGEX); private static final String JWT_PAYLOAD_USERNAME_PROPERTYKEY = "sub"; - private HtUserdataManager dbUserManager; + private static HtUserdataManager dbUserManager; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -91,47 +91,46 @@ public class UserdataHttpServlet extends HttpServlet { private void handleGetRequest(HttpServletRequest req, HttpServletResponse resp, String key) { final String username = this.getUsername(req); - if(username==null) { + if (username == null) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } sendJsonResponse(resp, - key == null ? this.dbUserManager.getUserdata(username) : this.dbUserManager.getUserdata(username, key)); + key == null ? dbUserManager.getUserdata(username) : dbUserManager.getUserdata(username, key)); } private void handlePutRequest(HttpServletRequest req, HttpServletResponse resp, String data, String key) { final String username = this.getUsername(req); - if(username==null) { + if (username == null) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } - boolean success = key == null ? this.dbUserManager.setUserdata(username, data) - : this.dbUserManager.setUserdata(username, key, data); + boolean success = key == null ? dbUserManager.setUserdata(username, data) + : dbUserManager.setUserdata(username, key, data); resp.setStatus(success ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } private void handleDeleteRequest(HttpServletRequest req, HttpServletResponse resp, String key) { final String username = this.getUsername(req); - if(username==null) { + if (username == null) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } - boolean success = key == null ? this.dbUserManager.removeUserdata(username) - : this.dbUserManager.removeUserdata(username, key); + boolean success = + key == null ? dbUserManager.removeUserdata(username) : dbUserManager.removeUserdata(username, key); resp.setStatus(success ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } private String getUsername(HttpServletRequest req) { final String authHeader = req.getHeader("Authorization"); - if(authHeader==null) { + if (authHeader == null) { return null; } String username = null; - if(authHeader.startsWith("Basic")) { + if (authHeader.startsWith("Basic")) { username = BaseHTTPClient.decodeBasicAuthHeaderUsername(authHeader); - } - else if(authHeader.startsWith("Bearer")) { + } else if (authHeader.startsWith("Bearer")) { username = decodeJWTPayloadUsername(authHeader, JWT_PAYLOAD_USERNAME_PROPERTYKEY); } return username; @@ -139,16 +138,16 @@ public class UserdataHttpServlet extends HttpServlet { public static String decodeJWTPayloadUsername(String authHeader, String key) { String username = null; - if(authHeader.startsWith("Bearer")) { + if (authHeader.startsWith("Bearer")) { authHeader = authHeader.substring(7); } String[] tmp = authHeader.split("\\."); - if(tmp.length==3) { + if (tmp.length == 3) { final String decoded = new String(Base64.getDecoder().decode(tmp[1])); - JSONObject o = new JSONObject(decoded); - if(o.has(key)) { + JSONObject o = new JSONObject(decoded); + if (o.has(key)) { username = o.getString(key); - if(username!=null && username.contains("@")) { + if (username != null && username.contains("@")) { username = username.split("@")[0]; } } @@ -168,8 +167,8 @@ public class UserdataHttpServlet extends HttpServlet { } - public void setDatabaseClient(HtUserdataManager dbUserManager) { - this.dbUserManager = dbUserManager; + public void setDatabaseClient(HtUserdataManager dbMgr) { + dbUserManager = dbMgr; } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/AboutHttpServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/AboutHttpServlet.java index 64b5fab9f..cd75ca2a8 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/AboutHttpServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/AboutHttpServlet.java @@ -34,8 +34,6 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpHeaders; -//import org.apache.karaf.bundle.core.BundleInfo; -//import org.apache.karaf.bundle.core.BundleService; import org.onap.ccsdk.features.sdnr.wt.common.Resources; import org.onap.ccsdk.features.sdnr.wt.common.file.PomFile; import org.onap.ccsdk.features.sdnr.wt.common.file.PomPropertiesFile; @@ -83,8 +81,7 @@ public class AboutHttpServlet extends HttpServlet { private final Map<Integer, String> BUNDLESTATE_LUT; private final Map<String, String> data; private final String readmeContent; - // private BundleService bundleService; - private String jsonContent; + private final String jsonContent; public AboutHttpServlet() { @@ -114,10 +111,6 @@ public class AboutHttpServlet extends HttpServlet { return def; } - // public void setBundleService(BundleService bundleService) { - // this.bundleService = bundleService; - // } - /** * collect static versioning data */ @@ -152,22 +145,11 @@ public class AboutHttpServlet extends HttpServlet { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentLength(output.length); resp.setContentType(ctype.getMimeType()); - ServletOutputStream os = null; - try { - os = resp.getOutputStream(); + try (ServletOutputStream os = resp.getOutputStream()) { os.write(output); } catch (IOException e) { LOG.warn("problem writing response for {}: {}", uri, e); - } finally { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - LOG.warn("problem closing response stream: {}", e); - } - } } - } else { this.doGetFile(uri, resp); } @@ -183,7 +165,7 @@ public class AboutHttpServlet extends HttpServlet { if (content == null) { return def; } - String lines[] = content.split("\n"); + String[] lines = content.split("\n"); for (String line : lines) { if (line.startsWith("git.commit.id")) { def = line.substring("git.commit.id=".length()); @@ -207,7 +189,7 @@ public class AboutHttpServlet extends HttpServlet { this.data.put(PLACEHOLDER_KARAF_INFO, SystemInfo.get()); this.data.put(PLACEHOLDER_DEVICEMANAGER_TABLE, this.getDevicemanagerBundles(ctype)); } catch (Exception e) { - LOG.warn("problem collecting system data: {}", e); + LOG.warn("problem collecting system data: ", e); } } @@ -228,7 +210,7 @@ public class AboutHttpServlet extends HttpServlet { Attributes attr = manifest.getMainAttributes(); return attr.getValue(key); } catch (IOException e) { - LOG.warn("problem reading manifest: {}", e); + LOG.warn("problem reading manifest: ", e); } return null; @@ -282,12 +264,12 @@ public class AboutHttpServlet extends HttpServlet { BundleContext context = thisbundle == null ? null : thisbundle.getBundleContext(); if (context == null) { LOG.debug("no bundle context available"); - return ctype==ContentType.MARKDOWN?"":"[]"; + return ctype == ContentType.MARKDOWN ? "" : "[]"; } Bundle[] bundles = context.getBundles(); if (bundles == null || bundles.length <= 0) { LOG.debug("no bundles found"); - return ctype==ContentType.MARKDOWN?NO_DEVICEMANAGERS_RUNNING_MESSAGE:"[]"; + return ctype == ContentType.MARKDOWN ? NO_DEVICEMANAGERS_RUNNING_MESSAGE : "[]"; } LOG.debug("found {} bundles", bundles.length); MarkdownTable table = new MarkdownTable(); @@ -302,10 +284,10 @@ public class AboutHttpServlet extends HttpServlet { continue; } table.addRow(new String[] {String.valueOf(bundle.getBundleId()), bundle.getVersion().toString(), name, - BUNDLESTATE_LUT.getOrDefault(bundle.getState(), "unknown")}); + BUNDLESTATE_LUT.getOrDefault(bundle.getState(), UNKNOWN)}); } - return ctype==ContentType.MARKDOWN?table.toMarkDown():table.toJson(); + return ctype == ContentType.MARKDOWN ? table.toMarkDown() : table.toJson(); } /** @@ -329,7 +311,7 @@ public class AboutHttpServlet extends HttpServlet { try { resp.getOutputStream().write(data); } catch (IOException e) { - LOG.debug("unable to send data : {}", e); + LOG.debug("unable to send data: ", e); } } @@ -352,7 +334,7 @@ public class AboutHttpServlet extends HttpServlet { case "bmp": return "image/" + ext; case "json": - return "application/json"; + return MIMETYPE_JSON; case "html": case "htm": return "text/html"; @@ -382,7 +364,7 @@ public class AboutHttpServlet extends HttpServlet { */ private String render(ContentType ctype, String content) { if (content == null) { - content = ctype==ContentType.MARKDOWN? this.readmeContent:this.jsonContent; + content = ctype == ContentType.MARKDOWN ? this.readmeContent : this.jsonContent; } if (content == null) { return null; diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/MarkdownTable.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/MarkdownTable.java index 1580a0fe3..e13ca8203 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/MarkdownTable.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/about/MarkdownTable.java @@ -47,10 +47,20 @@ public class MarkdownTable { this.rows.add(values); } + private int getColNumbers() { + int cols = 0; + if (this.columns != null) { + cols = this.columns.length; + } else { + cols = !this.rows.isEmpty() ? this.rows.get(0).length : 0; + } + return cols; + } + public String toMarkDown() { StringBuilder sb = new StringBuilder(); - final int cols = - this.columns != null ? this.columns.length : this.rows.size() > 0 ? this.rows.get(0).length : 0; + + final int cols = this.getColNumbers(); if (cols > 0) { sb.append("|"); for (int i = 0; i < cols; i++) { @@ -75,9 +85,8 @@ public class MarkdownTable { public String toJson() { JSONArray a = new JSONArray(); - final int cols = - this.columns != null ? this.columns.length : this.rows.size() > 0 ? this.rows.get(0).length : 0; - if (cols > 0) { + final int cols = this.getColNumbers(); + if (cols > 0 && this.columns!=null) { for (String[] row : this.rows) { JSONObject o = new JSONObject(); for (int i = 0; i < cols; i++) { diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderServiceImpl.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderServiceImpl.java index 2bf67fde9..5a99c8ab3 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderServiceImpl.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderServiceImpl.java @@ -45,6 +45,7 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.HtUserdataManager; import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.IEsConfig; import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.SdnrDbType; import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.ReadTransaction; import org.opendaylight.mdsal.binding.api.RpcProviderService; import org.opendaylight.mdsal.common.api.LogicalDatastoreType; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore; @@ -136,6 +137,7 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab private final HtUserdataManager dbUserManager; private final DataBroker dataBroker; private final MsServlet mediatorServerServlet; + public DataProviderServiceImpl(final RpcProviderService rpcProviderService, MsServlet mediatorServerServlet, DataBroker dataBroker) throws Exception { this.configuration = new ConfigurationFileRepresentation(CONFIGURATIONFILE); @@ -151,7 +153,7 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab mediatorServerServlet.setDataProvider(this.dataProvider.getHtDatabaseMediatorServer()); this.dbUserManager = new HtUserdataManagerImpl(this.dataProvider.getRawClient()); // Register ourselves as the REST API RPC implementation - LOG.info("Register RPC Service " + DataProviderServiceImpl.class.getSimpleName()); + LOG.info("Register RPC Service {}", DataProviderServiceImpl.class.getSimpleName()); this.rpcReg = rpcProviderService.registerRpcImplementation(DataProviderService.class, this); } @@ -425,11 +427,15 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab private ReadTlsKeyEntryOutputBuilder readTlsKeys(ReadTlsKeyEntryInput input) { Optional<Keystore> result = Optional.empty(); - try { - result = this.dataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, KEYSTORE_IIF) - .get(); - } catch (InterruptedException | ExecutionException e) { + try (ReadTransaction transaction = this.dataBroker.newReadOnlyTransaction()) { + result = transaction.read(LogicalDatastoreType.CONFIGURATION, KEYSTORE_IIF).get(); + } catch (ExecutionException e) { LOG.warn("problem reading netconf-keystore: ", e); + + } catch (InterruptedException e) { + LOG.warn("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); } ReadTlsKeyEntryOutputBuilder output = new ReadTlsKeyEntryOutputBuilder(); if (result.isEmpty()) { @@ -439,11 +445,12 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab if (keyCredential == null) { return output.setData(Arrays.asList()).setPagination(EMPTY_PAGINATION); } - long pageNum = input.getPagination() == null ? DEFAULT_PAGE - : input.getPagination().getPage() == null ? DEFAULT_PAGE : input.getPagination().getPage().longValue(); - long size = input.getPagination() == null ? DEFAULT_PAGESIZE - : input.getPagination().getSize() == null ? DEFAULT_PAGESIZE - : input.getPagination().getSize().longValue(); + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Pagination pagination = + input.getPagination(); + long pageNum = pagination == null ? DEFAULT_PAGE + : pagination.getPage() == null ? DEFAULT_PAGE : pagination.getPage().longValue(); + long size = pagination == null ? DEFAULT_PAGESIZE + : pagination.getSize() == null ? DEFAULT_PAGESIZE : pagination.getSize().longValue(); long from = pageNum > 0 ? (pageNum - 1) * size : 0; output.setData(keyCredential.keySet().stream().skip(from).limit(size).map(e -> e.getKeyId()) .collect(Collectors.toList())); diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/Program.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/Program.java index 56973f459..8afc440fd 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/Program.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/Program.java @@ -413,7 +413,7 @@ public class Program { } private static long getTimeoutOptionMillis(CommandLine cmd) throws ParseException { - return getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, DEFAULT_DATABASEWAIT_SECONDS) * 1000; + return getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, DEFAULT_DATABASEWAIT_SECONDS) * 1000L; } /** diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/ElasticsearchDataMigrationProvider.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/ElasticsearchDataMigrationProvider.java index 3cfa8c17f..0254f843b 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/ElasticsearchDataMigrationProvider.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/ElasticsearchDataMigrationProvider.java @@ -66,12 +66,13 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchDataMigrationProvider.class); + private static final String LOG_DELETING_INDEX = "deleting index {}"; private final HtDatabaseClient dbClient; public ElasticsearchDataMigrationProvider(String url, String username, String password, boolean trustAll, long timeoutms) throws Exception { - dbClient = HtDatabaseClient.getClient(new HostInfo[] {HostInfo.parse(url)}, username, password, trustAll, - true, timeoutms); + dbClient = HtDatabaseClient.getClient(new HostInfo[] {HostInfo.parse(url)}, username, password, trustAll, true, + timeoutms); } @Override @@ -215,7 +216,7 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider } List<Release> foundReleases = new ArrayList<>(); //if there are active aliases reduce indices to the active ones - if (aliases != null && aliases.size() > 0) { + if (aliases != null && !aliases.isEmpty()) { indices = indices.subList(aliases.getLinkedIndices()); } for (Release r : Release.values()) { @@ -368,7 +369,7 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider } ReleaseInformation ri = ReleaseInformation.getInstance(release); AcknowledgedResponse response; - if (entries.size() <= 0) { + if (entries.isEmpty()) { LOG.info("no aliases to clear"); } else { //check for every component of release if alias exists @@ -387,10 +388,10 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider } } else { //try to find malformed typed index with alias name - IndicesEntry entry2ToDelete = entries2.findByIndex(aliasToDelete); + IndicesEntry entry2ToDelete = entries2 == null ? null : entries2.findByIndex(aliasToDelete); if (entry2ToDelete != null) { try { - LOG.info("deleting index {}", entry2ToDelete.getName()); + LOG.info(LOG_DELETING_INDEX, entry2ToDelete.getName()); response = this.dbClient.deleteIndex(new DeleteIndexRequest(entry2ToDelete.getName())); LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed"); } catch (IOException e) { @@ -404,7 +405,7 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider if (entries2 == null) { return false; } - if (entries2.size() <= 0) { + if (entries2.isEmpty()) { LOG.info("no indices to clear"); } else { //check for every component of release if index exists @@ -413,7 +414,7 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider IndicesEntry entryToDelete = entries2.findByIndex(indexToDelete); if (entryToDelete != null) { try { - LOG.info("deleting index {}", entryToDelete.getName()); + LOG.info(LOG_DELETING_INDEX, entryToDelete.getName()); response = this.dbClient.deleteIndex(new DeleteIndexRequest(entryToDelete.getName())); LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed"); } catch (IOException e) { @@ -452,7 +453,7 @@ public class ElasticsearchDataMigrationProvider implements DataMigrationProvider } for (IndicesEntry index : indices) { try { - LOG.info("deleting index {}", index.getName()); + LOG.info(LOG_DELETING_INDEX, index.getName()); this.dbClient.deleteIndex(new DeleteIndexRequest(index.getName())); } catch (IOException e) { LOG.error("problem deleting index {}: {}", index.getName(), e); diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/MariaDbDataMigrationProvider.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/MariaDbDataMigrationProvider.java index d46fc4e2e..55ba66ba6 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/MariaDbDataMigrationProvider.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/database/MariaDbDataMigrationProvider.java @@ -58,6 +58,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic private static final Logger LOG = LoggerFactory.getLogger(MariaDbDataMigrationProvider.class); private static final SdnrDbType DBTYPE = SdnrDbType.MARIADB; + private static final String LOG_DELETING_INDEX = "deleting index {}"; private final SqlDBClient dbClient; public MariaDbDataMigrationProvider(String url, String username, String password, boolean trustAll, @@ -211,7 +212,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic } List<Release> foundReleases = new ArrayList<>(); //if there are active aliases reduce indices to the active ones - if (aliases != null && aliases.size() > 0) { + if (aliases != null && !aliases.isEmpty()) { indices = indices.subList(aliases.getLinkedIndices()); } for (Release r : Release.values()) { @@ -337,7 +338,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic } ReleaseInformation ri = ReleaseInformation.getInstance(release); boolean response; - if (entries.size() <= 0) { + if (entries.isEmpty()) { LOG.info("no aliases to clear"); } else { //check for every component of release if alias exists @@ -358,7 +359,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic IndicesEntry entry2ToDelete = entries2.findByIndex(aliasToDelete); if (entry2ToDelete != null) { try { - LOG.info("deleting index {}", entry2ToDelete.getName()); + LOG.info(LOG_DELETING_INDEX, entry2ToDelete.getName()); response = this.dbClient.deleteTable(entry2ToDelete.getName()); LOG.info(response ? "succeeded" : "failed"); } catch (SQLException e) { @@ -372,7 +373,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic if (entries2 == null) { return false; } - if (entries2.size() <= 0) { + if (entries2.isEmpty()) { LOG.info("no indices to clear"); } else { //check for every component of release if index exists @@ -381,7 +382,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic IndicesEntry entryToDelete = entries2.findByIndex(indexToDelete); if (entryToDelete != null) { try { - LOG.info("deleting index {}", entryToDelete.getName()); + LOG.info(LOG_DELETING_INDEX, entryToDelete.getName()); response = this.dbClient.deleteTable(entryToDelete.getName()); LOG.info(response ? "succeeded" : "failed"); } catch (SQLException e) { @@ -420,7 +421,7 @@ public class MariaDbDataMigrationProvider implements DataMigrationProviderServic } for (IndicesEntry index : indices) { try { - LOG.info("deleting index {}", index.getName()); + LOG.info(LOG_DELETING_INDEX, index.getName()); this.dbClient.deleteTable(index.getName()); } catch (SQLException e) { LOG.error("problem deleting index {}: {}", index.getName(), e); diff --git a/sdnr/wt/oauth-provider/provider-jar/pom.xml b/sdnr/wt/oauth-provider/provider-jar/pom.xml index b73602d36..41d5c96b7 100644 --- a/sdnr/wt/oauth-provider/provider-jar/pom.xml +++ b/sdnr/wt/oauth-provider/provider-jar/pom.xml @@ -64,17 +64,6 @@ <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> - <version>3.11.0</version> - <exclusions> - <exclusion> - <groupId>com.fasterxml.jackson.core</groupId> - <artifactId>jackson-databind</artifactId> - </exclusion> - <exclusion> - <groupId>commons-codec</groupId> - <artifactId>commons-codec</artifactId> - </exclusion> - </exclusions> </dependency> <dependency> <groupId>com.highstreet-technologies.aaa</groupId> diff --git a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/data/Config.java b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/data/Config.java index a6dff6769..3ebc144d3 100644 --- a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/data/Config.java +++ b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/data/Config.java @@ -44,9 +44,9 @@ public class Config { private static final String DEFAULT_TOKENSECRET = generateSecret(); private static final String DEFAULT_REDIRECTURI = "/odlux/index.html#/oauth?token="; private static final String DEFAULT_SUPPORTODLUSERS = "true"; + private static Random random; private static Config _instance; - private List<OAuthProviderConfig> providers; private String redirectUri; private String supportOdlUsers; @@ -166,8 +166,9 @@ public class Config { public static String generateSecret(int targetStringLength) { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' - Random random = new Random(); - + if(random==null) { + random = new Random(); + } String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); @@ -197,7 +198,7 @@ public class Config { String envvar = mkey.substring(2, mkey.length() - 1); String env = System.getenv(envvar); tmp = tmp.replace(mkey, env == null ? "" : env); - if (env != null && env != "") { + if (env != null && env.isEmpty()) { found = true; } } catch (SecurityException e) { diff --git a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/http/AuthHttpServlet.java b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/http/AuthHttpServlet.java index 9a9f4fc04..85fe1ced2 100644 --- a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/http/AuthHttpServlet.java +++ b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/http/AuthHttpServlet.java @@ -75,10 +75,8 @@ public class AuthHttpServlet extends HttpServlet { public static final String REDIRECTURI = BASEURI + "/redirect"; private static final String REDIRECTURI_FORMAT = REDIRECTURI + "/%s"; private static final String POLICIESURI = BASEURI + "/policies"; - //private static final String PROVIDERID_REGEX = "^\\" + BASEURI + "\\/providers\\/([^\\/]+)$"; private static final String REDIRECTID_REGEX = "^\\" + BASEURI + "\\/redirect\\/([^\\/]+)$"; private static final String LOGIN_REDIRECT_REGEX = "^\\" + LOGINURI + "\\/([^\\/]+)$"; - //private static final Pattern PROVIDERID_PATTERN = Pattern.compile(PROVIDERID_REGEX); private static final Pattern REDIRECTID_PATTERN = Pattern.compile(REDIRECTID_REGEX); private static final Pattern LOGIN_REDIRECT_PATTERN = Pattern.compile(LOGIN_REDIRECT_REGEX); @@ -96,13 +94,12 @@ public class AuthHttpServlet extends HttpServlet { private final ObjectMapper mapper; /* state <=> AuthProviderService> */ private final Map<String, AuthService> providerStore; - private Authenticator odlAuthenticator; - private IdMService odlIdentityService; private final TokenCreator tokenCreator; private final Config config; - private ShiroConfiguration shiroConfiguration; - private DataBroker dataBroker; - private MdSalAuthorizationStore mdsalAuthStore; + private static Authenticator odlAuthenticator; + private static IdMService odlIdentityService; + private static ShiroConfiguration shiroConfiguration; + private static MdSalAuthorizationStore mdsalAuthStore; public AuthHttpServlet() throws IOException { this.config = Config.getInstance(); @@ -116,21 +113,20 @@ public class AuthHttpServlet extends HttpServlet { } - public void setOdlAuthenticator(Authenticator odlAuthenticator) { - this.odlAuthenticator = odlAuthenticator; + public void setOdlAuthenticator(Authenticator odlAuthenticator2) { + odlAuthenticator = odlAuthenticator2; } - public void setOdlIdentityService(IdMService odlIdentityService) { - this.odlIdentityService = odlIdentityService; + public void setOdlIdentityService(IdMService odlIdentityService2) { + odlIdentityService = odlIdentityService2; } - public void setShiroConfiguration(ShiroConfiguration shiroConfiguration) { - this.shiroConfiguration = shiroConfiguration; + public void setShiroConfiguration(ShiroConfiguration shiroConfiguration2) { + shiroConfiguration = shiroConfiguration2; } public void setDataBroker(DataBroker dataBroker) { - this.dataBroker = dataBroker; - this.mdsalAuthStore = new MdSalAuthorizationStore(this.dataBroker); + mdsalAuthStore = new MdSalAuthorizationStore(dataBroker); } @Override @@ -152,10 +148,12 @@ public class AuthHttpServlet extends HttpServlet { } } + private void handleLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException { this.logout(); - this.sendResponse(resp, HttpServletResponse.SC_OK,""); + this.sendResponse(resp, HttpServletResponse.SC_OK, ""); } + private void handleLoginRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException { final String uri = req.getRequestURI(); final Matcher matcher = LOGIN_REDIRECT_PATTERN.matcher(uri); @@ -163,7 +161,6 @@ public class AuthHttpServlet extends HttpServlet { final String id = matcher.group(1); AuthService provider = this.providerStore.getOrDefault(id, null); if (provider != null) { - //provider.setLocalHostUrl(getHost(req)); String redirectUrl = getHost(req) + String.format(REDIRECTURI_FORMAT, id); provider.sendLoginRedirectResponse(resp, redirectUrl); return; @@ -185,7 +182,7 @@ public class AuthHttpServlet extends HttpServlet { * @return */ private List<OdlPolicy> getPoliciesForUser(HttpServletRequest req) { - List<Urls> urlRules = this.shiroConfiguration.getUrls(); + List<Urls> urlRules = shiroConfiguration.getUrls(); UserTokenPayload data = this.getUserInfo(req); List<OdlPolicy> policies = new ArrayList<>(); if (urlRules != null) { @@ -209,7 +206,7 @@ public class AuthHttpServlet extends HttpServlet { } else if (authClass.equals(CLASSNAME_ODLBEARERANDBASICAUTH)) { policy = this.getTokenBasedPolicy(urlRule, matcher, data); } else if (authClass.equals(CLASSNAME_ODLMDSALAUTH)) { - policy = this.getMdSalBasedPolicy(urlRule, matcher, data); + policy = this.getMdSalBasedPolicy(urlRule, data); } if (policy.isPresent()) { policies.add(policy.get()); @@ -236,13 +233,12 @@ public class AuthHttpServlet extends HttpServlet { * extract policy rule for user from MD-SAL not yet supported * * @param urlRule - * @param matcher * @param data * @return */ - private Optional<OdlPolicy> getMdSalBasedPolicy(Urls urlRule, Matcher matcher, UserTokenPayload data) { - if (this.mdsalAuthStore != null) { - return data != null ? this.mdsalAuthStore.getPolicy(urlRule.getPairKey(), data.getRoles()) + private Optional<OdlPolicy> getMdSalBasedPolicy(Urls urlRule, UserTokenPayload data) { + if (mdsalAuthStore != null) { + return data != null ? mdsalAuthStore.getPolicy(urlRule.getPairKey(), data.getRoles()) : Optional.of(OdlPolicy.denyAll(urlRule.getPairKey())); } return Optional.empty(); @@ -293,8 +289,9 @@ public class AuthHttpServlet extends HttpServlet { if ("anon".equals(key)) { return null; } + List<Main> list = shiroConfiguration.getMain(); Optional<Main> main = - this.shiroConfiguration.getMain().stream().filter((e) -> e.getPairKey().equals(key)).findFirst(); + list == null ? Optional.empty() : list.stream().filter(e -> e.getPairKey().equals(key)).findFirst(); if (main.isPresent()) { return main.get().getPairValue(); } @@ -314,7 +311,7 @@ public class AuthHttpServlet extends HttpServlet { if (!username.contains("@")) { username = String.format("%s@%s", username, domain); } - List<String> roles = this.odlIdentityService.listRoles(username, domain); + List<String> roles = odlIdentityService.listRoles(username, domain); return UserTokenPayload.create(username, roles); } } @@ -440,8 +437,8 @@ public class AuthHttpServlet extends HttpServlet { } HttpServletRequest req = new HeadersOnlyHttpServletRequest( Map.of("Authorization", BaseHTTPClient.getAuthorizationHeaderValue(username, password))); - if (this.odlAuthenticator.authenticate(req)) { - List<String> roles = this.odlIdentityService.listRoles(username, domain); + if (odlAuthenticator.authenticate(req)) { + List<String> roles = odlIdentityService.listRoles(username, domain); UserTokenPayload data = new UserTokenPayload(); data.setPreferredUsername(username); data.setFamilyName(""); @@ -467,6 +464,7 @@ public class AuthHttpServlet extends HttpServlet { os.write(output); } + private void logout() { final Subject subject = SecurityUtils.getSubject(); try { diff --git a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/MdSalAuthorizationStore.java b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/MdSalAuthorizationStore.java index b181af040..293fe33f9 100644 --- a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/MdSalAuthorizationStore.java +++ b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/MdSalAuthorizationStore.java @@ -27,6 +27,7 @@ import java.util.concurrent.ExecutionException; import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.OdlPolicy; import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.OdlPolicy.PolicyMethods; import org.opendaylight.mdsal.binding.api.DataBroker; +import org.opendaylight.mdsal.binding.api.ReadTransaction; import org.opendaylight.mdsal.common.api.LogicalDatastoreType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.HttpAuthorization; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.Policies; @@ -49,17 +50,25 @@ public class MdSalAuthorizationStore { public Optional<OdlPolicy> getPolicy(String path, List<String> userRoles) { InstanceIdentifier<Policies> iif = InstanceIdentifier.create(HttpAuthorization.class).child(Policies.class); Optional<Policies> odata = Optional.empty(); - try { - odata = this.dataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.CONFIGURATION, iif).get(); - } catch (InterruptedException | ExecutionException e) { + try (ReadTransaction transaction = this.dataBroker.newReadOnlyTransaction()) { + odata = transaction.read(LogicalDatastoreType.CONFIGURATION, iif).get(); + } catch (ExecutionException e) { LOG.warn("unable to read policies from mdsal: ", e); + } catch (InterruptedException e) { + LOG.warn("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); } if (odata.isEmpty()) { return Optional.empty(); } - + List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies> data = + odata.get().getPolicies(); + if (data == null) { + return Optional.empty(); + } Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.aaa.rev161214.http.authorization.policies.Policies> entry = - odata.get().getPolicies().stream().filter((e) -> path.equals(e.getResource())).findFirst(); + data.stream().filter(e -> path.equals(e.getResource())).findFirst(); if (entry.isEmpty()) { return Optional.empty(); } @@ -96,7 +105,7 @@ public class MdSalAuthorizationStore { methods.setPatch(true); break; default: - LOG.warn("unknown http method {}",action); + LOG.warn("unknown http method {}", action); break; } } diff --git a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/TokenCreator.java b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/TokenCreator.java index e7e9b72f9..cf8109ef0 100644 --- a/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/TokenCreator.java +++ b/sdnr/wt/oauth-provider/provider-jar/src/main/java/org/onap/ccsdk/features/sdnr/wt/oauthprovider/providers/TokenCreator.java @@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory; public class TokenCreator { private static final Logger LOG = LoggerFactory.getLogger(AuthHttpServlet.class.getName()); - private static final long DEFAULT_TOKEN_LIFETIME_MS = 30 * 60 * 1000; + private static final long DEFAULT_TOKEN_LIFETIME_MS = 30 * 60 * 1000L; private final String issuer; private static TokenCreator _instance; private final String secret; @@ -98,8 +98,8 @@ public class TokenCreator { return new Date().getTime() + DEFAULT_TOKEN_LIFETIME_MS; } - public long getDefaultExp(long exp_in) { - return new Date().getTime() + exp_in; + public long getDefaultExp(long expIn) { + return new Date().getTime() + expIn; } public UserTokenPayload decode(HttpServletRequest req) throws JWTDecodeException { diff --git a/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/ReducedSchemaInfo.java b/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/ReducedSchemaInfo.java index f6e6c5d0d..9bc51d4c5 100644 --- a/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/ReducedSchemaInfo.java +++ b/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/ReducedSchemaInfo.java @@ -21,7 +21,9 @@ */ package org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data; +import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; public class ReducedSchemaInfo { private String namespace; @@ -34,14 +36,23 @@ public class ReducedSchemaInfo { public ReducedSchemaInfo(QName qname) { this.namespace = qname.getNamespace().toString(); - this.revision = qname.getRevision().isPresent() ? qname.getRevision().get().toString() : null; + Optional<Revision> orev = qname.getRevision(); + this.revision = orev.isPresent() ? orev.get().toString() : null; this.type = qname.getLocalName(); } public boolean equals(QName obj) { - return this.namespace.equals(obj.getNamespace().toString()) && this.type.equals(obj.getLocalName()) - && ((this.revision == null && obj.getRevision().isEmpty()) - || (this.revision.equals(obj.getRevision().get().toString()))); + Optional<Revision> orev = obj.getRevision(); + if (this.namespace.equals(obj.getNamespace().toString()) && this.type.equals(obj.getLocalName())) { + if (this.revision == null) { + return orev.isEmpty(); + } else if (orev.isEmpty()) { + return false; + } else { + return orev.get().toString().equals(this.revision); + } + } + return false; } public String getNamespace() { diff --git a/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/SchemaInfo.java b/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/SchemaInfo.java index b920ffe71..032659c47 100644 --- a/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/SchemaInfo.java +++ b/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/SchemaInfo.java @@ -24,7 +24,9 @@ package org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; public class SchemaInfo { private String namespace; @@ -33,14 +35,18 @@ public class SchemaInfo { public SchemaInfo() {} - - public SchemaInfo(QName qname) { - this(qname.getNamespace().toString(), - qname.getRevision().isPresent() ? qname.getRevision().get().toString() : null, new ArrayList<>()); + this(qname.getNamespace().toString(), getRevision(qname), new ArrayList<>()); this.notification.add(qname.getLocalName()); } + private static String getRevision(QName qname) { + Optional<Revision> orev = qname.getRevision(); + return orev.isPresent() ? orev.get().toString() : null; + } + + + public SchemaInfo(String namespace, String revision, List<String> notifications) { this.namespace = namespace; this.revision = revision; @@ -78,8 +84,7 @@ public class SchemaInfo { */ @JsonIgnore public boolean isValid() { - return this.namespace != null - && (this.notification == null || (this.notification != null && !this.notification.isEmpty())); + return this.namespace != null && (this.notification == null || !this.notification.isEmpty()); } /** @@ -95,7 +100,7 @@ public class SchemaInfo { return true; } //if namespace does not match => false - if (!this.namespace.equals(schema.getNamespace().toString())) { + if (!this.namespace.equals(schema.getNamespace())) { return false; } //if revision of scope is set and it does not match and is not '*' => false @@ -120,8 +125,9 @@ public class SchemaInfo { if (this.revision == null && qname.getRevision().isEmpty()) { return true; } + Optional<Revision> orev = qname.getRevision(); if (this.revision != null) { - return this.revision.equals(qname.getRevision().isEmpty() ? null : qname.getRevision().get().toString()); + return this.revision.equals(orev.isEmpty() ? null : orev.get().toString()); } return false; } diff --git a/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/Scope.java b/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/Scope.java index b30aed1a6..4368ed550 100644 --- a/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/Scope.java +++ b/sdnr/wt/websocketmanager/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/model/data/Scope.java @@ -112,7 +112,7 @@ public class Scope { public static List<Scope> createList(String nodeId, List<QName> qnames) { List<Scope> scopes = new ArrayList<>(); - Optional<Scope> listElem = null; + Optional<Scope> listElem; for (QName qname : qnames) { listElem = scopes.stream().filter(e -> e.schema != null && e.schema.equalsNamespaceAndRevision(qname)) .findFirst(); diff --git a/sdnr/wt/websocketmanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/WebSocketManagerSocket.java b/sdnr/wt/websocketmanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/WebSocketManagerSocket.java index 7c12c4baa..7cc6d7272 100644 --- a/sdnr/wt/websocketmanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/WebSocketManagerSocket.java +++ b/sdnr/wt/websocketmanager/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager/WebSocketManagerSocket.java @@ -80,8 +80,12 @@ public class WebSocketManagerSocket extends WebSocketAdapter { .get(SEND_MESSAGE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); LOG.info("message sent"); } - } catch (InterruptedException | ExecutionException | TimeoutException e) { + } catch (ExecutionException | TimeoutException e) { LOG.warn("problem pushing message: ", e); + } catch (InterruptedException e) { + LOG.warn("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); } if (messageQueue.isEmpty()) { @@ -163,7 +167,7 @@ public class WebSocketManagerSocket extends WebSocketAdapter { closed = false; this.sendingSyncThread.start(); clientList.put(String.valueOf(this.hashCode()), this); - LOG.debug("client connected from " + this.getRemoteAdr()); + LOG.debug("client connected from {}", this.getRemoteAdr()); } @Override @@ -171,12 +175,12 @@ public class WebSocketManagerSocket extends WebSocketAdapter { clientList.remove(String.valueOf(this.hashCode())); this.sendingSyncThread.interrupt(); closed = true; - LOG.debug("client disconnected from " + this.getRemoteAdr()); + LOG.debug("client disconnected from {}", this.getRemoteAdr()); } @Override public void onWebSocketError(Throwable cause) { - LOG.debug("error caused on " + this.getRemoteAdr() + " :" + cause.getMessage()); + LOG.debug("error caused on {}: ",this.getRemoteAdr(), cause); } private String getRemoteAdr() { @@ -212,11 +216,11 @@ public class WebSocketManagerSocket extends WebSocketAdapter { } } catch (JsonProcessingException e) { - LOG.warn("problem set scope: " + e.getMessage()); + LOG.warn("problem set scope: {}" ,e.getMessage()); try { this.send(mapper.writeValueAsString(ScopeRegistrationResponse.error(e.getMessage()))); } catch (JsonProcessingException e1) { - LOG.warn("problem sending error response via ws: " + e1); + LOG.warn("problem sending error response via ws: ", e1); } } return ret; @@ -232,7 +236,7 @@ public class WebSocketManagerSocket extends WebSocketAdapter { this.sendToAll(notification.getNodeId(), notification.getType(), request); } } catch (Exception e) { - LOG.warn("handle ws request failed:" + e.getMessage()); + LOG.warn("handle ws request failed:",e); } } @@ -241,7 +245,9 @@ public class WebSocketManagerSocket extends WebSocketAdapter { LOG.trace("sending {}", msg); this.messageQueue.put(msg); } catch (InterruptedException e) { - LOG.warn("problem putting message into sending queue: " + e.getMessage()); + LOG.warn("problem putting message into sending queue: {}", e.getMessage()); + // Restore interrupted state... + Thread.currentThread().interrupt(); } } @@ -294,8 +300,13 @@ public class WebSocketManagerSocket extends WebSocketAdapter { } public static void broadCast(DOMNotificationOutput domNotificationOutput) { - // TODO Auto-generated method stub - + if (clientList.size() > 0) { + Set<Entry<String, WebSocketManagerSocket>> e = clientList.entrySet(); + WebSocketManagerSocket s = e.iterator().next().getValue(); + if (s != null) { + s.sendToAll(domNotificationOutput); + } + } } } diff --git a/sdnr/wt/websocketmanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager2/test/UserScopeTest.java b/sdnr/wt/websocketmanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager2/test/UserScopeTest.java index 885ded348..ca3d6918c 100644 --- a/sdnr/wt/websocketmanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager2/test/UserScopeTest.java +++ b/sdnr/wt/websocketmanager/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/websocketmanager2/test/UserScopeTest.java @@ -58,6 +58,16 @@ public class UserScopeTest { } + @Test + public void testSchemaInfoClass() { + ReducedSchemaInfo si = new ReducedSchemaInfo(ProblemNotification.QNAME); + assertTrue(si.equals(ProblemNotification.QNAME)); + assertFalse(si.equals(ObjectCreationNotification.QNAME)); + si.setRevision(null); + assertFalse(si.equals(ProblemNotification.QNAME)); + + } + private static final Scope buildScope(String nodeId, String namespace, String revision, List<String> notifications) { Scope scope = new Scope(); |