From 52d1616151680d46cceb62cba752465ffd75a298 Mon Sep 17 00:00:00 2001 From: highstreetherbert Date: Fri, 10 Jul 2020 17:18:59 +0200 Subject: Reformat sdnr data-provider to ONAP code style Reformat to ONAP code style Issue-ID: SDNC-1275 Signed-off-by: highstreetherbert Change-Id: I16230015ab8af278ec9f865690b9308d8fa2c78a Signed-off-by: highstreetherbert --- .../dataprovider/model/ArchiveCleanProvider.java | 6 +- .../sdnr/wt/dataprovider/model/DataProvider.java | 10 +- .../dataprovider/model/HtDatabaseMaintenance.java | 4 +- .../wt/dataprovider/model/IEntityDataProvider.java | 6 +- .../sdnr/wt/dataprovider/model/IEsConfig.java | 6 +- .../wt/dataprovider/model/NetconfTimeStamp.java | 104 +-- .../dataprovider/model/StatusChangedHandler.java | 17 +- .../model/types/NetconfTimeStampImpl.java | 67 +- .../wt/dataprovider/data/DataObjectAcessor.java | 39 +- .../wt/dataprovider/data/DataObjectAcessorPm.java | 242 ++--- .../dataprovider/data/DataObjectAcessorStatus.java | 45 +- .../wt/dataprovider/data/DataTreeChildObject.java | 27 +- .../sdnr/wt/dataprovider/data/DataTreeObject.java | 4 +- .../data/ElasticSearchDataProvider.java | 122 +-- .../wt/dataprovider/data/FaultEntityManager.java | 11 +- .../dataprovider/data/HtDatabaseEventsService.java | 110 ++- .../data/HtDatabaseMaintenanceService.java | 26 +- .../data/MediatorServerDataProvider.java | 104 +-- .../sdnr/wt/dataprovider/data/ODLVersionLUT.java | 75 +- .../sdnr/wt/dataprovider/data/QueryByFilter.java | 316 ++++--- .../sdnr/wt/dataprovider/data/QueryResult.java | 41 +- .../sdnr/wt/dataprovider/data/SystemInfo.java | 526 +++++------ .../wt/dataprovider/data/YangFileProvider.java | 326 ++++--- .../sdnr/wt/dataprovider/data/YangFilename.java | 77 +- .../database/EsDataObjectReaderWriter.java | 442 ++++----- .../database/EsDataObjectReaderWriter2.java | 100 ++- .../wt/dataprovider/http/AboutHttpServlet.java | 566 ++++++------ .../wt/dataprovider/http/DataTreeHttpServlet.java | 42 +- .../wt/dataprovider/http/GetYangSchemaRequest.java | 64 +- .../sdnr/wt/dataprovider/http/MsServlet.java | 159 ++-- .../wt/dataprovider/http/ReadyHttpServlet.java | 55 +- .../dataprovider/http/YangSchemaHttpServlet.java | 170 ++-- .../wt/dataprovider/impl/DataProviderImpl.java | 13 +- .../dataprovider/impl/DataProviderServiceImpl.java | 122 ++- .../sdnr/wt/dataprovider/impl/EsConfig.java | 38 +- .../wt/dataprovider/yangtools/YangToolsCloner.java | 37 +- .../wt/dataprovider/yangtools/YangToolsMapper.java | 351 ++++---- .../dataprovider/yangtools/YangToolsMapper2.java | 434 ++++----- .../sdnr/wt/dataprovider/test/TestAbout.java | 180 ++-- .../wt/dataprovider/test/TestCRUDforDatabase.java | 994 ++++++++++----------- .../sdnr/wt/dataprovider/test/TestConfig.java | 35 +- .../wt/dataprovider/test/TestConfiguration.java | 4 +- .../wt/dataprovider/test/TestDataMappings.java | 283 +++--- .../test/TestDataTreeSerialization.java | 2 +- .../wt/dataprovider/test/TestEventService.java | 440 ++++----- .../wt/dataprovider/test/TestFilterConversion.java | 65 +- .../wt/dataprovider/test/TestImplementation.java | 78 +- .../test/TestMaintenanceServiceData.java | 14 +- .../test/TestMediatorServerService.java | 94 +- .../dataprovider/test/TestNetconfNodeBuilder.java | 6 +- .../wt/dataprovider/test/TestNetconfTimestamp.java | 77 +- .../sdnr/wt/dataprovider/test/TestNuMappings.java | 4 +- .../wt/dataprovider/test/TestTimestampFilter.java | 251 +++--- .../sdnr/wt/dataprovider/test/TestYangCloning.java | 12 +- .../dataprovider/test/TestYangGenSalMapping.java | 150 ++-- .../wt/dataprovider/test/TestYangProvider.java | 283 +++--- .../setup/DataMigrationProviderImpl.java | 108 +-- .../setup/DataMigrationProviderService.java | 81 +- .../sdnr/wt/dataprovider/setup/Program.java | 200 +++-- .../wt/dataprovider/setup/ReleaseInformation.java | 301 ++++--- .../setup/data/BaseSearchHitConverter.java | 46 +- .../wt/dataprovider/setup/data/ComponentData.java | 68 +- .../wt/dataprovider/setup/data/ComponentName.java | 63 +- .../wt/dataprovider/setup/data/ConfigData.java | 15 +- .../wt/dataprovider/setup/data/ConfigName.java | 55 +- .../wt/dataprovider/setup/data/DataContainer.java | 196 ++-- .../setup/data/DataMigrationReport.java | 54 +- .../wt/dataprovider/setup/data/DatabaseInfo.java | 72 +- .../setup/data/KeepDataSearchHitConverter.java | 27 +- .../setup/data/MavenDatabasePluginInitFile.java | 42 +- .../sdnr/wt/dataprovider/setup/data/Release.java | 148 +-- .../setup/data/SearchHitConverter.java | 61 +- .../setup/elalto/ElAltoReleaseInformation.java | 126 +-- .../elalto/FrankfurtConnectionlogConverter.java | 119 ++- .../setup/elalto/FrankfurtEventlogConverter.java | 27 +- .../elalto/FrankfurtFaultcurrentConverter.java | 67 +- .../setup/elalto/FrankfurtFaultlogConverter.java | 65 +- .../elalto/FrankfurtMaintenanceConverter.java | 73 +- .../FrankfurtRequiredNetworkElementConverter.java | 61 +- .../frankfurt/FrankfurtReleaseInformation.java | 108 +-- .../setup/frankfurt/data/ConnectionLogStatus.java | 14 +- .../setup/guilin/GuilinReleaseInformation.java | 76 +- .../sdnr/wt/dataprovider/setup/TestData.java | 231 +++-- .../setup/TestElAltoReleaseInformation.java | 6 +- .../setup/TestElAltoToFrankfurtConversion.java | 173 ++-- .../setup/TestFrankfurtReleaseInformation.java | 6 +- .../dataprovider/setup/TestMigrationProvider.java | 10 +- 87 files changed, 5302 insertions(+), 5273 deletions(-) (limited to 'sdnr') diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/ArchiveCleanProvider.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/ArchiveCleanProvider.java index 559ed3148..2af7324e5 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/ArchiveCleanProvider.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/ArchiveCleanProvider.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model; import java.util.Date; @@ -23,6 +23,7 @@ public interface ArchiveCleanProvider { /** * Remove all index data older, than specified from faultlog and eventlog + * * @param olderAreOutdated time to specify older elements * @return number of removed elements */ @@ -30,6 +31,7 @@ public interface ArchiveCleanProvider { /** * Get number of elements older then + * * @param olderAreOutdated date to compare with and specify older elements * @return number of elements */ diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/DataProvider.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/DataProvider.java index 15cc89212..a9e334668 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/DataProvider.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/DataProvider.java @@ -67,6 +67,7 @@ public interface DataProvider extends ArchiveCleanProvider { /** * write internal equipment to database + * * @param internalEquipment with mandatory fields. */ void writeInventory(Inventory internalEquipment); @@ -81,6 +82,7 @@ public interface DataProvider extends ArchiveCleanProvider { /** * Update after new mountpoint registration + * * @param networkElementConnectionEntitiy data * @param nodeId of device (mountpoint name) */ @@ -101,9 +103,9 @@ public interface DataProvider extends ArchiveCleanProvider { */ void doWritePerformanceData(List list); - /** - * @return - */ - HtDatabaseClient getRawClient(); + /** + * @return + */ + HtDatabaseClient getRawClient(); } diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/HtDatabaseMaintenance.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/HtDatabaseMaintenance.java index 11681c05f..51fe25d89 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/HtDatabaseMaintenance.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/HtDatabaseMaintenance.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model; import java.util.List; diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEntityDataProvider.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEntityDataProvider.java index 95ea0752b..9ba10cd0b 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEntityDataProvider.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEntityDataProvider.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model; import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.StatusChangedHandler.StatusKey; @@ -31,7 +31,7 @@ public interface IEntityDataProvider { public void setReadyStatus(boolean status); /** Set some static status information after startup */ - public void setStatus(StatusKey key,String value); + public void setStatus(StatusKey key, String value); /** Database configuration information **/ public IEsConfig getEsConfig(); diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEsConfig.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEsConfig.java index f41095db9..0f8f5e37d 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEsConfig.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/IEsConfig.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model; import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; @@ -44,5 +44,5 @@ public interface IEsConfig { void registerConfigChangedListener(IConfigChangedListener archiveCleanService); - + } diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/NetconfTimeStamp.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/NetconfTimeStamp.java index 5bed9f7a3..26962c2e6 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/NetconfTimeStamp.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/NetconfTimeStamp.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model; import java.time.LocalDateTime; @@ -27,61 +27,63 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types. */ public interface NetconfTimeStamp { - /** - * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format - * - * @return String with Date in NETCONF/YANG Format Version 1.0. - */ - String getTimeStampAsNetconfString(); + /** + * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format + * + * @return String with Date in NETCONF/YANG Format Version 1.0. + */ + String getTimeStampAsNetconfString(); - /** - * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format - - * @return String with Date in NETCONF/YANG Format Version 1.0. - */ - String getTimeStampAsNetconfString(Date date); + /** + * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format + * + * @return String with Date in NETCONF/YANG Format Version 1.0. + */ + String getTimeStampAsNetconfString(Date date); - /** - * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format in GMT - * - * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. - */ - DateAndTime getTimeStamp(); + /** + * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * + * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. + */ + DateAndTime getTimeStamp(); - /** - * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT - * @param date specifying the date and time - * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. - */ - DateAndTime getTimeStamp(Date date); + /** + * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * + * @param date specifying the date and time + * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. + */ + DateAndTime getTimeStamp(Date date); - /** - * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT - * @param date specifying the date and time - * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. - */ - DateAndTime getTimeStamp(String date); + /** + * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * + * @param date specifying the date and time + * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. + */ + DateAndTime getTimeStamp(String date); - /** - * Return the String with a NETCONF time converted to long - * - * @param netconfTime as String according the formats given above - * @return Epoch milliseconds - * @throws IllegalArgumentException In case of no compliant time format definition for the string - */ - long getTimeStampFromNetconfAsMilliseconds(String netconfTime) throws IllegalArgumentException; + /** + * Return the String with a NETCONF time converted to long + * + * @param netconfTime as String according the formats given above + * @return Epoch milliseconds + * @throws IllegalArgumentException In case of no compliant time format definition for the string + */ + long getTimeStampFromNetconfAsMilliseconds(String netconfTime) throws IllegalArgumentException; - /** - * Deliver String result. - * - * @param netconfTime as String according the formats given above - * @return If successful: String in ISO8601 Format for database and presentation. If "wrong formed - * input" the Input string with the prefix "Maleformed date" is delivered back. - */ - String getTimeStampFromNetconf(String netconfTime); + /** + * Deliver String result. + * + * @param netconfTime as String according the formats given above + * @return If successful: String in ISO8601 Format for database and presentation. If "wrong formed input" the Input + * string with the prefix "Maleformed date" is delivered back. + */ + String getTimeStampFromNetconf(String netconfTime); - Date getDateFromNetconf(String netconfTime); + Date getDateFromNetconf(String netconfTime); - String getTimeStampAsNetconfString(LocalDateTime dt); + String getTimeStampAsNetconfString(LocalDateTime dt); -} \ No newline at end of file +} diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/StatusChangedHandler.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/StatusChangedHandler.java index fa64d4d3e..d97ee8463 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/StatusChangedHandler.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/StatusChangedHandler.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,16 +14,17 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model; public interface StatusChangedHandler { - public enum StatusKey { - CLUSTER_SIZE, - - } - public void onStatusChanged(StatusKey key,String newValue); - + public enum StatusKey { + CLUSTER_SIZE, + + } + + public void onStatusChanged(StatusKey key, String newValue); + } diff --git a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/NetconfTimeStampImpl.java b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/NetconfTimeStampImpl.java index f5dd65269..c7f921708 100644 --- a/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/NetconfTimeStampImpl.java +++ b/sdnr/wt/data-provider/model/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/model/types/NetconfTimeStampImpl.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types; import java.time.LocalDateTime; @@ -41,32 +41,25 @@ import org.slf4j.LoggerFactory; * Format2 NETCONF - pattern from ietf-yang-types "2013-07-15" Pattern: * "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[\+\-](\d{2}):(\d{2}))" * - * Format3 NETCONF DateAndTime CoreModel-CoreFoundationModule-TypeDefinitions vom - * 2016-07-01 Example1: 20170118114449.1Z Example2: 20170118114449.1-0500 Pattern: - * "\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}.\d+?(Z|[\+\-](\d{2})(\d{2}))" typedef DateAndTime { description - * "This primitive type defines the date and time according to the following structure: - * 'yyyyMMddhhmmss.s[Z|{+|-}HHMm]' where: yyyy '0000'..'9999' year MM '01'..'12' month dd '01'..'31' - * day hh '00'..'23' hour mm '00'..'59' minute ss '00'..'59' second s '.0'..'.9' tenth of second - * (set to '.0' if EMS or NE cannot support this granularity) Z 'Z' indicates UTC (rather than local - * time) {+|-} '+' or '-' delta from UTC HH '00'..'23' time zone difference in hours Mm '00'..'59' - * time zone difference in minutes."; type string; } Format4 E/// specific Example1: - * 2017-01-23T13:32:38-05:00 Example2: 2017-01-23T13:32-05:00 + * Format3 NETCONF DateAndTime CoreModel-CoreFoundationModule-TypeDefinitions vom 2016-07-01 Example1: 20170118114449.1Z + * Example2: 20170118114449.1-0500 Pattern: "\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}.\d+?(Z|[\+\-](\d{2})(\d{2}))" typedef + * DateAndTime { description "This primitive type defines the date and time according to the following structure: + * 'yyyyMMddhhmmss.s[Z|{+|-}HHMm]' where: yyyy '0000'..'9999' year MM '01'..'12' month dd '01'..'31' day hh '00'..'23' + * hour mm '00'..'59' minute ss '00'..'59' second s '.0'..'.9' tenth of second (set to '.0' if EMS or NE cannot support + * this granularity) Z 'Z' indicates UTC (rather than local time) {+|-} '+' or '-' delta from UTC HH '00'..'23' time + * zone difference in hours Mm '00'..'59' time zone difference in minutes."; type string; } Format4 E/// specific + * Example1: 2017-01-23T13:32:38-05:00 Example2: 2017-01-23T13:32-05:00 * * Input formats netconfTime as String according the formats given above * * Return format is String in ISO8601 Format for database and presentation. * - * Example formats: - * 1) ISO8601. Example 2017-01-18T11:44:49.482-05:00 - * 2) Microwave ONF. Examples 20170118114449.1Z, 20170118114449.1-0500 - * 3.1) Ericson. Example: 2017-01-23T13:32:38-05:00 - * 3.2) Ericson. Example: 2017-01-23T13:32-05:00 - * Always 10 Groups, - * 1:Year 2:Month 3:day 4:Hour 5:minute 6:optional sec 7:optional ms 8:optional Z or 9:offset - * signedhour 10:min + * Example formats: 1) ISO8601. Example 2017-01-18T11:44:49.482-05:00 2) Microwave ONF. Examples 20170118114449.1Z, + * 20170118114449.1-0500 3.1) Ericson. Example: 2017-01-23T13:32:38-05:00 3.2) Ericson. Example: 2017-01-23T13:32-05:00 + * Always 10 Groups, 1:Year 2:Month 3:day 4:Hour 5:minute 6:optional sec 7:optional ms 8:optional Z or 9:offset + * signedhour 10:min * - * Template: - * private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); + * Template: private static final NetconfTimeStamp NETCONFTIME_CONVERTER = NetconfTimeStamp.getConverter(); */ public class NetconfTimeStampImpl implements NetconfTimeStamp { @@ -77,22 +70,20 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { /** * Specify the input format expected from netconf, and from specific devices. */ - private static DateTimeFormatter formatterInput = DateTimeFormatter.ofPattern("" - + "[yyyy-MM-dd'T'HH:mm[:ss][.SSS][.SS][.S][xxx][xx][X][Z]]" - + "[yyyyMMddHHmmss[.SSS][.SS][.S][xxx][xx][X][Z]]" - ).withZone(ZoneOffset.UTC); + private static DateTimeFormatter formatterInput = + DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd'T'HH:mm[:ss][.SSS][.SS][.S][xxx][xx][X][Z]]" + + "[yyyyMMddHHmmss[.SSS][.SS][.S][xxx][xx][X][Z]]").withZone(ZoneOffset.UTC); /** * Specify output format that is used internally */ - private static DateTimeFormatter formatterOutput = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z'") - .withZone(ZoneOffset.UTC); + private static DateTimeFormatter formatterOutput = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z'").withZone(ZoneOffset.UTC); /** * Use static access */ - private NetconfTimeStampImpl() { - } + private NetconfTimeStampImpl() {} /* * ------------------------------------ Public function @@ -100,6 +91,7 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { /** * Use this function to get the converter + * * @return global converter */ public static NetconfTimeStamp getConverter() { @@ -118,12 +110,12 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { /** * Get actual timestamp as NETCONF specific type NETCONF/YANG 1.0 Format - + * * @return String with Date in NETCONF/YANG Format Version 1.0. */ @Override public String getTimeStampAsNetconfString(Date date) { - return ZonedDateTime.ofInstant(date.toInstant(),ZoneOffset.UTC).format(formatterOutput); + return ZonedDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC).format(formatterOutput); } @@ -140,6 +132,7 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { /** * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * * @param date specifying the date and time * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. */ @@ -147,8 +140,10 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { public DateAndTime getTimeStamp(Date date) { return DateAndTime.getDefaultInstance(getTimeStampAsNetconfString(date)); } + /** * Get time from date as NETCONF specific type NETCONF/YANG 1.0 Format in GMT + * * @param date specifying the date and time * @return DateAndTime Type 1.0. Date in NETCONF/YANG Format Version 1.0. */ @@ -173,14 +168,14 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { throw new IllegalArgumentException( "No pattern for NETCONF data string: " + netconfTime + " Msg:" + e.getMessage()); } - } + } /** * Deliver String result. * * @param netconfTime as String according the formats given above - * @return If successful: String in ISO8601 Format for database and presentation. If "wrong formed - * input" the Input string with the prefix "Maleformed date" is delivered back. + * @return If successful: String in ISO8601 Format for database and presentation. If "wrong formed input" the Input + * string with the prefix "Maleformed date" is delivered back. */ @Override public String getTimeStampFromNetconf(String netconfTime) { @@ -189,7 +184,7 @@ public class NetconfTimeStampImpl implements NetconfTimeStamp { return inputUTC; } catch (Exception e) { LOG.info(e.getMessage()); - } + } LOG.debug("No pattern for NETCONF data string: {}", netconfTime); return "Malformed date: " + netconfTime; // Error handling } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessor.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessor.java index b7abe5950..3fe2a62af 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessor.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessor.java @@ -33,28 +33,29 @@ import org.slf4j.LoggerFactory; public class DataObjectAcessor extends EsDataObjectReaderWriter { - private static final Logger LOG = LoggerFactory.getLogger(DataObjectAcessor.class); + private static final Logger LOG = LoggerFactory.getLogger(DataObjectAcessor.class); - public DataObjectAcessor(HtDatabaseClient dbClient, Entity entity, Class clazz) throws ClassNotFoundException { - this(dbClient, entity, clazz, true); - LOG.info("Create {}", this.getClass().getName()); - } + public DataObjectAcessor(HtDatabaseClient dbClient, Entity entity, Class clazz) throws ClassNotFoundException { + this(dbClient, entity, clazz, true); + LOG.info("Create {}", this.getClass().getName()); + } - public DataObjectAcessor(HtDatabaseClient dbClient, Entity entity, Class clazz, boolean idSupported) throws ClassNotFoundException { - super(dbClient, entity, clazz); - if (idSupported) { - setEsIdAttributeName("_id"); - } - } + public DataObjectAcessor(HtDatabaseClient dbClient, Entity entity, Class clazz, boolean idSupported) + throws ClassNotFoundException { + super(dbClient, entity, clazz); + if (idSupported) { + setEsIdAttributeName("_id"); + } + } - QueryResult getData(EntityInput input) { - long page = QueryByFilter.getPage(input); - long pageSize = QueryByFilter.getPageSize(input); + QueryResult getData(EntityInput input) { + long page = QueryByFilter.getPage(input); + long pageSize = QueryByFilter.getPageSize(input); LOG.info("Request: {}", this.getDataTypeName()); - QueryBuilder query = QueryByFilter.fromFilter(input.getFilter()).from((page - 1) * pageSize).size(pageSize); - QueryByFilter.setSortOrder(query, input.getSortorder()); - SearchResult result = doReadAll(query,query.contains("range")); - return new QueryResult<>(page, pageSize, result); - } + QueryBuilder query = QueryByFilter.fromFilter(input.getFilter()).from((page - 1) * pageSize).size(pageSize); + QueryByFilter.setSortOrder(query, input.getSortorder()); + SearchResult result = doReadAll(query, query.contains("range")); + return new QueryResult<>(page, pageSize, result); + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorPm.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorPm.java index ec1a20880..8eb51b6aa 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorPm.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorPm.java @@ -42,124 +42,128 @@ import org.slf4j.LoggerFactory; public class DataObjectAcessorPm extends DataObjectAcessor { - private final Logger LOG = LoggerFactory.getLogger(DataObjectAcessorPm.class); - - private static final String UUID_KEY = "uuid-interface"; - private static final String NODE_KEY = "node-name"; - private static final String KEY = "node-name"; - - - enum Intervall { - PMDATA15M("historicalperformance15min", "historicalperformance15min"), - PMDATA24H("historicalperformance24h", "historicalperformance24h"); - - String index; - String type; - - Intervall(String index, String type) { - this.index = index; - this.type = type; - } - - public String getIndex() { - return index; - } - - public String getType() { - return type; - } - } - - private ExtRestClient dbClient; - private Intervall mode; - - public DataObjectAcessorPm(HtDatabaseClient dbClient, Intervall mode, Entity entity, Class clazz) throws ClassNotFoundException { - super(dbClient, entity, clazz, false); - this.dbClient = dbClient; - this.mode = mode; - } - - /** - * get aggregated list of ltps for filter NODE_KEY - * @param input - * @return - * @throws IOException - */ - QueryResult getDataLtpList(EntityInput input) throws IOException { - long page = QueryByFilter.getPage(input); - long pageSize = QueryByFilter.getPageSize(input); - Filter nodeFilter = QueryByFilter.getFilter(input.getFilter(), NODE_KEY); - if (nodeFilter != null) { - SearchRequest request = new SearchRequest(mode.getIndex(), mode.getType()); - request.setQuery(QueryBuilders.matchQuery(NODE_KEY, nodeFilter.getFiltervalue()).aggregations(UUID_KEY).size(0)); - try { - SearchResponse response = this.dbClient.search(request); - AggregationEntries aggs = response.getAggregations(UUID_KEY); - String[] uuids = aggs.getKeysAsPagedStringList(pageSize, pageSize * (page - 1)); - long totalSize = aggs.size(); - return new QueryResult(page, pageSize, new SearchResult(uuids, totalSize)); - } catch (IOException e) { - throw new IOException("problem reading ltps for req="+request, e); - } - } else { - String msg = "no nodename in filter found "; - LOG.debug(msg); - throw new IllegalArgumentException(msg); - } - } - -// QueryResult getDataDeviceList(EntityInput input) throws IOException { -// -// long page = QueryByFilter.getPage(input); -// long pageSize = QueryByFilter.getPageSize(input); -// -// SearchRequest request = new SearchRequest(mode.getIndex(), mode.getType()); -// request.setQuery(QueryBuilders.matchAllQuery().aggregations(KEY).size(0)); -//// try { -// SearchResponse response = this.dbClient.search(request); -// AggregationEntries aggs = response.getAggregations(KEY); -// String[] uuids = aggs.getKeysAsPagedStringList(pageSize, pageSize * (page - 1)); -// long totalSize = aggs.size(); -// return new QueryResult(page, pageSize, new SearchResult(uuids, totalSize)); -//// } catch (IOException e) { -//// throw new IOException("problem reading nodes for req="+request, e); -//// } -// } - /** - * get aggregated devices list - * @param input filter should be empty/no filter handled, only sortorder for KEY ('node-name') - * @return - * @throws IOException - */ - QueryResult getDataDeviceList(EntityInput input) throws IOException { - - long page = QueryByFilter.getPage(input); - long pageSize = QueryByFilter.getPageSize(input); - - Sortorder soNode = QueryByFilter.getSortOrder(input.getSortorder(), KEY); - SearchRequest request = new SearchRequest(mode.getIndex(), mode.getType()); - QueryBuilder query = null; - if (soNode != null) { - query = QueryBuilders.matchAllQuery() - .aggregations(KEY, - soNode.getSortorder() == SortOrder.Ascending - ? org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder.ASCENDING - : org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder.DESCENDING) - .size(0); - } else { - query = QueryBuilders.matchAllQuery().aggregations(KEY).size(0); - } - request.setQuery(query); - try { - SearchResponse response = this.dbClient.search(request); - AggregationEntries aggs = response.getAggregations(KEY); - String[] uuids = aggs.getKeysAsPagedStringList(pageSize, pageSize * (page - 1)); - long totalSize = aggs.size(); - return new QueryResult(page, pageSize, new SearchResult(uuids, totalSize)); - } catch (IOException e) { - throw new IOException("problem reading nodes for req=" + request, e); - } - - } + private final Logger LOG = LoggerFactory.getLogger(DataObjectAcessorPm.class); + + private static final String UUID_KEY = "uuid-interface"; + private static final String NODE_KEY = "node-name"; + private static final String KEY = "node-name"; + + + enum Intervall { + PMDATA15M("historicalperformance15min", "historicalperformance15min"), PMDATA24H("historicalperformance24h", + "historicalperformance24h"); + + String index; + String type; + + Intervall(String index, String type) { + this.index = index; + this.type = type; + } + + public String getIndex() { + return index; + } + + public String getType() { + return type; + } + } + + private ExtRestClient dbClient; + private Intervall mode; + + public DataObjectAcessorPm(HtDatabaseClient dbClient, Intervall mode, Entity entity, Class clazz) + throws ClassNotFoundException { + super(dbClient, entity, clazz, false); + this.dbClient = dbClient; + this.mode = mode; + } + + /** + * get aggregated list of ltps for filter NODE_KEY + * + * @param input + * @return + * @throws IOException + */ + QueryResult getDataLtpList(EntityInput input) throws IOException { + long page = QueryByFilter.getPage(input); + long pageSize = QueryByFilter.getPageSize(input); + Filter nodeFilter = QueryByFilter.getFilter(input.getFilter(), NODE_KEY); + if (nodeFilter != null) { + SearchRequest request = new SearchRequest(mode.getIndex(), mode.getType()); + request.setQuery( + QueryBuilders.matchQuery(NODE_KEY, nodeFilter.getFiltervalue()).aggregations(UUID_KEY).size(0)); + try { + SearchResponse response = this.dbClient.search(request); + AggregationEntries aggs = response.getAggregations(UUID_KEY); + String[] uuids = aggs.getKeysAsPagedStringList(pageSize, pageSize * (page - 1)); + long totalSize = aggs.size(); + return new QueryResult(page, pageSize, new SearchResult(uuids, totalSize)); + } catch (IOException e) { + throw new IOException("problem reading ltps for req=" + request, e); + } + } else { + String msg = "no nodename in filter found "; + LOG.debug(msg); + throw new IllegalArgumentException(msg); + } + } + + // QueryResult getDataDeviceList(EntityInput input) throws IOException { + // + // long page = QueryByFilter.getPage(input); + // long pageSize = QueryByFilter.getPageSize(input); + // + // SearchRequest request = new SearchRequest(mode.getIndex(), mode.getType()); + // request.setQuery(QueryBuilders.matchAllQuery().aggregations(KEY).size(0)); + //// try { + // SearchResponse response = this.dbClient.search(request); + // AggregationEntries aggs = response.getAggregations(KEY); + // String[] uuids = aggs.getKeysAsPagedStringList(pageSize, pageSize * (page - 1)); + // long totalSize = aggs.size(); + // return new QueryResult(page, pageSize, new SearchResult(uuids, totalSize)); + //// } catch (IOException e) { + //// throw new IOException("problem reading nodes for req="+request, e); + //// } + // } + /** + * get aggregated devices list + * + * @param input filter should be empty/no filter handled, only sortorder for KEY ('node-name') + * @return + * @throws IOException + */ + QueryResult getDataDeviceList(EntityInput input) throws IOException { + + long page = QueryByFilter.getPage(input); + long pageSize = QueryByFilter.getPageSize(input); + + Sortorder soNode = QueryByFilter.getSortOrder(input.getSortorder(), KEY); + SearchRequest request = new SearchRequest(mode.getIndex(), mode.getType()); + QueryBuilder query = null; + if (soNode != null) { + query = QueryBuilders.matchAllQuery() + .aggregations(KEY, + soNode.getSortorder() == SortOrder.Ascending + ? org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder.ASCENDING + : org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder.DESCENDING) + .size(0); + } else { + query = QueryBuilders.matchAllQuery().aggregations(KEY).size(0); + } + request.setQuery(query); + try { + SearchResponse response = this.dbClient.search(request); + AggregationEntries aggs = response.getAggregations(KEY); + String[] uuids = aggs.getKeysAsPagedStringList(pageSize, pageSize * (page - 1)); + long totalSize = aggs.size(); + return new QueryResult(page, pageSize, new SearchResult(uuids, totalSize)); + } catch (IOException e) { + throw new IOException("problem reading nodes for req=" + request, e); + } + + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorStatus.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorStatus.java index c1a6b2936..4dd52f43a 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorStatus.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataObjectAcessorStatus.java @@ -37,39 +37,34 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro public class DataObjectAcessorStatus extends DataObjectAcessor { - final String ESDATATYPE_FAULTCURRENT_SEVERITY_KEY = "severity"; + final String ESDATATYPE_FAULTCURRENT_SEVERITY_KEY = "severity"; - private final ExtRestClient dbClient; - private final Entity entity; + private final ExtRestClient dbClient; + private final Entity entity; - public DataObjectAcessorStatus(HtDatabaseClient dbClient, Entity entity) - throws ClassNotFoundException { - super(dbClient, entity, Data.class, false); - this.dbClient = dbClient; - this.entity = entity; - } + public DataObjectAcessorStatus(HtDatabaseClient dbClient, Entity entity) throws ClassNotFoundException { + super(dbClient, entity, Data.class, false); + this.dbClient = dbClient; + this.entity = entity; + } - QueryResult getDataStatus() throws IOException { - SearchRequest request = getNewInstanceOfSearchRequest(entity); - request.setQuery( - QueryBuilders.matchAllQuery().aggregations(ESDATATYPE_FAULTCURRENT_SEVERITY_KEY).size(0)); - SearchResponse response = this.dbClient.search(request); - AggregationEntries aggs = response.getAggregations(ESDATATYPE_FAULTCURRENT_SEVERITY_KEY); + QueryResult getDataStatus() throws IOException { + SearchRequest request = getNewInstanceOfSearchRequest(entity); + request.setQuery(QueryBuilders.matchAllQuery().aggregations(ESDATATYPE_FAULTCURRENT_SEVERITY_KEY).size(0)); + SearchResponse response = this.dbClient.search(request); + AggregationEntries aggs = response.getAggregations(ESDATATYPE_FAULTCURRENT_SEVERITY_KEY); - Data[] data = { new DataBuilder().setFaults(new FaultsBuilder(). - setCriticals(aggs.getOrDefault("Critical",0L)). - setMajors(aggs.getOrDefault("Major", 0L)). - setMinors(aggs.getOrDefault("Minor", 0L)). - setWarnings(aggs.getOrDefault("Warning", 0L)). - build()).build() }; - long toalsize = data.length; - return new QueryResult(1L, 1L, new SearchResult(data, toalsize)); + Data[] data = {new DataBuilder().setFaults(new FaultsBuilder().setCriticals(aggs.getOrDefault("Critical", 0L)) + .setMajors(aggs.getOrDefault("Major", 0L)).setMinors(aggs.getOrDefault("Minor", 0L)) + .setWarnings(aggs.getOrDefault("Warning", 0L)).build()).build()}; + long toalsize = data.length; + return new QueryResult(1L, 1L, new SearchResult(data, toalsize)); - } + } private static SearchRequest getNewInstanceOfSearchRequest(Entity entity) { - return new SearchRequest(entity.getName(), entity.getName()); + return new SearchRequest(entity.getName(), entity.getName()); } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeChildObject.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeChildObject.java index f75989acd..a92265a84 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeChildObject.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeChildObject.java @@ -29,17 +29,18 @@ import java.util.Map; */ public class DataTreeChildObject { - private final String label; - private final String ownSeverity; - private final String childrenSeveritySummary; - private final boolean isMatch; - private final Map children; - - public DataTreeChildObject(String label,boolean isMatch,Mapchildren,String ownSeverity,String childrenSeveritySummary) { - this.label = label; - this.isMatch = isMatch; - this.children = children; - this.ownSeverity = ownSeverity; - this.childrenSeveritySummary = childrenSeveritySummary; - } + private final String label; + private final String ownSeverity; + private final String childrenSeveritySummary; + private final boolean isMatch; + private final Map children; + + public DataTreeChildObject(String label, boolean isMatch, Map children, + String ownSeverity, String childrenSeveritySummary) { + this.label = label; + this.isMatch = isMatch; + this.children = children; + this.ownSeverity = ownSeverity; + this.childrenSeveritySummary = childrenSeveritySummary; + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeObject.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeObject.java index cc3f6cc55..4333dccb4 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeObject.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/DataTreeObject.java @@ -27,6 +27,6 @@ import java.util.HashMap; * @author Michael Dürre * */ -public class DataTreeObject extends HashMap { - +public class DataTreeObject extends HashMap { + } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ElasticSearchDataProvider.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ElasticSearchDataProvider.java index 4fa0a57cc..08db03475 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ElasticSearchDataProvider.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ElasticSearchDataProvider.java @@ -75,11 +75,11 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement private static final Logger LOG = LoggerFactory.getLogger(ElasticSearchDataProvider.class); - private static final String EXCEPTION_UNABLE_TO_WRITE_IN_DATABASE = "unable to write data to database"; - private static final String EXCEPTION_UNABLE_TO_UPDATE_IN_DATABASE = "unable to update data in database"; - private static final String EXCEPTION_UNABLE_TO_REMOVE_FROM_DATABASE = "unable to remove data from database"; + private static final String EXCEPTION_UNABLE_TO_WRITE_IN_DATABASE = "unable to write data to database"; + private static final String EXCEPTION_UNABLE_TO_UPDATE_IN_DATABASE = "unable to update data in database"; + private static final String EXCEPTION_UNABLE_TO_REMOVE_FROM_DATABASE = "unable to remove data from database"; - private static final boolean DEFAULT_TRUSTALLCERTS = false; + private static final boolean DEFAULT_TRUSTALLCERTS = false; private final HtDatabaseClient dbClient; private final DataObjectAcessor eventRWFaultCurrent; @@ -96,54 +96,58 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement private final DataObjectAcessorStatus readStatus; private final HtDatabaseEventsService databaseService; private final HtDatabaseMaintenanceService databaseMaintenanceService; + public HtDatabaseClient getRawClient() { - return this.dbClient; + return this.dbClient; } + public ElasticSearchDataProvider(HostInfo[] hosts) throws Exception { - this(hosts,null,null,DEFAULT_TRUSTALLCERTS); + this(hosts, null, null, DEFAULT_TRUSTALLCERTS); } - public ElasticSearchDataProvider(HostInfo[] hosts,String authUsername,String authPassword, boolean trustAllCerts) throws Exception { - super(); - LOG.info("Start {}", this.getClass().getName()); - this.dbClient = new HtDatabaseClient(hosts,authUsername,authPassword,trustAllCerts); - this.mediatorserverRW = new DataObjectAcessor<>(dbClient, Entity.MediatorServer, + public ElasticSearchDataProvider(HostInfo[] hosts, String authUsername, String authPassword, boolean trustAllCerts) + throws Exception { + super(); + LOG.info("Start {}", this.getClass().getName()); + + this.dbClient = new HtDatabaseClient(hosts, authUsername, authPassword, trustAllCerts); + this.mediatorserverRW = new DataObjectAcessor<>(dbClient, Entity.MediatorServer, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.mediator.server.list.output.Data.class); - this.mediatorserverRW.setWriteInterface(MediatorServerEntity.class); + this.mediatorserverRW.setWriteInterface(MediatorServerEntity.class); - this.maintenanceRW = new DataObjectAcessor<>(dbClient, Entity.Maintenancemode, + this.maintenanceRW = new DataObjectAcessor<>(dbClient, Entity.Maintenancemode, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.maintenance.list.output.Data.class); - this.maintenanceRW.setWriteInterface(MaintenanceEntity.class); + this.maintenanceRW.setWriteInterface(MaintenanceEntity.class); - this.equipmentRW = new DataObjectAcessor<>(dbClient, Entity.Inventoryequipment, + this.equipmentRW = new DataObjectAcessor<>(dbClient, Entity.Inventoryequipment, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.Data.class); - this.eventRWFaultCurrent = new DataObjectAcessor<>(dbClient, Entity.Faultcurrent, + this.eventRWFaultCurrent = new DataObjectAcessor<>(dbClient, Entity.Faultcurrent, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.faultcurrent.list.output.Data.class); - this.eventRWFaultLog = new DataObjectAcessor<>(dbClient, Entity.Faultlog, + this.eventRWFaultLog = new DataObjectAcessor<>(dbClient, Entity.Faultlog, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.faultlog.list.output.Data.class); - this.connnectionlogRW = new DataObjectAcessor<>(dbClient, Entity.Connectionlog, + this.connnectionlogRW = new DataObjectAcessor<>(dbClient, Entity.Connectionlog, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.connectionlog.list.output.Data.class); - this.eventlogRW = new DataObjectAcessor<>(dbClient, Entity.Eventlog, + this.eventlogRW = new DataObjectAcessor<>(dbClient, Entity.Eventlog, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.eventlog.list.output.Data.class); - this.networkelementConnectionRW = new DataObjectAcessor<>(dbClient, Entity.NetworkelementConnection, + this.networkelementConnectionRW = new DataObjectAcessor<>(dbClient, Entity.NetworkelementConnection, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.network.element.connection.list.output.Data.class); - this.networkelementConnectionRW.setWriteInterface(NetworkElementConnectionEntity.class); + this.networkelementConnectionRW.setWriteInterface(NetworkElementConnectionEntity.class); - this.pm15mRW = new DataObjectAcessorPm<>(dbClient, Intervall.PMDATA15M, Entity.Historicalperformance15min, + this.pm15mRW = new DataObjectAcessorPm<>(dbClient, Intervall.PMDATA15M, Entity.Historicalperformance15min, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.Data.class); - this.pm24hRW = new DataObjectAcessorPm<>(dbClient, Intervall.PMDATA24H, Entity.Historicalperformance24h, + this.pm24hRW = new DataObjectAcessorPm<>(dbClient, Intervall.PMDATA24H, Entity.Historicalperformance24h, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._24h.list.output.Data.class); - this.readStatus = new DataObjectAcessorStatus(dbClient, Entity.Faultcurrent ); + this.readStatus = new DataObjectAcessorStatus(dbClient, Entity.Faultcurrent); - this.databaseService = new HtDatabaseEventsService(dbClient, this); - this.databaseMaintenanceService = new HtDatabaseMaintenanceService(dbClient); + this.databaseService = new HtDatabaseEventsService(dbClient, this); + this.databaseMaintenanceService = new HtDatabaseMaintenanceService(dbClient); } /*------------------------- @@ -157,8 +161,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement ReadFaultcurrentListOutputBuilder outputBuilder = new ReadFaultcurrentListOutputBuilder(); - QueryResult result = this.eventRWFaultCurrent - .getData(input); + QueryResult result = + this.eventRWFaultCurrent.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.faultcurrent.list.output.PaginationBuilder( @@ -171,8 +175,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //eventRWFaultLog public ReadFaultlogListOutputBuilder readFaultLogList(EntityInput input) { ReadFaultlogListOutputBuilder outputBuilder = new ReadFaultlogListOutputBuilder(); - QueryResult result = this.eventRWFaultLog - .getData(input); + QueryResult result = + this.eventRWFaultLog.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.faultlog.list.output.PaginationBuilder( @@ -185,8 +189,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //maintenanceRW public ReadMaintenanceListOutputBuilder readMaintenanceList(EntityInput input) { ReadMaintenanceListOutputBuilder outputBuilder = new ReadMaintenanceListOutputBuilder(); - QueryResult result = this.maintenanceRW - .getData(input); + QueryResult result = + this.maintenanceRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.maintenance.list.output.PaginationBuilder( @@ -200,8 +204,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement public ReadMediatorServerListOutputBuilder readMediatorServerList(EntityInput input) { ReadMediatorServerListOutputBuilder outputBuilder = new ReadMediatorServerListOutputBuilder(); - QueryResult result = this.mediatorserverRW - .getData(input); + QueryResult result = + this.mediatorserverRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.mediator.server.list.output.PaginationBuilder( @@ -212,11 +216,11 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.network.element.connection.list.output.Data //org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.network.element.connection.list.output.PaginationBuilder //networkelementConnectionRW - public ReadNetworkElementConnectionListOutputBuilder readNetworkElementConnectionList( - EntityInput input) { - ReadNetworkElementConnectionListOutputBuilder outputBuilder = new ReadNetworkElementConnectionListOutputBuilder(); - QueryResult result = this.networkelementConnectionRW - .getData(input); + public ReadNetworkElementConnectionListOutputBuilder readNetworkElementConnectionList(EntityInput input) { + ReadNetworkElementConnectionListOutputBuilder outputBuilder = + new ReadNetworkElementConnectionListOutputBuilder(); + QueryResult result = + this.networkelementConnectionRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.network.element.connection.list.output.PaginationBuilder( @@ -229,8 +233,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //equipmentRW public ReadInventoryListOutputBuilder readInventoryList(EntityInput input) { ReadInventoryListOutputBuilder outputBuilder = new ReadInventoryListOutputBuilder(); - QueryResult result = this.equipmentRW - .getData(input); + QueryResult result = + this.equipmentRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.PaginationBuilder( @@ -243,8 +247,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //connnectionlogRW public ReadConnectionlogListOutputBuilder readConnectionlogList(EntityInput input) { ReadConnectionlogListOutputBuilder outputBuilder = new ReadConnectionlogListOutputBuilder(); - QueryResult result = this.connnectionlogRW - .getData(input); + QueryResult result = + this.connnectionlogRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.connectionlog.list.output.PaginationBuilder( @@ -257,8 +261,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //eventlogRW public ReadEventlogListOutputBuilder readEventlogList(ReadEventlogListInput input) throws IOException { ReadEventlogListOutputBuilder outputBuilder = new ReadEventlogListOutputBuilder(); - QueryResult result = this.eventlogRW - .getData(input); + QueryResult result = + this.eventlogRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.eventlog.list.output.PaginationBuilder( @@ -270,8 +274,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.PaginationBuilder public ReadPmdata15mListOutputBuilder readPmdata15mList(EntityInput input) { ReadPmdata15mListOutputBuilder outputBuilder = new ReadPmdata15mListOutputBuilder(); - QueryResult result = this.pm15mRW - .getData(input); + QueryResult result = + this.pm15mRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.PaginationBuilder( @@ -283,8 +287,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement //org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._24h.list.output.Pagination public ReadPmdata24hListOutputBuilder readPmdata24hList(EntityInput input) { ReadPmdata24hListOutputBuilder outputBuilder = new ReadPmdata24hListOutputBuilder(); - QueryResult result = this.pm24hRW - .getData(input); + QueryResult result = + this.pm24hRW.getData(input); outputBuilder.setData(result.getResult().getHits()); outputBuilder.setPagination( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._24h.list.output.PaginationBuilder( @@ -318,14 +322,14 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement ReadPmdata24hLtpListOutputBuilder outputBuilder = new ReadPmdata24hLtpListOutputBuilder(); new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._24h.ltp.list.output.PaginationBuilder(); - outputBuilder.setPagination(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._24h.ltp.list.output.PaginationBuilder( - result.getPagination()).build()); + outputBuilder.setPagination( + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._24h.ltp.list.output.PaginationBuilder( + result.getPagination()).build()); outputBuilder.setData(result.getResult().getHits()); return outputBuilder; } - public ReadPmdata24hDeviceListOutputBuilder readPmdata24hDeviceList(EntityInput input) - throws IOException { + public ReadPmdata24hDeviceListOutputBuilder readPmdata24hDeviceList(EntityInput input) throws IOException { QueryResult result = pm24hRW.getDataDeviceList(input); @@ -338,7 +342,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement } public ReadStatusOutputBuilder readStatus() throws IOException { - QueryResult result = readStatus.getDataStatus(); + QueryResult result = + readStatus.getDataStatus(); ReadStatusOutputBuilder outputBuilder = new ReadStatusOutputBuilder(); outputBuilder.setData(result.getResult().getHits()); @@ -349,7 +354,7 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement return this.dbClient.waitForYellowStatus(unit.toMillis(timeout)); } - public CreateNetworkElementConnectionOutputBuilder createNetworkElementConnection( + public CreateNetworkElementConnectionOutputBuilder createNetworkElementConnection( NetworkElementConnectionEntity input) throws IOException { String id = this.networkelementConnectionRW.update(input, input.getNodeId()); if (id == null) { @@ -375,7 +380,8 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement return builder; } - public DeleteNetworkElementConnectionOutputBuilder deleteNetworkElementConnection(DeleteNetworkElementConnectionInput input) throws IOException { + public DeleteNetworkElementConnectionOutputBuilder deleteNetworkElementConnection( + DeleteNetworkElementConnectionInput input) throws IOException { boolean removed = this.networkelementConnectionRW.remove(input.getId()); if (!removed) { throw new IOException(EXCEPTION_UNABLE_TO_REMOVE_FROM_DATABASE); @@ -425,7 +431,7 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement } public CreateMaintenanceOutputBuilder createMaintenance(CreateMaintenanceInput input) throws IOException { - String id = this.maintenanceRW.write(input, input.getNodeId()); + String id = this.maintenanceRW.write(input, input.getNodeId()); if (id == null) { throw new IOException(EXCEPTION_UNABLE_TO_WRITE_IN_DATABASE); } @@ -433,7 +439,7 @@ public class ElasticSearchDataProvider /*extends BaseStatusProvider /* implement return builder; } - public CreateMediatorServerOutputBuilder createMediatorServer(CreateMediatorServerInput input) throws IOException { + public CreateMediatorServerOutputBuilder createMediatorServer(CreateMediatorServerInput input) throws IOException { String id = this.mediatorserverRW.write(input, null); if (id == null) { diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/FaultEntityManager.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/FaultEntityManager.java index 16b13ba96..7efdab110 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/FaultEntityManager.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/FaultEntityManager.java @@ -33,18 +33,18 @@ public class FaultEntityManager { private static final Pattern pattern = Pattern.compile(".*\\[layerProtocol=(.*)\\]"); /** - * The leading indication for notification or events that are not in the - * currentProblem data of the ONF Coremodel + * The leading indication for notification or events that are not in the currentProblem data of the ONF Coremodel */ private static final String NOCURRENTPROBLEMINDICATION = "#"; /** * Specific problems are not moving into current problem list + * * @param problemName to be verified * @return true if problem is current */ public static boolean isManagedAsCurrentProblem(String problemName) { - return ! problemName.startsWith(NOCURRENTPROBLEMINDICATION); + return !problemName.startsWith(NOCURRENTPROBLEMINDICATION); } public static boolean isManagedAsCurrentProblem(Fault problem) { @@ -53,6 +53,7 @@ public class FaultEntityManager { /** * Specific problems are not moving into current problem list + * * @param fault to be verified * @return true if cleared indication */ @@ -62,9 +63,10 @@ public class FaultEntityManager { /** * Create a specific ES id for the current log. + * * @return a string with the generated ES Id */ - public static String genSpecificEsId(String nodeName, String objectId, String problemName) { + public static String genSpecificEsId(String nodeName, String objectId, String problemName) { String uuId; @@ -86,6 +88,7 @@ public class FaultEntityManager { /** * Create Es id + * * @param fault used to create uuid for faultcurrent * @return String with Id */ diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java index 4a4b332d6..d255cadcd 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseEventsService.java @@ -63,8 +63,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Event service, writing all events into the database into the appropriate - * index. + * Event service, writing all events into the database into the appropriate index. * * @author herbert */ @@ -88,7 +87,8 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid // --- Construct and initialize - public HtDatabaseEventsService(HtDatabaseClient client, ElasticSearchDataProvider elasticSearchDataProvider) throws Exception { + public HtDatabaseEventsService(HtDatabaseClient client, ElasticSearchDataProvider elasticSearchDataProvider) + throws Exception { LOG.info("Create {} start", HtDatabaseEventsService.class); this.dataProvider = elasticSearchDataProvider; @@ -100,27 +100,27 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid eventRWEventLogDevicemanager = new EsDataObjectReaderWriter2<>(client, Entity.Eventlog, EventlogEntity.class, EventlogBuilder.class); - eventRWEquipment = new EsDataObjectReaderWriter2<>(client, Entity.Inventoryequipment, - InventoryEntity.class, InventoryBuilder.class); + eventRWEquipment = new EsDataObjectReaderWriter2<>(client, Entity.Inventoryequipment, InventoryEntity.class, + InventoryBuilder.class); eventRWFaultCurrentDB = new EsDataObjectReaderWriter2<>(client, Entity.Faultcurrent, FaultcurrentEntity.class, FaultcurrentBuilder.class); - eventRWFaultLogDB = new EsDataObjectReaderWriter2<>(client, Entity.Faultlog, - FaultlogEntity.class, FaultlogBuilder.class); + eventRWFaultLogDB = new EsDataObjectReaderWriter2<>(client, Entity.Faultlog, FaultlogEntity.class, + FaultlogBuilder.class); eventRWConnectionLogDB = new EsDataObjectReaderWriter2<>(client, Entity.Connectionlog, ConnectionlogEntity.class, ConnectionlogBuilder.class); networkelementConnectionDB = new EsDataObjectReaderWriter2<>(client, Entity.NetworkelementConnection, NetworkElementConnectionEntity.class, NetworkElementConnectionBuilder.class) - .setEsIdAttributeName("_id"); + .setEsIdAttributeName("_id"); - pmData15mDB = new EsDataObjectReaderWriter2<>(client, Entity.Historicalperformance15min, - PmdataEntity.class, PmdataEntityBuilder.class); + pmData15mDB = new EsDataObjectReaderWriter2<>(client, Entity.Historicalperformance15min, PmdataEntity.class, + PmdataEntityBuilder.class); - pmData24hDB = new EsDataObjectReaderWriter2<>(client, Entity.Historicalperformance24h, - PmdataEntity.class, PmdataEntityBuilder.class); + pmData24hDB = new EsDataObjectReaderWriter2<>(client, Entity.Historicalperformance24h, PmdataEntity.class, + PmdataEntityBuilder.class); } catch (Exception e) { LOG.error("Can not start database client. Exception: {}", e); @@ -142,6 +142,7 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid eventRWConnectionLogDB.write(event, null); } + // -- Event log @Override public void writeEventLog(EventlogEntity event) { @@ -163,7 +164,7 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid } LOG.debug("Write fault to faultlog: {}", fault.toString()); - eventRWFaultLogDB.write(fault,null); + eventRWFaultLogDB.write(fault, null); } // -- Fault current @@ -248,6 +249,7 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid /** * write internal equipment to database + * * @param internalEquipment with mandatory fields. */ @Override @@ -256,14 +258,14 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid if (assertIfClientNullForNodeName(internalEquipment.getNodeId())) { return; } - if(internalEquipment.getManufacturerIdentifier()==null) { - internalEquipment = new InventoryBuilder(internalEquipment).setManufacturerIdentifier("").build(); + if (internalEquipment.getManufacturerIdentifier() == null) { + internalEquipment = new InventoryBuilder(internalEquipment).setManufacturerIdentifier("").build(); } - if(internalEquipment.getDate()==null) { - internalEquipment = new InventoryBuilder(internalEquipment).setDate("").build(); + if (internalEquipment.getDate() == null) { + internalEquipment = new InventoryBuilder(internalEquipment).setDate("").build(); } - - eventRWEquipment.write(internalEquipment, internalEquipment.getNodeId()+"/"+internalEquipment.getUuid()); + + eventRWEquipment.write(internalEquipment, internalEquipment.getNodeId() + "/" + internalEquipment.getUuid()); } @@ -275,18 +277,22 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid * @param nodeId Id for this DB element */ @Override - public void updateNetworkConnectionDeviceType(NetworkElementConnectionEntity networkElementConnectionEntitiy, String nodeId) { + public void updateNetworkConnectionDeviceType(NetworkElementConnectionEntity networkElementConnectionEntitiy, + String nodeId) { this.networkelementConnectionDB.update(networkElementConnectionEntitiy, nodeId); } /** * Update after new mountpoint registration + * * @param networkElementConnectionEntitiy data * @param nodeId of device (mountpoint name) */ @Override - public void updateNetworkConnection22(NetworkElementConnectionEntity networkElementConnectionEntitiy, String nodeId) { - this.networkelementConnectionDB.updateOrCreate(networkElementConnectionEntitiy, nodeId, Arrays.asList("is-required", "username", "password")); + public void updateNetworkConnection22(NetworkElementConnectionEntity networkElementConnectionEntitiy, + String nodeId) { + this.networkelementConnectionDB.updateOrCreate(networkElementConnectionEntitiy, nodeId, + Arrays.asList("is-required", "username", "password")); } /* please do not remove */ @@ -302,15 +308,16 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid NetworkElementConnectionEntity e = this.networkelementConnectionDB.read(nodeId); if (e != null && (isRequired = e.isIsRequired()) != null) { if (isRequired) { - LOG.debug("updating connection status for {} of required ne to disconnected",nodeId); - this.networkelementConnectionDB.update(new UpdateNetworkElementConnectionInputBuilder().setStatus(ConnectionLogStatus.Disconnected).build(), nodeId); + LOG.debug("updating connection status for {} of required ne to disconnected", nodeId); + this.networkelementConnectionDB.update(new UpdateNetworkElementConnectionInputBuilder() + .setStatus(ConnectionLogStatus.Disconnected).build(), nodeId); } else { - LOG.debug("remove networkelement-connection for {} entry because of non-required",nodeId); + LOG.debug("remove networkelement-connection for {} entry because of non-required", nodeId); this.networkelementConnectionDB.remove(nodeId); } - } - else { - LOG.warn("Unable to update connection-status. dbentry for {} not found in networkelement-connection",nodeId); + } else { + LOG.warn("Unable to update connection-status. dbentry for {} not found in networkelement-connection", + nodeId); } } @@ -349,6 +356,7 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid /** * Verify status of client + * * @param event that is printed with message * @return true if client is null */ @@ -359,8 +367,10 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid private boolean assertIfClientNullForNodeName(Object object) { return assertIfClientNull("No DB, can not handle node: {}", object); } + /** * Verify status of client + * * @param message to print including {} for object printout. * @return true if client is null */ @@ -378,6 +388,7 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid private static class EsEventBase { /** * Query to get older Elements + * * @param netconfTimeStamp to identify older Elements * @return QueryBuilder for older elements related to timestamp */ @@ -388,29 +399,31 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid private static class EsFaultLogDevicemanager { /** * Get older Elements + * * @param netconfTimeStamp to identify query elements older than this timestamp. * @return QueryBuilder for related elements */ public static QueryBuilder getQueryForTimeStamp(String netconfTimeStamp) { return new RangeQueryBuilder("timestamp").lte(netconfTimeStamp); } - } - public static class EsFaultCurrent { + } + public static class EsFaultCurrent { /** * @param nodeName name of the node * @return query builder */ - public static QueryBuilder getQueryForOneNode( String nodeName) { + public static QueryBuilder getQueryForOneNode(String nodeName) { return QueryBuilders.matchQuery("node-id", nodeName); } - public static QueryBuilder getQueryForOneNodeAndObjectId( String nodeName, String objectId) { + public static QueryBuilder getQueryForOneNodeAndObjectId(String nodeName, String objectId) { BoolQueryBuilder bq = QueryBuilders.boolQuery(); bq.must(QueryBuilders.matchQuery("node-id", nodeName)); bq.must(QueryBuilders.matchQuery("object-id", objectId)); return bq; } } + @Override public List getNetworkElementConnections() { return this.networkelementConnectionDB.doReadAll().getHits(); @@ -431,28 +444,29 @@ public class HtDatabaseEventsService implements ArchiveCleanProvider, DataProvid id.append(date != null ? date.getValue() : "null"); switch (granularityPeriod) { - case Period15Min: - pmData15mDB.write(elem, id.toString()); - break; - case Period24Hours: - pmData24hDB.write(elem, id.toString()); - break; - case Unknown: - default: - LOG.debug("Unknown granularity {} id {}", granularityPeriod, id); - break; + case Period15Min: + pmData15mDB.write(elem, id.toString()); + break; + case Period24Hours: + pmData24hDB.write(elem, id.toString()); + break; + case Unknown: + default: + LOG.debug("Unknown granularity {} id {}", granularityPeriod, id); + break; } - } ); + }); } - @NonNull GranularityPeriodType nnGetGranularityPeriodType(@Nullable GranularityPeriodType granularityPeriod) { + @NonNull + GranularityPeriodType nnGetGranularityPeriodType(@Nullable GranularityPeriodType granularityPeriod) { return granularityPeriod != null ? granularityPeriod : GranularityPeriodType.Unknown; } - @Override - public HtDatabaseClient getRawClient() { - return this.client; - } + @Override + public HtDatabaseClient getRawClient() { + return this.client; + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseMaintenanceService.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseMaintenanceService.java index 245b89003..a675f6876 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseMaintenanceService.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/HtDatabaseMaintenanceService.java @@ -61,6 +61,7 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { /** * Get existing object for mountpoint to manage maintenance mode + * * @return Object with configuration */ @Override @@ -74,26 +75,23 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { } @Override - public - MaintenanceEntity setMaintenance(MaintenanceEntity m) { + public MaintenanceEntity setMaintenance(MaintenanceEntity m) { if (maintenanceRW != null) { - if (maintenanceRW.write(m, m.getNodeId() ) == null) { - throw new IllegalArgumentException("Problem writing to database: "+m.getId()); + if (maintenanceRW.write(m, m.getNodeId()) == null) { + throw new IllegalArgumentException("Problem writing to database: " + m.getId()); } - LOG.info("Wrote maintenance object {}", m.toString()); + LOG.info("Wrote maintenance object {}", m.toString()); } return m; } @Override - public - List getAll() { + public List getAll() { return maintenanceRW != null ? maintenanceRW.doReadAll().getHits() : new ArrayList<>(); } @Override - public - MaintenanceEntity createIfNotExists(String mountpointId) { + public MaintenanceEntity createIfNotExists(String mountpointId) { MaintenanceEntity deviceMaintenanceMode = null; if (maintenanceRW != null) { deviceMaintenanceMode = maintenanceRW.read(mountpointId); @@ -111,8 +109,7 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { } @Override - public - void deleteIfNotRequired(String mountPointNodeName) { + public void deleteIfNotRequired(String mountPointNodeName) { if (!this.isRequireNe(mountPointNodeName)) { if (maintenanceRW != null) { @@ -128,6 +125,7 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { /** * Provide default maintenanceinformation for a device + * * @param mountpointId nodeId of device * @return default data */ @@ -143,14 +141,14 @@ public class HtDatabaseMaintenanceService implements HtDatabaseMaintenance { deviceMaintenanceModeBuilder.setStart(now); deviceMaintenanceModeBuilder.setEnd(now); deviceMaintenanceModeBuilder.setActive(false); - + // Reference to all //consistent to UI input to null/not empty string //deviceMaintenanceModeBuilder.setObjectIdRef(""); //deviceMaintenanceModeBuilder.setProblem(""); - + return deviceMaintenanceModeBuilder.build(); - } + } // -- Private /** diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java index 0d2e39bcb..38e5b13e2 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/MediatorServerDataProvider.java @@ -38,66 +38,66 @@ import org.slf4j.LoggerFactory; public class MediatorServerDataProvider implements AutoCloseable { - private static final Logger LOG = LoggerFactory.getLogger(MediatorServerDataProvider.class); + private static final Logger LOG = LoggerFactory.getLogger(MediatorServerDataProvider.class); - private final HtDatabaseClient dbClient; - private final DataObjectAcessor mediatorserverRW; - private final int REFRESH_INTERVAL = 60; - private final Map entries; - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - private boolean isRunning; + private final HtDatabaseClient dbClient; + private final DataObjectAcessor mediatorserverRW; + private final int REFRESH_INTERVAL = 60; + private final Map entries; + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + private boolean isRunning; - public MediatorServerDataProvider(HostInfo[] hosts) throws Exception { - this(hosts, null, null); - } + public MediatorServerDataProvider(HostInfo[] hosts) throws Exception { + this(hosts, null, null); + } - public MediatorServerDataProvider(HostInfo[] hosts, String authUsername, String authPassword) throws Exception { - super(); - LOG.info("Start {}", this.getClass().getName()); - this.entries = new HashMap<>(); - this.dbClient = new HtDatabaseClient(hosts, authUsername, authPassword); - this.mediatorserverRW = new DataObjectAcessor<>(dbClient, Entity.MediatorServer, Data.class); - this.scheduler.scheduleAtFixedRate(onTick, this.REFRESH_INTERVAL, this.REFRESH_INTERVAL, TimeUnit.SECONDS); - } + public MediatorServerDataProvider(HostInfo[] hosts, String authUsername, String authPassword) throws Exception { + super(); + LOG.info("Start {}", this.getClass().getName()); + this.entries = new HashMap<>(); + this.dbClient = new HtDatabaseClient(hosts, authUsername, authPassword); + this.mediatorserverRW = new DataObjectAcessor<>(dbClient, Entity.MediatorServer, Data.class); + this.scheduler.scheduleAtFixedRate(onTick, this.REFRESH_INTERVAL, this.REFRESH_INTERVAL, TimeUnit.SECONDS); + } - private final Runnable onTick = new Runnable() { + private final Runnable onTick = new Runnable() { - @Override - public void run() { - isRunning = true; - runIt(); - isRunning = false; - } + @Override + public void run() { + isRunning = true; + runIt(); + isRunning = false; + } - }; + }; - private void runIt() { - SearchResult result = MediatorServerDataProvider.this.mediatorserverRW.doReadAll(); - List data = result.getHits(); - for (Data item : data) { - MediatorServerDataProvider.this.entries.put(item.getId(), item); - } - } + private void runIt() { + SearchResult result = MediatorServerDataProvider.this.mediatorserverRW.doReadAll(); + List data = result.getHits(); + for (Data item : data) { + MediatorServerDataProvider.this.entries.put(item.getId(), item); + } + } - /** - * - * @param dbServerId - * @return url or null if not exists - */ - public String getHostUrl(String dbServerId) { - Data info = this.entries.getOrDefault(dbServerId, null); - return info == null ? null : info.getUrl(); - } + /** + * + * @param dbServerId + * @return url or null if not exists + */ + public String getHostUrl(String dbServerId) { + Data info = this.entries.getOrDefault(dbServerId, null); + return info == null ? null : info.getUrl(); + } - public boolean triggerReloadSync() { - if (!isRunning) { - runIt(); - } - return true; - } + public boolean triggerReloadSync() { + if (!isRunning) { + runIt(); + } + return true; + } - @Override - public void close() throws Exception { - this.scheduler.shutdown(); - } + @Override + public void close() throws Exception { + this.scheduler.shutdown(); + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ODLVersionLUT.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ODLVersionLUT.java index 330b0baf5..8027fb2c5 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ODLVersionLUT.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/ODLVersionLUT.java @@ -23,41 +23,42 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.data; public class ODLVersionLUT { - public static String getONAPReleaseName(String onapCCSDKVersion,String def) { - if(onapCCSDKVersion==null) { - return def; - } - if(onapCCSDKVersion.startsWith("1.6.")) { - return "ONAP Guillin"; - } - if(onapCCSDKVersion.startsWith("1.5.")) { - return "ONAP Frankfurt"; - } - if(onapCCSDKVersion.startsWith("1.4.")) { - return "ONAP El Alto"; - } - if(onapCCSDKVersion.startsWith("1.3.")) { - return "ONAP El Alto"; - } - return def; - } - public static String getOdlVersion(String onapCCSDKVersion,String def) { - - if(onapCCSDKVersion==null) { - return def; - } - if(onapCCSDKVersion.startsWith("1.6.")) { - return "sodium-SRX (0.11.X)"; - } - if(onapCCSDKVersion.startsWith("1.5.")) { - return "neon-SR1 (0.10.1)"; - } - if(onapCCSDKVersion.startsWith("1.4.")) { - return "neon-SR1 (0.10.1)"; - } - if(onapCCSDKVersion.startsWith("1.3.")) { - return "fluorine-SR2 (0.9.2)"; - } - return def; - } + public static String getONAPReleaseName(String onapCCSDKVersion, String def) { + if (onapCCSDKVersion == null) { + return def; + } + if (onapCCSDKVersion.startsWith("1.6.")) { + return "ONAP Guillin"; + } + if (onapCCSDKVersion.startsWith("1.5.")) { + return "ONAP Frankfurt"; + } + if (onapCCSDKVersion.startsWith("1.4.")) { + return "ONAP El Alto"; + } + if (onapCCSDKVersion.startsWith("1.3.")) { + return "ONAP El Alto"; + } + return def; + } + + public static String getOdlVersion(String onapCCSDKVersion, String def) { + + if (onapCCSDKVersion == null) { + return def; + } + if (onapCCSDKVersion.startsWith("1.6.")) { + return "sodium-SRX (0.11.X)"; + } + if (onapCCSDKVersion.startsWith("1.5.")) { + return "neon-SR1 (0.10.1)"; + } + if (onapCCSDKVersion.startsWith("1.4.")) { + return "neon-SR1 (0.10.1)"; + } + if (onapCCSDKVersion.startsWith("1.3.")) { + return "fluorine-SR2 (0.9.2)"; + } + return def; + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryByFilter.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryByFilter.java index a83dfd975..b6a502071 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryByFilter.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryByFilter.java @@ -44,12 +44,12 @@ import org.slf4j.LoggerFactory; public class QueryByFilter { - private static final Logger LOG = LoggerFactory.getLogger(DataObjectAcessorPm.class); - private static final List timestampValueNames = Arrays.asList("timestamp","start","end"); + private static final Logger LOG = LoggerFactory.getLogger(DataObjectAcessorPm.class); + private static final List timestampValueNames = Arrays.asList("timestamp", "start", "end"); - private QueryByFilter() { - //Hide - } + private QueryByFilter() { + //Hide + } static long getPage(EntityInput input) { return getPage(input, 1); @@ -88,7 +88,7 @@ public class QueryByFilter { } - public static Sortorder getSortOrder(@Nullable List list, String prop) { + public static Sortorder getSortOrder(@Nullable List list, String prop) { if (list == null) { return null; } @@ -100,7 +100,7 @@ public class QueryByFilter { return null; } - public static Filter getFilter(@Nullable List list, String prop) { + public static Filter getFilter(@Nullable List list, String prop) { if (list == null) { return null; } @@ -112,161 +112,157 @@ public class QueryByFilter { return null; } - public static QueryBuilder fromFilter(@Nullable List filters) { + public static QueryBuilder fromFilter(@Nullable List filters) { return fromFilter(filters, ""); } - private static String fillTimeStamp(String value) { - int idx=value.lastIndexOf("*"); - final String REPLACE="0000-00-00T00:00:00.0Z"; - String s = value.substring(0,idx)+REPLACE.substring(idx); - if(Integer.parseInt(s.substring(5,7))==0) { - s=s.substring(0,5)+"01-"+s.substring(8); + private static String fillTimeStamp(String value) { + int idx = value.lastIndexOf("*"); + final String REPLACE = "0000-00-00T00:00:00.0Z"; + String s = value.substring(0, idx) + REPLACE.substring(idx); + if (Integer.parseInt(s.substring(5, 7)) == 0) { + s = s.substring(0, 5) + "01-" + s.substring(8); } - if(Integer.parseInt(s.substring(8,10))==0) { - s=s.substring(0,8)+"01"+s.substring(10); + if (Integer.parseInt(s.substring(8, 10)) == 0) { + s = s.substring(0, 8) + "01" + s.substring(10); } return s; - } - /** - * convert timestamp with ending placeholder in filter to elasticsearch filter - * e.g. 2017* => gte: 2017-01-01T00:00:00Z, lt:2018-01-01T00:00:00Z - * - * 201* => 2010-01... 2020 .. - * 2018-* => 2018-01... <=> 2019-01 - * - */ - private static @Nullable QueryBuilder fromTimestampSearchFilter(String property,String value) { - if(!value.endsWith("*")) { + } + + /** + * convert timestamp with ending placeholder in filter to elasticsearch filter e.g. 2017* => gte: + * 2017-01-01T00:00:00Z, lt:2018-01-01T00:00:00Z + * + * 201* => 2010-01... 2020 .. 2018-* => 2018-01... <=> 2019-01 + * + */ + private static @Nullable QueryBuilder fromTimestampSearchFilter(String property, String value) { + if (!value.endsWith("*")) { return null; } - int idx=value.lastIndexOf("*"); + int idx = value.lastIndexOf("*"); String lowerEnd = fillTimeStamp(value); - String upperEnd =null; + String upperEnd = null; NetconfTimeStamp converter = NetconfTimeStampImpl.getConverter(); Date dt = null; - try{ - dt=converter.getDateFromNetconf(lowerEnd); - } - catch(Exception e) { + try { + dt = converter.getDateFromNetconf(lowerEnd); + } catch (Exception e) { } - if(dt==null) { + if (dt == null) { return null; } -// property.substring(0,idx)+REPLACE.substring(idx+1); - Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + // property.substring(0,idx)+REPLACE.substring(idx+1); + Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTime(dt); int tmpvalue; - switch(idx) { - case 1: // (2*) - c.set(Calendar.YEAR,c.get(Calendar.YEAR)+1000); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 2: // (20*) - c.set(Calendar.YEAR,c.get(Calendar.YEAR)+100); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 3: // (200*) - c.set(Calendar.YEAR,c.get(Calendar.YEAR)+10); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 4: // (2000*) - case 5: // (2000-*) - c.set(Calendar.YEAR,c.get(Calendar.YEAR)+1); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 6: //switch 10 months (2000-0* or 2000-1*) - tmpvalue = c.get(Calendar.MONTH); - if(tmpvalue<9) { - c.set(Calendar.MONTH,9); - } - else { - c.set(Calendar.YEAR,c.get(Calendar.YEAR)+1); - c.set(Calendar.MONTH,0); + switch (idx) { + case 1: // (2*) + c.set(Calendar.YEAR, c.get(Calendar.YEAR) + 1000); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 2: // (20*) + c.set(Calendar.YEAR, c.get(Calendar.YEAR) + 100); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 3: // (200*) + c.set(Calendar.YEAR, c.get(Calendar.YEAR) + 10); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 4: // (2000*) + case 5: // (2000-*) + c.set(Calendar.YEAR, c.get(Calendar.YEAR) + 1); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 6: //switch 10 months (2000-0* or 2000-1*) + tmpvalue = c.get(Calendar.MONTH); + if (tmpvalue < 9) { + c.set(Calendar.MONTH, 9); + } else { + c.set(Calendar.YEAR, c.get(Calendar.YEAR) + 1); + c.set(Calendar.MONTH, 0); } upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 7: //switch one month (2018-01* or 2018-01-*) - case 8: - c.add(Calendar.MONTH, 1); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 9: // (2018-01-0*) - tmpvalue = c.get(Calendar.DAY_OF_MONTH); - if(tmpvalue==1) { - c.set(Calendar.DAY_OF_MONTH, 10); - }else if(tmpvalue==10) { - c.set(Calendar.DAY_OF_MONTH, 20); - }else if(tmpvalue==20) { - if(c.getActualMaximum(Calendar.DAY_OF_MONTH)<30) { - c.set(Calendar.DAY_OF_MONTH,1); - c.add(Calendar.MONTH,1); + break; + case 7: //switch one month (2018-01* or 2018-01-*) + case 8: + c.add(Calendar.MONTH, 1); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 9: // (2018-01-0*) + tmpvalue = c.get(Calendar.DAY_OF_MONTH); + if (tmpvalue == 1) { + c.set(Calendar.DAY_OF_MONTH, 10); + } else if (tmpvalue == 10) { + c.set(Calendar.DAY_OF_MONTH, 20); + } else if (tmpvalue == 20) { + if (c.getActualMaximum(Calendar.DAY_OF_MONTH) < 30) { + c.set(Calendar.DAY_OF_MONTH, 1); + c.add(Calendar.MONTH, 1); + } else { + c.set(Calendar.DAY_OF_MONTH, 30); + } + } else if (tmpvalue == 30) { + c.set(Calendar.DAY_OF_MONTH, 1); + c.add(Calendar.MONTH, 1); + } else { + break; } - else { - c.set(Calendar.DAY_OF_MONTH,30); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 10: // (2018-01-01*) + case 11: // (2018-01-01T*) + c.add(Calendar.DAY_OF_MONTH, 1); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 12: // (2018-01-01T1*) + tmpvalue = c.get(Calendar.HOUR_OF_DAY); + if (tmpvalue == 20) { + c.set(Calendar.HOUR_OF_DAY, 0); + c.add(Calendar.DAY_OF_MONTH, 1); + } else { + c.add(Calendar.HOUR_OF_DAY, 10); } - }else if(tmpvalue==30) { - c.set(Calendar.DAY_OF_MONTH,1); - c.add(Calendar.MONTH,1); - } - else { + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 13: // (2018-01-01T11*) + case 14: // (2018-01-01T11-*) + c.add(Calendar.HOUR_OF_DAY, 1); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 15: // (2018-01-01T11-3*) + c.add(Calendar.MINUTE, 10); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 16: // (2018-01-01T11-32*) + case 17: // (2018-01-01T11-32-*) + c.add(Calendar.MINUTE, 1); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 18: // (2018-01-01T11-32-1*) + c.add(Calendar.SECOND, 10); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); + break; + case 19: // (2018-01-01T11-32-11*) + case 20: // (2018-01-01T11-32-11.*) + c.add(Calendar.SECOND, 1); + upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); break; - } - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 10: // (2018-01-01*) - case 11: // (2018-01-01T*) - c.add(Calendar.DAY_OF_MONTH,1); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 12: // (2018-01-01T1*) - tmpvalue = c.get(Calendar.HOUR_OF_DAY); - if(tmpvalue==20) { - c.set(Calendar.HOUR_OF_DAY,0); - c.add(Calendar.DAY_OF_MONTH,1); - } - else { - c.add(Calendar.HOUR_OF_DAY,10); - } - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 13: // (2018-01-01T11*) - case 14: // (2018-01-01T11-*) - c.add(Calendar.HOUR_OF_DAY,1); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 15: // (2018-01-01T11-3*) - c.add(Calendar.MINUTE,10); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 16: // (2018-01-01T11-32*) - case 17: // (2018-01-01T11-32-*) - c.add(Calendar.MINUTE,1); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 18: // (2018-01-01T11-32-1*) - c.add(Calendar.SECOND,10); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; - case 19: // (2018-01-01T11-32-11*) - case 20: // (2018-01-01T11-32-11.*) - c.add(Calendar.SECOND,1); - upperEnd = converter.getTimeStampAsNetconfString(c.getTime()); - break; default: break; } - if(upperEnd==null) { + if (upperEnd == null) { return null; } return QueryBuilders.rangeQuery(property).gte(lowerEnd).lt(upperEnd); } + private static QueryBuilder fromFilter(@Nullable List filters, String prefix) { if (filters == null || filters.size() == 0) { return QueryBuilders.matchAllQuery(); @@ -274,17 +270,16 @@ public class QueryByFilter { } else if (filters.size() == 1) { QueryBuilder query; String p = filters.get(0).getProperty(); - String v= filters.get(0).getFiltervalue(); + String v = filters.get(0).getFiltervalue(); if ("id".equals(p)) { p = "_id"; - } - else { - // v=v.toLowerCase(); + } else { + // v=v.toLowerCase(); } if (DbFilter.hasSearchParams(v)) { - if(p!=null && timestampValueNames.contains(p.toLowerCase())) { - query = fromTimestampSearchFilter(p,v); - if(query!=null) { + if (p != null && timestampValueNames.contains(p.toLowerCase())) { + query = fromTimestampSearchFilter(p, v); + if (query != null) { return query; } } @@ -295,50 +290,45 @@ public class QueryByFilter { RangeQueryBuilder q = DbFilter.getRangeQuery((prefix != null ? prefix : "") + p, v); if (q != null) { return q; - } - else { + } else { return QueryBuilders.matchQuery((prefix != null ? prefix : "") + p, v); } - } - else { + } else { return QueryBuilders.matchQuery((prefix != null ? prefix : "") + p, v); } - } - else { + } else { BoolQueryBuilder query = new BoolQueryBuilder(); QueryBuilder tmpQuery; for (Filter fi : filters) { String p = fi.getProperty(); - String v=fi.getFiltervalue(); + String v = fi.getFiltervalue(); if ("id".equals(p)) { p = "_id"; + } else { + // v=v.toLowerCase(); } - else { - // v=v.toLowerCase(); - } - if(DbFilter.hasSearchParams(v)) { - if(p!=null && timestampValueNames.contains(p.toLowerCase())) { - tmpQuery=fromTimestampSearchFilter(p,v); - if(tmpQuery!=null) { + if (DbFilter.hasSearchParams(v)) { + if (p != null && timestampValueNames.contains(p.toLowerCase())) { + tmpQuery = fromTimestampSearchFilter(p, v); + if (tmpQuery != null) { query.must(tmpQuery); - }else { - query.must(QueryBuilders.regex((prefix != null ? prefix : "") + p,DbFilter.createDatabaseRegex(v))); + } else { + query.must(QueryBuilders.regex((prefix != null ? prefix : "") + p, + DbFilter.createDatabaseRegex(v))); } - }else { - query.must(QueryBuilders.regex((prefix != null ? prefix : "") + p,DbFilter.createDatabaseRegex(v))); + } else { + query.must(QueryBuilders.regex((prefix != null ? prefix : "") + p, + DbFilter.createDatabaseRegex(v))); } - } - else if (DbFilter.isComparisonValid(v)) { - RangeQueryBuilder q = DbFilter.getRangeQuery((prefix != null ? prefix : "") + p,v); - if(q!=null) { + } else if (DbFilter.isComparisonValid(v)) { + RangeQueryBuilder q = DbFilter.getRangeQuery((prefix != null ? prefix : "") + p, v); + if (q != null) { query.must(q); + } else { + query.must(QueryBuilders.matchQuery((prefix != null ? prefix : "") + p, v)); } - else { - query.must(QueryBuilders.matchQuery((prefix != null ? prefix : "") + p,v)); - } - } - else { - query.must(QueryBuilders.matchQuery((prefix != null ? prefix : "") + p,v)); + } else { + query.must(QueryBuilders.matchQuery((prefix != null ? prefix : "") + p, v)); } } LOG.trace("Query result. {}", query.toJSON()); diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryResult.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryResult.java index 87e1a7cdb..61e524192 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryResult.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/QueryResult.java @@ -29,27 +29,26 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro public class QueryResult { - private SearchResult result; - private PaginationOutputG pagination; - - public QueryResult(long page, long pageSize, SearchResult result) { - this.result = result; - - PaginationBuilder x = new PaginationBuilder(); - x.setPage(BigInteger.valueOf(page)); - x.setSize(pageSize); - x.setTotal(BigInteger.valueOf(result.getTotal())); - pagination = x.build(); - } - - public SearchResult getResult() { - return result; - } - - PaginationOutputG getPagination() { - return pagination; - } - + private SearchResult result; + private PaginationOutputG pagination; + + public QueryResult(long page, long pageSize, SearchResult result) { + this.result = result; + + PaginationBuilder x = new PaginationBuilder(); + x.setPage(BigInteger.valueOf(page)); + x.setSize(pageSize); + x.setTotal(BigInteger.valueOf(result.getTotal())); + pagination = x.build(); + } + + public SearchResult getResult() { + return result; + } + + PaginationOutputG getPagination() { + return pagination; + } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java index dce309c33..9b8806ab8 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/SystemInfo.java @@ -48,284 +48,290 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; public class SystemInfo { - private static NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH)); - private static NumberFormat fmtDec = new DecimalFormat("###,###.##", new DecimalFormatSymbols(Locale.ENGLISH)); - private static NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH)); - private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); - protected static boolean showMemoryPools = false; + private static NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH)); + private static NumberFormat fmtDec = new DecimalFormat("###,###.##", new DecimalFormatSymbols(Locale.ENGLISH)); + private static NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH)); + private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); + protected static boolean showMemoryPools = false; - public static String getMdSalVersion(String def) { - return getMdSalVersion("", def); - } - public static String getYangToolsVersion(String def) { - return getYangToolsVersion("", def); - } - - public static String getMdSalVersion(String baseOdlDirectory,String def) { - return getFeatureVersionByFolder(baseOdlDirectory,"system/org/opendaylight/mdsal/mdsal-binding-api/",def); - } - public static String getYangToolsVersion(String baseOdlDirectory,String def) { - return getFeatureVersionByFolder(baseOdlDirectory,"system/org/opendaylight/yangtools/odl-yangtools-common/",def); - } - private static String getFeatureVersionByFolder(String baseOdlDirectory,String dir,String def) { - final String regex = "^[0-9]+\\.[0-9]+\\.[0-9]+(-SNAPSHOT)?$"; - Stream entries=null; - try { - if(baseOdlDirectory!=null && baseOdlDirectory.length()>0 && !baseOdlDirectory.endsWith("/")) { - baseOdlDirectory+="/"; - } - entries = Files.list(new File(baseOdlDirectory+dir).toPath()); - } catch (IOException e) { - - } - if(entries==null) { - return def; - } - final Pattern pattern = Pattern.compile(regex); - - Iterator it = entries.iterator(); - Path p;File f; - while(it.hasNext()) { - p = it.next(); - f=p.toFile(); - if(f.isDirectory()) { - final Matcher matcher = pattern.matcher(f.getName().toString()); - if(matcher.find()) { - def= matcher.group(0); - break; - } - } - } - entries.close(); - return def; - } - public static String get() throws Exception { - StringBuilder sb = new StringBuilder(); - int maxNameLen; + public static String getMdSalVersion(String def) { + return getMdSalVersion("", def); + } - RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); - ThreadMXBean threads = ManagementFactory.getThreadMXBean(); - MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); - ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean(); + public static String getYangToolsVersion(String def) { + return getYangToolsVersion("", def); + } - // - // print Karaf informations - // - maxNameLen = 25; - sb.append("Karaf\n"); - printValue(sb, "Karaf version", maxNameLen, System.getProperty("karaf.version")); - printValue(sb, "Karaf home", maxNameLen, System.getProperty("karaf.home")); - printValue(sb, "Karaf base", maxNameLen, System.getProperty("karaf.base")); - String osgi = getOsgiFramework(); - if (osgi != null) { - printValue(sb, "OSGi Framework", maxNameLen, osgi); - } + public static String getMdSalVersion(String baseOdlDirectory, String def) { + return getFeatureVersionByFolder(baseOdlDirectory, "system/org/opendaylight/mdsal/mdsal-binding-api/", def); + } - sb.append("JVM\n"); - printValue(sb, "Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion()); - printValue(sb, "Version", maxNameLen, System.getProperty("java.version")); - printValue(sb, "Vendor", maxNameLen, runtime.getVmVendor()); - printValue(sb, "Pid", maxNameLen, getPid()); - printValue(sb, "Uptime", maxNameLen, printDuration(runtime.getUptime())); - try { - Class sunOS = Class.forName("com.sun.management.OperatingSystemMXBean"); - printValue(sb, "Process CPU time", maxNameLen, - printDuration(getValueAsLong(sunOS, "getProcessCpuTime") / 1000000.0)); - printValue(sb, "Process CPU load", maxNameLen, fmtDec.format(getValueAsDouble(sunOS, "getProcessCpuLoad"))); - printValue(sb, "System CPU load", maxNameLen, fmtDec.format(getValueAsDouble(sunOS, "getSystemCpuLoad"))); - } catch (Throwable t) { - } - try { - Class unixOS = Class.forName("com.sun.management.UnixOperatingSystemMXBean"); - printValue(sb, "Open file descriptors", maxNameLen, - printLong(getValueAsLong(unixOS, "getOpenFileDescriptorCount"))); - printValue(sb, "Max file descriptors", maxNameLen, - printLong(getValueAsLong(unixOS, "getMaxFileDescriptorCount"))); - } catch (Throwable t) { - } - printValue(sb, "Total compile time", maxNameLen, - printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime())); + public static String getYangToolsVersion(String baseOdlDirectory, String def) { + return getFeatureVersionByFolder(baseOdlDirectory, "system/org/opendaylight/yangtools/odl-yangtools-common/", + def); + } - sb.append("Threads\n"); - printValue(sb, "Live threads", maxNameLen, Integer.toString(threads.getThreadCount())); - printValue(sb, "Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount())); - printValue(sb, "Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount())); - printValue(sb, "Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount())); + private static String getFeatureVersionByFolder(String baseOdlDirectory, String dir, String def) { + final String regex = "^[0-9]+\\.[0-9]+\\.[0-9]+(-SNAPSHOT)?$"; + Stream entries = null; + try { + if (baseOdlDirectory != null && baseOdlDirectory.length() > 0 && !baseOdlDirectory.endsWith("/")) { + baseOdlDirectory += "/"; + } + entries = Files.list(new File(baseOdlDirectory + dir).toPath()); + } catch (IOException e) { - sb.append("Memory\n"); - printValue(sb, "Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed())); - printValue(sb, "Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax())); - printValue(sb, "Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted())); - printValue(sb, "Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount())); - for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { - String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = " - + printDuration(gc.getCollectionTime()); - printValue(sb, "Garbage collector", maxNameLen, val); - } + } + if (entries == null) { + return def; + } + final Pattern pattern = Pattern.compile(regex); -// if (showMemoryPools) { -// List memoryPools = ManagementFactory.getMemoryPoolMXBeans(); -// sb.append("Memory Pools\n"); -// printValue(sb, "Total Memory Pools", maxNameLen, printLong(memoryPools.size())); -// String spaces4 = " "; -// for (MemoryPoolMXBean pool : memoryPools) { -// String name = pool.getName(); -// MemoryType type = pool.getType(); -// printValue(sb, spaces4 + "Pool (" + type + ")", maxNameLen, name); -// -// // PeakUsage/CurrentUsage -// MemoryUsage peakUsage = pool.getPeakUsage(); -// MemoryUsage usage = pool.getUsage(); -// -// if (usage != null && peakUsage != null) { -// long init = peakUsage.getInit(); -// long used = peakUsage.getUsed(); -// long committed = peakUsage.getCommitted(); -// long max = peakUsage.getMax(); -// sb.append(spaces4 + spaces4 + "Peak Usage\n"); -// printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init)); -// printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used)); -// printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed)); -// printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max)); -// -// init = usage.getInit(); -// used = usage.getUsed(); -// committed = usage.getCommitted(); -// max = usage.getMax(); -// sb.append(spaces4 + spaces4 + "Current Usage\n"); -// printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init)); -// printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used)); -// printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed)); -// printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max)); -// } -// } -// } + Iterator it = entries.iterator(); + Path p; + File f; + while (it.hasNext()) { + p = it.next(); + f = p.toFile(); + if (f.isDirectory()) { + final Matcher matcher = pattern.matcher(f.getName().toString()); + if (matcher.find()) { + def = matcher.group(0); + break; + } + } + } + entries.close(); + return def; + } - sb.append("Classes\n"); - printValue(sb, "Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount())); - printValue(sb, "Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount())); - printValue(sb, "Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount())); + public static String get() throws Exception { + StringBuilder sb = new StringBuilder(); + int maxNameLen; - sb.append("Operating system\n"); - printValue(sb, "Name", maxNameLen, os.getName() + " version " + os.getVersion()); - printValue(sb, "Architecture", maxNameLen, os.getArch()); - printValue(sb, "Processors", maxNameLen, Integer.toString(os.getAvailableProcessors())); - try { - printValue(sb, "Total physical memory", maxNameLen, - printSizeInKb(getSunOsValueAsLong(os, "getTotalPhysicalMemorySize"))); - printValue(sb, "Free physical memory", maxNameLen, - printSizeInKb(getSunOsValueAsLong(os, "getFreePhysicalMemorySize"))); - printValue(sb, "Committed virtual memory", maxNameLen, - printSizeInKb(getSunOsValueAsLong(os, "getCommittedVirtualMemorySize"))); - printValue(sb, "Total swap space", maxNameLen, - printSizeInKb(getSunOsValueAsLong(os, "getTotalSwapSpaceSize"))); - printValue(sb, "Free swap space", maxNameLen, - printSizeInKb(getSunOsValueAsLong(os, "getFreeSwapSpaceSize"))); - } catch (Throwable t) { - } - return sb.toString(); - } + RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); + ThreadMXBean threads = ManagementFactory.getThreadMXBean(); + MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); + ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean(); - private static String getPid() { - // In Java 9 the new process API can be used: - // long pid = ProcessHandle.current().getPid(); - String name = ManagementFactory.getRuntimeMXBean().getName(); - String[] parts = name.split("@"); - return parts[0]; - } + // + // print Karaf informations + // + maxNameLen = 25; + sb.append("Karaf\n"); + printValue(sb, "Karaf version", maxNameLen, System.getProperty("karaf.version")); + printValue(sb, "Karaf home", maxNameLen, System.getProperty("karaf.home")); + printValue(sb, "Karaf base", maxNameLen, System.getProperty("karaf.base")); + String osgi = getOsgiFramework(); + if (osgi != null) { + printValue(sb, "OSGi Framework", maxNameLen, osgi); + } - private static long getSunOsValueAsLong(OperatingSystemMXBean os, String name) throws Exception { - Method mth = os.getClass().getMethod(name); - return (Long) mth.invoke(os); - } + sb.append("JVM\n"); + printValue(sb, "Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion()); + printValue(sb, "Version", maxNameLen, System.getProperty("java.version")); + printValue(sb, "Vendor", maxNameLen, runtime.getVmVendor()); + printValue(sb, "Pid", maxNameLen, getPid()); + printValue(sb, "Uptime", maxNameLen, printDuration(runtime.getUptime())); + try { + Class sunOS = Class.forName("com.sun.management.OperatingSystemMXBean"); + printValue(sb, "Process CPU time", maxNameLen, + printDuration(getValueAsLong(sunOS, "getProcessCpuTime") / 1000000.0)); + printValue(sb, "Process CPU load", maxNameLen, fmtDec.format(getValueAsDouble(sunOS, "getProcessCpuLoad"))); + printValue(sb, "System CPU load", maxNameLen, fmtDec.format(getValueAsDouble(sunOS, "getSystemCpuLoad"))); + } catch (Throwable t) { + } + try { + Class unixOS = Class.forName("com.sun.management.UnixOperatingSystemMXBean"); + printValue(sb, "Open file descriptors", maxNameLen, + printLong(getValueAsLong(unixOS, "getOpenFileDescriptorCount"))); + printValue(sb, "Max file descriptors", maxNameLen, + printLong(getValueAsLong(unixOS, "getMaxFileDescriptorCount"))); + } catch (Throwable t) { + } + printValue(sb, "Total compile time", maxNameLen, + printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime())); - private static long getValueAsLong(Class osImpl, String name) throws Exception { - if (osImpl.isInstance(os)) { - Method mth = osImpl.getMethod(name); - return (Long) mth.invoke(os); - } - return -1; - } + sb.append("Threads\n"); + printValue(sb, "Live threads", maxNameLen, Integer.toString(threads.getThreadCount())); + printValue(sb, "Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount())); + printValue(sb, "Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount())); + printValue(sb, "Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount())); - private static double getValueAsDouble(Class osImpl, String name) throws Exception { - if (osImpl.isInstance(os)) { - Method mth = osImpl.getMethod(name); - return (Double) mth.invoke(os); - } - return -1; - } + sb.append("Memory\n"); + printValue(sb, "Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed())); + printValue(sb, "Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax())); + printValue(sb, "Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted())); + printValue(sb, "Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount())); + for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { + String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = " + + printDuration(gc.getCollectionTime()); + printValue(sb, "Garbage collector", maxNameLen, val); + } - private static String printLong(long i) { - return fmtI.format(i); - } + // if (showMemoryPools) { + // List memoryPools = ManagementFactory.getMemoryPoolMXBeans(); + // sb.append("Memory Pools\n"); + // printValue(sb, "Total Memory Pools", maxNameLen, printLong(memoryPools.size())); + // String spaces4 = " "; + // for (MemoryPoolMXBean pool : memoryPools) { + // String name = pool.getName(); + // MemoryType type = pool.getType(); + // printValue(sb, spaces4 + "Pool (" + type + ")", maxNameLen, name); + // + // // PeakUsage/CurrentUsage + // MemoryUsage peakUsage = pool.getPeakUsage(); + // MemoryUsage usage = pool.getUsage(); + // + // if (usage != null && peakUsage != null) { + // long init = peakUsage.getInit(); + // long used = peakUsage.getUsed(); + // long committed = peakUsage.getCommitted(); + // long max = peakUsage.getMax(); + // sb.append(spaces4 + spaces4 + "Peak Usage\n"); + // printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init)); + // printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used)); + // printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed)); + // printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max)); + // + // init = usage.getInit(); + // used = usage.getUsed(); + // committed = usage.getCommitted(); + // max = usage.getMax(); + // sb.append(spaces4 + spaces4 + "Current Usage\n"); + // printValue(sb, spaces4 + spaces4 + spaces4 + "init", maxNameLen, printLong(init)); + // printValue(sb, spaces4 + spaces4 + spaces4 + "used", maxNameLen, printLong(used)); + // printValue(sb, spaces4 + spaces4 + spaces4 + "committed", maxNameLen, printLong(committed)); + // printValue(sb, spaces4 + spaces4 + spaces4 + "max", maxNameLen, printLong(max)); + // } + // } + // } - private static String printSizeInKb(double size) { - return fmtI.format((long) (size / 1024)) + " kbytes"; - } + sb.append("Classes\n"); + printValue(sb, "Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount())); + printValue(sb, "Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount())); + printValue(sb, "Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount())); - protected static String printDuration(double uptime) { - uptime /= 1000; - if (uptime < 60) { - return fmtD.format(uptime) + " seconds"; - } - uptime /= 60; - if (uptime < 60) { - long minutes = (long) uptime; - String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute"); - return s; - } - uptime /= 60; - if (uptime < 24) { - long hours = (long) uptime; - long minutes = (long) ((uptime - hours) * 60); - String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour"); - if (minutes != 0) { - s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute"); - } - return s; - } - uptime /= 24; - long days = (long) uptime; - long hours = (long) ((uptime - days) * 24); - String s = fmtI.format(days) + (days > 1 ? " days" : " day"); - if (hours != 0) { - s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour"); - } - return s; - } + sb.append("Operating system\n"); + printValue(sb, "Name", maxNameLen, os.getName() + " version " + os.getVersion()); + printValue(sb, "Architecture", maxNameLen, os.getArch()); + printValue(sb, "Processors", maxNameLen, Integer.toString(os.getAvailableProcessors())); + try { + printValue(sb, "Total physical memory", maxNameLen, + printSizeInKb(getSunOsValueAsLong(os, "getTotalPhysicalMemorySize"))); + printValue(sb, "Free physical memory", maxNameLen, + printSizeInKb(getSunOsValueAsLong(os, "getFreePhysicalMemorySize"))); + printValue(sb, "Committed virtual memory", maxNameLen, + printSizeInKb(getSunOsValueAsLong(os, "getCommittedVirtualMemorySize"))); + printValue(sb, "Total swap space", maxNameLen, + printSizeInKb(getSunOsValueAsLong(os, "getTotalSwapSpaceSize"))); + printValue(sb, "Free swap space", maxNameLen, + printSizeInKb(getSunOsValueAsLong(os, "getFreeSwapSpaceSize"))); + } catch (Throwable t) { + } + return sb.toString(); + } - static void printSysValue(StringBuilder sb, String prop, int pad) { - printValue(sb, prop, pad, System.getProperty(prop)); - } + private static String getPid() { + // In Java 9 the new process API can be used: + // long pid = ProcessHandle.current().getPid(); + String name = ManagementFactory.getRuntimeMXBean().getName(); + String[] parts = name.split("@"); + return parts[0]; + } - static void printValue(StringBuilder sb, String name, int pad, String value) { - sb.append(" " + // SimpleAnsi.INTENSITY_BOLD + - name + // SimpleAnsi.INTENSITY_NORMAL + - spaces(pad - name.length()) + " " + value + "\n"); - } + private static long getSunOsValueAsLong(OperatingSystemMXBean os, String name) throws Exception { + Method mth = os.getClass().getMethod(name); + return (Long) mth.invoke(os); + } - static String spaces(int nb) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < nb; i++) { - sb.append(' '); - } - return sb.toString(); - } + private static long getValueAsLong(Class osImpl, String name) throws Exception { + if (osImpl.isInstance(os)) { + Method mth = osImpl.getMethod(name); + return (Long) mth.invoke(os); + } + return -1; + } - static String getOsgiFramework() { - try { - Callable call = new Callable() { - @Override - public String call() throws Exception { - BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext(); - Bundle sysBundle = context.getBundle(0); - return sysBundle.getSymbolicName() + "-" + sysBundle.getVersion(); - } - }; - return call.call(); - } catch (Throwable t) { - // We're not in OSGi, just safely return null - return null; - } - } + private static double getValueAsDouble(Class osImpl, String name) throws Exception { + if (osImpl.isInstance(os)) { + Method mth = osImpl.getMethod(name); + return (Double) mth.invoke(os); + } + return -1; + } + + private static String printLong(long i) { + return fmtI.format(i); + } + + private static String printSizeInKb(double size) { + return fmtI.format((long) (size / 1024)) + " kbytes"; + } + + protected static String printDuration(double uptime) { + uptime /= 1000; + if (uptime < 60) { + return fmtD.format(uptime) + " seconds"; + } + uptime /= 60; + if (uptime < 60) { + long minutes = (long) uptime; + String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute"); + return s; + } + uptime /= 60; + if (uptime < 24) { + long hours = (long) uptime; + long minutes = (long) ((uptime - hours) * 60); + String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour"); + if (minutes != 0) { + s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute"); + } + return s; + } + uptime /= 24; + long days = (long) uptime; + long hours = (long) ((uptime - days) * 24); + String s = fmtI.format(days) + (days > 1 ? " days" : " day"); + if (hours != 0) { + s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour"); + } + return s; + } + + static void printSysValue(StringBuilder sb, String prop, int pad) { + printValue(sb, prop, pad, System.getProperty(prop)); + } + + static void printValue(StringBuilder sb, String name, int pad, String value) { + sb.append(" " + // SimpleAnsi.INTENSITY_BOLD + + name + // SimpleAnsi.INTENSITY_NORMAL + + spaces(pad - name.length()) + " " + value + "\n"); + } + + static String spaces(int nb) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < nb; i++) { + sb.append(' '); + } + return sb.toString(); + } + + static String getOsgiFramework() { + try { + Callable call = new Callable() { + @Override + public String call() throws Exception { + BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext(); + Bundle sysBundle = context.getBundle(0); + return sysBundle.getSymbolicName() + "-" + sysBundle.getVersion(); + } + }; + return call.call(); + } catch (Throwable t) { + // We're not in OSGi, just safely return null + return null; + } + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFileProvider.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFileProvider.java index d54afd642..4f259aa4b 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFileProvider.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFileProvider.java @@ -42,169 +42,167 @@ import org.slf4j.LoggerFactory; public class YangFileProvider { - private static final Logger LOG = LoggerFactory.getLogger(YangFileProvider.class); - - private static final FilenameFilter yangFilenameFilter = new FilenameFilter() { - - @Override - public boolean accept(File dir, String name) { - return name.toLowerCase().endsWith(".yang"); - } - }; - - private static final int BUFFER_SIZE = 1024; - - private final Path mainSourcePath; - private final List additionalSources; - - public YangFileProvider(String path) { - this.mainSourcePath = new File(path).toPath(); - this.additionalSources = new ArrayList<>(); - } - - public boolean hasFileForModule(String module, String version) { - return this.mainSourcePath.resolve(YangFilename.createFilename(module, version)).toFile().exists(); - } - - public boolean hasFileForModule(String module) { - return this.findYangFiles(module).size() > 0; - } - - private List findYangFiles(String module) { - List list = new ArrayList<>(); - String[] files = this.mainSourcePath.toFile().list(yangFilenameFilter); - YangFilename yangfile; - for (String file : files) { - files = this.mainSourcePath.toFile().list(yangFilenameFilter); - for (String fn : files) { - try { - yangfile = new YangFilename(this.mainSourcePath.resolve(fn).toString()); - if (yangfile.getModule().equals(module)) { - list.add(yangfile); - } - } catch (ParseException e) { - LOG.warn("unable to handle yangfile {}: {}", file, e); - } - } - } - for (Path addPath : this.additionalSources) { - files = addPath.toFile().list(yangFilenameFilter); - for (String file : files) { - try { - yangfile = new YangFilename(addPath.resolve(file).toString()); - if (yangfile.getModule().equals(module)) { - list.add(yangfile); - } - } catch (ParseException e) { - LOG.warn("unable to handle yangfile {}: {}", file, e); - } - } - } - return list; - } - - /** - * get yang file from source with specified version or least newer one if - * version is null then the latest one - * - * @param module - * @param version - * @return - * @throws ParseException - */ - private @Nullable YangFilename getYangFile(@Nonnull String module, @Nullable String version) throws ParseException { - YangFilename f = null; - List list = this.findYangFiles(module); - - list.sort(SortByDateAscComparator.getInstance()); - - // find specific version or nearest oldest - if (version != null) { - Date rev = YangFilename.parseRevision(version); - for (YangFilename item : list) { - if (rev.equals(item.getRevision())) { - f = item; - break; - } - if (item.getRevision().after(rev)) { - f = item; - break; - } - } - } - // get latest - else { - f = list.get(list.size() - 1); - } - return f; - } - - /** - * write filestream directly to output stream easier for http handling - * - * @param module - * @param version - * @param outputStream - * @return - * @throws IOException - * @throws ParseException - */ - public int writeOutput(@Nonnull String module, @Nullable String version, @Nonnull OutputStream outputStream) - throws IOException, ParseException { - YangFilename fn = this.getYangFile(module, version); - if(fn==null) { - return 0; - } - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead = -1; - int sumlen = 0; - InputStream inputStream = null ; - try { - inputStream= new FileInputStream(fn.getFilename()); - - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - sumlen += bytesRead; - }} - catch(IOException e) { - LOG.warn("problem sending {}: {}",fn.getFilename(),e); - } - finally { - if(inputStream!=null) { - inputStream.close(); - } - } - return sumlen; - } - - private static class SortByDateAscComparator implements Comparator { - - private static SortByDateAscComparator instance; - - @Override - public int compare(YangFilename o1, YangFilename o2) { - return o1.getRevision().compareTo(o2.getRevision()); - } - - public static Comparator getInstance() { - if (instance == null) { - instance = new SortByDateAscComparator(); - } - return instance; - } - - } - - public YangFilename getFileForModule(String module, String rev) throws ParseException { - return this.getYangFile(module, rev); - } - - public YangFilename getFileForModule(String module) throws ParseException { - return this.getFileForModule(module, null); - } - - public boolean hasFileOrNewerForModule(String module, String version) throws ParseException { - return this.getYangFile(module, version) != null; - } + private static final Logger LOG = LoggerFactory.getLogger(YangFileProvider.class); + + private static final FilenameFilter yangFilenameFilter = new FilenameFilter() { + + @Override + public boolean accept(File dir, String name) { + return name.toLowerCase().endsWith(".yang"); + } + }; + + private static final int BUFFER_SIZE = 1024; + + private final Path mainSourcePath; + private final List additionalSources; + + public YangFileProvider(String path) { + this.mainSourcePath = new File(path).toPath(); + this.additionalSources = new ArrayList<>(); + } + + public boolean hasFileForModule(String module, String version) { + return this.mainSourcePath.resolve(YangFilename.createFilename(module, version)).toFile().exists(); + } + + public boolean hasFileForModule(String module) { + return this.findYangFiles(module).size() > 0; + } + + private List findYangFiles(String module) { + List list = new ArrayList<>(); + String[] files = this.mainSourcePath.toFile().list(yangFilenameFilter); + YangFilename yangfile; + for (String file : files) { + files = this.mainSourcePath.toFile().list(yangFilenameFilter); + for (String fn : files) { + try { + yangfile = new YangFilename(this.mainSourcePath.resolve(fn).toString()); + if (yangfile.getModule().equals(module)) { + list.add(yangfile); + } + } catch (ParseException e) { + LOG.warn("unable to handle yangfile {}: {}", file, e); + } + } + } + for (Path addPath : this.additionalSources) { + files = addPath.toFile().list(yangFilenameFilter); + for (String file : files) { + try { + yangfile = new YangFilename(addPath.resolve(file).toString()); + if (yangfile.getModule().equals(module)) { + list.add(yangfile); + } + } catch (ParseException e) { + LOG.warn("unable to handle yangfile {}: {}", file, e); + } + } + } + return list; + } + + /** + * get yang file from source with specified version or least newer one if version is null then the latest one + * + * @param module + * @param version + * @return + * @throws ParseException + */ + private @Nullable YangFilename getYangFile(@Nonnull String module, @Nullable String version) throws ParseException { + YangFilename f = null; + List list = this.findYangFiles(module); + + list.sort(SortByDateAscComparator.getInstance()); + + // find specific version or nearest oldest + if (version != null) { + Date rev = YangFilename.parseRevision(version); + for (YangFilename item : list) { + if (rev.equals(item.getRevision())) { + f = item; + break; + } + if (item.getRevision().after(rev)) { + f = item; + break; + } + } + } + // get latest + else { + f = list.get(list.size() - 1); + } + return f; + } + + /** + * write filestream directly to output stream easier for http handling + * + * @param module + * @param version + * @param outputStream + * @return + * @throws IOException + * @throws ParseException + */ + public int writeOutput(@Nonnull String module, @Nullable String version, @Nonnull OutputStream outputStream) + throws IOException, ParseException { + YangFilename fn = this.getYangFile(module, version); + if (fn == null) { + return 0; + } + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + int sumlen = 0; + InputStream inputStream = null; + try { + inputStream = new FileInputStream(fn.getFilename()); + + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + sumlen += bytesRead; + } + } catch (IOException e) { + LOG.warn("problem sending {}: {}", fn.getFilename(), e); + } finally { + if (inputStream != null) { + inputStream.close(); + } + } + return sumlen; + } + + private static class SortByDateAscComparator implements Comparator { + + private static SortByDateAscComparator instance; + + @Override + public int compare(YangFilename o1, YangFilename o2) { + return o1.getRevision().compareTo(o2.getRevision()); + } + + public static Comparator getInstance() { + if (instance == null) { + instance = new SortByDateAscComparator(); + } + return instance; + } + + } + + public YangFilename getFileForModule(String module, String rev) throws ParseException { + return this.getYangFile(module, rev); + } + + public YangFilename getFileForModule(String module) throws ParseException { + return this.getFileForModule(module, null); + } + + public boolean hasFileOrNewerForModule(String module, String version) throws ParseException { + return this.getYangFile(module, version) != null; + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFilename.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFilename.java index fcee3cbdb..e5d0b18cd 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFilename.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/data/YangFilename.java @@ -29,39 +29,46 @@ import java.util.regex.Pattern; public class YangFilename { - private static final String REGEX = "([^\\/]*)@([0-9]{4}-[0-9]{2}-[0-9]{2}).yang"; - private static final Pattern pattern = Pattern.compile(REGEX, Pattern.MULTILINE); - private final String filename; - private final Matcher matcher; - private Date revision; - private String module; - public static Date parseRevision(String sRevision) throws ParseException { - final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); - return fmt.parse(sRevision); - } - public YangFilename(String fn) throws ParseException { - this.filename = fn; - matcher = pattern.matcher(this.filename); - if(!matcher.find()) { - throw new ParseException("unknown filename format", 0); - } - this.module= matcher.group(1); - this.revision=parseRevision(matcher.group(2)); - - } - public static String createFilename(String module, String rev) { - return String.format("%s@%s.yang", module,rev); - } - public YangFilename(String module, String rev) throws ParseException { - this(createFilename(module, rev)); - } - public String getFilename() { - return this.filename; - } - public Date getRevision() { - return this.revision; - } - public String getModule() { - return this.module; - } + private static final String REGEX = "([^\\/]*)@([0-9]{4}-[0-9]{2}-[0-9]{2}).yang"; + private static final Pattern pattern = Pattern.compile(REGEX, Pattern.MULTILINE); + private final String filename; + private final Matcher matcher; + private Date revision; + private String module; + + public static Date parseRevision(String sRevision) throws ParseException { + final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); + return fmt.parse(sRevision); + } + + public YangFilename(String fn) throws ParseException { + this.filename = fn; + matcher = pattern.matcher(this.filename); + if (!matcher.find()) { + throw new ParseException("unknown filename format", 0); + } + this.module = matcher.group(1); + this.revision = parseRevision(matcher.group(2)); + + } + + public static String createFilename(String module, String rev) { + return String.format("%s@%s.yang", module, rev); + } + + public YangFilename(String module, String rev) throws ParseException { + this(createFilename(module, rev)); + } + + public String getFilename() { + return this.filename; + } + + public Date getRevision() { + return this.revision; + } + + public String getModule() { + return this.module; + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java index cca5eb648..c0518c664 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter.java @@ -42,239 +42,260 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; /** - * Class to rw yang-tool generated objects into elasticsearch database. For "ES _id" exchange the esIdAddAtributteName is used. - * This attribute mast be of type String and contains for read and write operations the object id. - * The function can be used without id handling. - * If id handling is required the parameter needs to be specified by class definition in yang and setting the name by using setAttributeName() + * Class to rw yang-tool generated objects into elasticsearch database. For "ES _id" exchange the esIdAddAtributteName + * is used. This attribute mast be of type String and contains for read and write operations the object id. The function + * can be used without id handling. If id handling is required the parameter needs to be specified by class definition + * in yang and setting the name by using setAttributeName() * * @param Yang tools generated class object. */ public class EsDataObjectReaderWriter { - private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter.class); - - /** Typename for elastic search data schema **/ - private String dataTypeName; - - /** Elasticsearch Database client to be used **/ - private DatabaseClient db; - - /** Mapper with configuration to use opendaylight yang-tools builder pattern for object creation **/ - private YangToolsMapper yangtoolsMapper; - - /** Class of T as attribute to allow JSON to Class object mapping **/ - private Class clazz; - - /** Field is used to write id. If null no id handling **/ - private @Nullable Field field; - - /** Attribute that is used as id field for the database object **/ - private @Nullable String esIdAddAtributteName; - - /** Interface to be used for write operations. Rule for write: T extends S and **/ - private Class writeInterfaceClazz; // == "S" - - /** - * Elasticsearch database read and write for specific class, defined by opendaylight yang-tools. - * - * @param db Database access client - * @param dataTypeName typename in database schema - * @param clazz class of type to be handled - * @throws ClassNotFoundException - */ - public EsDataObjectReaderWriter(DatabaseClient db, Entity dataTypeName, Class clazz) throws ClassNotFoundException { - this(db, dataTypeName.getName(), clazz); - } - public EsDataObjectReaderWriter(DatabaseClient db, String dataTypeName, Class clazz) throws ClassNotFoundException { - LOG.info("Create {} for datatype {} class {}", this.getClass().getName(), dataTypeName, clazz.getName()); - - this.esIdAddAtributteName = null; - this.field = null; - this.writeInterfaceClazz = clazz; - this.db = db; - this.dataTypeName = dataTypeName; - this.yangtoolsMapper = new YangToolsMapper(); - //this.yangtoolsMapper.assertBuilderClass(clazz); - this.clazz = clazz; -// -// if (! db.isExistsIndex(dataTypeName)) { -// throw new IllegalArgumentException("Index "+dataTypeName+" not existing."); -// } - } - - public String getDataTypeName() { - return dataTypeName; - } - public Class getClazz() { - return clazz; - } - /** - * Simlar to {@link #setEsIdAttributeName()}, but adapts the parameter to yangtools attribute naming schema - * @param esIdAttributeName is converted to UnderscoreCamelCase - * @return this for further operations. - */ - public EsDataObjectReaderWriter setEsIdAttributeNameCamelized(String esIdAttributeName) { - return setEsIdAttributeName(YangToolsMapper.toCamelCaseAttributeName(esIdAttributeName)); - } - - /** - * Attribute name of class that is containing the object id - * @param esIdAttributeName of the implementation class for the yangtools interface. - * Expected attribute name format is CamelCase with leading underline. @ - * @return this for further operations. - * @throws SecurityException if no access or IllegalArgumentException if wrong type or no attribute with this name. - */ - public EsDataObjectReaderWriter setEsIdAttributeName(String esIdAttributeName) { - LOG.debug("Set attribute '{}'", esIdAttributeName); - this.esIdAddAtributteName = null; // Reset status - this.field = null; - - Field attributeField; - try { - Builder builder = yangtoolsMapper.getBuilder(clazz); - T object = builder.build(); - attributeField = object.getClass().getDeclaredField(esIdAttributeName); - if (attributeField.getType().equals(String.class)) { - attributeField.setAccessible(true); - this.esIdAddAtributteName = esIdAttributeName; //Set new status if everything OK - this.field = attributeField; - } else { - String msg = "Wrong field type " + attributeField.getType().getName() + " of " + esIdAttributeName; - LOG.debug(msg); - throw new IllegalArgumentException(msg); - } - } catch (NoSuchFieldException e) { - // Convert to run-time exception - String msg = "NoSuchFieldException for '" + esIdAttributeName + "' in class " + clazz.getName(); - LOG.debug(msg); - throw new IllegalArgumentException(msg); - } catch (SecurityException e) { - LOG.debug("Access problem "+esIdAttributeName,e); - throw e; + private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter.class); + + /** Typename for elastic search data schema **/ + private String dataTypeName; + + /** Elasticsearch Database client to be used **/ + private DatabaseClient db; + + /** Mapper with configuration to use opendaylight yang-tools builder pattern for object creation **/ + private YangToolsMapper yangtoolsMapper; + + /** Class of T as attribute to allow JSON to Class object mapping **/ + private Class clazz; + + /** Field is used to write id. If null no id handling **/ + private @Nullable Field field; + + /** Attribute that is used as id field for the database object **/ + private @Nullable String esIdAddAtributteName; + + /** Interface to be used for write operations. Rule for write: T extends S and **/ + private Class writeInterfaceClazz; // == "S" + + /** + * Elasticsearch database read and write for specific class, defined by opendaylight yang-tools. + * + * @param db Database access client + * @param dataTypeName typename in database schema + * @param clazz class of type to be handled + * @throws ClassNotFoundException + */ + public EsDataObjectReaderWriter(DatabaseClient db, Entity dataTypeName, Class clazz) + throws ClassNotFoundException { + this(db, dataTypeName.getName(), clazz); } - return this; - } - - /** - * Specify subclass of T for write operations. - * @param writeInterfaceClazz - */ - public EsDataObjectReaderWriter setWriteInterface( @Nonnull Class writeInterfaceClazz ) { - LOG.debug("Set write interface to {}", writeInterfaceClazz); - if (writeInterfaceClazz == null) - throw new IllegalArgumentException("Null not allowed here."); - - this.writeInterfaceClazz = writeInterfaceClazz; - return this; - } - - /** - * Write child object to database with specific id - * @param object - * @param @Nullable esId use the id or if null generate unique id - * @return String with id or null - */ - public @Nullable String write(S object, @Nullable String esId) { - if (writeInterfaceClazz.isInstance(object)) { - try { - String json = yangtoolsMapper.writeValueAsString(object); - return db.doWriteRaw(dataTypeName, esId, json); - } catch (JsonProcessingException e) { - LOG.error("Write problem: ", e); - } - } else { - LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null", - writeInterfaceClazz.getName()); + + public EsDataObjectReaderWriter(DatabaseClient db, String dataTypeName, Class clazz) + throws ClassNotFoundException { + LOG.info("Create {} for datatype {} class {}", this.getClass().getName(), dataTypeName, clazz.getName()); + + this.esIdAddAtributteName = null; + this.field = null; + this.writeInterfaceClazz = clazz; + this.db = db; + this.dataTypeName = dataTypeName; + this.yangtoolsMapper = new YangToolsMapper(); + //this.yangtoolsMapper.assertBuilderClass(clazz); + this.clazz = clazz; + // + // if (! db.isExistsIndex(dataTypeName)) { + // throw new IllegalArgumentException("Index "+dataTypeName+" not existing."); + // } } - return null; - } - /** - * Update partial child object to database with match/term query - * @param object - * @param esId - * @return String with esId or null - */ - public @Nullable boolean update(S object, QueryBuilder query) { - if (writeInterfaceClazz.isInstance(object)) { - try { - String json = yangtoolsMapper.writeValueAsString(object); - return db.doUpdate(this.dataTypeName,json,query); - } catch (JsonProcessingException e) { - LOG.error("Update problem: ", e); - } - } else { - LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null", - writeInterfaceClazz.getName()); + + public String getDataTypeName() { + return dataTypeName; } - return false; - } - /** - * Write/ update partial child object to database with specific id Write if not - * exists, else update - * @param object - * @param esId - * @return String with esId or null - */ - public @Nullable String update(S object, String esId) { - return this.update(object, esId,null); - } - public @Nullable String update(S object, String esId,List onylForInsert) { - if (writeInterfaceClazz.isInstance(object)) { - try { - String json = yangtoolsMapper.writeValueAsString(object); - return db.doUpdateOrCreate(dataTypeName, esId, json,onylForInsert); - } catch (JsonProcessingException e) { - LOG.error("Update problem: ", e); - } - } else { - LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null", - writeInterfaceClazz.getName()); + + public Class getClazz() { + return clazz; + } + + /** + * Simlar to {@link #setEsIdAttributeName()}, but adapts the parameter to yangtools attribute naming schema + * + * @param esIdAttributeName is converted to UnderscoreCamelCase + * @return this for further operations. + */ + public EsDataObjectReaderWriter setEsIdAttributeNameCamelized(String esIdAttributeName) { + return setEsIdAttributeName(YangToolsMapper.toCamelCaseAttributeName(esIdAttributeName)); + } + + /** + * Attribute name of class that is containing the object id + * + * @param esIdAttributeName of the implementation class for the yangtools interface. Expected attribute name format + * is CamelCase with leading underline. @ + * @return this for further operations. + * @throws SecurityException if no access or IllegalArgumentException if wrong type or no attribute with this name. + */ + public EsDataObjectReaderWriter setEsIdAttributeName(String esIdAttributeName) { + LOG.debug("Set attribute '{}'", esIdAttributeName); + this.esIdAddAtributteName = null; // Reset status + this.field = null; + + Field attributeField; + try { + Builder builder = yangtoolsMapper.getBuilder(clazz); + T object = builder.build(); + attributeField = object.getClass().getDeclaredField(esIdAttributeName); + if (attributeField.getType().equals(String.class)) { + attributeField.setAccessible(true); + this.esIdAddAtributteName = esIdAttributeName; //Set new status if everything OK + this.field = attributeField; + } else { + String msg = "Wrong field type " + attributeField.getType().getName() + " of " + esIdAttributeName; + LOG.debug(msg); + throw new IllegalArgumentException(msg); + } + } catch (NoSuchFieldException e) { + // Convert to run-time exception + String msg = "NoSuchFieldException for '" + esIdAttributeName + "' in class " + clazz.getName(); + LOG.debug(msg); + throw new IllegalArgumentException(msg); + } catch (SecurityException e) { + LOG.debug("Access problem " + esIdAttributeName, e); + throw e; + } + return this; + } + + /** + * Specify subclass of T for write operations. + * + * @param writeInterfaceClazz + */ + public EsDataObjectReaderWriter setWriteInterface(@Nonnull Class writeInterfaceClazz) { + LOG.debug("Set write interface to {}", writeInterfaceClazz); + if (writeInterfaceClazz == null) + throw new IllegalArgumentException("Null not allowed here."); + + this.writeInterfaceClazz = writeInterfaceClazz; + return this; + } + + /** + * Write child object to database with specific id + * + * @param object + * @param @Nullable esId use the id or if null generate unique id + * @return String with id or null + */ + public @Nullable String write(S object, @Nullable String esId) { + if (writeInterfaceClazz.isInstance(object)) { + try { + String json = yangtoolsMapper.writeValueAsString(object); + return db.doWriteRaw(dataTypeName, esId, json); + } catch (JsonProcessingException e) { + LOG.error("Write problem: ", e); + } + } else { + LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null", + writeInterfaceClazz.getName()); + } + return null; + } + + /** + * Update partial child object to database with match/term query + * + * @param object + * @param esId + * @return String with esId or null + */ + public @Nullable boolean update(S object, QueryBuilder query) { + if (writeInterfaceClazz.isInstance(object)) { + try { + String json = yangtoolsMapper.writeValueAsString(object); + return db.doUpdate(this.dataTypeName, json, query); + } catch (JsonProcessingException e) { + LOG.error("Update problem: ", e); + } + } else { + LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null", + writeInterfaceClazz.getName()); + } + return false; + } + + /** + * Write/ update partial child object to database with specific id Write if not exists, else update + * + * @param object + * @param esId + * @return String with esId or null + */ + public @Nullable String update(S object, String esId) { + return this.update(object, esId, null); + } + + public @Nullable String update(S object, String esId, List onylForInsert) { + if (writeInterfaceClazz.isInstance(object)) { + try { + String json = yangtoolsMapper.writeValueAsString(object); + return db.doUpdateOrCreate(dataTypeName, esId, json, onylForInsert); + } catch (JsonProcessingException e) { + LOG.error("Update problem: ", e); + } + } else { + LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null", + writeInterfaceClazz.getName()); + } + return null; } - return null; - } /** * Read object from database, by using the id field + * * @param object * @return */ public @Nullable T read(String esId) { - @Nullable T res = (T)null; - if (esId != null) { - String json = db.doReadJsonData(dataTypeName, esId); - try { - res = yangtoolsMapper.readValue(json.getBytes(), clazz); - } catch (IOException e) { - LOG.error("Problem: ", e); - } - } + @Nullable + T res = (T) null; + if (esId != null) { + String json = db.doReadJsonData(dataTypeName, esId); + try { + res = yangtoolsMapper.readValue(json.getBytes(), clazz); + } catch (IOException e) { + LOG.error("Problem: ", e); + } + } return res; } /** * Remove object + * * @param esId to identify the object. * @return success */ public boolean remove(String esId) { - return db.doRemove(this.dataTypeName, esId); + return db.doRemove(this.dataTypeName, esId); + } + + public int remove(QueryBuilder query) { + return this.db.doRemove(this.dataTypeName, query); } - public int remove(QueryBuilder query) { - return this.db.doRemove(this.dataTypeName, query); - } /** * Get all elements of related type + * * @return all Elements */ public SearchResult doReadAll() { return doReadAll(null); } + public SearchResult doReadAll(QueryBuilder query) { - return this.doReadAll(query,false); - } + return this.doReadAll(query, false); + } + /** * Read all existing objects of a type + * * @param query for the elements * @return the list of all objects */ @@ -310,26 +331,27 @@ public class EsDataObjectReaderWriter { return res; } - /* --------------------------------------------- + /* --------------------------------------------- * Private functions */ - private void setEsId(T object, String esId) { - if (field != null) { - try { - field.set(object, esId); - } catch (IllegalArgumentException | IllegalAccessException e) { - LOG.debug("Field set problem.", e); } + private void setEsId(T object, String esId) { + if (field != null) { + try { + field.set(object, esId); + } catch (IllegalArgumentException | IllegalAccessException e) { + LOG.debug("Field set problem.", e); + } + } } - } private @Nullable T getT(String jsonString) { - try { - return yangtoolsMapper.readValue( jsonString, clazz ); - } catch (IOException e) { - LOG.info("Mapping problem", e); - return (T)null; - } + try { + return yangtoolsMapper.readValue(jsonString, clazz); + } catch (IOException e) { + LOG.info("Mapping problem", e); + return (T) null; + } } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java index f11bccb53..e0f6e4aea 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/database/EsDataObjectReaderWriter2.java @@ -44,20 +44,21 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; /** - * Class to rw yang-tool generated objects into elasticsearch database. For "ES _id" exchange the esIdAddAtributteName is used. - * This attribute mast be of type String and contains for read and write operations the object id. - * The function can be used without id handling. - * If id handling is required the parameter needs to be specified by class definition in yang and setting the name by using setAttributeName() + * Class to rw yang-tool generated objects into elasticsearch database. For "ES _id" exchange the esIdAddAtributteName + * is used. This attribute mast be of type String and contains for read and write operations the object id. The function + * can be used without id handling. If id handling is required the parameter needs to be specified by class definition + * in yang and setting the name by using setAttributeName() * - * Due to using Jackson base interfaces the org.eclipse.jdt.annotation.NonNull needs to be used here to get rid of warnings + * Due to using Jackson base interfaces the org.eclipse.jdt.annotation.NonNull needs to be used here to get rid of + * warnings * * @param Yang tools generated class object. */ public class EsDataObjectReaderWriter2 { - private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter2.class); + private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter2.class); - /** Typename for elastic search data schema **/ + /** Typename for elastic search data schema **/ private String dataTypeName; /** Elasticsearch Database client to be used **/ @@ -75,7 +76,7 @@ public class EsDataObjectReaderWriter2 { /** Attribute that is used as id field for the database object **/ private @Nullable String esIdAddAtributteName; - /** Interface to be used for write operations. Rule for write: T extends S and **/ + /** Interface to be used for write operations. Rule for write: T extends S and **/ private Class writeInterfaceClazz; // == "S" /** @@ -86,13 +87,20 @@ public class EsDataObjectReaderWriter2 { * @param clazz class of type to be handled * @throws ClassNotFoundException */ - public > EsDataObjectReaderWriter2(DatabaseClient db, Entity dataTypeName, @Nonnull Class clazz, @Nullable Class builderClazz) throws ClassNotFoundException { + public > EsDataObjectReaderWriter2(DatabaseClient db, + Entity dataTypeName, @Nonnull Class clazz, @Nullable Class builderClazz) + throws ClassNotFoundException { this(db, dataTypeName.getName(), clazz, builderClazz); } - public > EsDataObjectReaderWriter2(DatabaseClient db, Entity dataTypeName, @Nonnull Class clazz) throws ClassNotFoundException { + + public > EsDataObjectReaderWriter2(DatabaseClient db, + Entity dataTypeName, @Nonnull Class clazz) throws ClassNotFoundException { this(db, dataTypeName.getName(), clazz, null); } - public > EsDataObjectReaderWriter2(DatabaseClient db, String dataTypeName, @Nonnull Class clazz, @Nullable Class builderClazz) throws ClassNotFoundException { + + public > EsDataObjectReaderWriter2(DatabaseClient db, + String dataTypeName, @Nonnull Class clazz, @Nullable Class builderClazz) + throws ClassNotFoundException { LOG.info("Create {} for datatype {} class {}", this.getClass().getName(), dataTypeName, clazz.getName()); this.esIdAddAtributteName = null; @@ -106,6 +114,7 @@ public class EsDataObjectReaderWriter2 { /** * Simlar to {@link #setEsIdAttributeName()}, but adapts the parameter to yangtools attribute naming schema + * * @param esIdAttributeName is converted to UnderscoreCamelCase * @return this for further operations. */ @@ -115,8 +124,9 @@ public class EsDataObjectReaderWriter2 { /** * Attribute name of class that is containing the object id - * @param esIdAttributeName of the implementation class for the yangtools interface. - * Expected attribute name format is CamelCase with leading underline. @ + * + * @param esIdAttributeName of the implementation class for the yangtools interface. Expected attribute name format + * is CamelCase with leading underline. @ * @return this for further operations. * @throws SecurityException if no access or IllegalArgumentException if wrong type or no attribute with this name. */ @@ -151,7 +161,7 @@ public class EsDataObjectReaderWriter2 { LOG.debug(msg); throw new IllegalArgumentException(msg); } catch (SecurityException e) { - LOG.debug("Access problem "+esIdAttributeName,e); + LOG.debug("Access problem " + esIdAttributeName, e); throw e; } return this; @@ -159,9 +169,10 @@ public class EsDataObjectReaderWriter2 { /** * Specify subclass of T for write operations. + * * @param writeInterfaceClazz */ - public EsDataObjectReaderWriter2 setWriteInterface( @Nonnull Class writeInterfaceClazz ) { + public EsDataObjectReaderWriter2 setWriteInterface(@Nonnull Class writeInterfaceClazz) { LOG.debug("Set write interface to {}", writeInterfaceClazz); if (writeInterfaceClazz == null) { throw new IllegalArgumentException("Null not allowed here."); @@ -183,11 +194,12 @@ public class EsDataObjectReaderWriter2 { /** * Write child object to database with specific id + * * @param object to be written * @param esId use the id or if null generate unique id * @return String with id or null */ - public @Nullable String write( S object, @Nullable String esId) { + public @Nullable String write(S object, @Nullable String esId) { if (object != null && writeInterfaceClazz.isInstance(object)) { try { String json = yangtoolsMapper.writeValueAsString(object); @@ -196,13 +208,15 @@ public class EsDataObjectReaderWriter2 { LOG.error("Write problem: ", e); } } else { - LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null", + LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null", writeInterfaceClazz.getName()); } return null; } + /** * Update partial child object to database with match/term query + * * @param of object * @param object to write * @param query for write of specific attributes @@ -212,39 +226,41 @@ public class EsDataObjectReaderWriter2 { if (object != null && writeInterfaceClazz.isInstance(object)) { try { String json = yangtoolsMapper.writeValueAsString(object); - return db.doUpdate(this.dataTypeName,json,query); + return db.doUpdate(this.dataTypeName, json, query); } catch (JsonProcessingException e) { LOG.error("Update problem: ", e); } } else { - LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null", + LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null", writeInterfaceClazz.getName()); } return false; } + /** - * Write/ update partial child object to database with specific id Write if not - * exists, else update + * Write/ update partial child object to database with specific id Write if not exists, else update + * * @param object * @param esId * @return String with esId or null */ public @Nullable String update(S object, String esId) { - return this.updateOrCreate(object, esId,null); + return this.updateOrCreate(object, esId, null); } + /** * See {@link doUpdateOrCreate(String dataTypeName, String esId, String json, List doNotUpdateField) } */ - public @Nullable String updateOrCreate(S object, String esId,List onlyForInsert) { + public @Nullable String updateOrCreate(S object, String esId, List onlyForInsert) { if (object != null && writeInterfaceClazz.isInstance(object)) { try { String json = yangtoolsMapper.writeValueAsString(object); - return db.doUpdateOrCreate(dataTypeName, esId, json,onlyForInsert); + return db.doUpdateOrCreate(dataTypeName, esId, json, onlyForInsert); } catch (JsonProcessingException e) { LOG.error("Update problem: ", e); } } else { - LOG.error("Type {} does not provide interface {}", object!=null?object.getClass().getName():"null", + LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null", writeInterfaceClazz.getName()); } return null; @@ -252,6 +268,7 @@ public class EsDataObjectReaderWriter2 { /** * Read object from database, by using the id field + * * @param object * @return */ @@ -275,6 +292,7 @@ public class EsDataObjectReaderWriter2 { /** * Remove object + * * @param esId to identify the object. * @return success */ @@ -285,18 +303,23 @@ public class EsDataObjectReaderWriter2 { public int remove(QueryBuilder query) { return this.db.doRemove(this.dataTypeName, query); } + /** * Get all elements of related type + * * @return all Elements */ public SearchResult doReadAll() { return doReadAll(null); } + public SearchResult doReadAll(QueryBuilder query) { - return this.doReadAll(query,false); + return this.doReadAll(query, false); } + /** * Read all existing objects of a type + * * @param query for the elements * @return the list of all objects */ @@ -304,21 +327,21 @@ public class EsDataObjectReaderWriter2 { public SearchResult doReadAll(QueryBuilder query, boolean ignoreException) { SearchResult res = new SearchResult<>(); - int idx = 0; //Idx for getAll - int iterateLength = 100; //Step width for iterate + int idx = 0; //Idx for getAll + int iterateLength = 100; //Step width for iterate SearchResult result; List hits; do { - if(query!=null) { - LOG.debug("read data in {} with query {}",dataTypeName,query.toJSON()); - result=db.doReadByQueryJsonData( dataTypeName, query,ignoreException); - } - else { - result = db.doReadAllJsonData(dataTypeName,ignoreException); + if (query != null) { + LOG.debug("read data in {} with query {}", dataTypeName, query.toJSON()); + result = db.doReadByQueryJsonData(dataTypeName, query, ignoreException); + } else { + result = db.doReadAllJsonData(dataTypeName, ignoreException); } - hits=result.getHits(); - LOG.debug("Read: {} elements: {} Failures: {}",dataTypeName,hits.size(), yangtoolsMapper.getMappingFailures()); + hits = result.getHits(); + LOG.debug("Read: {} elements: {} Failures: {}", dataTypeName, hits.size(), + yangtoolsMapper.getMappingFailures()); T object; idx += result.getHits().size(); @@ -349,13 +372,14 @@ public class EsDataObjectReaderWriter2 { try { field.set(object, esId); } catch (IllegalArgumentException | IllegalAccessException e) { - LOG.debug("Field set problem.", e); } + LOG.debug("Field set problem.", e); + } } } private @Nullable T getT(String jsonString) { try { - return yangtoolsMapper.readValue( jsonString, clazz ); + return yangtoolsMapper.readValue(jsonString, clazz); } catch (IOException e) { LOG.info("Mapping problem", e); return null; diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/AboutHttpServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/AboutHttpServlet.java index 8c33a29e7..120684298 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/AboutHttpServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/AboutHttpServlet.java @@ -45,304 +45,312 @@ import org.slf4j.LoggerFactory; public class AboutHttpServlet extends HttpServlet { - /** - * - */ - private static final long serialVersionUID = 1L; - private static final Logger LOG = LoggerFactory.getLogger(AboutHttpServlet.class); - private static final String UNKNOWN = "unknown"; - private static final String METAINF_MAVEN = "/META-INF/maven/"; - private static final String EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE = "unable to read inner pom file: {}"; + /** + * + */ + private static final long serialVersionUID = 1L; + private static final Logger LOG = LoggerFactory.getLogger(AboutHttpServlet.class); + private static final String UNKNOWN = "unknown"; + private static final String METAINF_MAVEN = "/META-INF/maven/"; + private static final String EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE = "unable to read inner pom file: {}"; - private static final String URI_PRE = "/about"; - private static final String RES_BASEPATH = "about/"; + private static final String URI_PRE = "/about"; + private static final String RES_BASEPATH = "about/"; - private static final String PLACEHOLDER_ONAP_RELEASENAME = "{release-name}"; - private static final String PLACEHOLDER_ONAP_RELEASEVERSION = "{release-version}"; - private static final String PLACEHOLDER_ODL_RELEASENAME = "{odl-version}"; - private static final String PLACEHOLDER_BUILD_TIMESTAMP = "{build-time}"; - private static final String PLACEHOLDER_ODLUX_REVISION = "{odlux-revision}"; - private static final String PLACEHOLDER_PACKAGE_GITHASH = "{package-githash}"; - private static final String PLACEHOLDER_PACAKGE_VERSION = "{package-version}"; - private static final String PLACEHOLDER_CCSDK_VERSION = "{ccsdk-version}"; - private static final String PLACEHOLDER_CLUSTER_SIZE = "{cluster-size}"; - private static final String PLACEHOLDER_MDSAL_VERSION = "{mdsal-version}"; - private static final String PLACEHOLDER_YANGTOOLS_VERSION = "{yangtools-version}"; - private static final String PLACEHOLDER_KARAF_INFO = "{karaf-info}"; - private static final String README_FILE = "README.md"; + private static final String PLACEHOLDER_ONAP_RELEASENAME = "{release-name}"; + private static final String PLACEHOLDER_ONAP_RELEASEVERSION = "{release-version}"; + private static final String PLACEHOLDER_ODL_RELEASENAME = "{odl-version}"; + private static final String PLACEHOLDER_BUILD_TIMESTAMP = "{build-time}"; + private static final String PLACEHOLDER_ODLUX_REVISION = "{odlux-revision}"; + private static final String PLACEHOLDER_PACKAGE_GITHASH = "{package-githash}"; + private static final String PLACEHOLDER_PACAKGE_VERSION = "{package-version}"; + private static final String PLACEHOLDER_CCSDK_VERSION = "{ccsdk-version}"; + private static final String PLACEHOLDER_CLUSTER_SIZE = "{cluster-size}"; + private static final String PLACEHOLDER_MDSAL_VERSION = "{mdsal-version}"; + private static final String PLACEHOLDER_YANGTOOLS_VERSION = "{yangtools-version}"; + private static final String PLACEHOLDER_KARAF_INFO = "{karaf-info}"; + private static final String README_FILE = "README.md"; - private final String groupId = "org.onap.ccsdk.features.sdnr.wt"; - private final String artifactId = "sdnr-wt-data-provider-provider"; + private final String groupId = "org.onap.ccsdk.features.sdnr.wt"; + private final String artifactId = "sdnr-wt-data-provider-provider"; - private final Map data; - private final String readmeContent; + private final Map data; + private final String readmeContent; - public AboutHttpServlet() { + public AboutHttpServlet() { - this.data = new HashMap<>(); - this.collectStaticData(); - this.readmeContent = this.render(this.getResourceFileContent(README_FILE)); - } + this.data = new HashMap<>(); + this.collectStaticData(); + this.readmeContent = this.render(this.getResourceFileContent(README_FILE)); + } - /** - * collect static versioning data - */ - private void collectStaticData() { - PomPropertiesFile props = this.getPomProperties(); - final String ccsdkVersion = this.getPomParentVersion(); - this.data.put(PLACEHOLDER_ONAP_RELEASENAME, ODLVersionLUT.getONAPReleaseName(ccsdkVersion, UNKNOWN)); - this.data.put(PLACEHOLDER_ODL_RELEASENAME, ODLVersionLUT.getOdlVersion(ccsdkVersion, UNKNOWN)); - this.data.put(PLACEHOLDER_BUILD_TIMESTAMP, props != null ? props.getBuildDate().toString() : ""); - this.data.put(PLACEHOLDER_ODLUX_REVISION, this.getPomProperty("odlux.buildno")); - this.data.put(PLACEHOLDER_PACAKGE_VERSION, this.getManifestValue("Bundle-Version")); - this.data.put(PLACEHOLDER_CCSDK_VERSION, ccsdkVersion); - this.data.put(PLACEHOLDER_ONAP_RELEASEVERSION, "1.8.1-SNAPSHOT"); - this.data.put(PLACEHOLDER_MDSAL_VERSION, SystemInfo.getMdSalVersion(UNKNOWN)); - this.data.put(PLACEHOLDER_YANGTOOLS_VERSION, SystemInfo.getYangToolsVersion(UNKNOWN)); - this.data.put(PLACEHOLDER_PACKAGE_GITHASH, this.getGitHash(UNKNOWN)); - } + /** + * collect static versioning data + */ + private void collectStaticData() { + PomPropertiesFile props = this.getPomProperties(); + final String ccsdkVersion = this.getPomParentVersion(); + this.data.put(PLACEHOLDER_ONAP_RELEASENAME, ODLVersionLUT.getONAPReleaseName(ccsdkVersion, UNKNOWN)); + this.data.put(PLACEHOLDER_ODL_RELEASENAME, ODLVersionLUT.getOdlVersion(ccsdkVersion, UNKNOWN)); + this.data.put(PLACEHOLDER_BUILD_TIMESTAMP, props != null ? props.getBuildDate().toString() : ""); + this.data.put(PLACEHOLDER_ODLUX_REVISION, this.getPomProperty("odlux.buildno")); + this.data.put(PLACEHOLDER_PACAKGE_VERSION, this.getManifestValue("Bundle-Version")); + this.data.put(PLACEHOLDER_CCSDK_VERSION, ccsdkVersion); + this.data.put(PLACEHOLDER_ONAP_RELEASEVERSION, "1.8.1-SNAPSHOT"); + this.data.put(PLACEHOLDER_MDSAL_VERSION, SystemInfo.getMdSalVersion(UNKNOWN)); + this.data.put(PLACEHOLDER_YANGTOOLS_VERSION, SystemInfo.getYangToolsVersion(UNKNOWN)); + this.data.put(PLACEHOLDER_PACKAGE_GITHASH, this.getGitHash(UNKNOWN)); + } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String uri = req.getRequestURI().substring(URI_PRE.length()); - LOG.debug("request for {}", uri); - if (uri.length() <= 0 || uri.equals("/")) { - // collect data - this.collectData(); - // render readme - String content = this.render(); - byte[] output = content != null ? content.getBytes() : new byte[0]; - // output - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentLength(output.length); - resp.setContentType("text/plain"); - ServletOutputStream os = null; - try{ - 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); - } - } - } + String uri = req.getRequestURI().substring(URI_PRE.length()); + LOG.debug("request for {}", uri); + if (uri.length() <= 0 || uri.equals("/")) { + // collect data + this.collectData(); + // render readme + String content = this.render(); + byte[] output = content != null ? content.getBytes() : new byte[0]; + // output + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentLength(output.length); + resp.setContentType("text/plain"); + ServletOutputStream os = null; + try { + 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); - } - } + } else { + this.doGetFile(uri, resp); + } + } - /** - * load git.commit.id from jar /META-INF/git.properties - * - * @param def - */ - private String getGitHash(String def) { - String content = Resources.getFileContent(AboutHttpServlet.class, "/META-INF/git.properties"); - if (content == null) { - return def; - } - String lines[] = content.split("\n"); - for (String line : lines) { - if (line.startsWith("git.commit.id")) { - def = line.substring("git.commit.id=".length()); - break; - } - } - return def; - } + /** + * load git.commit.id from jar /META-INF/git.properties + * + * @param def + */ + private String getGitHash(String def) { + String content = Resources.getFileContent(AboutHttpServlet.class, "/META-INF/git.properties"); + if (content == null) { + return def; + } + String lines[] = content.split("\n"); + for (String line : lines) { + if (line.startsWith("git.commit.id")) { + def = line.substring("git.commit.id=".length()); + break; + } + } + return def; + } - private String getResourceFileContent(String filename) { - LOG.debug("try ti get content of {}", filename); - return Resources.getFileContent(AboutHttpServlet.class, RES_BASEPATH + filename); - } + private String getResourceFileContent(String filename) { + LOG.debug("try ti get content of {}", filename); + return Resources.getFileContent(AboutHttpServlet.class, RES_BASEPATH + filename); + } - /** - * collect dynamic data for about.md - */ - private void collectData() { - LOG.info("collecting dynamic data"); - try { - this.data.put(PLACEHOLDER_KARAF_INFO, SystemInfo.get()); - } catch (Exception e) { - LOG.warn("problem collecting system data: {}", e); - } - } + /** + * collect dynamic data for about.md + */ + private void collectData() { + LOG.info("collecting dynamic data"); + try { + this.data.put(PLACEHOLDER_KARAF_INFO, SystemInfo.get()); + } catch (Exception e) { + LOG.warn("problem collecting system data: {}", e); + } + } - /** - * get value for key out of /META-INF/MANIFEST.MF - * @param key - * @return - */ - private String getManifestValue(String key) { - URL url = Resources.getUrlForRessource(AboutHttpServlet.class, "/META-INF/MANIFEST.MF"); - if (url == null) { - return null; - } - Manifest manifest; - try { - manifest = new Manifest(url.openStream()); - Attributes attr = manifest.getMainAttributes(); - return attr.getValue(key); - } catch (IOException e) { - LOG.warn("problem reading manifest: {}", e); - } - return null; + /** + * get value for key out of /META-INF/MANIFEST.MF + * + * @param key + * @return + */ + private String getManifestValue(String key) { + URL url = Resources.getUrlForRessource(AboutHttpServlet.class, "/META-INF/MANIFEST.MF"); + if (url == null) { + return null; + } + Manifest manifest; + try { + manifest = new Manifest(url.openStream()); + Attributes attr = manifest.getMainAttributes(); + return attr.getValue(key); + } catch (IOException e) { + LOG.warn("problem reading manifest: {}", e); + } + return null; - } - /** - * get object representation of /META-INF/maven/groupId/artifactId/pom.properties - * @return - */ - private PomPropertiesFile getPomProperties() { - URL url = Resources.getUrlForRessource(AboutHttpServlet.class, - METAINF_MAVEN + groupId + "/" + artifactId + "/pom.properties"); - PomPropertiesFile propfile; - if (url == null) { - return null; - } - try { - propfile = new PomPropertiesFile(url.openStream()); - return propfile; - } catch (Exception e) { - LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e); - } - return null; - } - /** - * get value for key out of /META-INF/maven/groupId/artifactId/pom.xml in properties section - * @param key - * @return - */ - private String getPomProperty(String key) { - LOG.info("try to get pom property for {}", key); - URL url = Resources.getUrlForRessource(AboutHttpServlet.class, - METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml"); - if (url == null) { - return null; - } - PomFile pomfile; - try { - pomfile = new PomFile(url.openStream()); - return pomfile.getProperty(key); - } catch (Exception e) { - LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e); - } - return null; - } - /** - * get parent pom version out of /META-INF/maven/groupId/artifactId/pom.xml - * @return - */ - private String getPomParentVersion() { - LOG.info("try to get pom parent version"); - URL url = Resources.getUrlForRessource(AboutHttpServlet.class, - METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml"); - if (url == null) { - return null; - } - PomFile pomfile; - try { - pomfile = new PomFile(url.openStream()); - return pomfile.getParentVersion(); - } catch (Exception e) { - LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e); - } - return null; - } + } - /** - * get file by uri from resources and write out to response stream - * @param uri - * @param resp - */ - private void doGetFile(String uri, HttpServletResponse resp) { - String content = this.getResourceFileContent(uri); - if (content == null) { - try { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - } catch (IOException e) { - LOG.debug("unable to send error response : {}", e); - } - } else { - byte[] data = content.getBytes(); - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType(this.getContentType(uri)); - try { - resp.getOutputStream().write(data); - } catch (IOException e) { - LOG.debug("unable to send data : {}", e); - } - } + /** + * get object representation of /META-INF/maven/groupId/artifactId/pom.properties + * + * @return + */ + private PomPropertiesFile getPomProperties() { + URL url = Resources.getUrlForRessource(AboutHttpServlet.class, + METAINF_MAVEN + groupId + "/" + artifactId + "/pom.properties"); + PomPropertiesFile propfile; + if (url == null) { + return null; + } + try { + propfile = new PomPropertiesFile(url.openStream()); + return propfile; + } catch (Exception e) { + LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e); + } + return null; + } - } + /** + * get value for key out of /META-INF/maven/groupId/artifactId/pom.xml in properties section + * + * @param key + * @return + */ + private String getPomProperty(String key) { + LOG.info("try to get pom property for {}", key); + URL url = Resources.getUrlForRessource(AboutHttpServlet.class, + METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml"); + if (url == null) { + return null; + } + PomFile pomfile; + try { + pomfile = new PomFile(url.openStream()); + return pomfile.getProperty(key); + } catch (Exception e) { + LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e); + } + return null; + } - /** - * create http response contentType by filename - * @param filename - * @return - */ - private String getContentType(String filename) { - String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); - switch (ext) { - case "jpg": - case "jpeg": - case "svg": - case "png": - case "gif": - case "bmp": - return "image/" + ext; - case "json": - return "application/json"; - case "html": - case "htm": - return "text/html"; - case "txt": - case "md": - default: - return "text/plain"; - } - } + /** + * get parent pom version out of /META-INF/maven/groupId/artifactId/pom.xml + * + * @return + */ + private String getPomParentVersion() { + LOG.info("try to get pom parent version"); + URL url = Resources.getUrlForRessource(AboutHttpServlet.class, + METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml"); + if (url == null) { + return null; + } + PomFile pomfile; + try { + pomfile = new PomFile(url.openStream()); + return pomfile.getParentVersion(); + } catch (Exception e) { + LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e); + } + return null; + } - /** - * render this.readmeContent with this.data - * @return - */ - private String render() { - return this.render(null); - } + /** + * get file by uri from resources and write out to response stream + * + * @param uri + * @param resp + */ + private void doGetFile(String uri, HttpServletResponse resp) { + String content = this.getResourceFileContent(uri); + if (content == null) { + try { + resp.sendError(HttpServletResponse.SC_NOT_FOUND); + } catch (IOException e) { + LOG.debug("unable to send error response : {}", e); + } + } else { + byte[] data = content.getBytes(); + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType(this.getContentType(uri)); + try { + resp.getOutputStream().write(data); + } catch (IOException e) { + LOG.debug("unable to send data : {}", e); + } + } - /** - * render content with this.data - * @param content - * @return - */ - private String render(String content) { - if (content == null) { - content = this.readmeContent; - } - if (content == null) { - return null; - } - for (Entry entry : this.data.entrySet()) { - if (entry.getValue() != null && content.contains(entry.getKey())) { - content = content.replace(entry.getKey(), entry.getValue()); - } - } + } - return content; - } + /** + * create http response contentType by filename + * + * @param filename + * @return + */ + private String getContentType(String filename) { + String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); + switch (ext) { + case "jpg": + case "jpeg": + case "svg": + case "png": + case "gif": + case "bmp": + return "image/" + ext; + case "json": + return "application/json"; + case "html": + case "htm": + return "text/html"; + case "txt": + case "md": + default: + return "text/plain"; + } + } - public void setClusterSize(String value) { - this.data.put(PLACEHOLDER_CLUSTER_SIZE, value); - } -} \ No newline at end of file + /** + * render this.readmeContent with this.data + * + * @return + */ + private String render() { + return this.render(null); + } + + /** + * render content with this.data + * + * @param content + * @return + */ + private String render(String content) { + if (content == null) { + content = this.readmeContent; + } + if (content == null) { + return null; + } + for (Entry entry : this.data.entrySet()) { + if (entry.getValue() != null && content.contains(entry.getKey())) { + content = content.replace(entry.getKey(), entry.getValue()); + } + } + + return content; + } + + public void setClusterSize(String value) { + this.data.put(PLACEHOLDER_CLUSTER_SIZE, value); + } +} 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 322392379..490f3cac8 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 @@ -34,24 +34,26 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; * @author Michael Dürre * */ -public class DataTreeHttpServlet extends HttpServlet{ - - /** - * @param rawClient - */ - public void setDatabaseClient(HtDatabaseClient rawClient) { - - - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - final String uri = req.getRequestURI(); - } - private void readInventoryTree(String filter) { - - } - private void doJsonResponse(HttpServletResponse resp,Object data) { - - } +public class DataTreeHttpServlet extends HttpServlet { + + /** + * @param rawClient + */ + public void setDatabaseClient(HtDatabaseClient rawClient) { + + + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + final String uri = req.getRequestURI(); + } + + private void readInventoryTree(String filter) { + + } + + private void doJsonResponse(HttpServletResponse resp, Object data) { + + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/GetYangSchemaRequest.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/GetYangSchemaRequest.java index 87210f29a..fd2784804 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/GetYangSchemaRequest.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/GetYangSchemaRequest.java @@ -25,37 +25,37 @@ import javax.servlet.http.HttpServletRequest; public class GetYangSchemaRequest { - private static final String URI_PREFIX = "/yang-schema/"; - private final String module; - private final String version; - - public String getModule() { - return this.module; - } - - public String getVersion() { - return this.version; - } - - public boolean hasVersion() { - return this.version != null; - } - - public GetYangSchemaRequest(HttpServletRequest req) throws Exception { - String uri = req.getRequestURI().substring(URI_PREFIX.length()); - - String[] hlp = uri.split("/"); - if (hlp.length < 1) { - throw new Exception("no module request found"); - - } else if (hlp.length == 1) { - this.module = hlp[0]; - this.version = null; - } else { - this.module = hlp[0]; - this.version = hlp[1]; - } - - } + private static final String URI_PREFIX = "/yang-schema/"; + private final String module; + private final String version; + + public String getModule() { + return this.module; + } + + public String getVersion() { + return this.version; + } + + public boolean hasVersion() { + return this.version != null; + } + + public GetYangSchemaRequest(HttpServletRequest req) throws Exception { + String uri = req.getRequestURI().substring(URI_PREFIX.length()); + + String[] hlp = uri.split("/"); + if (hlp.length < 1) { + throw new Exception("no module request found"); + + } else if (hlp.length == 1) { + this.module = hlp[0]; + this.version = null; + } else { + this.module = hlp[0]; + this.version = hlp[1]; + } + + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java index ec5661acd..725256b17 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/MsServlet.java @@ -33,81 +33,86 @@ import org.slf4j.LoggerFactory; public class MsServlet extends BaseServlet { - /** - * - */ - private static Logger LOG = LoggerFactory.getLogger(MsServlet.class); - private static final long serialVersionUID = -5361461082028405171L; - private static final String OFFLINE_RESPONSE_MESSAGE = "MediatorServer interface is offline"; - private static boolean trustAll = false; - private static MediatorServerDataProvider entryProvider; - public MsServlet() { - super(); - } - - @Override - protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setStatus(200); - } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); - } - @Override - protected String getOfflineResponse() { - return OFFLINE_RESPONSE_MESSAGE; - } - - public void triggerReloadDatabaseEntries() { - LOG.debug("external reload triggered"); - entryProvider.triggerReloadSync(); - } - - @Override - protected boolean isOff() { - return false; - } - - @Override - protected String getRemoteUrl(String uri) { - String dbServerId = "0"; - if (uri == null) - uri = ""; - if (uri.length() > 0) { - uri = uri.substring("/ms/".length()); - int idx= uri.indexOf("/"); - dbServerId = uri.substring(0,idx); - uri=uri.substring(idx); - } - LOG.debug("request for ms server with id={}",dbServerId); - String url= this.getBaseUrl(dbServerId) + uri; - LOG.debug("dest-url: {}",url); - return url; - } - - protected String getBaseUrl(String dbServerId) { - return entryProvider.getHostUrl(dbServerId); - } - @Override - protected boolean doTrustAll() { - return trustAll; - } - @Override - protected void trustAll(boolean trust) { - trustAll = trust; - } - - public void setDataProvider(MediatorServerDataProvider mediatorServerDataProvider) { - entryProvider = mediatorServerDataProvider; - } - - @Override - protected boolean trustInsecure() { - return trustAll; - } - - @Override - protected boolean isCorsEnabled() { - return false; - } + /** + * + */ + private static Logger LOG = LoggerFactory.getLogger(MsServlet.class); + private static final long serialVersionUID = -5361461082028405171L; + private static final String OFFLINE_RESPONSE_MESSAGE = "MediatorServer interface is offline"; + private static boolean trustAll = false; + private static MediatorServerDataProvider entryProvider; + + public MsServlet() { + super(); + } + + @Override + protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setStatus(200); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doGet(req, resp); + } + + @Override + protected String getOfflineResponse() { + return OFFLINE_RESPONSE_MESSAGE; + } + + public void triggerReloadDatabaseEntries() { + LOG.debug("external reload triggered"); + entryProvider.triggerReloadSync(); + } + + @Override + protected boolean isOff() { + return false; + } + + @Override + protected String getRemoteUrl(String uri) { + String dbServerId = "0"; + if (uri == null) + uri = ""; + if (uri.length() > 0) { + uri = uri.substring("/ms/".length()); + int idx = uri.indexOf("/"); + dbServerId = uri.substring(0, idx); + uri = uri.substring(idx); + } + LOG.debug("request for ms server with id={}", dbServerId); + String url = this.getBaseUrl(dbServerId) + uri; + LOG.debug("dest-url: {}", url); + return url; + } + + protected String getBaseUrl(String dbServerId) { + return entryProvider.getHostUrl(dbServerId); + } + + @Override + protected boolean doTrustAll() { + return trustAll; + } + + @Override + protected void trustAll(boolean trust) { + trustAll = trust; + } + + public void setDataProvider(MediatorServerDataProvider mediatorServerDataProvider) { + entryProvider = mediatorServerDataProvider; + } + + @Override + protected boolean trustInsecure() { + return trustAll; + } + + @Override + protected boolean isCorsEnabled() { + return false; + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/ReadyHttpServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/ReadyHttpServlet.java index 8e1ced7da..e20f453a1 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/ReadyHttpServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/ReadyHttpServlet.java @@ -33,35 +33,34 @@ import org.slf4j.LoggerFactory; public class ReadyHttpServlet extends HttpServlet { - /** - * - */ - private static final long serialVersionUID = 1L; - private static final Logger LOG = LoggerFactory.getLogger(ReadyHttpServlet.class); - private static boolean status; + /** + * + */ + private static final long serialVersionUID = 1L; + private static final Logger LOG = LoggerFactory.getLogger(ReadyHttpServlet.class); + private static boolean status; - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - if(isReady()) { - resp.setStatus(HttpServletResponse.SC_OK); - } - else { - - try { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - }catch(IOException | IllegalStateException e) { - LOG.warn("unable to write out 404 res not found: {}",e); - } - } - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - private static boolean isReady() { - return status; - } + if (isReady()) { + resp.setStatus(HttpServletResponse.SC_OK); + } else { - public static void setStatus(boolean s) { - status = s; - LOG.info("status is set to ready: {}",status); - } + try { + resp.sendError(HttpServletResponse.SC_NOT_FOUND); + } catch (IOException | IllegalStateException e) { + LOG.warn("unable to write out 404 res not found: {}", e); + } + } + } + + private static boolean isReady() { + return status; + } + + public static void setStatus(boolean s) { + status = s; + LOG.info("status is set to ready: {}", status); + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/YangSchemaHttpServlet.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/YangSchemaHttpServlet.java index 967ae26cb..075f4f766 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/YangSchemaHttpServlet.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/http/YangSchemaHttpServlet.java @@ -34,90 +34,90 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class YangSchemaHttpServlet extends HttpServlet { - /** - * - */ - private static final long serialVersionUID = 1L; - private static final Logger LOG = LoggerFactory.getLogger(YangSchemaHttpServlet.class); - - private static final String schemaCachePath = "cache/schema/"; - - private final YangFileProvider fileProvider; - - public YangSchemaHttpServlet() { - this.fileProvider = new YangFileProvider(schemaCachePath); - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - GetYangSchemaRequest request = null; - try { - request = new GetYangSchemaRequest(req); - } catch (Exception e) { - LOG.warn("bad request for yang-schema: {}", e); - } - if (request != null) { - int len; - LOG.debug("request for yang-schema for module {} with version {}", request.getModule(), - request.getVersion()); - if (request.hasVersion()) { - boolean has=false; - try { - has = this.fileProvider.hasFileOrNewerForModule(request.getModule(), request.getVersion()); - } catch (ParseException e1) { - LOG.warn("unable to parse revision: {}" ,e1); - } - if(has) { - - try { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/plain"); - len = this.fileProvider.writeOutput(request.getModule(), request.getVersion(), - resp.getOutputStream()); - resp.setContentLength(len); - - } catch (ParseException e) { - LOG.warn("unable to parse revision: {}", e); - }catch (IOException | IllegalStateException e) { - LOG.warn("unable to write out module {}@{}: {}",request.getModule(), request.getVersion(), e); - } - } else { - try { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - }catch(IOException | IllegalStateException e) { - LOG.warn("unable to write out 404 res not found: {}",e); - } - } - - } else if (this.fileProvider.hasFileForModule(request.getModule())) { - - try { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/plain"); - len = this.fileProvider.writeOutput(request.getModule(), null, resp.getOutputStream()); - resp.setContentLength(len); - } catch (ParseException e) { - LOG.warn(e.getMessage()); - }catch(IOException | IllegalStateException e) { - LOG.warn("unable to write out module {}: {}",request.getModule(), e); - } - - } else { - try { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - }catch(IOException | IllegalStateException e) { - LOG.warn("unable to write out 404 res not found: {}",e); - } - } - } else { - try { - resp.sendError(HttpServletResponse.SC_BAD_REQUEST); - }catch(IOException | IllegalStateException e) { - LOG.warn("unable to write out 400 bad request: {}",e); - } - } - - } + /** + * + */ + private static final long serialVersionUID = 1L; + private static final Logger LOG = LoggerFactory.getLogger(YangSchemaHttpServlet.class); + + private static final String schemaCachePath = "cache/schema/"; + + private final YangFileProvider fileProvider; + + public YangSchemaHttpServlet() { + this.fileProvider = new YangFileProvider(schemaCachePath); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + GetYangSchemaRequest request = null; + try { + request = new GetYangSchemaRequest(req); + } catch (Exception e) { + LOG.warn("bad request for yang-schema: {}", e); + } + if (request != null) { + int len; + LOG.debug("request for yang-schema for module {} with version {}", request.getModule(), + request.getVersion()); + if (request.hasVersion()) { + boolean has = false; + try { + has = this.fileProvider.hasFileOrNewerForModule(request.getModule(), request.getVersion()); + } catch (ParseException e1) { + LOG.warn("unable to parse revision: {}", e1); + } + if (has) { + + try { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("text/plain"); + len = this.fileProvider.writeOutput(request.getModule(), request.getVersion(), + resp.getOutputStream()); + resp.setContentLength(len); + + } catch (ParseException e) { + LOG.warn("unable to parse revision: {}", e); + } catch (IOException | IllegalStateException e) { + LOG.warn("unable to write out module {}@{}: {}", request.getModule(), request.getVersion(), e); + } + } else { + try { + resp.sendError(HttpServletResponse.SC_NOT_FOUND); + } catch (IOException | IllegalStateException e) { + LOG.warn("unable to write out 404 res not found: {}", e); + } + } + + } else if (this.fileProvider.hasFileForModule(request.getModule())) { + + try { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("text/plain"); + len = this.fileProvider.writeOutput(request.getModule(), null, resp.getOutputStream()); + resp.setContentLength(len); + } catch (ParseException e) { + LOG.warn(e.getMessage()); + } catch (IOException | IllegalStateException e) { + LOG.warn("unable to write out module {}: {}", request.getModule(), e); + } + + } else { + try { + resp.sendError(HttpServletResponse.SC_NOT_FOUND); + } catch (IOException | IllegalStateException e) { + LOG.warn("unable to write out 404 res not found: {}", e); + } + } + } else { + try { + resp.sendError(HttpServletResponse.SC_BAD_REQUEST); + } catch (IOException | IllegalStateException e) { + LOG.warn("unable to write out 400 bad request: {}", e); + } + } + + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderImpl.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderImpl.java index 2465fc622..286af7aa3 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderImpl.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/DataProviderImpl.java @@ -47,7 +47,7 @@ public class DataProviderImpl implements IEntityDataProvider, AutoCloseable { private DataProviderServiceImpl rpcApiService; private AboutHttpServlet aboutServlet; private HtDatabaseClient dbClient; - + // Blueprint 1 public DataProviderImpl() { super(); @@ -57,18 +57,21 @@ public class DataProviderImpl implements IEntityDataProvider, AutoCloseable { public void setRpcProviderService(RpcProviderService rpcProviderService) { this.rpcProviderService = rpcProviderService; } + public void setMediatorServerServlet(MsServlet servlet) { this.mediatorServerServlet = servlet; } + public void setAboutServlet(AboutHttpServlet aboutServlet) { this.aboutServlet = aboutServlet; } + public void init() throws Exception { LOG.info("Session Initiated start {}", APPLICATION_NAME); // Start RPC Service - this.rpcApiService = new DataProviderServiceImpl(rpcProviderService,this.mediatorServerServlet); + this.rpcApiService = new DataProviderServiceImpl(rpcProviderService, this.mediatorServerServlet); LOG.info("Session Initiated end. Initialization done"); } @@ -117,13 +120,13 @@ public class DataProviderImpl implements IEntityDataProvider, AutoCloseable { @Override public void setReadyStatus(boolean status) { - ReadyHttpServlet.setStatus(status); + ReadyHttpServlet.setStatus(status); } @Override public void setStatus(StatusKey key, String value) { - if(this.aboutServlet!=null) { - if(key==StatusKey.CLUSTER_SIZE) { + if (this.aboutServlet != null) { + if (key == StatusKey.CLUSTER_SIZE) { this.aboutServlet.setClusterSize(value); } } 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 2f3b7ee80..4b8564395 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 @@ -100,28 +100,33 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab private static final Logger LOG = LoggerFactory.getLogger(DataProviderServiceImpl.class); public static final String CONFIGURATIONFILE = "etc/dataprovider.properties"; - private static final long DATABASE_TIMEOUT_MS = 120*1000L; + private static final long DATABASE_TIMEOUT_MS = 120 * 1000L; private final ObjectRegistration<@NonNull DataProviderServiceImpl> rpcReg; private final ElasticSearchDataProvider dataProvider; private final ConfigurationFileRepresentation configuration; private final EsConfig esConfig; - private final MediatorServerDataProvider mediatorServerDataProvider; + private final MediatorServerDataProvider mediatorServerDataProvider; - DataProviderServiceImpl(final RpcProviderService rpcProviderService,MsServlet mediatorServerServlet) throws Exception { + DataProviderServiceImpl(final RpcProviderService rpcProviderService, MsServlet mediatorServerServlet) + throws Exception { this.configuration = new ConfigurationFileRepresentation(CONFIGURATIONFILE); this.esConfig = new EsConfig(configuration); - this.dataProvider = new ElasticSearchDataProvider(esConfig.getHosts(),esConfig.getBasicAuthUsername(),esConfig.getBasicAuthPassword(),esConfig.trustAllCerts()); - this.dataProvider.waitForYellowDatabaseStatus(DATABASE_TIMEOUT_MS,TimeUnit.MILLISECONDS); - this.mediatorServerDataProvider = new MediatorServerDataProvider(esConfig.getHosts(),esConfig.getBasicAuthUsername(),esConfig.getBasicAuthPassword()); + this.dataProvider = new ElasticSearchDataProvider(esConfig.getHosts(), esConfig.getBasicAuthUsername(), + esConfig.getBasicAuthPassword(), esConfig.trustAllCerts()); + this.dataProvider.waitForYellowDatabaseStatus(DATABASE_TIMEOUT_MS, TimeUnit.MILLISECONDS); + this.mediatorServerDataProvider = new MediatorServerDataProvider(esConfig.getHosts(), + esConfig.getBasicAuthUsername(), esConfig.getBasicAuthPassword()); mediatorServerServlet.setDataProvider(this.mediatorServerDataProvider); // Register ourselves as the REST API RPC implementation LOG.info("Register RPC Service " + DataProviderServiceImpl.class.getSimpleName()); this.rpcReg = rpcProviderService.registerRpcImplementation(DataProviderService.class, this); } + private void sendResyncCallbackToApiGateway() { - mediatorServerDataProvider.triggerReloadSync(); + mediatorServerDataProvider.triggerReloadSync(); } + /** * @return dataProvider */ @@ -130,8 +135,9 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab } public HtDatabaseClient getRawClient() { - return this.dataProvider.getRawClient(); + return this.dataProvider.getRawClient(); } + /** * @return data provider for Maintenance() */ @@ -156,22 +162,27 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab } @Override - public ListenableFuture> readFaultcurrentList(ReadFaultcurrentListInput input) { + public ListenableFuture> readFaultcurrentList( + ReadFaultcurrentListInput input) { LOG.debug("RPC Request: getFaultCurrentEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readFaultCurrentList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readFaultCurrentList(input)); return result.buildFuture(); } + @Override public ListenableFuture> readFaultlogList(ReadFaultlogListInput input) { LOG.debug("RPC Request: getFaultCurrentEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readFaultLogList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readFaultLogList(input)); return result.buildFuture(); } @Override public ListenableFuture> readMaintenanceList(ReadMaintenanceListInput input) { LOG.debug("RPC Request: getMaintenanceEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readMaintenanceList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readMaintenanceList(input)); return result.buildFuture(); } @@ -179,7 +190,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> readMediatorServerList( ReadMediatorServerListInput input) { LOG.debug("RPC Request: getMediatorServerEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readMediatorServerList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readMediatorServerList(input)); return result.buildFuture(); } @@ -187,7 +199,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> readNetworkElementConnectionList( ReadNetworkElementConnectionListInput input) { LOG.debug("RPC Request: getNetworkElementConnectionEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readNetworkElementConnectionList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readNetworkElementConnectionList(input)); return result.buildFuture(); } @@ -195,21 +208,25 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab @Override public ListenableFuture> readPmdata15mList(ReadPmdata15mListInput input) { LOG.debug("RPC Request: getNetworkElementConnectionEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readPmdata15mList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readPmdata15mList(input)); return result.buildFuture(); } + @Override public ListenableFuture> readPmdata24hList(ReadPmdata24hListInput input) { LOG.debug("RPC Request: getNetworkElementConnectionEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readPmdata24hList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readPmdata24hList(input)); return result.buildFuture(); } + @Override public ListenableFuture> readStatus(ReadStatusInput input) { LOG.debug("RPC Request: getStatusEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readStatus()); + RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.readStatus()); return result.buildFuture(); } @@ -217,43 +234,53 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab @Override public ListenableFuture> readInventoryList(ReadInventoryListInput input) { LOG.debug("RPC Request: getInventoryEntityList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readInventoryList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readInventoryList(input)); return result.buildFuture(); } @Override - public ListenableFuture> readPmdata15mLtpList(ReadPmdata15mLtpListInput input) { + public ListenableFuture> readPmdata15mLtpList( + ReadPmdata15mLtpListInput input) { LOG.debug("RPC Request: readPmdataLtpList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readPmdata15mLtpList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readPmdata15mLtpList(input)); return result.buildFuture(); } @Override - public ListenableFuture> readPmdata15mDeviceList(ReadPmdata15mDeviceListInput input) { - LOG.debug("RPC Request: readPmdataDeviceList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readPmdata15mDeviceList(input)); - return result.buildFuture(); + public ListenableFuture> readPmdata15mDeviceList( + ReadPmdata15mDeviceListInput input) { + LOG.debug("RPC Request: readPmdataDeviceList with input {}", input); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readPmdata15mDeviceList(input)); + return result.buildFuture(); } @Override - public ListenableFuture> readPmdata24hLtpList(ReadPmdata24hLtpListInput input) { + public ListenableFuture> readPmdata24hLtpList( + ReadPmdata24hLtpListInput input) { LOG.debug("RPC Request: readPmdataLtpList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readPmdata24hLtpList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readPmdata24hLtpList(input)); return result.buildFuture(); } @Override - public ListenableFuture> readPmdata24hDeviceList(ReadPmdata24hDeviceListInput input) { - LOG.debug("RPC Request: readPmdataDeviceList with input {}", input); - RpcResultBuilder result = read(()-> DataProviderServiceImpl.this.dataProvider.readPmdata24hDeviceList(input)); - return result.buildFuture(); + public ListenableFuture> readPmdata24hDeviceList( + ReadPmdata24hDeviceListInput input) { + LOG.debug("RPC Request: readPmdataDeviceList with input {}", input); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readPmdata24hDeviceList(input)); + return result.buildFuture(); } @Override public ListenableFuture> readConnectionlogList( ReadConnectionlogListInput input) { LOG.debug("RPC Request: readConnectionlogList with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.readConnectionlogList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readConnectionlogList(input)); return result.buildFuture(); } @@ -261,7 +288,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> createNetworkElementConnection( CreateNetworkElementConnectionInput input) { LOG.debug("RPC Request: createNetworkElementConnection with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.createNetworkElementConnection(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.createNetworkElementConnection(input)); return result.buildFuture(); } @@ -269,14 +297,16 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> updateNetworkElementConnection( UpdateNetworkElementConnectionInput input) { LOG.debug("RPC Request: updateNetworkElementConnection with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.updateNetworkElementConnection(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.updateNetworkElementConnection(input)); return result.buildFuture(); } @Override public ListenableFuture> deleteNetworkElementConnection( DeleteNetworkElementConnectionInput input) { - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.deleteNetworkElementConnection(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.deleteNetworkElementConnection(input)); return result.buildFuture(); } @@ -284,7 +314,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> deleteMediatorServer( DeleteMediatorServerInput input) { LOG.debug("RPC Request: deleteMediatorServer with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.deleteMediatorServer(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.deleteMediatorServer(input)); this.sendResyncCallbackToApiGateway(); return result.buildFuture(); } @@ -293,7 +324,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> createMediatorServer( CreateMediatorServerInput input) { LOG.debug("RPC Request: createMediatorServer with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.createMediatorServer(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.createMediatorServer(input)); this.sendResyncCallbackToApiGateway(); return result.buildFuture(); } @@ -301,14 +333,16 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab @Override public ListenableFuture> createMaintenance(CreateMaintenanceInput input) { LOG.debug("RPC Request: createMaintenance with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.createMaintenance(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.createMaintenance(input)); return result.buildFuture(); } @Override public ListenableFuture> deleteMaintenance(DeleteMaintenanceInput input) { LOG.debug("RPC Request: deleteMaintenance with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.deleteMaintenance(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.deleteMaintenance(input)); return result.buildFuture(); } @@ -316,7 +350,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab public ListenableFuture> updateMediatorServer( UpdateMediatorServerInput input) { LOG.debug("RPC Request: updateMediatorServer with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.updateMediatorServer(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.updateMediatorServer(input)); this.sendResyncCallbackToApiGateway(); return result.buildFuture(); } @@ -324,14 +359,16 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab @Override public ListenableFuture> updateMaintenance(UpdateMaintenanceInput input) { LOG.debug("RPC Request: updateMaintenance with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.updateMaintenance(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.updateMaintenance(input)); return result.buildFuture(); } @Override public ListenableFuture> readEventlogList(ReadEventlogListInput input) { LOG.debug("RPC Request: readEventlogList with input {}", input); - RpcResultBuilder result = read(() -> DataProviderServiceImpl.this.dataProvider.readEventlogList(input)); + RpcResultBuilder result = + read(() -> DataProviderServiceImpl.this.dataProvider.readEventlogList(input)); return result.buildFuture(); } @@ -352,7 +389,8 @@ public class DataProviderServiceImpl implements DataProviderService, AutoCloseab Builder get() throws IOException; } - private static RpcResultBuilder read(GetEntityInput inputgetter ) { + private static RpcResultBuilder read( + GetEntityInput inputgetter) { RpcResultBuilder result; try { Builder outputBuilder = inputgetter.get(); diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java index fc3701099..001437771 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/impl/EsConfig.java @@ -51,7 +51,7 @@ public class EsConfig implements Configuration, IEsConfig { private static final String PROPERTY_KEY_AUTH_USERNAME = "esAuthUsername"; private static final String PROPERTY_KEY_AUTH_PASSWORD = "esAuthPassword"; - + private static String defaultHostinfo = "${SDNRDBURL}";//printHosts(new HostInfo[] { new HostInfo("sdnrdb", 9200, Protocol.HTTP) }); private static final String DEFAULT_VALUE_CLUSTER = ""; /** check db data in this interval [in seconds] 0 deactivated */ @@ -59,10 +59,10 @@ public class EsConfig implements Configuration, IEsConfig { /** keep data for this time [in seconds] 30 days */ private static final String DEFAULT_ARCHIVE_LIMIT_SEC = String.valueOf(60L * 60L * 24L * 30L); //private static final String DEFAULT_KEY_NODE = "elasticsearchnode"; - private static final String DEFAULT_VALUE_NODE = "elasticsearchnode"; - private static final String DEFAULT_VALUE_DBUSERNAME = "${SDNRDBUSERNAME}"; - private static final String DEFAULT_VALUE_DBPASSWORD = "${SDNRDBPASSWORD}"; - private static final String DEFAULT_VALUE_TRUSTALLCERTS = "${SDNRDBTRUSTALLCERTS}"; + private static final String DEFAULT_VALUE_NODE = "elasticsearchnode"; + private static final String DEFAULT_VALUE_DBUSERNAME = "${SDNRDBUSERNAME}"; + private static final String DEFAULT_VALUE_DBPASSWORD = "${SDNRDBPASSWORD}"; + private static final String DEFAULT_VALUE_TRUSTALLCERTS = "${SDNRDBTRUSTALLCERTS}"; private final ConfigurationFileRepresentation configuration; @@ -93,9 +93,11 @@ public class EsConfig implements Configuration, IEsConfig { String dbHosts = configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_DBHOSTS); return parseHosts(dbHosts); } + public void setHosts(HostInfo[] hosts) { this.configuration.setProperty(SECTION_MARKER_ES, PROPERTY_KEY_DBHOSTS, printHosts(hosts)); } + @Override public String getCluster() { return configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_ARCHIVE_INTERVAL); @@ -106,22 +108,27 @@ public class EsConfig implements Configuration, IEsConfig { } public boolean hasBasicAuthCredentials() { - return this.getBasicAuthUsername()!=null && this.getBasicAuthPassword()!=null && - !this.getBasicAuthUsername().isEmpty() && !this.getBasicAuthPassword().isEmpty() ; + return this.getBasicAuthUsername() != null && this.getBasicAuthPassword() != null + && !this.getBasicAuthUsername().isEmpty() && !this.getBasicAuthPassword().isEmpty(); } + public String getBasicAuthUsername() { - return this.configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_USERNAME); + return this.configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_USERNAME); } + public String getBasicAuthPassword() { - return this.configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_PASSWORD); + return this.configuration.getProperty(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_PASSWORD); } + @Override public long getArchiveCheckIntervalSeconds() { return configuration.getPropertyLong(SECTION_MARKER_ES, PROPERTY_KEY_ARCHIVE_INTERVAL).orElse(0L); } + public boolean trustAllCerts() { - return configuration.getPropertyBoolean(SECTION_MARKER_ES, PROPERTY_KEY_TRUSTALLCERTS); + return configuration.getPropertyBoolean(SECTION_MARKER_ES, PROPERTY_KEY_TRUSTALLCERTS); } + public void setArchiveCheckIntervalSeconds(long seconds) { configuration.setProperty(SECTION_MARKER_ES, PROPERTY_KEY_ARCHIVE_INTERVAL, seconds); } @@ -150,10 +157,13 @@ public class EsConfig implements Configuration, IEsConfig { configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_ARCHIVE_INTERVAL, DEFAULT_ARCHIVE_INTERVAL_SEC); configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_NODE, DEFAULT_VALUE_NODE); - configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_USERNAME, DEFAULT_VALUE_DBUSERNAME); - configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_PASSWORD, DEFAULT_VALUE_DBPASSWORD); - configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_TRUSTALLCERTS, DEFAULT_VALUE_TRUSTALLCERTS); - + configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_USERNAME, + DEFAULT_VALUE_DBUSERNAME); + configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_AUTH_PASSWORD, + DEFAULT_VALUE_DBPASSWORD); + configuration.setPropertyIfNotAvailable(SECTION_MARKER_ES, PROPERTY_KEY_TRUSTALLCERTS, + DEFAULT_VALUE_TRUSTALLCERTS); + } @Override diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsCloner.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsCloner.java index 555b38533..a9a658387 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsCloner.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsCloner.java @@ -46,12 +46,15 @@ public class YangToolsCloner { private YangToolsCloner(int ac) { this.accessor = ac; } + public static YangToolsCloner instance() { return instance(ACCESSOR_METHOD); } + public static YangToolsCloner instance(int ac) { return new YangToolsCloner(ac); } + /** * * @param source source object @@ -88,9 +91,10 @@ public class YangToolsCloner { * @param clazz Class of return object * @return cloned object */ - public T clone(S source, Class clazz) { + public T clone(S source, Class clazz) { return clone(source, clazz, null); } + /** * * @param source source object @@ -98,10 +102,9 @@ public class YangToolsCloner { * @attrList if empty copy all else list of attribute Names to clone * @return cloned object */ - public T clone(S source, Class clazz, - @Nullable List attrList) { + public T clone(S source, Class clazz, @Nullable List attrList) { if (source == null) { - return (T)null; + return (T) null; } Field[] attributeFields; Field sourceField; @@ -121,7 +124,7 @@ public class YangToolsCloner { attributeField.setAccessible(true); try { - if(accessor==ACCESSOR_FIELD) { + if (accessor == ACCESSOR_FIELD) { sourceField = source.getClass().getDeclaredField(attributeField.getName()); sourceField.setAccessible(true); if (attributeField.getType().equals(String.class) && !sourceField.getType().equals(String.class)) { @@ -129,10 +132,9 @@ public class YangToolsCloner { } else { attributeField.set(object, sourceField.get(source)); } - } - else if(accessor==ACCESSOR_METHOD) { + } else if (accessor == ACCESSOR_METHOD) { String getter = getter(attributeField.getName()); - System.out.println("getter="+getter); + System.out.println("getter=" + getter); m = source.getClass().getDeclaredMethod(getter); m.setAccessible(true); if (attributeField.getType().equals(String.class) && !m.getReturnType().equals(String.class)) { @@ -147,7 +149,7 @@ public class YangToolsCloner { String msg = "no such field " + attributeField.getName() + " in class " + source.getClass().getName(); LOG.debug(msg); // throw new IllegalArgumentException(msg); - } catch (IllegalAccessException|SecurityException e) { + } catch (IllegalAccessException | SecurityException e) { LOG.debug("Access problem " + attributeField.getName(), e); } catch (IllegalArgumentException e) { LOG.debug("argument problem " + attributeField.getName(), e); @@ -160,12 +162,14 @@ public class YangToolsCloner { } private static String getter(String name) { - return String.format("%s%s%s","get",name.substring(1, 2).toUpperCase(),name.substring(2)); + return String.format("%s%s%s", "get", name.substring(1, 2).toUpperCase(), name.substring(2)); } - public > B cloneToBuilder(S source, B builder){ - return cloneToBuilder(source, builder,null); + + public > B cloneToBuilder(S source, B builder) { + return cloneToBuilder(source, builder, null); } - public > B cloneToBuilder(S source, B builder, + + public > B cloneToBuilder(S source, B builder, @Nullable List attrList) { Field[] attributeFields; Field sourceField; @@ -183,7 +187,7 @@ public class YangToolsCloner { attributeField.setAccessible(true); try { - if(accessor==ACCESSOR_FIELD) { + if (accessor == ACCESSOR_FIELD) { sourceField = source.getClass().getDeclaredField(attributeField.getName()); sourceField.setAccessible(true); if (attributeField.getType().equals(String.class) && !sourceField.getType().equals(String.class)) { @@ -191,8 +195,7 @@ public class YangToolsCloner { } else { attributeField.set(builder, sourceField.get(source)); } - } - else if(accessor==ACCESSOR_METHOD) { + } else if (accessor == ACCESSOR_METHOD) { m = source.getClass().getDeclaredMethod(getter(attributeField.getName())); m.setAccessible(true); if (attributeField.getType().equals(String.class) && !m.getReturnType().equals(String.class)) { @@ -207,7 +210,7 @@ public class YangToolsCloner { String msg = "no such field " + attributeField.getName() + " in class " + source.getClass().getName(); LOG.debug(msg); // throw new IllegalArgumentException(msg); - } catch (IllegalAccessException|SecurityException e) { + } catch (IllegalAccessException | SecurityException e) { LOG.debug("Access problem " + attributeField.getName(), e); } catch (IllegalArgumentException e) { LOG.debug("argument problem " + attributeField.getName(), e); diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper.java index 768e6683b..0b1e7d520 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper.java @@ -48,183 +48,190 @@ import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; + /** - * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or deserialization of DataObject to/from JSON - * TODO ChoiceIn and Credentials deserialization only for LoginPasswordBuilder + * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or + * deserialization of DataObject to/from JSON TODO ChoiceIn and Credentials deserialization only for + * LoginPasswordBuilder */ public class YangToolsMapper extends ObjectMapper { - private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper.class); - private static final long serialVersionUID = 1L; - private static BundleContext context; - - public YangToolsMapper() { - super(); - configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); - setSerializationInclusion(Include.NON_NULL); - setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector()); - SimpleModule dateAndTimeSerializerModule = new SimpleModule(); - dateAndTimeSerializerModule.addSerializer(DateAndTime.class,new CustomDateAndTimeSerializer()); - registerModule(dateAndTimeSerializerModule ); - Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper.class); - context = bundle != null ? bundle.getBundleContext() : null; - } - - @Override - public String writeValueAsString(Object value) throws JsonProcessingException { - // TODO Auto-generated method stub - return super.writeValueAsString(value); - } - /** - * Get Builder object for yang tools interface. - * @param yang-tools base datatype - * @param clazz class with interface. - * @return builder for interface or null if not existing - */ - @SuppressWarnings("unchecked") - public @Nullable Builder getBuilder(Class clazz) { - String builder = clazz.getName() + "Builder"; - try { - Class clazzBuilder = findClass(builder); - return (Builder) clazzBuilder.newInstance(); - } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { - LOG.debug("Problem ", e); - return null; - } - } - - /** - * Callback for handling mapping failures. - * @return - */ - public int getMappingFailures() { - return 0; - } - - /** - * Provide mapping of string to attribute names, generated by yang-tools. - * "netconf-id" converted to "_netconfId" - * @param name with attribute name, not null or empty - * @return converted string or null if name was empty or null - */ - public @Nullable static String toCamelCaseAttributeName(final String name) { - if (name == null || name.isEmpty()) - return null; - - final StringBuilder ret = new StringBuilder(name.length()); - if (!name.startsWith("_")) - ret.append('_'); - int start = 0; - for (final String word : name.split("-")) { - if (!word.isEmpty()) { - if (start++ == 0) { - ret.append(Character.toLowerCase(word.charAt(0))); - } else { - ret.append(Character.toUpperCase(word.charAt(0))); - } - ret.append(word.substring(1)); - } - } - return ret.toString(); - } - - /** - * Adapted Builder callbacks - */ - private static class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector { - private static final long serialVersionUID = 1L; - - @Override + private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper.class); + private static final long serialVersionUID = 1L; + private static BundleContext context; + + public YangToolsMapper() { + super(); + configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); + setSerializationInclusion(Include.NON_NULL); + setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector()); + SimpleModule dateAndTimeSerializerModule = new SimpleModule(); + dateAndTimeSerializerModule.addSerializer(DateAndTime.class, new CustomDateAndTimeSerializer()); + registerModule(dateAndTimeSerializerModule); + Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper.class); + context = bundle != null ? bundle.getBundleContext() : null; + } + + @Override + public String writeValueAsString(Object value) throws JsonProcessingException { + // TODO Auto-generated method stub + return super.writeValueAsString(value); + } + + /** + * Get Builder object for yang tools interface. + * + * @param yang-tools base datatype + * @param clazz class with interface. + * @return builder for interface or null if not existing + */ + @SuppressWarnings("unchecked") + public @Nullable Builder getBuilder(Class clazz) { + String builder = clazz.getName() + "Builder"; + try { + Class clazzBuilder = findClass(builder); + return (Builder) clazzBuilder.newInstance(); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { + LOG.debug("Problem ", e); + return null; + } + } + + /** + * Callback for handling mapping failures. + * + * @return + */ + public int getMappingFailures() { + return 0; + } + + /** + * Provide mapping of string to attribute names, generated by yang-tools. "netconf-id" converted to "_netconfId" + * + * @param name with attribute name, not null or empty + * @return converted string or null if name was empty or null + */ + public @Nullable static String toCamelCaseAttributeName(final String name) { + if (name == null || name.isEmpty()) + return null; + + final StringBuilder ret = new StringBuilder(name.length()); + if (!name.startsWith("_")) + ret.append('_'); + int start = 0; + for (final String word : name.split("-")) { + if (!word.isEmpty()) { + if (start++ == 0) { + ret.append(Character.toLowerCase(word.charAt(0))); + } else { + ret.append(Character.toUpperCase(word.charAt(0))); + } + ret.append(word.substring(1)); + } + } + return ret.toString(); + } + + /** + * Adapted Builder callbacks + */ + private static class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector { + private static final long serialVersionUID = 1L; + + @Override public Class findPOJOBuilder(AnnotatedClass ac) { - try { - String builder = null; - if (ac.getRawType().equals(Credentials.class)) { - builder = "org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder"; - //System.out.println(DataContainer.class.isAssignableFrom(ac.getRawType())); - //System.out.println(ChoiceIn.class.isAssignableFrom(ac.getRawType())); - - } - else if(ac.getRawType().equals(DateAndTime.class)) { - builder = DateAndTimeBuilder.class.getName(); - } - - else { - if (ac.getRawType().isInterface()) { - builder = ac.getName()+"Builder"; - } - } - if (builder != null) { - //System.out.println("XX1: "+ac.getRawType()); - //System.out.println("XX2: "+builder); - //Class innerBuilder = Class.forName(builder); - Class innerBuilder = findClass(builder); - //System.out.println("Builder found: "+ innerBuilder); - return innerBuilder; - } - } catch( ClassNotFoundException e ) { - // No problem .. try next - } - return super.findPOJOBuilder(ac); + try { + String builder = null; + if (ac.getRawType().equals(Credentials.class)) { + builder = + "org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder"; + //System.out.println(DataContainer.class.isAssignableFrom(ac.getRawType())); + //System.out.println(ChoiceIn.class.isAssignableFrom(ac.getRawType())); + + } else if (ac.getRawType().equals(DateAndTime.class)) { + builder = DateAndTimeBuilder.class.getName(); + } + + else { + if (ac.getRawType().isInterface()) { + builder = ac.getName() + "Builder"; + } + } + if (builder != null) { + //System.out.println("XX1: "+ac.getRawType()); + //System.out.println("XX2: "+builder); + //Class innerBuilder = Class.forName(builder); + Class innerBuilder = findClass(builder); + //System.out.println("Builder found: "+ innerBuilder); + return innerBuilder; + } + } catch (ClassNotFoundException e) { + // No problem .. try next + } + return super.findPOJOBuilder(ac); + } + + @Override + public Value findPOJOBuilderConfig(AnnotatedClass ac) { + if (ac.hasAnnotation(JsonPOJOBuilder.class)) { + return super.findPOJOBuilderConfig(ac); + } + return new JsonPOJOBuilder.Value("build", "set"); + } + } + + private static Class findClass(String name) throws ClassNotFoundException { + // Try to find in other bundles + if (context != null) { + //OSGi environment + for (Bundle b : context.getBundles()) { + try { + return b.loadClass(name); + } catch (ClassNotFoundException e) { + // No problem, this bundle doesn't have the class + } + } + throw new ClassNotFoundException("Can not find Class in OSGi context."); + } else { + return Class.forName(name); + } + // not found in any bundle + } + + public static class DateAndTimeBuilder { + + private final String _value; + + public DateAndTimeBuilder(String v) { + this._value = v; + } + + public DateAndTime build() { + return new DateAndTime(_value); + } + + } + public static class CustomDateAndTimeSerializer extends StdSerializer { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public CustomDateAndTimeSerializer() { + this(null); + } + + protected CustomDateAndTimeSerializer(Class t) { + super(t); + } + + @Override + public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(value.getValue()); } - @Override - public Value findPOJOBuilderConfig(AnnotatedClass ac) { - if (ac.hasAnnotation(JsonPOJOBuilder.class)) { - return super.findPOJOBuilderConfig(ac); - } - return new JsonPOJOBuilder.Value("build", "set"); - } - } - - private static Class findClass(String name) throws ClassNotFoundException { - // Try to find in other bundles - if (context != null) { - //OSGi environment - for (Bundle b : context.getBundles()) { - try { - return b.loadClass(name); - } catch (ClassNotFoundException e) { - // No problem, this bundle doesn't have the class - } - } - throw new ClassNotFoundException("Can not find Class in OSGi context."); - } else { - return Class.forName(name); - } - // not found in any bundle - } - public static class DateAndTimeBuilder{ - - private final String _value; - - public DateAndTimeBuilder(String v) { - this._value= v; - } - - public DateAndTime build() { - return new DateAndTime(_value); - } - - } - public static class CustomDateAndTimeSerializer extends StdSerializer{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public CustomDateAndTimeSerializer() { - this(null); - } - protected CustomDateAndTimeSerializer(Class t) { - super(t); - } - - @Override - public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeString(value.getValue()); - } - - } + } } diff --git a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper2.java b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper2.java index 8f0de4f73..ce67c39dd 100644 --- a/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper2.java +++ b/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper2.java @@ -49,219 +49,231 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer; import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime; + /** - * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or deserialization of DataObject to/from JSON - * TODO ChoiceIn and Credentials deserialization only for LoginPasswordBuilder + * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or + * deserialization of DataObject to/from JSON TODO ChoiceIn and Credentials deserialization only for + * LoginPasswordBuilder */ public class YangToolsMapper2 extends ObjectMapper { - private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper2.class); - private static final long serialVersionUID = 1L; - private static String ENTITY = "Entity"; - private static String BUILDER = "Builder"; - - private @Nullable Class clazz; - private @Nullable Class> builderClazz; - - private BundleContext context; - - public > YangToolsMapper2(Class clazz, Class builderClazz) throws ClassNotFoundException { - super(); - configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); - setSerializationInclusion(Include.NON_NULL); - setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector()); - SimpleModule dateAndTimeSerializerModule = new SimpleModule(); - dateAndTimeSerializerModule.addSerializer(DateAndTime.class, new CustomDateAndTimeSerializer()); - registerModule(dateAndTimeSerializerModule ); - Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper2.class); - - this.clazz = clazz; - this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz)) ; - context = bundle != null ? bundle.getBundleContext() : null; - } - - public YangToolsMapper2() throws ClassNotFoundException { - this(null, null); - } - - - @Override - public String writeValueAsString(Object value) throws JsonProcessingException { - return super.writeValueAsString(value); - } - /** - * Get Builder object for yang tools interface. - * @param yang-tools base datatype - * @param clazz class with interface. - * @return builder for interface or null if not existing - */ - @SuppressWarnings("unchecked") - public @Nullable Builder getBuilder(Class clazz) { - try { - //Class clazzBuilder = getBuilderClass(getBuilderClassName(clazz)); - return (Builder) builderClazz.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - LOG.debug("Problem ", e); - return null; - } - } - - /** - * Callback for handling mapping failures. - * @return - */ - public int getMappingFailures() { - return 0; - } - - /** - * Provide mapping of string to attribute names, generated by yang-tools. - * "netconf-id" converted to "_netconfId" - * @param name with attribute name, not null or empty - * @return converted string or null if name was empty or null - */ - public @Nullable static String toCamelCaseAttributeName(final String name) { - if (name == null || name.isEmpty()) - return null; - - final StringBuilder ret = new StringBuilder(name.length()); - if (!name.startsWith("_")) - ret.append('_'); - int start = 0; - for (final String word : name.split("-")) { - if (!word.isEmpty()) { - if (start++ == 0) { - ret.append(Character.toLowerCase(word.charAt(0))); - } else { - ret.append(Character.toUpperCase(word.charAt(0))); - } - ret.append(word.substring(1)); - } - } - return ret.toString(); - } - - /** Verify if builder is available - * @throws ClassNotFoundException **/ - public Class assertBuilderClass(Class clazz) throws ClassNotFoundException { - return getBuilderClass(getBuilderClassName(clazz)); - } - - // --- Private functions - - /** - * Create name of builder class - * @param - * @param clazz - * @return builders class name - * @throws ClassNotFoundException - */ - private static String getBuilderClassName(Class clazz) { - return clazz.getName() + BUILDER; -// String clazzName = clazz.getName(); -// if (clazzName.endsWith(ENTITY)) { -// return clazzName.replace(ENTITY, BUILDER); -// } else { -// return clazzName + BUILDER; -// } - } - - /** - * Search builder in context - * @param name - * @return - * @throws ClassNotFoundException - */ - @SuppressWarnings("unchecked") - private > Class getBuilderClass(String name) throws ClassNotFoundException { - // Try to find in other bundles - if (context != null) { - //OSGi environment - for (Bundle b : context.getBundles()) { - try { - return (Class) b.loadClass(name); - } catch (ClassNotFoundException e) { - // No problem, this bundle doesn't have the class - } - } - throw new ClassNotFoundException("Can not find Class in OSGi context."); - } else { - return (Class) Class.forName(name); - } - // not found in any bundle - } - - // --- Classes - - /** - * Adapted Builder callbacks - */ - private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector { - private static final long serialVersionUID = 1L; - - @Override - public Class findPOJOBuilder(AnnotatedClass ac) { - - if (ac.getRawType().equals(Credentials.class)) { - return org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder.class; - - } else if (ac.getRawType().equals(DateAndTime.class)) { - return DateAndTimeBuilder.class; - - } else if (ac.getRawType().equals(clazz)) { - return builderClazz; - } - - if (ac.getRawType().isInterface()) { - String builder = getBuilderClassName(ac.getRawType()); - try { - Class innerBuilder = getBuilderClass(builder); - return innerBuilder; - } catch (ClassNotFoundException e) { - // No problem .. try next - } - } - return super.findPOJOBuilder(ac); - } - - @Override - public Value findPOJOBuilderConfig(AnnotatedClass ac) { - if (ac.hasAnnotation(JsonPOJOBuilder.class)) { - return super.findPOJOBuilderConfig(ac); - } - return new JsonPOJOBuilder.Value("build", "set"); - } - } - - public static class DateAndTimeBuilder{ - - private final String _value; - - public DateAndTimeBuilder(String v) { - this._value= v; - } - - public DateAndTime build() { - return new DateAndTime(_value); - } - - } - public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime>{ - - private static final long serialVersionUID = 1L; - - public CustomDateAndTimeSerializer() { - this(null); - } - protected CustomDateAndTimeSerializer(Class t) { - super(t); - } - - @Override - public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeString(value.getValue()); - } - - } + private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper2.class); + private static final long serialVersionUID = 1L; + private static String ENTITY = "Entity"; + private static String BUILDER = "Builder"; + + private @Nullable Class clazz; + private @Nullable Class> builderClazz; + + private BundleContext context; + + public > YangToolsMapper2(Class clazz, Class builderClazz) + throws ClassNotFoundException { + super(); + configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); + setSerializationInclusion(Include.NON_NULL); + setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector()); + SimpleModule dateAndTimeSerializerModule = new SimpleModule(); + dateAndTimeSerializerModule.addSerializer(DateAndTime.class, new CustomDateAndTimeSerializer()); + registerModule(dateAndTimeSerializerModule); + Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper2.class); + + this.clazz = clazz; + this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz)); + context = bundle != null ? bundle.getBundleContext() : null; + } + + public YangToolsMapper2() throws ClassNotFoundException { + this(null, null); + } + + + @Override + public String writeValueAsString(Object value) throws JsonProcessingException { + return super.writeValueAsString(value); + } + + /** + * Get Builder object for yang tools interface. + * + * @param yang-tools base datatype + * @param clazz class with interface. + * @return builder for interface or null if not existing + */ + @SuppressWarnings("unchecked") + public @Nullable Builder getBuilder(Class clazz) { + try { + //Class clazzBuilder = getBuilderClass(getBuilderClassName(clazz)); + return (Builder) builderClazz.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + LOG.debug("Problem ", e); + return null; + } + } + + /** + * Callback for handling mapping failures. + * + * @return + */ + public int getMappingFailures() { + return 0; + } + + /** + * Provide mapping of string to attribute names, generated by yang-tools. "netconf-id" converted to "_netconfId" + * + * @param name with attribute name, not null or empty + * @return converted string or null if name was empty or null + */ + public @Nullable static String toCamelCaseAttributeName(final String name) { + if (name == null || name.isEmpty()) + return null; + + final StringBuilder ret = new StringBuilder(name.length()); + if (!name.startsWith("_")) + ret.append('_'); + int start = 0; + for (final String word : name.split("-")) { + if (!word.isEmpty()) { + if (start++ == 0) { + ret.append(Character.toLowerCase(word.charAt(0))); + } else { + ret.append(Character.toUpperCase(word.charAt(0))); + } + ret.append(word.substring(1)); + } + } + return ret.toString(); + } + + /** + * Verify if builder is available + * + * @throws ClassNotFoundException + **/ + public Class assertBuilderClass(Class clazz) throws ClassNotFoundException { + return getBuilderClass(getBuilderClassName(clazz)); + } + + // --- Private functions + + /** + * Create name of builder class + * + * @param + * @param clazz + * @return builders class name + * @throws ClassNotFoundException + */ + private static String getBuilderClassName(Class clazz) { + return clazz.getName() + BUILDER; + // String clazzName = clazz.getName(); + // if (clazzName.endsWith(ENTITY)) { + // return clazzName.replace(ENTITY, BUILDER); + // } else { + // return clazzName + BUILDER; + // } + } + + /** + * Search builder in context + * + * @param name + * @return + * @throws ClassNotFoundException + */ + @SuppressWarnings("unchecked") + private > Class getBuilderClass(String name) throws ClassNotFoundException { + // Try to find in other bundles + if (context != null) { + //OSGi environment + for (Bundle b : context.getBundles()) { + try { + return (Class) b.loadClass(name); + } catch (ClassNotFoundException e) { + // No problem, this bundle doesn't have the class + } + } + throw new ClassNotFoundException("Can not find Class in OSGi context."); + } else { + return (Class) Class.forName(name); + } + // not found in any bundle + } + + // --- Classes + + /** + * Adapted Builder callbacks + */ + private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector { + private static final long serialVersionUID = 1L; + + @Override + public Class findPOJOBuilder(AnnotatedClass ac) { + + if (ac.getRawType().equals(Credentials.class)) { + return org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder.class; + + } else if (ac.getRawType().equals(DateAndTime.class)) { + return DateAndTimeBuilder.class; + + } else if (ac.getRawType().equals(clazz)) { + return builderClazz; + } + + if (ac.getRawType().isInterface()) { + String builder = getBuilderClassName(ac.getRawType()); + try { + Class innerBuilder = getBuilderClass(builder); + return innerBuilder; + } catch (ClassNotFoundException e) { + // No problem .. try next + } + } + return super.findPOJOBuilder(ac); + } + + @Override + public Value findPOJOBuilderConfig(AnnotatedClass ac) { + if (ac.hasAnnotation(JsonPOJOBuilder.class)) { + return super.findPOJOBuilderConfig(ac); + } + return new JsonPOJOBuilder.Value("build", "set"); + } + } + + public static class DateAndTimeBuilder { + + private final String _value; + + public DateAndTimeBuilder(String v) { + this._value = v; + } + + public DateAndTime build() { + return new DateAndTime(_value); + } + + } + public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime> { + + private static final long serialVersionUID = 1L; + + public CustomDateAndTimeSerializer() { + this(null); + } + + protected CustomDateAndTimeSerializer(Class t) { + super(t); + } + + @Override + public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(value.getValue()); + } + + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestAbout.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestAbout.java index 372435343..f147e8724 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestAbout.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestAbout.java @@ -43,92 +43,96 @@ import javax.servlet.http.HttpServletResponse; public class TestAbout { - private static final String REPO_MDSAL_DIR = "system/org/opendaylight/mdsal/mdsal-binding-api/3.0.9/"; - private static final String REPO_YANGTOOLS_DIR = "system/org/opendaylight/yangtools/odl-yangtools-common/2.1.11"; - @BeforeClass - public static void before() throws IOException { - //create temporary odl folder structure in tmp - Files.createDirectories(new File(REPO_MDSAL_DIR).toPath() ); - Files.createDirectories(new File(REPO_YANGTOOLS_DIR).toPath() ); - } - @AfterClass - public static void after() throws IOException { - //delete created dirs - delete(new File("system/")); - } - private static void delete(File file) throws IOException { - - for (File childFile : file.listFiles()) { - - if (childFile.isDirectory()) { - delete(childFile); - } else { - if (!childFile.delete()) { - throw new IOException(); - } - } - } - - if (!file.delete()) { - throw new IOException(); - } - } - @Test - public void testReadmeRequest() throws IOException, ServletException { - AboutHelperServlet servlet =new AboutHelperServlet(); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURI()).thenReturn("/about"); - StringWriter out = new StringWriter(); - ServletOutputStream printOut = new ServletOutputStream() { - - @Override - public void write(int arg0) throws IOException { - out.write(arg0); - } - }; - when(response.getOutputStream()).thenReturn(printOut); - servlet.doGet(request,response); - verify(response).setStatus(200); - verify(response).setContentType("text/plain"); - System.out.println(out.getBuffer().toString()); - assertTrue(out.getBuffer().length()>0); - } - - @Test - public void testReadmeResourceRequest() throws IOException, ServletException { - AboutHelperServlet servlet =new AboutHelperServlet(); - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - when(request.getRequestURI()).thenReturn("/about/test.bmp"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ServletOutputStream printOut = new ServletOutputStream() { - - @Override - public void write(int arg0) throws IOException { - out.write(arg0); - } - }; - when(response.getOutputStream()).thenReturn(printOut); - servlet.doGet(request,response); - verify(response).setStatus(200); - verify(response).setContentType("image/bmp"); - assertTrue(out.size()>0); - } - - - - private class AboutHelperServlet extends AboutHttpServlet{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); - } - - } + private static final String REPO_MDSAL_DIR = "system/org/opendaylight/mdsal/mdsal-binding-api/3.0.9/"; + private static final String REPO_YANGTOOLS_DIR = "system/org/opendaylight/yangtools/odl-yangtools-common/2.1.11"; + + @BeforeClass + public static void before() throws IOException { + //create temporary odl folder structure in tmp + Files.createDirectories(new File(REPO_MDSAL_DIR).toPath()); + Files.createDirectories(new File(REPO_YANGTOOLS_DIR).toPath()); + } + + @AfterClass + public static void after() throws IOException { + //delete created dirs + delete(new File("system/")); + } + + private static void delete(File file) throws IOException { + + for (File childFile : file.listFiles()) { + + if (childFile.isDirectory()) { + delete(childFile); + } else { + if (!childFile.delete()) { + throw new IOException(); + } + } + } + + if (!file.delete()) { + throw new IOException(); + } + } + + @Test + public void testReadmeRequest() throws IOException, ServletException { + AboutHelperServlet servlet = new AboutHelperServlet(); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + when(request.getRequestURI()).thenReturn("/about"); + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + when(response.getOutputStream()).thenReturn(printOut); + servlet.doGet(request, response); + verify(response).setStatus(200); + verify(response).setContentType("text/plain"); + System.out.println(out.getBuffer().toString()); + assertTrue(out.getBuffer().length() > 0); + } + + @Test + public void testReadmeResourceRequest() throws IOException, ServletException { + AboutHelperServlet servlet = new AboutHelperServlet(); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + when(request.getRequestURI()).thenReturn("/about/test.bmp"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + when(response.getOutputStream()).thenReturn(printOut); + servlet.doGet(request, response); + verify(response).setStatus(200); + verify(response).setContentType("image/bmp"); + assertTrue(out.size() > 0); + } + + + + private class AboutHelperServlet extends AboutHttpServlet { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doGet(req, resp); + } + + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java index ce3ff6694..0294c6e50 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestCRUDforDatabase.java @@ -122,8 +122,8 @@ public class TestCRUDforDatabase { private static ElasticSearchDataProvider dbProvider; private static HtDatabaseClient dbRawProvider; - public static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer - .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; + public static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))}; @BeforeClass public static void init() throws Exception { @@ -149,40 +149,49 @@ public class TestCRUDforDatabase { public void testStatus() throws IOException { //== CLEAR AND CREATE ================================ - clearAndCreatefaultEntity("1", Entity.Faultcurrent.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", SeverityType.Critical); - createFaultEntity("Lorem Ipsum", Entity.Faultcurrent.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", SeverityType.Major); - createFaultEntity("3", Entity.Faultcurrent.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", SeverityType.Minor); - createFaultEntity("4", Entity.Faultcurrent.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", SeverityType.Warning); + clearAndCreatefaultEntity("1", Entity.Faultcurrent.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", + SeverityType.Critical); + createFaultEntity("Lorem Ipsum", Entity.Faultcurrent.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", + SeverityType.Major); + createFaultEntity("3", Entity.Faultcurrent.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", + SeverityType.Minor); + createFaultEntity("4", Entity.Faultcurrent.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", + SeverityType.Warning); //== READ ================================ - List readOutput = dbProvider.readStatus().getData(); + List readOutput = + dbProvider.readStatus().getData(); System.out.println(readOutput); - assertEquals(1,readOutput.get(0).getFaults().getMajors().intValue()); - assertEquals(1,readOutput.get(0).getFaults().getMinors().intValue()); - assertEquals(1,readOutput.get(0).getFaults().getWarnings().intValue()); - assertEquals(1,readOutput.get(0).getFaults().getCriticals().intValue()); + assertEquals(1, readOutput.get(0).getFaults().getMajors().intValue()); + assertEquals(1, readOutput.get(0).getFaults().getMinors().intValue()); + assertEquals(1, readOutput.get(0).getFaults().getWarnings().intValue()); + assertEquals(1, readOutput.get(0).getFaults().getCriticals().intValue()); //== DELETE ================================ - System.out.println("try to delete entries"); - try { - dbRawProvider.doRemove(Entity.Faultcurrent.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting entry: " + e.getMessage()); - } - - //== VERIFY DELETE =========================== - System.out.println("verify entries were deleted"); - readOutput = dbProvider.readStatus().getData(); - assertEquals(0,readOutput.get(0).getFaults().getMajors().intValue()); - assertEquals(0,readOutput.get(0).getFaults().getMinors().intValue()); - assertEquals(0,readOutput.get(0).getFaults().getWarnings().intValue()); - assertEquals(0,readOutput.get(0).getFaults().getCriticals().intValue()); + System.out.println("try to delete entries"); + try { + dbRawProvider.doRemove(Entity.Faultcurrent.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting entry: " + e.getMessage()); + } + + //== VERIFY DELETE =========================== + System.out.println("verify entries were deleted"); + readOutput = dbProvider.readStatus().getData(); + assertEquals(0, readOutput.get(0).getFaults().getMajors().intValue()); + assertEquals(0, readOutput.get(0).getFaults().getMinors().intValue()); + assertEquals(0, readOutput.get(0).getFaults().getWarnings().intValue()); + assertEquals(0, readOutput.get(0).getFaults().getCriticals().intValue()); } - @Test + @Test public void testMediatorServer() { final String NAME = "ms1"; final String URL = "http://11.23.45.55:4599"; @@ -229,8 +238,8 @@ public class TestCRUDforDatabase { System.out.println(data); // ==UPDATE============================ System.out.println("try to update entry"); - UpdateMediatorServerInput updateInput = new UpdateMediatorServerInputBuilder().setId(dbId2).setName(NAME2) - .setUrl(URL2).build(); + UpdateMediatorServerInput updateInput = + new UpdateMediatorServerInputBuilder().setId(dbId2).setName(NAME2).setUrl(URL2).build(); UpdateMediatorServerOutputBuilder updateOutput = null; try { updateOutput = dbProvider.updateMediatorServer(updateInput); @@ -274,7 +283,7 @@ public class TestCRUDforDatabase { assertEquals("delete not verifiied", 0, data.size()); } - @Test + @Test public void testNetworkElementConnectionCurrent() { System.out.println("networkElementConnection test start"); @@ -314,10 +323,10 @@ public class TestCRUDforDatabase { .setFilter(Arrays.asList(new FilterBuilder().setProperty("id").setFiltervalue(dbId).build())) .setPagination(getPagination(20, 1)).build(); - ReadNetworkElementConnectionListOutputBuilder readOperation = dbProvider - .readNetworkElementConnectionList(readInput); - List data = readOperation - .getData(); + ReadNetworkElementConnectionListOutputBuilder readOperation = + dbProvider.readNetworkElementConnectionList(readInput); + List data = + readOperation.getData(); assertNotNull(data); assertEquals(dbId, data.get(0).getId()); @@ -331,7 +340,8 @@ public class TestCRUDforDatabase { final String url2 = "10.5.10.2"; final long port2 = 5960; - UpdateNetworkElementConnectionInput updateInput = new UpdateNetworkElementConnectionInputBuilder().setId(dbId).setHost(url2).setPort(port2).setIsRequired(false).build(); + UpdateNetworkElementConnectionInput updateInput = new UpdateNetworkElementConnectionInputBuilder().setId(dbId) + .setHost(url2).setPort(port2).setIsRequired(false).build(); UpdateNetworkElementConnectionOutputBuilder updateOutput = null; try { updateOutput = dbProvider.updateNetworkElementConnection(updateInput); @@ -373,12 +383,12 @@ public class TestCRUDforDatabase { // ==DELETE============================ System.out.println("Try delete..."); - DeleteNetworkElementConnectionInput deleteInput = new DeleteNetworkElementConnectionInputBuilder().setId(dbId) - .build(); + DeleteNetworkElementConnectionInput deleteInput = + new DeleteNetworkElementConnectionInputBuilder().setId(dbId).build(); try { dbProvider.deleteNetworkElementConnection(deleteInput); } catch (Exception e) { - fail("problem deleting "+e.getMessage()); + fail("problem deleting " + e.getMessage()); } readInput = new ReadNetworkElementConnectionListInputBuilder() @@ -390,7 +400,7 @@ public class TestCRUDforDatabase { } - @Test + @Test public void testMaintenance() { System.out.println("Starting Maintenance tests..."); @@ -408,8 +418,8 @@ public class TestCRUDforDatabase { final boolean isActive = true; CreateMaintenanceOutputBuilder create = null; - CreateMaintenanceInput input = new CreateMaintenanceInputBuilder().setNodeId(nodeId).setActive(isActive) - .build(); + CreateMaintenanceInput input = + new CreateMaintenanceInputBuilder().setNodeId(nodeId).setActive(isActive).build(); String dbId = null; try { create = dbProvider.createMaintenance(input); @@ -429,8 +439,8 @@ public class TestCRUDforDatabase { .setFilter(Arrays.asList(new FilterBuilder().setProperty("id").setFiltervalue(dbId).build())) .setPagination(getPagination(20, 1)).build(); ReadMaintenanceListOutputBuilder readResult = dbProvider.readMaintenanceList(readinput); - List data = readResult - .getData(); + List data = + readResult.getData(); assertNotEquals(0, data.size()); assertNotNull(data); @@ -443,8 +453,8 @@ public class TestCRUDforDatabase { final String nodeId2 = "Name2"; final boolean isActive2 = false; - UpdateMaintenanceInput updateInput = new UpdateMaintenanceInputBuilder().setId(dbId).setNodeId(nodeId2) - .setActive(isActive2).build(); + UpdateMaintenanceInput updateInput = + new UpdateMaintenanceInputBuilder().setId(dbId).setNodeId(nodeId2).setActive(isActive2).build(); UpdateMaintenanceOutputBuilder updateResult = null; try { updateResult = dbProvider.updateMaintenance(updateInput); @@ -483,7 +493,9 @@ public class TestCRUDforDatabase { public void testFaultLog() { System.out.println("Starting fault log tests..."); - String dbId = clearAndCreatefaultEntity("1", Entity.Faultlog.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultlogInput", SeverityType.Critical); + String dbId = clearAndCreatefaultEntity("1", Entity.Faultlog.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultlogInput", + SeverityType.Critical); // ==READ=========================== System.out.println("try to read entry"); @@ -500,8 +512,8 @@ public class TestCRUDforDatabase { fail("Fault log not read: " + e.getMessage()); } - List data = readResult - .getData(); + List data = + readResult.getData(); assertNotNull(data); assertEquals(1, data.size()); @@ -509,17 +521,18 @@ public class TestCRUDforDatabase { assertEquals("Critical", data.get(0).getSeverity().toString()); assertEquals("s1", data.get(0).getNodeId()); - //== UPDATE ================================ + //== UPDATE ================================ System.out.println("try to update entry"); - dbRawProvider.doUpdateOrCreate(Entity.Faultlog.getName(), "1", "{'problem': 'CableLOS', 'severity': 'Major', 'node-id': 'test4657-78'}"); + dbRawProvider.doUpdateOrCreate(Entity.Faultlog.getName(), "1", + "{'problem': 'CableLOS', 'severity': 'Major', 'node-id': 'test4657-78'}"); System.out.println("try to search entry 1"); readinput = new ReadFaultlogListInputBuilder() .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-id").setFiltervalue("test").build())) .setPagination(getPagination(20, 1)).build(); - //== VERIFY UPDATE ================================ + //== VERIFY UPDATE ================================ readResult = dbProvider.readFaultLogList(readinput); data = readResult.getData(); @@ -544,7 +557,7 @@ public class TestCRUDforDatabase { assertEquals("Major", data.get(0).getSeverity().toString()); assertEquals("test4657-78", data.get(0).getNodeId()); - //== DELETE ================================ + //== DELETE ================================ System.out.println("try to clear entry"); try { @@ -553,9 +566,10 @@ public class TestCRUDforDatabase { fail("problem deleting entry: " + e.getMessage()); } - //== VERIFY DELETE =========================== + //== VERIFY DELETE =========================== System.out.println("verify entries deleted"); - readResult = dbProvider.readFaultLogList(new ReadFaultlogListInputBuilder().setPagination(getPagination(20, 1)).build()); + readResult = dbProvider + .readFaultLogList(new ReadFaultlogListInputBuilder().setPagination(getPagination(20, 1)).build()); data = readResult.getData(); assertEquals(0, data.size()); } @@ -563,12 +577,14 @@ public class TestCRUDforDatabase { @Test public void testFaultCurrent() { System.out.println("Starting faultCurrent test..."); - String dbId = null; - dbId = clearAndCreatefaultEntity("1", Entity.Faultcurrent.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", SeverityType.NonAlarmed); - assertEquals("1", dbId); + String dbId = null; + dbId = clearAndCreatefaultEntity("1", Entity.Faultcurrent.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", + SeverityType.NonAlarmed); + assertEquals("1", dbId); // ==READ=========================== - System.out.println("Trying to read..."); + System.out.println("Trying to read..."); ReadFaultcurrentListInput readinput = new ReadFaultcurrentListInputBuilder() @@ -583,8 +599,8 @@ public class TestCRUDforDatabase { fail("Fault log not read: " + e.getMessage()); } - List data = readResult - .getData(); + List data = + readResult.getData(); assertNotNull(data); @@ -601,12 +617,8 @@ public class TestCRUDforDatabase { // ==UPDATE============================ System.out.println("Trying to update..."); - String json = "{\n" + - "\"timestamp\": \"2019-12-28T11:55:58.3Z\",\n" + - "\"node-id\": \"SDN-Controller-0\",\n" + - "\"counter\": 75,\n" + - "\"problem\": \"connectionLossNeOAM\",\n" + - "}"; + String json = "{\n" + "\"timestamp\": \"2019-12-28T11:55:58.3Z\",\n" + "\"node-id\": \"SDN-Controller-0\",\n" + + "\"counter\": 75,\n" + "\"problem\": \"connectionLossNeOAM\",\n" + "}"; String updatedDbId = dbRawProvider.doUpdateOrCreate(Entity.Faultcurrent.getName(), dbId, json); assertEquals(dbId, updatedDbId); @@ -656,23 +668,21 @@ public class TestCRUDforDatabase { // ==CLEAR================================ System.out.println("Clear before test"); - try { - dbRawProvider.doRemove(Entity.Connectionlog.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + try { + dbRawProvider.doRemove(Entity.Connectionlog.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } // ==CREATE================================ System.out.println("Try create entry"); final String initialDbId = "1"; String dbId = null; - String json ="{\n" + - "\"timestamp\": \"2019-11-01T11:28:34.7Z\",\n" + - "\"status\": \"Connecting\",\n" + - "\"node-id\": \"sim2230\",\n" + - "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateConnectionlogInput\"\n" + - "}"; + String json = "{\n" + "\"timestamp\": \"2019-11-01T11:28:34.7Z\",\n" + "\"status\": \"Connecting\",\n" + + "\"node-id\": \"sim2230\",\n" + + "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateConnectionlogInput\"\n" + + "}"; dbId = dbRawProvider.doUpdateOrCreate(Entity.Connectionlog.getName(), initialDbId, json); @@ -693,8 +703,8 @@ public class TestCRUDforDatabase { fail("Connection log not read: " + e.getMessage()); } - List data = readResult - .getData(); + List data = + readResult.getData(); assertNotNull(data); assertEquals(1, data.size()); @@ -728,46 +738,42 @@ public class TestCRUDforDatabase { assertEquals("Connected", data.get(0).getStatus().toString()); assertEquals("sim2230", data.get(0).getNodeId()); - //== DELETE ================================ + //== DELETE ================================ - System.out.println("try to clear entry"); - try { - dbRawProvider.doRemove(Entity.Connectionlog.getName(), dbId); - } catch (Exception e) { - fail("problem deleting entry: " + e.getMessage()); - } + System.out.println("try to clear entry"); + try { + dbRawProvider.doRemove(Entity.Connectionlog.getName(), dbId); + } catch (Exception e) { + fail("problem deleting entry: " + e.getMessage()); + } - //== VERIFY DELETE =========================== - System.out.println("verify entries deleted"); - readResult = dbProvider.readConnectionlogList(new ReadConnectionlogListInputBuilder().setPagination(getPagination(20, 1)).build()); - data = readResult.getData(); - assertEquals(0, data.size()); + //== VERIFY DELETE =========================== + System.out.println("verify entries deleted"); + readResult = dbProvider.readConnectionlogList( + new ReadConnectionlogListInputBuilder().setPagination(getPagination(20, 1)).build()); + data = readResult.getData(); + assertEquals(0, data.size()); } - @Test + @Test public void testEventLog() { System.out.println("Test event log starting..."); // ==CLEAR================================ System.out.println("Clear before test"); - try { - dbRawProvider.doRemove(Entity.Eventlog.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + try { + dbRawProvider.doRemove(Entity.Eventlog.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } // ==CREATE============================ - String dbId = null; - String json = " {\n" + - "\"timestamp\": \"2019-11-08T16:39:23.0Z\",\n" + - "\"new-value\": \"done\",\n" + - "\"object-id\": \"SDN-Controller-0\",\n" + - "\"attribute-name\": \"startup\",\n" + - "\"counter\": 0,\n" + - "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Eventlog\",\n" + - "\"node-id\": \"SDN-Controller-0\"\n" + - "}"; + String dbId = null; + String json = " {\n" + "\"timestamp\": \"2019-11-08T16:39:23.0Z\",\n" + "\"new-value\": \"done\",\n" + + "\"object-id\": \"SDN-Controller-0\",\n" + "\"attribute-name\": \"startup\",\n" + "\"counter\": 0,\n" + + "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Eventlog\",\n" + + "\"node-id\": \"SDN-Controller-0\"\n" + "}"; dbId = dbRawProvider.doUpdateOrCreate(Entity.Eventlog.getName(), "1", json); assertNotNull(dbId); @@ -779,86 +785,83 @@ public class TestCRUDforDatabase { .setPagination(getPagination(20, 1)).build(); ReadEventlogListOutputBuilder readResult = null; try { - readResult = dbProvider.readEventlogList(readinput); + readResult = dbProvider.readEventlogList(readinput); } catch (Exception e) { fail("problem reading eventlog"); } - List data = readResult.getData(); - assertEquals(1,data.size()); + List data = + readResult.getData(); + assertEquals(1, data.size()); //== DELETE ================================ - System.out.println("try to clear entry"); - try { - dbRawProvider.doRemove(Entity.Eventlog.getName(), dbId); - } catch (Exception e) { - fail("problem deleting entry: " + e.getMessage()); - } + System.out.println("try to clear entry"); + try { + dbRawProvider.doRemove(Entity.Eventlog.getName(), dbId); + } catch (Exception e) { + fail("problem deleting entry: " + e.getMessage()); + } //== VERIFY DELETE =========================== - System.out.println("verify entries deleted"); - try { - readResult = dbProvider.readEventlogList(new ReadEventlogListInputBuilder().setPagination(getPagination(20, 1)).build()); + System.out.println("verify entries deleted"); + try { + readResult = dbProvider + .readEventlogList(new ReadEventlogListInputBuilder().setPagination(getPagination(20, 1)).build()); } catch (IOException e) { fail("problem reading eventlog"); } - data = readResult.getData(); - assertEquals(0, data.size()); + data = readResult.getData(); + assertEquals(0, data.size()); } - @Test + @Test public void testInventory() { - System.out.println("Test inventory starting..."); + System.out.println("Test inventory starting..."); - // ==CLEAR================================ - System.out.println("Clear before test"); - try { - dbRawProvider.doRemove(Entity.Inventoryequipment.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + // ==CLEAR================================ + System.out.println("Clear before test"); + try { + dbRawProvider.doRemove(Entity.Inventoryequipment.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } // ==CREATE============================ - String dbId = null; - String json = " {\"tree-level\": 1,\n" + - " \"parent-uuid\": \"SHELF-1.1.0.0\",\n" + - " \"node-id\": \"sim2\",\n" + - " \"uuid\": \"CARD-1.1.8.0\",\n" + - " \"contained-holder\": [ ],\n" + - " \"manufacturer-name\": \"Lorem Ipsum\",\n" + - " \"manufacturer-identifier\": \"ONF-Wireless-Transport\",\n" + - " \"serial\": \"sd-dsa-eqw\",\n" + - " \"date\": \"2008-10-21T00:00:00.0Z\",\n" + - "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Inventory\",\n" + - " \"version\": \"unknown\",\n" + - " \"description\": \"WS/DS3\",\n" + - " \"part-type-id\": \"unknown\",\n" + - " \"model-identifier\": \"model-id-s3s\",\n" + - " \"type-name\": \"p4.module\"}"; - - dbId = dbRawProvider.doUpdateOrCreate(Entity.Inventoryequipment.getName(), "1 1", json); - assertNotNull(dbId); + String dbId = null; + String json = " {\"tree-level\": 1,\n" + " \"parent-uuid\": \"SHELF-1.1.0.0\",\n" + + " \"node-id\": \"sim2\",\n" + " \"uuid\": \"CARD-1.1.8.0\",\n" + + " \"contained-holder\": [ ],\n" + " \"manufacturer-name\": \"Lorem Ipsum\",\n" + + " \"manufacturer-identifier\": \"ONF-Wireless-Transport\",\n" + " \"serial\": \"sd-dsa-eqw\",\n" + + " \"date\": \"2008-10-21T00:00:00.0Z\",\n" + + "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Inventory\",\n" + + " \"version\": \"unknown\",\n" + " \"description\": \"WS/DS3\",\n" + + " \"part-type-id\": \"unknown\",\n" + " \"model-identifier\": \"model-id-s3s\",\n" + + " \"type-name\": \"p4.module\"}"; + + dbId = dbRawProvider.doUpdateOrCreate(Entity.Inventoryequipment.getName(), "1 1", json); + assertNotNull(dbId); // ==READ=========================== - ReadInventoryListInput readinput = new ReadInventoryListInputBuilder() + ReadInventoryListInput readinput = new ReadInventoryListInputBuilder() .setFilter(Arrays.asList(new FilterBuilder().setProperty("id").setFiltervalue(dbId).build())) .setPagination(getPagination(20, 1)).build(); ReadInventoryListOutputBuilder readResult = null; try { - readResult = dbProvider.readInventoryList(readinput); + readResult = dbProvider.readInventoryList(readinput); } catch (Exception e) { - fail("Problem reading inventory list"+e.getMessage()); + fail("Problem reading inventory list" + e.getMessage()); } - List data = readResult.getData(); - assertEquals(1,data.size()); + List data = + readResult.getData(); + assertEquals(1, data.size()); assertEquals("Lorem Ipsum", data.get(0).getManufacturerName()); assertEquals("ONF-Wireless-Transport", data.get(0).getManufacturerIdentifier()); assertEquals("sim2", data.get(0).getNodeId()); @@ -869,15 +872,12 @@ public class TestCRUDforDatabase { System.out.println(data.get(0).getDate()); // ==UPDATE============================ - String updatedDbId=null; + String updatedDbId = null; final String[] holderArray = {"Lorem Ipsum 1", "Lorem Ipsum 2", "Lorem Ipsum &%/$_2"}; - String updatejson = " {" + - " \"node-id\": \"sim5\",\n" + - " \"contained-holder\": [ \"Lorem Ipsum 1\", \"Lorem Ipsum 2\", \"Lorem Ipsum &%/$_2\" ],\n" + - " \"serial\": \"sd-dsa-eww\",\n" + - " \"date\": \"2008-11-21T00:00:00.0Z\",\n" + - " \"part-type-id\": \"not unknown\",\n" + - "}"; + String updatejson = " {" + " \"node-id\": \"sim5\",\n" + + " \"contained-holder\": [ \"Lorem Ipsum 1\", \"Lorem Ipsum 2\", \"Lorem Ipsum &%/$_2\" ],\n" + + " \"serial\": \"sd-dsa-eww\",\n" + " \"date\": \"2008-11-21T00:00:00.0Z\",\n" + + " \"part-type-id\": \"not unknown\",\n" + "}"; updatedDbId = dbRawProvider.doUpdateOrCreate(Entity.Inventoryequipment.getName(), dbId, updatejson); assertEquals(dbId, updatedDbId); @@ -886,12 +886,12 @@ public class TestCRUDforDatabase { readResult = dbProvider.readInventoryList(readinput); } catch (Exception e) { - fail("Problem reading inventory list"+e.getMessage()); + fail("Problem reading inventory list" + e.getMessage()); } data = readResult.getData(); - assertEquals(1,data.size()); + assertEquals(1, data.size()); assertEquals("Lorem Ipsum", data.get(0).getManufacturerName()); assertEquals("ONF-Wireless-Transport", data.get(0).getManufacturerIdentifier()); assertEquals("sim5", data.get(0).getNodeId()); @@ -899,10 +899,10 @@ public class TestCRUDforDatabase { assertEquals("WS/DS3", data.get(0).getDescription()); assertEquals("2008-11-21T00:00:00.0Z", data.get(0).getDate()); assertEquals("sd-dsa-eww", data.get(0).getSerial()); - assertEquals(holderArray.length,data.get(0).getContainedHolder().size()); - assertEquals(holderArray[0],data.get(0).getContainedHolder().get(0)); - assertEquals(holderArray[1],data.get(0).getContainedHolder().get(1)); - assertEquals(holderArray[2],data.get(0).getContainedHolder().get(2)); + assertEquals(holderArray.length, data.get(0).getContainedHolder().size()); + assertEquals(holderArray[0], data.get(0).getContainedHolder().get(0)); + assertEquals(holderArray[1], data.get(0).getContainedHolder().get(1)); + assertEquals(holderArray[2], data.get(0).getContainedHolder().get(2)); // ==DELETE============================ @@ -913,50 +913,50 @@ public class TestCRUDforDatabase { fail("problem deleting: " + e.getMessage()); } - // ==VERIFY DELETE ============================ + // ==VERIFY DELETE ============================ try { - readResult = dbProvider.readInventoryList(readinput); + readResult = dbProvider.readInventoryList(readinput); - } catch (Exception e) { - fail("Problem reading inventory list"+e.getMessage()); - } + } catch (Exception e) { + fail("Problem reading inventory list" + e.getMessage()); + } - data = readResult.getData(); - assertEquals(0,data.size()); + data = readResult.getData(); + assertEquals(0, data.size()); } - @Test - public void test15MinPerformanceReadLtpListWithoutNodeIdSetThrowsException() { + @Test + public void test15MinPerformanceReadLtpListWithoutNodeIdSetThrowsException() { - System.out.println("Reading 15m ltp list without node id filter set throws an exception test start..."); + System.out.println("Reading 15m ltp list without node id filter set throws an exception test start..."); - try { - dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + try { + dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } - System.out.println("create entries..."); + System.out.println("create entries..."); - createPerformanceData("1", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); - createPerformanceData("2", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); + createPerformanceData("1", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); + createPerformanceData("2", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); - createPerformanceData("4", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a3"); - createPerformanceData("5", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); - createPerformanceData("6", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); - createPerformanceData("3", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); + createPerformanceData("4", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a3"); + createPerformanceData("5", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); + createPerformanceData("6", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); + createPerformanceData("3", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); - System.out.println("trying to read, should throw exception..."); + System.out.println("trying to read, should throw exception..."); - ReadPmdata15mLtpListInput readLtp = new ReadPmdata15mLtpListInputBuilder() - .setPagination(getPagination(20, 1)).build(); + ReadPmdata15mLtpListInput readLtp = + new ReadPmdata15mLtpListInputBuilder().setPagination(getPagination(20, 1)).build(); - ReadPmdata15mLtpListOutputBuilder readltpResult = null; + ReadPmdata15mLtpListOutputBuilder readltpResult = null; - try { + try { readltpResult = dbProvider.readPmdata15mLtpList(readLtp); fail("No exception thrown!"); } catch (Exception e) { @@ -965,299 +965,302 @@ public class TestCRUDforDatabase { assertEquals("no nodename in filter found ", e.getMessage()); } - assertNull(readltpResult); + assertNull(readltpResult); - //== DELETE ================================ + //== DELETE ================================ - System.out.println("try to clear entry"); - try { - dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting entry: " + e.getMessage()); - } + System.out.println("try to clear entry"); + try { + dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting entry: " + e.getMessage()); + } - //== VERIFY DELETE =========================== - System.out.println("verify entries deleted"); - List data = dbProvider.readPmdata15mList(new ReadPmdata15mListInputBuilder() - .setPagination(getPagination(20, 1)).build()).getData(); + //== VERIFY DELETE =========================== + System.out.println("verify entries deleted"); + List data = + dbProvider + .readPmdata15mList( + new ReadPmdata15mListInputBuilder().setPagination(getPagination(20, 1)).build()) + .getData(); - assertEquals(0, data.size()); - } + assertEquals(0, data.size()); + } - @Test - public void test15MinPerformanceData() { + @Test + public void test15MinPerformanceData() { // == CLEAR BEFORE TESTS ============================ - System.out.println("Test 15 min performance..."); + System.out.println("Test 15 min performance..."); - try { - dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + try { + dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } // == CREATE ============================ - System.out.println("create entries..."); + System.out.println("create entries..."); - createPerformanceData("1", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); - createPerformanceData("2", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); + createPerformanceData("1", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); + createPerformanceData("2", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); - createPerformanceData("4", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a3"); - createPerformanceData("5", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); - createPerformanceData("6", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); - createPerformanceData("3", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); + createPerformanceData("4", GranularityPeriodType.Period15Min, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a3"); + createPerformanceData("5", GranularityPeriodType.Period15Min, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); + createPerformanceData("6", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); + createPerformanceData("3", GranularityPeriodType.Period15Min, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); // == READ ============================ - System.out.println("read list entries..."); + System.out.println("read list entries..."); - ReadPmdata15mListInput read = new ReadPmdata15mListInputBuilder() - .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) - .setPagination(getPagination(20, 1)).build(); + ReadPmdata15mListInput read = new ReadPmdata15mListInputBuilder() + .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) + .setPagination(getPagination(20, 1)).build(); - ReadPmdata15mListOutputBuilder readResult = null; + ReadPmdata15mListOutputBuilder readResult = null; - try { - readResult = dbProvider.readPmdata15mList(read); + try { + readResult = dbProvider.readPmdata15mList(read); } catch (Exception e) { fail("Problem reading 15m data"); } - List data = readResult - .getData(); + List data = + readResult.getData(); - assertNotNull(data); - assertEquals(2, data.size()); + assertNotNull(data); + assertEquals(2, data.size()); - System.out.println("read ltp entries with node name set..."); + System.out.println("read ltp entries with node name set..."); - ReadPmdata15mLtpListInput readLtp = new ReadPmdata15mLtpListInputBuilder() - .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) - .setPagination(getPagination(20, 1)).build(); + ReadPmdata15mLtpListInput readLtp = new ReadPmdata15mLtpListInputBuilder() + .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) + .setPagination(getPagination(20, 1)).build(); - ReadPmdata15mLtpListOutputBuilder readltpResult = null; + ReadPmdata15mLtpListOutputBuilder readltpResult = null; - try { - readltpResult = dbProvider.readPmdata15mLtpList(readLtp); - } catch (Exception e) { - fail("Problem reading 15m ltp data"); - } + try { + readltpResult = dbProvider.readPmdata15mLtpList(readLtp); + } catch (Exception e) { + fail("Problem reading 15m ltp data"); + } - List dataLtp = readltpResult.getData(); + List dataLtp = readltpResult.getData(); - assertNotNull(dataLtp); - assertEquals(2, dataLtp.size()); - assertTrue(dataLtp.contains("LP-MWPS-TTP-02")); - assertTrue(dataLtp.contains("LP-MWPS-TTP-01")); + assertNotNull(dataLtp); + assertEquals(2, dataLtp.size()); + assertTrue(dataLtp.contains("LP-MWPS-TTP-02")); + assertTrue(dataLtp.contains("LP-MWPS-TTP-01")); - System.out.println("read device entries..."); + System.out.println("read device entries..."); - ReadPmdata15mDeviceListInput readDevices = new ReadPmdata15mDeviceListInputBuilder() - .setPagination(getPagination(20, 1)).build(); + ReadPmdata15mDeviceListInput readDevices = + new ReadPmdata15mDeviceListInputBuilder().setPagination(getPagination(20, 1)).build(); - ReadPmdata15mDeviceListOutputBuilder readDeviceResult = null; + ReadPmdata15mDeviceListOutputBuilder readDeviceResult = null; - try { - readDeviceResult = dbProvider.readPmdata15mDeviceList(readDevices); - } catch (Exception e) { - fail("Problem reading 15m device data"); - } + try { + readDeviceResult = dbProvider.readPmdata15mDeviceList(readDevices); + } catch (Exception e) { + fail("Problem reading 15m device data"); + } - List dataDevice = readDeviceResult.getData(); + List dataDevice = readDeviceResult.getData(); - assertNotNull(dataDevice); - assertEquals(2, dataDevice.size()); - assertTrue(dataDevice.contains("a2")); - assertTrue(dataDevice.contains("a3")); + assertNotNull(dataDevice); + assertEquals(2, dataDevice.size()); + assertTrue(dataDevice.contains("a2")); + assertTrue(dataDevice.contains("a3")); - //== DELETE ================================ + //== DELETE ================================ - System.out.println("try to clear entry"); - try { - dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting entry: " + e.getMessage()); - } + System.out.println("try to clear entry"); + try { + dbRawProvider.doRemove(Entity.Historicalperformance15min.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting entry: " + e.getMessage()); + } - //== VERIFY DELETE =========================== - System.out.println("verify entries deleted"); - readResult = dbProvider.readPmdata15mList(new ReadPmdata15mListInputBuilder() - .setPagination(getPagination(20, 1)).build()); - data = readResult.getData(); - assertEquals(0, data.size()); + //== VERIFY DELETE =========================== + System.out.println("verify entries deleted"); + readResult = dbProvider + .readPmdata15mList(new ReadPmdata15mListInputBuilder().setPagination(getPagination(20, 1)).build()); + data = readResult.getData(); + assertEquals(0, data.size()); - } + } - @Test - public void test24hPerformanceData() { - System.out.println("Test 24h performance..."); + @Test + public void test24hPerformanceData() { + System.out.println("Test 24h performance..."); - try { - dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + try { + dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } - System.out.println("create entries..."); - GranularityPeriodType timeInterval = GranularityPeriodType.Period24Hours; - createPerformanceData("1", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); - createPerformanceData("2", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); - String aDbId = createPerformanceData("4", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-06", "a2"); + System.out.println("create entries..."); + GranularityPeriodType timeInterval = GranularityPeriodType.Period24Hours; + createPerformanceData("1", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); + createPerformanceData("2", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); + String aDbId = createPerformanceData("4", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-06", "a2"); - createPerformanceData("5", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); - createPerformanceData("6", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); - createPerformanceData("3", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); + createPerformanceData("5", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); + createPerformanceData("6", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); + createPerformanceData("3", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); - System.out.println("read all list entries..."); + System.out.println("read all list entries..."); - ReadPmdata24hListInput read = new ReadPmdata24hListInputBuilder() - .setPagination(getPagination(20, 1)).build(); + ReadPmdata24hListInput read = new ReadPmdata24hListInputBuilder().setPagination(getPagination(20, 1)).build(); - ReadPmdata24hListOutputBuilder readResult = null; + ReadPmdata24hListOutputBuilder readResult = null; - try { - readResult = dbProvider.readPmdata24hList(read); + try { + readResult = dbProvider.readPmdata24hList(read); } catch (Exception e) { fail("Problem reading 24h data"); } - List data = readResult - .getData(); + List data = + readResult.getData(); - assertNotNull(data); - assertEquals(6, data.size()); + assertNotNull(data); + assertEquals(6, data.size()); - System.out.println("filter list entries..."); + System.out.println("filter list entries..."); - read = new ReadPmdata24hListInputBuilder() - .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) - .setPagination(getPagination(20, 1)).build(); + read = new ReadPmdata24hListInputBuilder() + .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) + .setPagination(getPagination(20, 1)).build(); - readResult = null; + readResult = null; - try { - readResult = dbProvider.readPmdata24hList(read); + try { + readResult = dbProvider.readPmdata24hList(read); } catch (Exception e) { fail("Problem reading 24h data"); } - data = readResult.getData(); + data = readResult.getData(); - assertNotNull(data); - assertEquals(3, data.size()); + assertNotNull(data); + assertEquals(3, data.size()); - System.out.println("read ltp entries with node name set..."); + System.out.println("read ltp entries with node name set..."); - ReadPmdata24hLtpListInput readLtp = new ReadPmdata24hLtpListInputBuilder() - .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) - .setPagination(getPagination(20, 1)).build(); + ReadPmdata24hLtpListInput readLtp = new ReadPmdata24hLtpListInputBuilder() + .setFilter(Arrays.asList(new FilterBuilder().setProperty("node-name").setFiltervalue("a2").build())) + .setPagination(getPagination(20, 1)).build(); - ReadPmdata24hLtpListOutputBuilder readltpResult = null; + ReadPmdata24hLtpListOutputBuilder readltpResult = null; - try { - readltpResult = dbProvider.readPmdata24hLtpList(readLtp); - } catch (Exception e) { - fail("Problem reading 24h ltp data"); - } + try { + readltpResult = dbProvider.readPmdata24hLtpList(readLtp); + } catch (Exception e) { + fail("Problem reading 24h ltp data"); + } - List dataLtp = readltpResult.getData(); + List dataLtp = readltpResult.getData(); - assertNotNull(dataLtp); - assertEquals(3, dataLtp.size()); - assertTrue(dataLtp.contains("LP-MWPS-TTP-02")); - assertTrue(dataLtp.contains("LP-MWPS-TTP-01")); - assertTrue(dataLtp.contains("LP-MWPS-TTP-06")); + assertNotNull(dataLtp); + assertEquals(3, dataLtp.size()); + assertTrue(dataLtp.contains("LP-MWPS-TTP-02")); + assertTrue(dataLtp.contains("LP-MWPS-TTP-01")); + assertTrue(dataLtp.contains("LP-MWPS-TTP-06")); - System.out.println("read device entries..."); + System.out.println("read device entries..."); - ReadPmdata24hDeviceListInput readDevices = new ReadPmdata24hDeviceListInputBuilder() - .setPagination(getPagination(20, 1)).build(); + ReadPmdata24hDeviceListInput readDevices = + new ReadPmdata24hDeviceListInputBuilder().setPagination(getPagination(20, 1)).build(); - ReadPmdata24hDeviceListOutputBuilder readDeviceResult = null; + ReadPmdata24hDeviceListOutputBuilder readDeviceResult = null; - try { - readDeviceResult = dbProvider.readPmdata24hDeviceList(readDevices); - } catch (Exception e) { - fail("Problem reading 24h device data"); - } + try { + readDeviceResult = dbProvider.readPmdata24hDeviceList(readDevices); + } catch (Exception e) { + fail("Problem reading 24h device data"); + } - List dataDevice = readDeviceResult.getData(); + List dataDevice = readDeviceResult.getData(); - assertNotNull(dataDevice); - assertEquals(2, dataDevice.size()); - assertTrue(dataDevice.contains("a2")); - assertTrue(dataDevice.contains("a3")); + assertNotNull(dataDevice); + assertEquals(2, dataDevice.size()); + assertTrue(dataDevice.contains("a2")); + assertTrue(dataDevice.contains("a3")); - // == UPDATE ============================== + // == UPDATE ============================== - boolean success = dbRawProvider.doUpdate(Entity.Historicalperformance24h.getName(), "{'uuid-interface':'LTP-TEST-MWP-097'}", QueryBuilders.termQuery("_id", aDbId)); - assertTrue("update dbentry not succeeded",success); - try { - readltpResult = dbProvider.readPmdata24hLtpList(readLtp); + boolean success = dbRawProvider.doUpdate(Entity.Historicalperformance24h.getName(), + "{'uuid-interface':'LTP-TEST-MWP-097'}", QueryBuilders.termQuery("_id", aDbId)); + assertTrue("update dbentry not succeeded", success); + try { + readltpResult = dbProvider.readPmdata24hLtpList(readLtp); } catch (Exception e) { fail("Problem reading 24h ltp data"); } - // == VERIFY UPDATE ============================== + // == VERIFY UPDATE ============================== - dataLtp = readltpResult.getData(); + dataLtp = readltpResult.getData(); - assertNotNull(dataLtp); - assertEquals(3, dataLtp.size()); - assertTrue(dataLtp.contains("LP-MWPS-TTP-02")); - assertTrue(dataLtp.contains("LP-MWPS-TTP-01")); - assertTrue(dataLtp.contains("LTP-TEST-MWP-097")); + assertNotNull(dataLtp); + assertEquals(3, dataLtp.size()); + assertTrue(dataLtp.contains("LP-MWPS-TTP-02")); + assertTrue(dataLtp.contains("LP-MWPS-TTP-01")); + assertTrue(dataLtp.contains("LTP-TEST-MWP-097")); - //== DELETE =========================== + //== DELETE =========================== - System.out.println("try to clear entries"); - try { - dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting entry: " + e.getMessage()); - } + System.out.println("try to clear entries"); + try { + dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting entry: " + e.getMessage()); + } - //== VERIFY DELETE =========================== - System.out.println("verify entries deleted"); - readResult = dbProvider.readPmdata24hList(new ReadPmdata24hListInputBuilder() - .setPagination(getPagination(20, 1)).build()); - data = readResult.getData(); - assertEquals(0, data.size()); - } + //== VERIFY DELETE =========================== + System.out.println("verify entries deleted"); + readResult = dbProvider + .readPmdata24hList(new ReadPmdata24hListInputBuilder().setPagination(getPagination(20, 1)).build()); + data = readResult.getData(); + assertEquals(0, data.size()); + } - @Test - public void test24hPerformanceDataReadLtpListWithoutNodeIdSetThrowsException() { - System.out.println("Test 24 hour tp list without node id filter set throws an exception test start...\"..."); + @Test + public void test24hPerformanceDataReadLtpListWithoutNodeIdSetThrowsException() { + System.out.println("Test 24 hour tp list without node id filter set throws an exception test start...\"..."); - try { - dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } + try { + dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } - System.out.println("create entries..."); + System.out.println("create entries..."); - GranularityPeriodType timeInterval = GranularityPeriodType.Period24Hours; - createPerformanceData("1", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); - createPerformanceData("2", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); + GranularityPeriodType timeInterval = GranularityPeriodType.Period24Hours; + createPerformanceData("1", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a2"); + createPerformanceData("2", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a2"); - createPerformanceData("4", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a3"); - createPerformanceData("5", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); - createPerformanceData("6", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); - createPerformanceData("3", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); + createPerformanceData("4", timeInterval, "PM_RADIO_15M_6", "LP-MWPS-TTP-02", "a3"); + createPerformanceData("5", timeInterval, "PM_RADIO_15M_4", "LP-MWPS-TTP-01", "a3"); + createPerformanceData("6", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-03", "a3"); + createPerformanceData("3", timeInterval, "PM_RADIO_15M_7", "LP-MWPS-TTP-05", "a3"); - System.out.println("trying to read, should throw exception..."); + System.out.println("trying to read, should throw exception..."); - ReadPmdata24hLtpListInput readLtp = new ReadPmdata24hLtpListInputBuilder() - .setPagination(getPagination(20, 1)).build(); + ReadPmdata24hLtpListInput readLtp = + new ReadPmdata24hLtpListInputBuilder().setPagination(getPagination(20, 1)).build(); - ReadPmdata24hLtpListOutputBuilder readltpResult = null; + ReadPmdata24hLtpListOutputBuilder readltpResult = null; - try { + try { readltpResult = dbProvider.readPmdata24hLtpList(readLtp); fail("No exception thrown!"); } catch (Exception e) { @@ -1266,14 +1269,14 @@ public class TestCRUDforDatabase { assertEquals("no nodename in filter found ", e.getMessage()); } - assertNull(readltpResult); + assertNull(readltpResult); - try { - dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } - } + try { + dbRawProvider.doRemove(Entity.Historicalperformance24h.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } + } @Test public void testUrlEncoding() { @@ -1294,7 +1297,9 @@ public class TestCRUDforDatabase { public void testDoUpdateOrCreateWithNullId() { System.out.println("Test DoUpdateOrCreate doesn't create new database entry if null is passed"); - String dbId = clearAndCreatefaultEntity(null, Entity.Faultlog.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultlogInput", SeverityType.Critical); + String dbId = clearAndCreatefaultEntity(null, Entity.Faultlog.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultlogInput", + SeverityType.Critical); assertNull(dbId); } @@ -1302,44 +1307,47 @@ public class TestCRUDforDatabase { public void readTestFaultCurrentViaRawDbProvider() { System.out.println("Starting faultCurrent test..."); String dbId = null; - dbId = clearAndCreatefaultEntity("1", Entity.Faultcurrent.getName(), "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", SeverityType.Critical); + dbId = clearAndCreatefaultEntity("1", Entity.Faultcurrent.getName(), + "org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput", + SeverityType.Critical); assertEquals("1", dbId); - // ==READ=========================== + // ==READ=========================== System.out.println("Trying to read..."); - String readResult = null; - try { - readResult = dbRawProvider.doReadJsonData(Entity.Faultcurrent.getName(), dbId); + String readResult = null; + try { + readResult = dbRawProvider.doReadJsonData(Entity.Faultcurrent.getName(), dbId); - } catch (Exception e) { - fail("Fault log not read: " + e.getMessage()); - } + } catch (Exception e) { + fail("Fault log not read: " + e.getMessage()); + } - String expectedDbResult ="{\"severity\":\"Critical\",\"node-id\":\"s1\",\"problem\":\"signalIsLost\",\"counter\":4340,\"object-id\":\"LP-MWPS-RADIO\",\"implemented-interface\":\"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput\",\"type\":\"ProblemNotificationXml\",\"timestamp\":\"2019-10-28T11:55:58.3Z\"}"; + String expectedDbResult = + "{\"severity\":\"Critical\",\"node-id\":\"s1\",\"problem\":\"signalIsLost\",\"counter\":4340,\"object-id\":\"LP-MWPS-RADIO\",\"implemented-interface\":\"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.CreateFaultcurrentInput\",\"type\":\"ProblemNotificationXml\",\"timestamp\":\"2019-10-28T11:55:58.3Z\"}"; - System.out.println(readResult); - assertNotNull(readResult); - assertEquals(expectedDbResult, readResult); + System.out.println(readResult); + assertNotNull(readResult); + assertEquals(expectedDbResult, readResult); - SearchResult searchResult = dbRawProvider.doReadAllJsonData(Entity.Faultcurrent.getName()); - assertNotNull(searchResult); + SearchResult searchResult = dbRawProvider.doReadAllJsonData(Entity.Faultcurrent.getName()); + assertNotNull(searchResult); - List hits = searchResult.getHits(); + List hits = searchResult.getHits(); - assertNotNull(hits); - assertEquals(1, searchResult.getTotal()); - assertEquals(expectedDbResult, hits.get(0).getSourceAsString()); + assertNotNull(hits); + assertEquals(1, searchResult.getTotal()); + assertEquals(expectedDbResult, hits.get(0).getSourceAsString()); - //== DELETE ============================== - try { - dbRawProvider.doRemove(Entity.Faultcurrent.getName(), QueryBuilders.matchAllQuery()); - } catch (Exception e) { - fail("problem deleting: " + e.getMessage()); - } - //== VERIFY DELETE ======================== - searchResult = dbRawProvider.doReadAllJsonData(Entity.Faultcurrent.getName()); + //== DELETE ============================== + try { + dbRawProvider.doRemove(Entity.Faultcurrent.getName(), QueryBuilders.matchAllQuery()); + } catch (Exception e) { + fail("problem deleting: " + e.getMessage()); + } + //== VERIFY DELETE ======================== + searchResult = dbRawProvider.doReadAllJsonData(Entity.Faultcurrent.getName()); hits = searchResult.getHits(); assertNotNull(hits); assertEquals(0, searchResult.getTotal()); @@ -1348,25 +1356,20 @@ public class TestCRUDforDatabase { @Test public void testOutputCamelCase() { - try { - String jsonString="{\n" + - "\"timestamp\": \"2020-02-20T09:31:22.3Z\",\n" + - "\"object-id\": \"LP-MWPS-RADIO\",\n" + - "\"severity\": \"Critical\",\n" + - "\"counter\": 10,\n" + - "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Faultlog\",\n" + - "\"source-type\": \"Netconf\",\n" + - "\"node-id\": \"sim4\",\n" + - "\"problem\": \"signalIsLost\"\n" + - "}"; - YangToolsMapper yangtoolsMapper = new YangToolsMapper(); - FaultlogEntity log = yangtoolsMapper.readValue( jsonString, Faultlog.class ); - System.out.println(log ); - System.out.println(yangtoolsMapper.writeValueAsString(log)); - } catch (IOException e) { - fail(e.getMessage()); - } - + try { + String jsonString = "{\n" + "\"timestamp\": \"2020-02-20T09:31:22.3Z\",\n" + + "\"object-id\": \"LP-MWPS-RADIO\",\n" + "\"severity\": \"Critical\",\n" + "\"counter\": 10,\n" + + "\"implemented-interface\": \"org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.Faultlog\",\n" + + "\"source-type\": \"Netconf\",\n" + "\"node-id\": \"sim4\",\n" + "\"problem\": \"signalIsLost\"\n" + + "}"; + YangToolsMapper yangtoolsMapper = new YangToolsMapper(); + FaultlogEntity log = yangtoolsMapper.readValue(jsonString, Faultlog.class); + System.out.println(log); + System.out.println(yangtoolsMapper.writeValueAsString(log)); + } catch (IOException e) { + fail(e.getMessage()); + } + } private Pagination getPagination(long pageSize, int page) { @@ -1374,7 +1377,8 @@ public class TestCRUDforDatabase { } - private String clearAndCreatefaultEntity(String initialDbId, String entityType, String implementedInterface, SeverityType severity) { + private String clearAndCreatefaultEntity(String initialDbId, String entityType, String implementedInterface, + SeverityType severity) { // ==CLEAR BEFORE TEST============================ System.out.println("try to clear entry"); try { @@ -1387,23 +1391,19 @@ public class TestCRUDforDatabase { return createFaultEntity(initialDbId, entityType, implementedInterface, severity); } - private String createFaultEntity(String initialDbId, String entityType, String implementedInterface, SeverityType severity) { - // ==CREATE============================ + private String createFaultEntity(String initialDbId, String entityType, String implementedInterface, + SeverityType severity) { + // ==CREATE============================ System.out.println("try to create entry"); String dbId = null; try { - dbId = dbRawProvider.doUpdateOrCreate(entityType, initialDbId,"{\n" + - "\"timestamp\": \"2019-10-28T11:55:58.3Z\",\n" + - "\"object-id\": \"LP-MWPS-RADIO\",\n" + - "\"severity\": \""+severity.toString()+"\",\n" + - "\"node-id\": \"s1\",\n" + - "\"implemented-interface\": \""+implementedInterface+"\",\n" + - "\"counter\": 4340,\n" + - "\"problem\": \"signalIsLost\",\n" + - "\"type\": \"ProblemNotificationXml\"\n" + - "}"); + dbId = dbRawProvider.doUpdateOrCreate(entityType, initialDbId, + "{\n" + "\"timestamp\": \"2019-10-28T11:55:58.3Z\",\n" + "\"object-id\": \"LP-MWPS-RADIO\",\n" + + "\"severity\": \"" + severity.toString() + "\",\n" + "\"node-id\": \"s1\",\n" + + "\"implemented-interface\": \"" + implementedInterface + "\",\n" + "\"counter\": 4340,\n" + + "\"problem\": \"signalIsLost\",\n" + "\"type\": \"ProblemNotificationXml\"\n" + "}"); @@ -1414,65 +1414,31 @@ public class TestCRUDforDatabase { return dbId; } - private String createPerformanceData(String initialDbId, GranularityPeriodType timeInterval, String scannerId, String uuidInterface, String nodename) { - - String json = "{\n" + - "\"node-name\": \""+nodename+"\",\n" + - "\"uuid-interface\": \""+uuidInterface+"\",\n" + - "\"layer-protocol-name\": \"MWPS\",\n" + - "\"radio-signal-id\": \"Test8\",\n" + - "\"time-stamp\": \"2017-03-01T06:15:00.0Z\",\n" + - "\"granularity-period\": \""+timeInterval.toString()+"\",\n" + - "\"scanner-id\": \""+scannerId+"\",\n" + - "\"performance-data\": {\n" + - "\"cses\": 0,\n" + - "\"ses\": 0,\n" + - "\"es\": 0,\n" + - "\"tx-level-max\": 3,\n" + - "\"tx-level-avg\": 3,\n" + - "\"rx-level-min\": -44,\n" + - "\"rx-level-max\": -45,\n" + - "\"rx-level-avg\": -44,\n" + - "\"time2-states\": 0,\n" + - "\"time4-states-s\": 0,\n" + - "\"time4-states\": 0,\n" + - "\"time8-states\": -1,\n" + - "\"time16-states-s\": -1,\n" + - "\"time16-states\": 0,\n" + - "\"time32-states\": -1,\n" + - "\"time64-states\": 900,\n" + - "\"time128-states\": -1,\n" + - "\"time256-states\": -1,\n" + - "\"time512-states\": -1,\n" + - "\"time512-states-l\": -1,\n" + - "\"unavailability\": 0,\n" + - "\"tx-level-min\": 3,\n" + - "\"time1024-states\": -1,\n" + - "\"time1024-states-l\": -1,\n" + - "\"time2048-states\": -1,\n" + - "\"time2048-states-l\": -1,\n" + - "\"time4096-states\": -1,\n" + - "\"time4096-states-l\": -1,\n" + - "\"time8192-states\": -1,\n" + - "\"time8192-states-l\": -1,\n" + - "\"snir-min\": -99,\n" + - "\"snir-max\": -99,\n" + - "\"snir-avg\": -99,\n" + - "\"xpd-min\": -99,\n" + - "\"xpd-max\": -99,\n" + - "\"xpd-avg\": -99,\n" + - "\"rf-temp-min\": -99,\n" + - "\"rf-temp-max\": -99,\n" + - "\"rf-temp-avg\": -99,\n" + - "\"defect-blocks-sum\": -1,\n" + - "\"time-period\": 900\n" + - "},\n" + - "\"suspect-interval-flag\": false\n" + - "}"; - - if(timeInterval.equals(GranularityPeriodType.Period15Min)) { + private String createPerformanceData(String initialDbId, GranularityPeriodType timeInterval, String scannerId, + String uuidInterface, String nodename) { + + String json = "{\n" + "\"node-name\": \"" + nodename + "\",\n" + "\"uuid-interface\": \"" + uuidInterface + + "\",\n" + "\"layer-protocol-name\": \"MWPS\",\n" + "\"radio-signal-id\": \"Test8\",\n" + + "\"time-stamp\": \"2017-03-01T06:15:00.0Z\",\n" + "\"granularity-period\": \"" + + timeInterval.toString() + "\",\n" + "\"scanner-id\": \"" + scannerId + "\",\n" + + "\"performance-data\": {\n" + "\"cses\": 0,\n" + "\"ses\": 0,\n" + "\"es\": 0,\n" + + "\"tx-level-max\": 3,\n" + "\"tx-level-avg\": 3,\n" + "\"rx-level-min\": -44,\n" + + "\"rx-level-max\": -45,\n" + "\"rx-level-avg\": -44,\n" + "\"time2-states\": 0,\n" + + "\"time4-states-s\": 0,\n" + "\"time4-states\": 0,\n" + "\"time8-states\": -1,\n" + + "\"time16-states-s\": -1,\n" + "\"time16-states\": 0,\n" + "\"time32-states\": -1,\n" + + "\"time64-states\": 900,\n" + "\"time128-states\": -1,\n" + "\"time256-states\": -1,\n" + + "\"time512-states\": -1,\n" + "\"time512-states-l\": -1,\n" + "\"unavailability\": 0,\n" + + "\"tx-level-min\": 3,\n" + "\"time1024-states\": -1,\n" + "\"time1024-states-l\": -1,\n" + + "\"time2048-states\": -1,\n" + "\"time2048-states-l\": -1,\n" + "\"time4096-states\": -1,\n" + + "\"time4096-states-l\": -1,\n" + "\"time8192-states\": -1,\n" + "\"time8192-states-l\": -1,\n" + + "\"snir-min\": -99,\n" + "\"snir-max\": -99,\n" + "\"snir-avg\": -99,\n" + "\"xpd-min\": -99,\n" + + "\"xpd-max\": -99,\n" + "\"xpd-avg\": -99,\n" + "\"rf-temp-min\": -99,\n" + "\"rf-temp-max\": -99,\n" + + "\"rf-temp-avg\": -99,\n" + "\"defect-blocks-sum\": -1,\n" + "\"time-period\": 900\n" + "},\n" + + "\"suspect-interval-flag\": false\n" + "}"; + + if (timeInterval.equals(GranularityPeriodType.Period15Min)) { return dbRawProvider.doUpdateOrCreate(Entity.Historicalperformance15min.getName(), initialDbId, json); - }else { + } else { return dbRawProvider.doUpdateOrCreate(Entity.Historicalperformance24h.getName(), initialDbId, json); } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfig.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfig.java index 1b5e1afa7..c0234bfce 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfig.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfig.java @@ -44,15 +44,16 @@ public class TestConfig { @After @Before public void afterAndBefore() { - File f=new File(TESTFILENAME); - if(f.exists()) { + File f = new File(TESTFILENAME); + if (f.exists()) { LOG.info("Remove {}", f.getAbsolutePath()); f.delete(); } } + @Test public void test() { - ConfigurationFileRepresentation configuration=new ConfigurationFileRepresentation(TESTFILENAME); + ConfigurationFileRepresentation configuration = new ConfigurationFileRepresentation(TESTFILENAME); setSDNRDBURLEnv(); EsConfig esConfig = new EsConfig(configuration); LOG.info("Defaultconfiguration: {}", esConfig.toString()); @@ -61,19 +62,21 @@ public class TestConfig { assertEquals("sdnrdb", esConfig.getHosts()[0].hostname); } + public static void setSDNRDBURLEnv() { - setEnv("SDNRDBURL","http://sdnrdb:9200"); + setEnv("SDNRDBURL", "http://sdnrdb:9200"); + } + + public static void setEnv(String key, String value) { + try { + Map env = System.getenv(); + Class cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map writableEnv = (Map) field.get(env); + writableEnv.put(key, value); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } } - public static void setEnv(String key, String value) { - try { - Map env = System.getenv(); - Class cl = env.getClass(); - Field field = cl.getDeclaredField("m"); - field.setAccessible(true); - Map writableEnv = (Map) field.get(env); - writableEnv.put(key, value); - } catch (Exception e) { - throw new IllegalStateException("Failed to set environment variable", e); - } - } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfiguration.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfiguration.java index 30b1003c2..d06486550 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfiguration.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestConfiguration.java @@ -39,14 +39,14 @@ public class TestConfiguration { System.out.println("Configuration file " + CONFIGURATIONTESTFILE); File testConfigurationFile = ResourceFileLoader.getFile(this, CONFIGURATIONTESTFILE); - System.out.println("Located at: "+testConfigurationFile.getAbsolutePath()); + System.out.println("Located at: " + testConfigurationFile.getAbsolutePath()); ConfigurationFileRepresentation configuration = new ConfigurationFileRepresentation(testConfigurationFile); System.out.println("Configuration: " + configuration.getSection(EsConfig.SECTION_MARKER_ES)); EsConfig esConfig1 = new EsConfig(configuration); - System.out.println("ES config getArchiveLifetimeSeconds: "+esConfig1.getArchiveLifetimeSeconds()); + System.out.println("ES config getArchiveLifetimeSeconds: " + esConfig1.getArchiveLifetimeSeconds()); // fail("Not yet implemented"); diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataMappings.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataMappings.java index f68a6e8f3..a4b284e4f 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataMappings.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataMappings.java @@ -39,172 +39,121 @@ import org.opendaylight.yangtools.yang.binding.DataObject; public class TestDataMappings { - private static final HostInfo[] HOSTINFOS = new HostInfo[] {HostInfo.getDefault()}; - //public static final String ESDATATYPENAME = "faultcurrent"; - - private static class HtDatabaseClientHelper extends HtDatabaseClient { - - private final String json; - - public HtDatabaseClientHelper(String jsonResponse, HostInfo[] hosts) { - super(hosts); - this.json = jsonResponse; - - } - - @Override - public SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder qb) { - return new SearchResult<>(new SearchResponse(this.json).getHits()); - } - } - - private static class MapResult { - public final List mappedData; - public MapResult(String dataType, Class cls, String dbJson) throws ClassNotFoundException { - System.out.println(dbJson); - DatabaseClient db = new HtDatabaseClientHelper(dbJson,HOSTINFOS); - EsDataObjectReaderWriter dbrw=new EsDataObjectReaderWriter<>(db,dataType,cls); - this.mappedData=dbrw.doReadAll().getHits(); - } - } - - private static final String SEARCHJSON_FORMAT = "{\n" + - "\"took\": 0,\n" + - "\"timed_out\": false,\n" + - "\"_shards\": {\n" + - "\"total\": 5,\n" + - "\"successful\": 5,\n" + - "\"skipped\": 0,\n" + - "\"failed\": 0\n" + - "},\n" + - "\"hits\": {\n" + - "\"total\": 1,\n" + - "\"max_score\": 1,\n" + - "\"hits\": [\n" + - "{\n" + - "\"_index\": \"%s\",\n" + - "\"_type\": \"%s\",\n" + - "\"_id\": \"%s\",\n" + - "\"_score\": 1,\n" + - "\"_source\": %s}\n" + - "]\n" + - "}\n" + - "}"; - - private static final String MEDIATORSERVER_DB_ID="LumwSG0BFvcE3yf8MBM5"; - private static final String MEDIATOR_SERVERDB_JSON = "{\"url\":\"https://10.45.44.223:7590\",\"name\":\"test mediator server\"}"; - - private static final String FAULTCURRENT_DB_ID="LumwSG0BFvcE3yf8MBM5"; - private static final String FAULTCURRENT_DB_NODEID = "sim1"; - private static final int FAULTCURRENT_DB_COUNTER = 3; - private static final String FAULTCURRENT_DB_OBJECTID = "LPS-MWT-01"; - private static final String FAULTCURRENT_DB_PROBLEM = "rlsExceeded"; - private static final String FAULTCURRENT_DB_SEVERITY = "critical"; - private static final DateAndTime FAULTCURRENT_DB_TIMESTAMP = DateAndTime.getDefaultInstance("2019-09-18T13:07:05.8Z"); - - private static final String FAULTCURRENT_SERVERDB_JSON = "{\"node-id\":\""+FAULTCURRENT_DB_NODEID+"\","+ - "\"counter\":"+FAULTCURRENT_DB_COUNTER+","+ - "\"object-id\":\""+FAULTCURRENT_DB_OBJECTID+"\","+ - "\"problem\":\""+FAULTCURRENT_DB_PROBLEM+"\","+ - "\"timestamp\":\""+FAULTCURRENT_DB_TIMESTAMP.getValue()+"\","+ - "\"severity\":\""+FAULTCURRENT_DB_SEVERITY+"\""+ - "}"; - - - private static final String PMDATA15M_SERVERDB_JSON="{\n" + - "\"node-name\": \"sim2\",\n" + - "\"uuid-interface\": \"LP-MWPS-TTP-01\",\n" + - "\"layer-protocol-name\": \"MWPS\",\n" + - "\"radio-signal-id\": \"Test11\",\n" + - "\"time-stamp\": \"2017-07-04T14:00:00.0Z\",\n" + - "\"granularity-period\": \"PERIOD_15MIN\",\n" + - "\"scanner-id\": \"PM_RADIO_15M_9\",\n" + - "\"performance-data\": {\n" + - "\"es\": 0,\n" + - "\"rx-level-avg\": -41,\n" + - "\"time2-states\": -1,\n" + - "\"time4-states-s\": 0,\n" + - "\"time4-states\": 0,\n" + - "\"time8-states\": 0,\n" + - "\"time16-states-s\": -1,\n" + - "\"time16-states\": 0,\n" + - "\"time32-states\": 0,\n" + - "\"time64-states\": 0,\n" + - "\"time128-states\": 0,\n" + - "\"time256-states\": 900,\n" + - "\"time512-states\": -1,\n" + - "\"time512-states-l\": -1,\n" + - "\"time1024-states\": -1,\n" + - "\"time1024-states-l\": -1,\n" + - "\"time2048-states\": -1,\n" + - "\"time2048-states-l\": -1,\n" + - "\"time4096-states\": -1,\n" + - "\"time4096-states-l\": -1,\n" + - "\"time8192-states\": -1,\n" + - "\"time8192-states-l\": -1,\n" + - "\"snir-min\": -99,\n" + - "\"snir-max\": -99,\n" + - "\"snir-avg\": -99,\n" + - "\"xpd-min\": -99,\n" + - "\"xpd-max\": -99,\n" + - "\"xpd-avg\": -99,\n" + - "\"rf-temp-min\": -99,\n" + - "\"rf-temp-max\": -99,\n" + - "\"rf-temp-avg\": -99,\n" + - "\"defect-blocks-sum\": -1,\n" + - "\"time-period\": 900,\n" + - "\"tx-level-min\": 25,\n" + - "\"tx-level-max\": 25,\n" + - "\"tx-level-avg\": 25,\n" + - "\"rx-level-min\": -41,\n" + - "\"rx-level-max\": -41,\n" + - "\"unavailability\": 0,\n" + - "\"ses\": 0,\n" + - "\"cses\": 0\n" + - "},\n" + - "\"suspect-interval-flag\": false\n" + - "}"; - - //@Test -// public void testMediatorServer() throws ClassNotFoundException { -// -// MapResult result = new MapResult(EsMediatorServer.ESDATATYPENAME, -// EsMediatorServer.class, -// getSearchJson(EsMediatorServer.ESDATATYPENAME,MEDIATORSERVER_DB_ID,MEDIATOR_SERVERDB_JSON)); -// assertEquals("test mediator server", result.mappedData.get(0).getName()); -// assertEquals("https://10.45.44.223:7590", result.mappedData.get(0).getUrl()); -// assertEquals(MEDIATORSERVER_DB_ID, result.mappedData.get(0).getId()); -// -// } - //@Test -// public void testFaultCurrent() { -// -// MapResult result = new MapResult(ESDATATYPENAME, EsFaultCurrent.class, -// getSearchJson(ESDATATYPENAME, FAULTCURRENT_DB_ID, FAULTCURRENT_SERVERDB_JSON)); -// assertEquals(FAULTCURRENT_DB_ID, result.mappedData.get(0).getId()); -// assertEquals(FAULTCURRENT_DB_NODEID, result.mappedData.get(0).getNodeId()); -// assertEquals(FAULTCURRENT_DB_COUNTER, result.mappedData.get(0).getCounter().intValue()); -// assertEquals(FAULTCURRENT_DB_OBJECTID, result.mappedData.get(0).getObjectId()); -// assertEquals(FAULTCURRENT_DB_PROBLEM, result.mappedData.get(0).getProblem()); -// assertEquals(FAULTCURRENT_DB_SEVERITY, result.mappedData.get(0).getSeverity()); -// assertEquals(FAULTCURRENT_DB_TIMESTAMP, result.mappedData.get(0).getTimestamp()); -// } -// - @Test - public void testPmData15m() { - - YangToolsMapper mapper = new YangToolsMapper(); - try { - Data data =mapper.readValue(PMDATA15M_SERVERDB_JSON.getBytes(), Data.class); - System.out.println(data); - } catch (IOException e) { - e.printStackTrace(); - } - - - } - private String getSearchJson(String dataType,String dbId, String source) { - return String.format(SEARCHJSON_FORMAT,dataType,dataType, dbId,source); - } + private static final HostInfo[] HOSTINFOS = new HostInfo[] {HostInfo.getDefault()}; + //public static final String ESDATATYPENAME = "faultcurrent"; + + private static class HtDatabaseClientHelper extends HtDatabaseClient { + + private final String json; + + public HtDatabaseClientHelper(String jsonResponse, HostInfo[] hosts) { + super(hosts); + this.json = jsonResponse; + + } + + @Override + public SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder qb) { + return new SearchResult<>(new SearchResponse(this.json).getHits()); + } + } + + private static class MapResult { + public final List mappedData; + + public MapResult(String dataType, Class cls, String dbJson) throws ClassNotFoundException { + System.out.println(dbJson); + DatabaseClient db = new HtDatabaseClientHelper(dbJson, HOSTINFOS); + EsDataObjectReaderWriter dbrw = new EsDataObjectReaderWriter<>(db, dataType, cls); + this.mappedData = dbrw.doReadAll().getHits(); + } + } + + private static final String SEARCHJSON_FORMAT = "{\n" + "\"took\": 0,\n" + "\"timed_out\": false,\n" + + "\"_shards\": {\n" + "\"total\": 5,\n" + "\"successful\": 5,\n" + "\"skipped\": 0,\n" + "\"failed\": 0\n" + + "},\n" + "\"hits\": {\n" + "\"total\": 1,\n" + "\"max_score\": 1,\n" + "\"hits\": [\n" + "{\n" + + "\"_index\": \"%s\",\n" + "\"_type\": \"%s\",\n" + "\"_id\": \"%s\",\n" + "\"_score\": 1,\n" + + "\"_source\": %s}\n" + "]\n" + "}\n" + "}"; + + private static final String MEDIATORSERVER_DB_ID = "LumwSG0BFvcE3yf8MBM5"; + private static final String MEDIATOR_SERVERDB_JSON = + "{\"url\":\"https://10.45.44.223:7590\",\"name\":\"test mediator server\"}"; + + private static final String FAULTCURRENT_DB_ID = "LumwSG0BFvcE3yf8MBM5"; + private static final String FAULTCURRENT_DB_NODEID = "sim1"; + private static final int FAULTCURRENT_DB_COUNTER = 3; + private static final String FAULTCURRENT_DB_OBJECTID = "LPS-MWT-01"; + private static final String FAULTCURRENT_DB_PROBLEM = "rlsExceeded"; + private static final String FAULTCURRENT_DB_SEVERITY = "critical"; + private static final DateAndTime FAULTCURRENT_DB_TIMESTAMP = + DateAndTime.getDefaultInstance("2019-09-18T13:07:05.8Z"); + + private static final String FAULTCURRENT_SERVERDB_JSON = "{\"node-id\":\"" + FAULTCURRENT_DB_NODEID + "\"," + + "\"counter\":" + FAULTCURRENT_DB_COUNTER + "," + "\"object-id\":\"" + FAULTCURRENT_DB_OBJECTID + "\"," + + "\"problem\":\"" + FAULTCURRENT_DB_PROBLEM + "\"," + "\"timestamp\":\"" + + FAULTCURRENT_DB_TIMESTAMP.getValue() + "\"," + "\"severity\":\"" + FAULTCURRENT_DB_SEVERITY + "\"" + "}"; + + + private static final String PMDATA15M_SERVERDB_JSON = "{\n" + "\"node-name\": \"sim2\",\n" + + "\"uuid-interface\": \"LP-MWPS-TTP-01\",\n" + "\"layer-protocol-name\": \"MWPS\",\n" + + "\"radio-signal-id\": \"Test11\",\n" + "\"time-stamp\": \"2017-07-04T14:00:00.0Z\",\n" + + "\"granularity-period\": \"PERIOD_15MIN\",\n" + "\"scanner-id\": \"PM_RADIO_15M_9\",\n" + + "\"performance-data\": {\n" + "\"es\": 0,\n" + "\"rx-level-avg\": -41,\n" + "\"time2-states\": -1,\n" + + "\"time4-states-s\": 0,\n" + "\"time4-states\": 0,\n" + "\"time8-states\": 0,\n" + + "\"time16-states-s\": -1,\n" + "\"time16-states\": 0,\n" + "\"time32-states\": 0,\n" + + "\"time64-states\": 0,\n" + "\"time128-states\": 0,\n" + "\"time256-states\": 900,\n" + + "\"time512-states\": -1,\n" + "\"time512-states-l\": -1,\n" + "\"time1024-states\": -1,\n" + + "\"time1024-states-l\": -1,\n" + "\"time2048-states\": -1,\n" + "\"time2048-states-l\": -1,\n" + + "\"time4096-states\": -1,\n" + "\"time4096-states-l\": -1,\n" + "\"time8192-states\": -1,\n" + + "\"time8192-states-l\": -1,\n" + "\"snir-min\": -99,\n" + "\"snir-max\": -99,\n" + "\"snir-avg\": -99,\n" + + "\"xpd-min\": -99,\n" + "\"xpd-max\": -99,\n" + "\"xpd-avg\": -99,\n" + "\"rf-temp-min\": -99,\n" + + "\"rf-temp-max\": -99,\n" + "\"rf-temp-avg\": -99,\n" + "\"defect-blocks-sum\": -1,\n" + + "\"time-period\": 900,\n" + "\"tx-level-min\": 25,\n" + "\"tx-level-max\": 25,\n" + + "\"tx-level-avg\": 25,\n" + "\"rx-level-min\": -41,\n" + "\"rx-level-max\": -41,\n" + + "\"unavailability\": 0,\n" + "\"ses\": 0,\n" + "\"cses\": 0\n" + "},\n" + + "\"suspect-interval-flag\": false\n" + "}"; + + //@Test + // public void testMediatorServer() throws ClassNotFoundException { + // + // MapResult result = new MapResult(EsMediatorServer.ESDATATYPENAME, + // EsMediatorServer.class, + // getSearchJson(EsMediatorServer.ESDATATYPENAME,MEDIATORSERVER_DB_ID,MEDIATOR_SERVERDB_JSON)); + // assertEquals("test mediator server", result.mappedData.get(0).getName()); + // assertEquals("https://10.45.44.223:7590", result.mappedData.get(0).getUrl()); + // assertEquals(MEDIATORSERVER_DB_ID, result.mappedData.get(0).getId()); + // + // } + //@Test + // public void testFaultCurrent() { + // + // MapResult result = new MapResult(ESDATATYPENAME, EsFaultCurrent.class, + // getSearchJson(ESDATATYPENAME, FAULTCURRENT_DB_ID, FAULTCURRENT_SERVERDB_JSON)); + // assertEquals(FAULTCURRENT_DB_ID, result.mappedData.get(0).getId()); + // assertEquals(FAULTCURRENT_DB_NODEID, result.mappedData.get(0).getNodeId()); + // assertEquals(FAULTCURRENT_DB_COUNTER, result.mappedData.get(0).getCounter().intValue()); + // assertEquals(FAULTCURRENT_DB_OBJECTID, result.mappedData.get(0).getObjectId()); + // assertEquals(FAULTCURRENT_DB_PROBLEM, result.mappedData.get(0).getProblem()); + // assertEquals(FAULTCURRENT_DB_SEVERITY, result.mappedData.get(0).getSeverity()); + // assertEquals(FAULTCURRENT_DB_TIMESTAMP, result.mappedData.get(0).getTimestamp()); + // } + // + @Test + public void testPmData15m() { + + YangToolsMapper mapper = new YangToolsMapper(); + try { + Data data = mapper.readValue(PMDATA15M_SERVERDB_JSON.getBytes(), Data.class); + System.out.println(data); + } catch (IOException e) { + e.printStackTrace(); + } + + + } + + private String getSearchJson(String dataType, String dbId, String source) { + return String.format(SEARCHJSON_FORMAT, dataType, dataType, dbId, source); + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataTreeSerialization.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataTreeSerialization.java index 54b2dc00d..60a2c50e4 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataTreeSerialization.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestDataTreeSerialization.java @@ -29,5 +29,5 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.yangtools.YangToolsMapper; */ public class TestDataTreeSerialization { - //YangToolsMapper + //YangToolsMapper } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java index c528e3552..308bbf663 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestEventService.java @@ -70,251 +70,251 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro * */ public class TestEventService { - private static ElasticSearchDataProvider dbProvider; - private static HtDatabaseClient dbRawProvider; - private static HtDatabaseEventsService service = null; + private static ElasticSearchDataProvider dbProvider; + private static HtDatabaseClient dbRawProvider; + private static HtDatabaseEventsService service = null; - private static final String NODEID = "node1"; - private static final String NODEID2 = "node2"; - private static final String OBJECTREFID1 = "objid1"; - private static final String OBJECTREFID2 = "objid2"; + private static final String NODEID = "node1"; + private static final String NODEID2 = "node2"; + private static final String OBJECTREFID1 = "objid1"; + private static final String OBJECTREFID2 = "objid2"; - @BeforeClass - public static void init() throws Exception { + @BeforeClass + public static void init() throws Exception { - dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts); - dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS); - dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts); + dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts); + dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS); + dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts); - try { - service = new HtDatabaseEventsService(dbRawProvider, dbProvider); - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } + try { + service = new HtDatabaseEventsService(dbRawProvider, dbProvider); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } - @Test - public void testClearFaultsCurrent() { + @Test + public void testClearFaultsCurrent() { - service.clearFaultsCurrentOfNode(NODEID); - service.clearFaultsCurrentOfNode(NODEID2); + service.clearFaultsCurrentOfNode(NODEID); + service.clearFaultsCurrentOfNode(NODEID2); - List nodeIds = service.getAllNodesWithCurrentAlarms(); - if (nodeIds.size() > 0) { - for (String nodeId : nodeIds) { - service.clearFaultsCurrentOfNode(nodeId); - } - } - service.updateFaultCurrent(createFault(NODEID, OBJECTREFID1, "abc", SeverityType.Major)); - service.updateFaultCurrent(createFault(NODEID, OBJECTREFID1, "abcde", SeverityType.Major)); - service.updateFaultCurrent(createFault(NODEID, OBJECTREFID2, "abcde", SeverityType.Major)); - service.updateFaultCurrent(createFault(NODEID2, OBJECTREFID2, "abcde", SeverityType.Major)); - nodeIds = service.getAllNodesWithCurrentAlarms(); - assertTrue(nodeIds.size() == 2); - service.clearFaultsCurrentOfNodeWithObjectId(NODEID, OBJECTREFID1); - nodeIds = service.getAllNodesWithCurrentAlarms(); - assertTrue(nodeIds.size() == 2); - service.updateFaultCurrent(createFault(NODEID, OBJECTREFID2, "abcde", SeverityType.NonAlarmed)); - nodeIds = service.getAllNodesWithCurrentAlarms(); - assertTrue(nodeIds.size() == 1); - } + List nodeIds = service.getAllNodesWithCurrentAlarms(); + if (nodeIds.size() > 0) { + for (String nodeId : nodeIds) { + service.clearFaultsCurrentOfNode(nodeId); + } + } + service.updateFaultCurrent(createFault(NODEID, OBJECTREFID1, "abc", SeverityType.Major)); + service.updateFaultCurrent(createFault(NODEID, OBJECTREFID1, "abcde", SeverityType.Major)); + service.updateFaultCurrent(createFault(NODEID, OBJECTREFID2, "abcde", SeverityType.Major)); + service.updateFaultCurrent(createFault(NODEID2, OBJECTREFID2, "abcde", SeverityType.Major)); + nodeIds = service.getAllNodesWithCurrentAlarms(); + assertTrue(nodeIds.size() == 2); + service.clearFaultsCurrentOfNodeWithObjectId(NODEID, OBJECTREFID1); + nodeIds = service.getAllNodesWithCurrentAlarms(); + assertTrue(nodeIds.size() == 2); + service.updateFaultCurrent(createFault(NODEID, OBJECTREFID2, "abcde", SeverityType.NonAlarmed)); + nodeIds = service.getAllNodesWithCurrentAlarms(); + assertTrue(nodeIds.size() == 1); + } - private static FaultcurrentEntity createFault(String nodeId, String objectRefId, String problem, - SeverityType severity) { - return createFault(nodeId, objectRefId, problem, severity, NetconfTimeStampImpl.getConverter().getTimeStamp()); - } + private static FaultcurrentEntity createFault(String nodeId, String objectRefId, String problem, + SeverityType severity) { + return createFault(nodeId, objectRefId, problem, severity, NetconfTimeStampImpl.getConverter().getTimeStamp()); + } - /** - * @param nODENAME - * @param problem - * @param ts - * @param severity - * @return - */ - private static FaultcurrentEntity createFault(String nodeId, String objectRefId, String problem, - SeverityType severity, DateAndTime ts) { - return new FaultcurrentBuilder().setNodeId(nodeId).setObjectId(objectRefId).setTimestamp(ts) - .setSeverity(severity).setProblem(problem).build(); - } + /** + * @param nODENAME + * @param problem + * @param ts + * @param severity + * @return + */ + private static FaultcurrentEntity createFault(String nodeId, String objectRefId, String problem, + SeverityType severity, DateAndTime ts) { + return new FaultcurrentBuilder().setNodeId(nodeId).setObjectId(objectRefId).setTimestamp(ts) + .setSeverity(severity).setProblem(problem).build(); + } - @Test - public void testIndexClean() { - Date now = new Date(); - service.doIndexClean(now); - clearDbEntity(Entity.Eventlog); - clearDbEntity(Entity.Faultlog); - TestCRUDforDatabase.trySleep(1000); - service.writeEventLog(createEventLog(NODEID, OBJECTREFID1, "aaa", "abc", 1)); - service.writeEventLog(createEventLog(NODEID, OBJECTREFID1, "aaa", "avasvas", 2)); + @Test + public void testIndexClean() { + Date now = new Date(); + service.doIndexClean(now); + clearDbEntity(Entity.Eventlog); + clearDbEntity(Entity.Faultlog); + TestCRUDforDatabase.trySleep(1000); + service.writeEventLog(createEventLog(NODEID, OBJECTREFID1, "aaa", "abc", 1)); + service.writeEventLog(createEventLog(NODEID, OBJECTREFID1, "aaa", "avasvas", 2)); - service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 1)); - service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.NonAlarmed, 2)); - service.writeFaultLog(createFaultLog(NODEID2, OBJECTREFID2, "problem", SeverityType.Major, 1)); - TestCRUDforDatabase.trySleep(100); - now = new Date(); - int numOlds = service.getNumberOfOldObjects(now); - assertEquals(5, numOlds); - TestCRUDforDatabase.trySleep(100); - service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 3)); - service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.NonAlarmed, 5)); - service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 6)); - numOlds = service.getNumberOfOldObjects(now); - assertEquals(5, numOlds); - now = new Date(); - numOlds = service.getNumberOfOldObjects(now); - assertEquals(8, numOlds); - service.doIndexClean(now); - numOlds = service.getNumberOfOldObjects(now); - assertEquals(0, numOlds); + service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 1)); + service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.NonAlarmed, 2)); + service.writeFaultLog(createFaultLog(NODEID2, OBJECTREFID2, "problem", SeverityType.Major, 1)); + TestCRUDforDatabase.trySleep(100); + now = new Date(); + int numOlds = service.getNumberOfOldObjects(now); + assertEquals(5, numOlds); + TestCRUDforDatabase.trySleep(100); + service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 3)); + service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.NonAlarmed, 5)); + service.writeFaultLog(createFaultLog(NODEID, OBJECTREFID2, "problem", SeverityType.Major, 6)); + numOlds = service.getNumberOfOldObjects(now); + assertEquals(5, numOlds); + now = new Date(); + numOlds = service.getNumberOfOldObjects(now); + assertEquals(8, numOlds); + service.doIndexClean(now); + numOlds = service.getNumberOfOldObjects(now); + assertEquals(0, numOlds); - } + } - @Test - public void testPm() { - final String IFNAME1 = "if1"; - final String SCNID1 = "scn1"; - List list = Arrays.asList(createPmData(NODEID, IFNAME1, SCNID1), - createPmData(NODEID, IFNAME1, SCNID1), createPmData(NODEID, IFNAME1, SCNID1), - createPmData(NODEID, IFNAME1, SCNID1) + @Test + public void testPm() { + final String IFNAME1 = "if1"; + final String SCNID1 = "scn1"; + List list = + Arrays.asList(createPmData(NODEID, IFNAME1, SCNID1), createPmData(NODEID, IFNAME1, SCNID1), + createPmData(NODEID, IFNAME1, SCNID1), createPmData(NODEID, IFNAME1, SCNID1) - ); - service.doWritePerformanceData(list); - } + ); + service.doWritePerformanceData(list); + } - /** - * @param ifname - * @param ifUuid - * @param scannerId - * @param nodename3 - * @return - */ - private static PmdataEntity createPmData(String nodeId, String ifUuid, String scannerId) { - return new PmdataEntityBuilder().setNodeName(nodeId).setGranularityPeriod(GranularityPeriodType.Period15Min) - .setUuidInterface(ifUuid).setScannerId(scannerId).setLayerProtocolName("NETCONF") - .setPerformanceData(null).setSuspectIntervalFlag(true) - .setTimeStamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).build(); - } + /** + * @param ifname + * @param ifUuid + * @param scannerId + * @param nodename3 + * @return + */ + private static PmdataEntity createPmData(String nodeId, String ifUuid, String scannerId) { + return new PmdataEntityBuilder().setNodeName(nodeId).setGranularityPeriod(GranularityPeriodType.Period15Min) + .setUuidInterface(ifUuid).setScannerId(scannerId).setLayerProtocolName("NETCONF") + .setPerformanceData(null).setSuspectIntervalFlag(true) + .setTimeStamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).build(); + } - @Test - public void testNeConnection() { - service.removeNetworkConnection(NODEID); - service.removeNetworkConnection(NODEID2); + @Test + public void testNeConnection() { + service.removeNetworkConnection(NODEID); + service.removeNetworkConnection(NODEID2); - clearDbEntity(Entity.NetworkelementConnection); - List nes = service.getNetworkElementConnections(); - assertEquals(0, nes.size()); - service.updateNetworkConnection22(createNeConnection(NODEID, NetworkElementDeviceType.Unknown), NODEID); - service.updateNetworkConnection22(createNeConnection(NODEID2, NetworkElementDeviceType.ORAN), NODEID2); - nes = service.getNetworkElementConnections(); - assertEquals(2, nes.size()); - service.updateNetworkConnectionDeviceType(createNeConnection(NODEID, NetworkElementDeviceType.Wireless), - NODEID); - nes = service.getNetworkElementConnections(); - assertEquals(2, nes.size()); - boolean found = false; - for (NetworkElementConnectionEntity ne : nes) { - if (NODEID.equals(ne.getNodeId()) && ne.getDeviceType() == NetworkElementDeviceType.Wireless) { - found = true; - } - } - assertTrue(found); + clearDbEntity(Entity.NetworkelementConnection); + List nes = service.getNetworkElementConnections(); + assertEquals(0, nes.size()); + service.updateNetworkConnection22(createNeConnection(NODEID, NetworkElementDeviceType.Unknown), NODEID); + service.updateNetworkConnection22(createNeConnection(NODEID2, NetworkElementDeviceType.ORAN), NODEID2); + nes = service.getNetworkElementConnections(); + assertEquals(2, nes.size()); + service.updateNetworkConnectionDeviceType(createNeConnection(NODEID, NetworkElementDeviceType.Wireless), + NODEID); + nes = service.getNetworkElementConnections(); + assertEquals(2, nes.size()); + boolean found = false; + for (NetworkElementConnectionEntity ne : nes) { + if (NODEID.equals(ne.getNodeId()) && ne.getDeviceType() == NetworkElementDeviceType.Wireless) { + found = true; + } + } + assertTrue(found); - } + } - @Test - public void testConnectionLog() { - clearDbEntity(Entity.Connectionlog); - service.writeConnectionLog(createConnectionLog(NODEID, ConnectionLogStatus.Mounted)); - service.writeConnectionLog(createConnectionLog(NODEID, ConnectionLogStatus.Mounted)); - assertEquals(2, getDbEntityEntries(Entity.Connectionlog).getTotal()); - } + @Test + public void testConnectionLog() { + clearDbEntity(Entity.Connectionlog); + service.writeConnectionLog(createConnectionLog(NODEID, ConnectionLogStatus.Mounted)); + service.writeConnectionLog(createConnectionLog(NODEID, ConnectionLogStatus.Mounted)); + assertEquals(2, getDbEntityEntries(Entity.Connectionlog).getTotal()); + } - /** - * @param nodeId - * @param status - * @return - */ - private static ConnectionlogEntity createConnectionLog(String nodeId, ConnectionLogStatus status) { - return new ConnectionlogBuilder().setNodeId(nodeId) - .setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).setStatus(status).build(); - } + /** + * @param nodeId + * @param status + * @return + */ + private static ConnectionlogEntity createConnectionLog(String nodeId, ConnectionLogStatus status) { + return new ConnectionlogBuilder().setNodeId(nodeId) + .setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).setStatus(status).build(); + } - @Test - public void testInventory() { - clearDbEntity(Entity.Inventoryequipment); - service.writeInventory(createEquipment(NODEID, "uuid1")); - service.writeInventory(createEquipment(NODEID, "uuid2")); - service.writeInventory(createEquipment(NODEID2, "uuid3")); - service.writeInventory(createEquipment(NODEID2, "uuid4")); - service.writeInventory(createEquipment(NODEID2, "uuid5")); - assertEquals(5, getDbEntityEntries(Entity.Inventoryequipment).getTotal()); - } + @Test + public void testInventory() { + clearDbEntity(Entity.Inventoryequipment); + service.writeInventory(createEquipment(NODEID, "uuid1")); + service.writeInventory(createEquipment(NODEID, "uuid2")); + service.writeInventory(createEquipment(NODEID2, "uuid3")); + service.writeInventory(createEquipment(NODEID2, "uuid4")); + service.writeInventory(createEquipment(NODEID2, "uuid5")); + assertEquals(5, getDbEntityEntries(Entity.Inventoryequipment).getTotal()); + } - private static SearchResult getDbEntityEntries(Entity entity) { - return dbRawProvider.doReadAllJsonData(entity.getName()); - } + private static SearchResult getDbEntityEntries(Entity entity) { + return dbRawProvider.doReadAllJsonData(entity.getName()); + } - private static void clearDbEntity(Entity entity) { - DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName()); - query.setQuery(QueryBuilders.matchAllQuery().toJSON()); - try { - dbRawProvider.deleteByQuery(query); - } catch (IOException e) { - e.printStackTrace(); - } - TestCRUDforDatabase.trySleep(1000); - } + private static void clearDbEntity(Entity entity) { + DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName()); + query.setQuery(QueryBuilders.matchAllQuery().toJSON()); + try { + dbRawProvider.deleteByQuery(query); + } catch (IOException e) { + e.printStackTrace(); + } + TestCRUDforDatabase.trySleep(1000); + } - /** - * @param nodeId - * @param uuid - * @return - */ - private Inventory createEquipment(String nodeId, String uuid) { - return new InventoryBuilder().setNodeId(nodeId).setParentUuid("").setDescription("desc") - .setManufacturerName("manu").setUuid(uuid).build(); - } + /** + * @param nodeId + * @param uuid + * @return + */ + private Inventory createEquipment(String nodeId, String uuid) { + return new InventoryBuilder().setNodeId(nodeId).setParentUuid("").setDescription("desc") + .setManufacturerName("manu").setUuid(uuid).build(); + } - /** - * @param devType - * @param nodename3 - * @return - */ - private static NetworkElementConnectionEntity createNeConnection(String nodeId, NetworkElementDeviceType devType) { - return new NetworkElementConnectionBuilder().setNodeId(nodeId).setHost("host").setPort(1234L) - .setCoreModelCapability("123").setStatus(ConnectionLogStatus.Connected).setDeviceType(devType) - .setIsRequired(true).build(); - } + /** + * @param devType + * @param nodename3 + * @return + */ + private static NetworkElementConnectionEntity createNeConnection(String nodeId, NetworkElementDeviceType devType) { + return new NetworkElementConnectionBuilder().setNodeId(nodeId).setHost("host").setPort(1234L) + .setCoreModelCapability("123").setStatus(ConnectionLogStatus.Connected).setDeviceType(devType) + .setIsRequired(true).build(); + } - /** - * @param nodeId - * @param objectId - * @param problem - * @param severity - * @param counter - * @return - */ - private static FaultlogEntity createFaultLog(String nodeId, String objectId, String problem, SeverityType severity, - int counter) { - return new FaultlogBuilder().setNodeId(nodeId).setObjectId(objectId).setProblem(problem).setSeverity(severity) - .setCounter(counter).setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()) - .setSourceType(SourceType.Netconf).build(); - } + /** + * @param nodeId + * @param objectId + * @param problem + * @param severity + * @param counter + * @return + */ + private static FaultlogEntity createFaultLog(String nodeId, String objectId, String problem, SeverityType severity, + int counter) { + return new FaultlogBuilder().setNodeId(nodeId).setObjectId(objectId).setProblem(problem).setSeverity(severity) + .setCounter(counter).setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()) + .setSourceType(SourceType.Netconf).build(); + } - /** - * @param nodeId - * @param objectId - * @param attributeName - * @param newValue - * @param counter - * @return - */ - private static EventlogEntity createEventLog(String nodeId, String objectId, String attributeName, String newValue, - int counter) { - return new EventlogBuilder().setNodeId(nodeId).setObjectId(objectId).setAttributeName(attributeName) - .setNewValue(newValue).setCounter(counter) - .setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).setSourceType(SourceType.Netconf) - .build(); - } + /** + * @param nodeId + * @param objectId + * @param attributeName + * @param newValue + * @param counter + * @return + */ + private static EventlogEntity createEventLog(String nodeId, String objectId, String attributeName, String newValue, + int counter) { + return new EventlogBuilder().setNodeId(nodeId).setObjectId(objectId).setAttributeName(attributeName) + .setNewValue(newValue).setCounter(counter) + .setTimestamp(NetconfTimeStampImpl.getConverter().getTimeStamp()).setSourceType(SourceType.Netconf) + .build(); + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java index e2009411a..52ca2999d 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestFilterConversion.java @@ -39,36 +39,39 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro public class TestFilterConversion { - private static final String PROPERTY = "node-id"; - private static final String PROPERTY2 = "_id"; - private static final String PROPERTY3 = "timestamp"; + private static final String PROPERTY = "node-id"; + private static final String PROPERTY2 = "_id"; + private static final String PROPERTY3 = "timestamp"; - @Test - public void testQuestionMark() { - List filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build()); - QueryBuilder query = QueryByFilter.fromFilter(filters); - System.out.println(query.toJSON()); - assertTrue(query.toJSON().contains("{1,1}")); - assertNotNull(QueryByFilter.getFilter(filters, PROPERTY)); - assertNull(QueryByFilter.getFilter(filters, PROPERTY2)); - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build(), - new FilterBuilder().setProperty(PROPERTY2).setFiltervalue("abc").build()); - query = QueryByFilter.fromFilter(filters); - System.out.println(query.toJSON()); - assertNotNull(QueryByFilter.getFilter(filters, PROPERTY2)); - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build(), - new FilterBuilder().setProperty(PROPERTY3).setFiltervalue("<2019-06-13T15:00:12.0Z").build()); - query = QueryByFilter.fromFilter(filters); - List sortorder = Arrays - .asList(new SortorderBuilder().setProperty(PROPERTY).setSortorder(SortOrder.Ascending).build()); - QueryByFilter.setSortOrder(query, sortorder); - assertNotNull(QueryByFilter.getSortOrder(sortorder, PROPERTY)); - } - @Test - public void testSortorder() { - String f = "{\"input\":{\"filter\":[],\"sortorder\":[{\"property\":\"source-type\",\"sortorder\":\"ascending\"}],\"pagination\":{\"size\":10,\"page\":1}}}"; - - QueryBuilder query = QueryByFilter.setSortOrder(QueryByFilter.fromFilter(null), Arrays.asList(new SortorderBuilder().setProperty("source-type").setSortorder(SortOrder.Ascending).build())); - System.out.println(query.toJSON()); - } + @Test + public void testQuestionMark() { + List filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build()); + QueryBuilder query = QueryByFilter.fromFilter(filters); + System.out.println(query.toJSON()); + assertTrue(query.toJSON().contains("{1,1}")); + assertNotNull(QueryByFilter.getFilter(filters, PROPERTY)); + assertNull(QueryByFilter.getFilter(filters, PROPERTY2)); + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build(), + new FilterBuilder().setProperty(PROPERTY2).setFiltervalue("abc").build()); + query = QueryByFilter.fromFilter(filters); + System.out.println(query.toJSON()); + assertNotNull(QueryByFilter.getFilter(filters, PROPERTY2)); + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY).setFiltervalue("si?ba").build(), + new FilterBuilder().setProperty(PROPERTY3).setFiltervalue("<2019-06-13T15:00:12.0Z").build()); + query = QueryByFilter.fromFilter(filters); + List sortorder = + Arrays.asList(new SortorderBuilder().setProperty(PROPERTY).setSortorder(SortOrder.Ascending).build()); + QueryByFilter.setSortOrder(query, sortorder); + assertNotNull(QueryByFilter.getSortOrder(sortorder, PROPERTY)); + } + + @Test + public void testSortorder() { + String f = + "{\"input\":{\"filter\":[],\"sortorder\":[{\"property\":\"source-type\",\"sortorder\":\"ascending\"}],\"pagination\":{\"size\":10,\"page\":1}}}"; + + QueryBuilder query = QueryByFilter.setSortOrder(QueryByFilter.fromFilter(null), Arrays + .asList(new SortorderBuilder().setProperty("source-type").setSortorder(SortOrder.Ascending).build())); + System.out.println(query.toJSON()); + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java index 57e1438cc..cc880d1ad 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestImplementation.java @@ -44,43 +44,43 @@ import net.bytebuddy.implementation.bytecode.StackSize; */ public class TestImplementation { - @Test - public void test() { - TestConfig.setSDNRDBURLEnv(); - DataProviderImpl impl = new DataProviderImpl(); - impl.setRpcProviderService(new RpcProviderService() { - - @Override - public ObjectRegistration registerRpcImplementation(Class type, - T implementation, Set> paths) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ObjectRegistration registerRpcImplementation(Class type, - T implementation) { - // TODO Auto-generated method stub - return null; - } - }); - impl.setMediatorServerServlet(new MsServlet()); - impl.setAboutServlet(new AboutHttpServlet()); - try { - impl.init(); - } catch (Exception e) { - e.printStackTrace(); - fail("failed to init impl: "+e.getMessage()); - } - - impl.setStatus(StatusKey.CLUSTER_SIZE, "3"); - impl.setReadyStatus(true); - try { - impl.close(); - } catch (Exception e) { - e.printStackTrace(); - fail("failed to close impl: "+e.getMessage()); - } - } - + @Test + public void test() { + TestConfig.setSDNRDBURLEnv(); + DataProviderImpl impl = new DataProviderImpl(); + impl.setRpcProviderService(new RpcProviderService() { + + @Override + public ObjectRegistration registerRpcImplementation(Class type, + T implementation, Set> paths) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ObjectRegistration registerRpcImplementation(Class type, + T implementation) { + // TODO Auto-generated method stub + return null; + } + }); + impl.setMediatorServerServlet(new MsServlet()); + impl.setAboutServlet(new AboutHttpServlet()); + try { + impl.init(); + } catch (Exception e) { + e.printStackTrace(); + fail("failed to init impl: " + e.getMessage()); + } + + impl.setStatus(StatusKey.CLUSTER_SIZE, "3"); + impl.setReadyStatus(true); + try { + impl.close(); + } catch (Exception e) { + e.printStackTrace(); + fail("failed to close impl: " + e.getMessage()); + } + } + } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceServiceData.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceServiceData.java index 271fe2858..6c22b0ea1 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceServiceData.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMaintenanceServiceData.java @@ -49,14 +49,16 @@ public class TestMaintenanceServiceData { private static final String NODEID = "tmsnode1"; private static final String NODEID2 = "tmsnode2"; + @BeforeClass public static void init() throws Exception { dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts); dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS); dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts); - service = dbProvider.getHtDatabaseMaintenance(); + service = dbProvider.getHtDatabaseMaintenance(); } + @Test public void test() throws InterruptedException { clearDbEntity(Entity.Maintenancemode); @@ -67,25 +69,29 @@ public class TestMaintenanceServiceData { obj = service.getMaintenance(NODEID); assertNotNull(obj); List list = service.getAll(); - assertEquals("Verify for two ids", 2,list.size()); + assertEquals("Verify for two ids", 2, list.size()); service.deleteIfNotRequired(NODEID); obj = service.getMaintenance(NODEID); assertNull("Check if first id was removed", obj); - obj = service.setMaintenance(createMaintenance(NODEID,true)); + obj = service.setMaintenance(createMaintenance(NODEID, true)); } + /** * @param nodeId * @param active * @return */ private static MaintenanceEntity createMaintenance(String nodeId, Boolean active) { - return new MaintenanceBuilder().setNodeId(nodeId).setActive(active).setProblem("problem").setObjectIdRef("idref").build(); + return new MaintenanceBuilder().setNodeId(nodeId).setActive(active).setProblem("problem") + .setObjectIdRef("idref").build(); } + /** * Delete + * * @param entity */ private static void clearDbEntity(Entity entity) { diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java index 3192b7f7d..edd0f9edb 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestMediatorServerService.java @@ -45,52 +45,54 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.pro * */ public class TestMediatorServerService { - private static final String SERVERID = null; - private static ElasticSearchDataProvider dbProvider; - private static HtDatabaseClient dbRawProvider; - private static MediatorServerDataProvider service = null; + private static final String SERVERID = null; + private static ElasticSearchDataProvider dbProvider; + private static HtDatabaseClient dbRawProvider; + private static MediatorServerDataProvider service = null; - - @BeforeClass - public static void init() throws Exception { - dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts); - dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS); - dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts); - service = new MediatorServerDataProvider(TestCRUDforDatabase.hosts); - - - } - @Test - public void test() { - clearDbEntity(Entity.MediatorServer); - System.out.println(service.triggerReloadSync()); - String dbServerId="abc"; - String host = service.getHostUrl(dbServerId); - assertNull(host); - final String NAME="ms1"; - final String HOST = "http://10.20.30.40:7070"; - CreateMediatorServerOutputBuilder output = null; - try { - output = dbProvider.createMediatorServer(new CreateMediatorServerInputBuilder().setName(NAME).setUrl(HOST).build()); - } catch (IOException e) { - e.printStackTrace(); - fail("unable to create ms entry: "+e.getMessage()); - } - System.out.println(service.triggerReloadSync()); - host = service.getHostUrl(output.getId()); - assertEquals(HOST, host); - - } - - private static void clearDbEntity(Entity entity) { - DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName()); - query.setQuery(QueryBuilders.matchAllQuery().toJSON()); - try { - dbRawProvider.deleteByQuery(query); - } catch (IOException e) { - e.printStackTrace(); - } - TestCRUDforDatabase.trySleep(1000); - } + @BeforeClass + public static void init() throws Exception { + + dbProvider = new ElasticSearchDataProvider(TestCRUDforDatabase.hosts); + dbProvider.waitForYellowDatabaseStatus(30, TimeUnit.SECONDS); + dbRawProvider = new HtDatabaseClient(TestCRUDforDatabase.hosts); + service = new MediatorServerDataProvider(TestCRUDforDatabase.hosts); + + + } + + @Test + public void test() { + clearDbEntity(Entity.MediatorServer); + System.out.println(service.triggerReloadSync()); + String dbServerId = "abc"; + String host = service.getHostUrl(dbServerId); + assertNull(host); + final String NAME = "ms1"; + final String HOST = "http://10.20.30.40:7070"; + CreateMediatorServerOutputBuilder output = null; + try { + output = dbProvider + .createMediatorServer(new CreateMediatorServerInputBuilder().setName(NAME).setUrl(HOST).build()); + } catch (IOException e) { + e.printStackTrace(); + fail("unable to create ms entry: " + e.getMessage()); + } + System.out.println(service.triggerReloadSync()); + host = service.getHostUrl(output.getId()); + assertEquals(HOST, host); + + } + + private static void clearDbEntity(Entity entity) { + DeleteByQueryRequest query = new DeleteByQueryRequest(entity.getName()); + query.setQuery(QueryBuilders.matchAllQuery().toJSON()); + try { + dbRawProvider.deleteByQuery(query); + } catch (IOException e) { + e.printStackTrace(); + } + TestCRUDforDatabase.trySleep(1000); + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfNodeBuilder.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfNodeBuilder.java index 83b28a29f..f7a5a841c 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfNodeBuilder.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfNodeBuilder.java @@ -44,11 +44,11 @@ public class TestNetconfNodeBuilder { System.out.println(netconfNode); Credentials credentials = netconfNode.getCredentials(); - System.out.println("Class: "+credentials.getClass()+"\nContent: "+credentials); + System.out.println("Class: " + credentials.getClass() + "\nContent: " + credentials); if (credentials instanceof LoginPassword) { - LoginPassword loginPassword = (LoginPassword)credentials; - System.out.println("User: "+loginPassword.getUsername()+" Password"+loginPassword.getPassword()); + LoginPassword loginPassword = (LoginPassword) credentials; + System.out.println("User: " + loginPassword.getUsername() + " Password" + loginPassword.getPassword()); } else { System.out.println("Not expected class"); } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfTimestamp.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfTimestamp.java index 104f2272f..1081e3cfe 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfTimestamp.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNetconfTimestamp.java @@ -45,48 +45,51 @@ public class TestNetconfTimestamp { private static final String NETCONF_DEF4_MILLIS_STRING_MALFORMAED = "2020-01-09T05:40:41.0000Z"; private static final long NETCONF_DEF_MILLIS_LONG = 1578548441100L; - private static NetconfTimeStamp converter =NetconfTimeStampImpl.getConverter(); + private static NetconfTimeStamp converter = NetconfTimeStampImpl.getConverter(); - @Test + @Test public void test() { String ts = converter.getTimeStampAsNetconfString(); final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); final Matcher matcher = pattern.matcher(ts); assertTrue(matcher.find()); } - @Test - public void testMillis() { - long millis=converter.getTimeStampFromNetconfAsMilliseconds(NETCONF_DEF_MILLIS_STRING); - assertEquals(NETCONF_DEF_MILLIS_LONG,millis); - - } - @Test(expected = IllegalArgumentException.class) - public void testMillisMalformed() { - long millis=converter.getTimeStampFromNetconfAsMilliseconds(NETCONF_DEF_MILLIS_STRING_MALFORMAED); - - } - - @Test - public void test2() { - assertEquals(NETCONF_DEF_MILLIS_STRING,converter.getTimeStampFromNetconf(NETCONF_DEF2_MILLIS_STRING)); - assertEquals(NETCONF_DEF3_MILLIS_STRING_CORRECTED,converter.getTimeStampFromNetconf(NETCONF_DEF3_MILLIS_STRING)); - assertTrue(converter.getTimeStampFromNetconf(NETCONF_DEF4_MILLIS_STRING_MALFORMAED).startsWith("Malformed")); - } - - @Test - public void test3() { - Date dt = converter.getDateFromNetconf(NETCONF_DEF_MILLIS_STRING); - final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - c.setTime(dt); - assertEquals(2020,c.get(Calendar.YEAR)); - assertEquals(0,c.get(Calendar.MONTH)); - assertEquals(9,c.get(Calendar.DAY_OF_MONTH)); - assertEquals(5,c.get(Calendar.HOUR_OF_DAY)); - assertEquals(40,c.get(Calendar.MINUTE)); - assertEquals(41,c.get(Calendar.SECOND)); - assertEquals(100,c.get(Calendar.MILLISECOND)); - - - assertEquals(NETCONF_DEF_MILLIS_STRING,converter.getTimeStampAsNetconfString(dt)); - } + + @Test + public void testMillis() { + long millis = converter.getTimeStampFromNetconfAsMilliseconds(NETCONF_DEF_MILLIS_STRING); + assertEquals(NETCONF_DEF_MILLIS_LONG, millis); + + } + + @Test(expected = IllegalArgumentException.class) + public void testMillisMalformed() { + long millis = converter.getTimeStampFromNetconfAsMilliseconds(NETCONF_DEF_MILLIS_STRING_MALFORMAED); + + } + + @Test + public void test2() { + assertEquals(NETCONF_DEF_MILLIS_STRING, converter.getTimeStampFromNetconf(NETCONF_DEF2_MILLIS_STRING)); + assertEquals(NETCONF_DEF3_MILLIS_STRING_CORRECTED, + converter.getTimeStampFromNetconf(NETCONF_DEF3_MILLIS_STRING)); + assertTrue(converter.getTimeStampFromNetconf(NETCONF_DEF4_MILLIS_STRING_MALFORMAED).startsWith("Malformed")); + } + + @Test + public void test3() { + Date dt = converter.getDateFromNetconf(NETCONF_DEF_MILLIS_STRING); + final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + c.setTime(dt); + assertEquals(2020, c.get(Calendar.YEAR)); + assertEquals(0, c.get(Calendar.MONTH)); + assertEquals(9, c.get(Calendar.DAY_OF_MONTH)); + assertEquals(5, c.get(Calendar.HOUR_OF_DAY)); + assertEquals(40, c.get(Calendar.MINUTE)); + assertEquals(41, c.get(Calendar.SECOND)); + assertEquals(100, c.get(Calendar.MILLISECOND)); + + + assertEquals(NETCONF_DEF_MILLIS_STRING, converter.getTimeStampAsNetconfString(dt)); + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNuMappings.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNuMappings.java index a21b01b28..f9c8812a8 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNuMappings.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestNuMappings.java @@ -38,13 +38,13 @@ public class TestNuMappings { Faultcurrent c = new FaultcurrentBuilder().setSeverity(SeverityType.Critical).build(); YangToolsMapper mapper = new YangToolsMapper(); try { - System.out.println(mapper.writeValueAsString(c)+"<=>"+SeverityType.Critical.getName()); + System.out.println(mapper.writeValueAsString(c) + "<=>" + SeverityType.Critical.getName()); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { - Faultcurrent f=mapper.readValue( "{\"severity\":\"Critical\"}", Faultcurrent.class); + Faultcurrent f = mapper.readValue("{\"severity\":\"Critical\"}", Faultcurrent.class); System.out.println(f); System.out.println(mapper.writeValueAsString(f)); } catch (JsonParseException e) { diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestTimestampFilter.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestTimestampFilter.java index a71bfc824..39377d730 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestTimestampFilter.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestTimestampFilter.java @@ -36,121 +36,138 @@ 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.rev190801.entity.input.FilterBuilder; public class TestTimestampFilter { - - @Test - public void testTimestampRange() { - final String PROPERTY_TIMESTAMP = "timestamp"; - List filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2017*").build()); - QueryBuilder query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2017-01-01T00:00:00.0Z", "2018-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2000-01-01T00:00:00.0Z", "3000-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("20*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2000-01-01T00:00:00.0Z", "2100-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("205*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-01-01T00:00:00.0Z", "2060-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-01-01T00:00:00.0Z", "2051-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-01-01T00:00:00.0Z", "2051-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-1*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2051-01-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2050-11-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2050-11-01T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-0*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2050-10-10T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-02*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-02T00:00:00.0Z", "2050-10-03T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T00:00:00.0Z", "2050-10-15T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T00:00:00.0Z", "2050-10-15T00:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T1*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T10:00:00.0Z", "2050-10-14T20:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:00:00.0Z", "2050-10-14T13:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:00:00.0Z", "2050-10-14T13:00:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:4*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:40:00.0Z", "2050-10-14T12:50:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:00.0Z", "2050-10-14T12:43:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42:*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:00.0Z", "2050-10-14T12:43:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42:5*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:50.0Z", "2050-10-14T12:43:00.0Z"); - - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42:56*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:56.0Z", "2050-10-14T12:42:57.0Z"); - } - - @Test - public void testExtra() { - final String PROPERTY_TIMESTAMP = "end"; - List filters = null; - QueryBuilder query= null; - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2020-02-19T*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2020-02-19T00:00:00.0Z", "2020-02-20T00:00:00.0Z"); - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2020-02-19*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2020-02-19T00:00:00.0Z", "2020-02-20T00:00:00.0Z"); - filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2020*").build()); - query= QueryByFilter.fromFilter(filters ); - assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2020-01-01T00:00:00.0Z", "2021-01-01T00:00:00.0Z"); - - } - private void assertRange(JSONObject rangeQuery,String property,String lower,String upper) { - System.out.println("==test for "+rangeQuery.toString()); - assertTrue(rangeQuery.has("range")); - assertTrue(rangeQuery.getJSONObject("range").has(property)); - JSONObject o=rangeQuery.getJSONObject("range").getJSONObject(property); - assertNotNull(o); - assertTrue(o.has("lt")); - assertEquals(upper, o.getString("lt")); - assertTrue(o.has("gte")); - assertEquals(lower, o.getString("gte")); - System.out.println("succeeded"); - } + + @Test + public void testTimestampRange() { + final String PROPERTY_TIMESTAMP = "timestamp"; + List filters = + Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2017*").build()); + QueryBuilder query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2017-01-01T00:00:00.0Z", "2018-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2000-01-01T00:00:00.0Z", "3000-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("20*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2000-01-01T00:00:00.0Z", "2100-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("205*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-01-01T00:00:00.0Z", "2060-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-01-01T00:00:00.0Z", "2051-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-01-01T00:00:00.0Z", "2051-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-1*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2051-01-01T00:00:00.0Z"); + + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2050-11-01T00:00:00.0Z"); + + filters = + Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2050-11-01T00:00:00.0Z"); + + filters = + Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-0*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-01T00:00:00.0Z", "2050-10-10T00:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-02*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-02T00:00:00.0Z", "2050-10-03T00:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T00:00:00.0Z", "2050-10-15T00:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T00:00:00.0Z", "2050-10-15T00:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T1*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T10:00:00.0Z", "2050-10-14T20:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:00:00.0Z", "2050-10-14T13:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:00:00.0Z", "2050-10-14T13:00:00.0Z"); + + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:4*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:40:00.0Z", "2050-10-14T12:50:00.0Z"); + + filters = Arrays.asList( + new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:00.0Z", "2050-10-14T12:43:00.0Z"); + + filters = Arrays.asList( + new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42:*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:00.0Z", "2050-10-14T12:43:00.0Z"); + + filters = Arrays.asList( + new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42:5*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:50.0Z", "2050-10-14T12:43:00.0Z"); + + filters = Arrays.asList( + new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2050-10-14T12:42:56*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2050-10-14T12:42:56.0Z", "2050-10-14T12:42:57.0Z"); + } + + @Test + public void testExtra() { + final String PROPERTY_TIMESTAMP = "end"; + List filters = null; + QueryBuilder query = null; + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2020-02-19T*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2020-02-19T00:00:00.0Z", "2020-02-20T00:00:00.0Z"); + filters = Arrays + .asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2020-02-19*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2020-02-19T00:00:00.0Z", "2020-02-20T00:00:00.0Z"); + filters = Arrays.asList(new FilterBuilder().setProperty(PROPERTY_TIMESTAMP).setFiltervalue("2020*").build()); + query = QueryByFilter.fromFilter(filters); + assertRange(query.getInner(), PROPERTY_TIMESTAMP, "2020-01-01T00:00:00.0Z", "2021-01-01T00:00:00.0Z"); + + } + + private void assertRange(JSONObject rangeQuery, String property, String lower, String upper) { + System.out.println("==test for " + rangeQuery.toString()); + assertTrue(rangeQuery.has("range")); + assertTrue(rangeQuery.getJSONObject("range").has(property)); + JSONObject o = rangeQuery.getJSONObject("range").getJSONObject(property); + assertNotNull(o); + assertTrue(o.has("lt")); + assertEquals(upper, o.getString("lt")); + assertTrue(o.has("gte")); + assertEquals(lower, o.getString("gte")); + System.out.println("succeeded"); + } } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangCloning.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangCloning.java index f9267179b..ac97cfe0e 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangCloning.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangCloning.java @@ -22,7 +22,7 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.test; public class TestYangCloning { -/* + /* @Test public void testEquipment() { EquipmentBuilder equipmentBuilder = new EquipmentBuilder(); @@ -35,20 +35,20 @@ public class TestYangCloning { Equipment equipment = equipmentBuilder.build(); InventoryEntity output = YangToolsCloner.instance().cloneToBuilder(equipment, new InventoryBuilder()) .setNodeId("node1").setUuid("a.a.a").setId("node1"+"/"+"a.a.a").build(); - - + + System.out.println("source:"); System.out.println(equipment); System.out.println("result:"); System.out.println(output); - - + + } @Test public void testFaultCurrent() { ProblemNotificationXml source = new ProblemNotificationXml("node", "uuid", "problem", InternalSeverity.Critical,54,InternalDateAndTime.getTestpattern()); FaultcurrentEntity output = YangToolsCloner.instance().clone(source,Faultcurrent.class); - + System.out.println("source:"); System.out.println(source); System.out.println("result:"); diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangGenSalMapping.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangGenSalMapping.java index 2561a670b..4a0834248 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangGenSalMapping.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangGenSalMapping.java @@ -80,9 +80,10 @@ public class TestYangGenSalMapping { loginPasswordBuilder.setPassword("myTestPassword"); netconfNodeBuilder.setCredentials(loginPasswordBuilder.build()); - OdlHelloMessageCapabilitiesBuilder odlHelloMessageCapabilitiesBuilder = new OdlHelloMessageCapabilitiesBuilder(); + OdlHelloMessageCapabilitiesBuilder odlHelloMessageCapabilitiesBuilder = + new OdlHelloMessageCapabilitiesBuilder(); List uriList = new ArrayList<>(); - uriList.add( new Uri("test.uri") ); + uriList.add(new Uri("test.uri")); odlHelloMessageCapabilitiesBuilder.setCapability(uriList); netconfNodeBuilder.setOdlHelloMessageCapabilities(odlHelloMessageCapabilitiesBuilder.build()); @@ -98,7 +99,7 @@ public class TestYangGenSalMapping { NetconfNode generatedNode = mapper.readValue(res.getBytes(), NetconfNode.class); out(generatedNode.toString()); // Print it with specified indentation // Compare result - out("Equal? "+netconfNode.equals(generatedNode)); + out("Equal? " + netconfNode.equals(generatedNode)); } static class TestDataObjectBuilder implements Builder { @@ -118,20 +119,22 @@ public class TestYangGenSalMapping { } @Test - public void test2() throws ClassNotFoundException { + public void test2() throws ClassNotFoundException { - int databasePort = Integer.valueOf(System.getProperty("databaseport")!=null?System.getProperty("databaseport"):"49200"); - System.out.println("DB Port: "+databasePort); + int databasePort = Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"); + System.out.println("DB Port: " + databasePort); - HostInfo[] HOSTINFOS = new HostInfo[] { new HostInfo("localhost", databasePort ,Protocol.HTTP)}; + HostInfo[] HOSTINFOS = new HostInfo[] {new HostInfo("localhost", databasePort, Protocol.HTTP)}; DatabaseClient db = new HtDatabaseClient(HOSTINFOS); EsDataObjectReaderWriter dataRW = - new EsDataObjectReaderWriter<>(db, "inventorytest", org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.Data.class); + new EsDataObjectReaderWriter<>(db, "inventorytest", + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.Data.class); org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.Data d1; d1 = getInventoryDataBuilder("MyDescription", 23L).build(); - String id = dataRW.write(d1,null); + String id = dataRW.write(d1, null); org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.Data d2; d2 = dataRW.read(id); @@ -141,7 +144,7 @@ public class TestYangGenSalMapping { } @Test - public void test3() throws IOException { + public void test3() throws IOException { PerformanceDataBuilder performanceBuilder = new PerformanceDataBuilder(); performanceBuilder.setEs(99); @@ -190,59 +193,29 @@ public class TestYangGenSalMapping { @Test public void test5() throws IOException { - String jsonString = "{\n" + - " \"time-stamp\": \"2017-03-01T06:45:00.0Z\",\n" + - " \"node-name\": \"Sim2230\",\n" + - " \"uuid-interface\": \"LP-MWPS-TTP-RADIO\",\n" + - " \"scanner-id\": \"PM_RADIO_15M_14\",\n" + - " \"layer-protocol-name\": \"MWPS\",\n" + - " \"granularity-period\": \"Period15Min\",\n" + - " \"radio-signal-id\": \"Test8\",\n" + - " \"suspect-interval-flag\": false,\n" + - " \"performance-data\": {\n" + - " \"time4096-states-l\": -1,\n" + - " \"time16-states-s\": -1,\n" + - " \"tx-level-max\": 3,\n" + - " \"snir-max\": -99,\n" + - " \"time16-states\": 0,\n" + - " \"time64-states\": 900,\n" + - " \"unavailability\": 0,\n" + - " \"time8192-states-l\": -1,\n" + - " \"time512-states\": -1,\n" + - " \"xpd-min\": -99,\n" + - " \"xpd-avg\": -99,\n" + - " \"tx-level-avg\": 3,\n" + - " \"tx-level-min\": 3,\n" + - " \"rf-temp-min\": -99,\n" + - " \"rf-temp-avg\": -99,\n" + - " \"snir-avg\": -99,\n" + - " \"snir-min\": -99,\n" + - " \"time-period\": 900,\n" + - " \"time2-states\": 0,\n" + - " \"time4-states\": 0,\n" + - " \"time8-states\": -1,\n" + - " \"ses\": 0,\n" + - " \"time2048-states-l\": -1,\n" + - " \"time2048-states\": -1,\n" + - " \"xpd-max\": -99,\n" + - " \"rf-temp-max\": -99,\n" + - " \"time8192-states\": -1,\n" + - " \"time128-states\": -1,\n" + - " \"time256-states\": -1,\n" + - " \"rx-level-min\": -44,\n" + - " \"rx-level-avg\": -44,\n" + - " \"time1024-states-l\": -1,\n" + - " \"es\": 0,\n" + - " \"cses\": 0,\n" + - " \"time4-states-s\": 0,\n" + - " \"time1024-states\": -1,\n" + - " \"time512-states-l\": -1,\n" + - " \"time4096-states\": -1,\n" + - " \"rx-level-max\": -45,\n" + - " \"defect-blocks-sum\": -1,\n" + - " \"time32-states\": -1\n" + - " }\n" + - "}"; + String jsonString = "{\n" + " \"time-stamp\": \"2017-03-01T06:45:00.0Z\",\n" + + " \"node-name\": \"Sim2230\",\n" + " \"uuid-interface\": \"LP-MWPS-TTP-RADIO\",\n" + + " \"scanner-id\": \"PM_RADIO_15M_14\",\n" + " \"layer-protocol-name\": \"MWPS\",\n" + + " \"granularity-period\": \"Period15Min\",\n" + " \"radio-signal-id\": \"Test8\",\n" + + " \"suspect-interval-flag\": false,\n" + " \"performance-data\": {\n" + + " \"time4096-states-l\": -1,\n" + " \"time16-states-s\": -1,\n" + + " \"tx-level-max\": 3,\n" + " \"snir-max\": -99,\n" + " \"time16-states\": 0,\n" + + " \"time64-states\": 900,\n" + " \"unavailability\": 0,\n" + + " \"time8192-states-l\": -1,\n" + " \"time512-states\": -1,\n" + + " \"xpd-min\": -99,\n" + " \"xpd-avg\": -99,\n" + " \"tx-level-avg\": 3,\n" + + " \"tx-level-min\": 3,\n" + " \"rf-temp-min\": -99,\n" + + " \"rf-temp-avg\": -99,\n" + " \"snir-avg\": -99,\n" + " \"snir-min\": -99,\n" + + " \"time-period\": 900,\n" + " \"time2-states\": 0,\n" + + " \"time4-states\": 0,\n" + " \"time8-states\": -1,\n" + " \"ses\": 0,\n" + + " \"time2048-states-l\": -1,\n" + " \"time2048-states\": -1,\n" + + " \"xpd-max\": -99,\n" + " \"rf-temp-max\": -99,\n" + + " \"time8192-states\": -1,\n" + " \"time128-states\": -1,\n" + + " \"time256-states\": -1,\n" + " \"rx-level-min\": -44,\n" + + " \"rx-level-avg\": -44,\n" + " \"time1024-states-l\": -1,\n" + " \"es\": 0,\n" + + " \"cses\": 0,\n" + " \"time4-states-s\": 0,\n" + " \"time1024-states\": -1,\n" + + " \"time512-states-l\": -1,\n" + " \"time4096-states\": -1,\n" + + " \"rx-level-max\": -45,\n" + " \"defect-blocks-sum\": -1,\n" + + " \"time32-states\": -1\n" + " }\n" + "}"; // Map to JSON String to Object Data generatedNode = mapper.readValue(jsonString.getBytes(), Data.class); @@ -254,11 +227,12 @@ public class TestYangGenSalMapping { @Test public void test6() throws IOException, ClassNotFoundException { out(method()); - HtDatabaseClient dbClient = new HtDatabaseClient(new HostInfo[] { new HostInfo("sdnrdb", 9200, Protocol.HTTP) }); + HtDatabaseClient dbClient = new HtDatabaseClient(new HostInfo[] {new HostInfo("sdnrdb", 9200, Protocol.HTTP)}); String PMDATA15M_TYPE = "historicalperformance15min"; EsDataObjectReaderWriter pm15mRW = - new EsDataObjectReaderWriter<>(dbClient, PMDATA15M_TYPE, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.Data.class); + new EsDataObjectReaderWriter<>(dbClient, PMDATA15M_TYPE, + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.Data.class); pm15mRW.setEsIdAttributeName("_nodeName"); ReadPmdata15mListInputBuilder inputBuilder = new ReadPmdata15mListInputBuilder(); @@ -277,12 +251,13 @@ public class TestYangGenSalMapping { QueryBuilder query = fromFilter(input.getFilter()).from((page - 1) * pageSize).size(pageSize); setSortOrder(query, input.getSortorder()); - SearchResult result=pm15mRW.doReadAll(query); + SearchResult result = + pm15mRW.doReadAll(query); - out("Found: "+result.getHits().size()); - int t=0; + out("Found: " + result.getHits().size()); + int t = 0; for (Data hit : result.getHits()) { - out("Hit "+t+++":"+hit); + out("Hit " + t++ + ":" + hit); } setPagination(outputBuilder, page, pageSize, result.getTotal()); outputBuilder.setData(result.getHits()); @@ -292,19 +267,20 @@ public class TestYangGenSalMapping { public void test7() throws IOException, ClassNotFoundException { out(method()); String ESDATATYPE_MEDIATORSERVER = Entity.MediatorServer.getName(); - HtDatabaseClient dbClient = new HtDatabaseClient(new HostInfo[] { new HostInfo("sdnrdb", 9200, Protocol.HTTP) }); + HtDatabaseClient dbClient = new HtDatabaseClient(new HostInfo[] {new HostInfo("sdnrdb", 9200, Protocol.HTTP)}); EsDataObjectReaderWriter mediatorserverRW; mediatorserverRW = new EsDataObjectReaderWriter<>(dbClient, ESDATATYPE_MEDIATORSERVER, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.mediator.server.list.output.Data.class) - .setWriteInterface(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MediatorServerEntity.class) - .setEsIdAttributeName("_id"); + .setWriteInterface( + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.MediatorServerEntity.class) + .setEsIdAttributeName("_id"); CreateMediatorServerInputBuilder inputBuilder = new CreateMediatorServerInputBuilder(); inputBuilder.setName("Hans"); inputBuilder.setUrl("MyGreatUrl"); - String id = mediatorserverRW.write(inputBuilder.build(),"testid"); + String id = mediatorserverRW.write(inputBuilder.build(), "testid"); System.out.println(id); } @@ -314,15 +290,15 @@ public class TestYangGenSalMapping { out(method()); String input; input = "id-dd-dd"; - System.out.println("Map " + input + " to "+YangToolsMapper.toCamelCaseAttributeName(input)); + System.out.println("Map " + input + " to " + YangToolsMapper.toCamelCaseAttributeName(input)); input = "idDdGg"; - System.out.println("Map " + input + " to "+YangToolsMapper.toCamelCaseAttributeName(input)); + System.out.println("Map " + input + " to " + YangToolsMapper.toCamelCaseAttributeName(input)); input = "_idDdGg"; - System.out.println("Map " + input + " to "+YangToolsMapper.toCamelCaseAttributeName(input)); + System.out.println("Map " + input + " to " + YangToolsMapper.toCamelCaseAttributeName(input)); input = "--ff--gfg"; - System.out.println("Map " + input + " to "+YangToolsMapper.toCamelCaseAttributeName(input)); + System.out.println("Map " + input + " to " + YangToolsMapper.toCamelCaseAttributeName(input)); input = ""; - System.out.println("Map " + input + " to "+YangToolsMapper.toCamelCaseAttributeName(input)); + System.out.println("Map " + input + " to " + YangToolsMapper.toCamelCaseAttributeName(input)); } /* --------------------------------- @@ -333,7 +309,8 @@ public class TestYangGenSalMapping { return nameofCurrMethod; } - private org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.DataBuilder getInventoryDataBuilder(String description, long treeLevel) { + private org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.DataBuilder getInventoryDataBuilder( + String description, long treeLevel) { org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.DataBuilder dataBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.inventory.list.output.DataBuilder(); dataBuilder.setDescription(description); @@ -371,10 +348,9 @@ public class TestYangGenSalMapping { if (filters == null || filters.size() == 0) { return QueryBuilders.matchAllQuery(); - } else if(filters.size()==1){ + } else if (filters.size() == 1) { return QueryBuilders.matchQuery(filters.get(0).getProperty(), filters.get(0).getFiltervalue()); - } - else { + } else { BoolQueryBuilder query = new BoolQueryBuilder(); for (Filter fi : filters) { query.must(QueryBuilders.matchQuery((prefix != null ? prefix : "") + fi.getProperty(), @@ -384,6 +360,7 @@ public class TestYangGenSalMapping { } } + private static QueryBuilder setSortOrder(QueryBuilder query, @Nullable List sortorder) { return setSortOrder(query, sortorder, ""); } @@ -401,9 +378,12 @@ public class TestYangGenSalMapping { } - private static void setPagination(ReadPmdata15mListOutputBuilder outputBuilder, long page, long pageSize, long totalSize) { - org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.Pagination value = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.PaginationBuilder() - .setPage(BigInteger.valueOf(page)).setSize(pageSize).setTotal(BigInteger.valueOf(totalSize)).build(); + private static void setPagination(ReadPmdata15mListOutputBuilder outputBuilder, long page, long pageSize, + long totalSize) { + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.Pagination value = + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev190801.read.pmdata._15m.list.output.PaginationBuilder() + .setPage(BigInteger.valueOf(page)).setSize(pageSize).setTotal(BigInteger.valueOf(totalSize)) + .build(); outputBuilder.setPagination(value); } diff --git a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangProvider.java b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangProvider.java index 7341d5a33..19bd76cae 100644 --- a/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangProvider.java +++ b/sdnr/wt/data-provider/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/test/TestYangProvider.java @@ -55,145 +55,150 @@ import static org.mockito.Mockito.when; public class TestYangProvider { - private static final String TESTPATH = "cache/schema/"; - - - @BeforeClass - public static void init() { - Set perms; - FileAttribute attr; - perms = EnumSet.noneOf(PosixFilePermission.class); - - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_WRITE); - perms.add(PosixFilePermission.OWNER_EXECUTE); - - attr = PosixFilePermissions.asFileAttribute(perms); - try { - Files.createDirectories(new File(TESTPATH).toPath(),attr); - new File(TESTPATH+new YangFilename("module1","2010-01-01").getFilename()).createNewFile(); - new File(TESTPATH+new YangFilename("module2","2010-01-01").getFilename()).createNewFile(); - new File(TESTPATH+new YangFilename("module2","2010-04-01").getFilename()).createNewFile(); - new File(TESTPATH+new YangFilename("module3","2010-01-01").getFilename()).createNewFile(); - new File(TESTPATH+new YangFilename("module4","2010-05-01").getFilename()).createNewFile(); - new File(TESTPATH+new YangFilename("module5","2010-01-11").getFilename()).createNewFile(); - new File(TESTPATH+new YangFilename("module6","2010-01-01").getFilename()).createNewFile(); - } catch (IOException | ParseException e) { - - } - } - @AfterClass - public static void deinit() { - try { - Files.walk(new File("cache").toPath()) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } catch (IOException e) { - System.err.println(e); - } - } - @Test - public void testExisting() { - YangFileProvider provider= new YangFileProvider(TESTPATH); - assertTrue(provider.hasFileForModule("module1","2010-01-01")); - assertTrue(provider.hasFileForModule("module2")); - assertTrue(provider.hasFileForModule("module3")); - assertFalse(provider.hasFileForModule("module5","2010-01-01")); - } - @Test - public void testRevision() throws ParseException { - SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd"); - YangFileProvider provider= new YangFileProvider(TESTPATH); - YangFilename f1 = provider.getFileForModule("module1","2010-01-01"); - assertEquals("module1",f1.getModule()); - assertEquals(sdf.parse("2010-01-01"),f1.getRevision()); - YangFilename f2 = provider.getFileForModule("module2"); - assertEquals("module2",f2.getModule()); - assertEquals(sdf.parse("2010-04-01"),f2.getRevision()); - f2 = provider.getFileForModule("module2","2010-02-01"); - assertEquals("module2",f2.getModule()); - assertEquals(sdf.parse("2010-04-01"),f2.getRevision()); - YangFilename f3 = provider.getFileForModule("module3"); - assertEquals("module3",f3.getModule()); - assertEquals(sdf.parse("2010-01-01"),f3.getRevision()); - f3 = provider.getFileForModule("module3","2010-04-01"); - assertNull(f3); - } - @Test - public void testServlet() throws IOException, ServletException { - HelpYangSchemaHttpServlet servlet = new HelpYangSchemaHttpServlet(); - HttpServletRequest req = mock(HttpServletRequest.class); - HttpServletResponse resp = mock(HttpServletResponse.class); - - when(req.getRequestURI()).thenReturn("/yang-schema/module1"); - StringWriter out = new StringWriter(); - ServletOutputStream printOut = new ServletOutputStream() { - - @Override - public void write(int arg0) throws IOException { - out.write(arg0); - } - }; - when(resp.getOutputStream()).thenReturn(printOut); - servlet.doGet(req,resp); - verify(resp).setStatus(200); - verify(resp).setContentType("text/plain"); - - } - @Test - public void testServletBad() throws IOException, ServletException { - HelpYangSchemaHttpServlet servlet = new HelpYangSchemaHttpServlet(); - HttpServletRequest req = mock(HttpServletRequest.class); - HttpServletResponse resp = mock(HttpServletResponse.class); - - when(req.getRequestURI()).thenReturn("/yang-schema/module1/2020-01-01"); - StringWriter out = new StringWriter(); - ServletOutputStream printOut = new ServletOutputStream() { - - @Override - public void write(int arg0) throws IOException { - out.write(arg0); - } - }; - when(resp.getOutputStream()).thenReturn(printOut); - servlet.doGet(req,resp); - verify(resp).sendError(HttpServletResponse.SC_NOT_FOUND); - - } - @Test - public void testServletNear() throws IOException, ServletException { - HelpYangSchemaHttpServlet servlet = new HelpYangSchemaHttpServlet(); - HttpServletRequest req = mock(HttpServletRequest.class); - HttpServletResponse resp = mock(HttpServletResponse.class); - - when(req.getRequestURI()).thenReturn("/yang-schema/module2/2010-03-01"); - StringWriter out = new StringWriter(); - ServletOutputStream printOut = new ServletOutputStream() { - - @Override - public void write(int arg0) throws IOException { - out.write(arg0); - } - }; - when(resp.getOutputStream()).thenReturn(printOut); - servlet.doGet(req,resp); - verify(resp).setStatus(200); - verify(resp).setContentType("text/plain"); - - } - private static class HelpYangSchemaHttpServlet extends YangSchemaHttpServlet{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); - } - } + private static final String TESTPATH = "cache/schema/"; + + + @BeforeClass + public static void init() { + Set perms; + FileAttribute attr; + perms = EnumSet.noneOf(PosixFilePermission.class); + + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_WRITE); + perms.add(PosixFilePermission.OWNER_EXECUTE); + + attr = PosixFilePermissions.asFileAttribute(perms); + try { + Files.createDirectories(new File(TESTPATH).toPath(), attr); + new File(TESTPATH + new YangFilename("module1", "2010-01-01").getFilename()).createNewFile(); + new File(TESTPATH + new YangFilename("module2", "2010-01-01").getFilename()).createNewFile(); + new File(TESTPATH + new YangFilename("module2", "2010-04-01").getFilename()).createNewFile(); + new File(TESTPATH + new YangFilename("module3", "2010-01-01").getFilename()).createNewFile(); + new File(TESTPATH + new YangFilename("module4", "2010-05-01").getFilename()).createNewFile(); + new File(TESTPATH + new YangFilename("module5", "2010-01-11").getFilename()).createNewFile(); + new File(TESTPATH + new YangFilename("module6", "2010-01-01").getFilename()).createNewFile(); + } catch (IOException | ParseException e) { + + } + } + + @AfterClass + public static void deinit() { + try { + Files.walk(new File("cache").toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile) + .forEach(File::delete); + } catch (IOException e) { + System.err.println(e); + } + } + + @Test + public void testExisting() { + YangFileProvider provider = new YangFileProvider(TESTPATH); + assertTrue(provider.hasFileForModule("module1", "2010-01-01")); + assertTrue(provider.hasFileForModule("module2")); + assertTrue(provider.hasFileForModule("module3")); + assertFalse(provider.hasFileForModule("module5", "2010-01-01")); + } + + @Test + public void testRevision() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + YangFileProvider provider = new YangFileProvider(TESTPATH); + YangFilename f1 = provider.getFileForModule("module1", "2010-01-01"); + assertEquals("module1", f1.getModule()); + assertEquals(sdf.parse("2010-01-01"), f1.getRevision()); + YangFilename f2 = provider.getFileForModule("module2"); + assertEquals("module2", f2.getModule()); + assertEquals(sdf.parse("2010-04-01"), f2.getRevision()); + f2 = provider.getFileForModule("module2", "2010-02-01"); + assertEquals("module2", f2.getModule()); + assertEquals(sdf.parse("2010-04-01"), f2.getRevision()); + YangFilename f3 = provider.getFileForModule("module3"); + assertEquals("module3", f3.getModule()); + assertEquals(sdf.parse("2010-01-01"), f3.getRevision()); + f3 = provider.getFileForModule("module3", "2010-04-01"); + assertNull(f3); + } + + @Test + public void testServlet() throws IOException, ServletException { + HelpYangSchemaHttpServlet servlet = new HelpYangSchemaHttpServlet(); + HttpServletRequest req = mock(HttpServletRequest.class); + HttpServletResponse resp = mock(HttpServletResponse.class); + + when(req.getRequestURI()).thenReturn("/yang-schema/module1"); + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + when(resp.getOutputStream()).thenReturn(printOut); + servlet.doGet(req, resp); + verify(resp).setStatus(200); + verify(resp).setContentType("text/plain"); + + } + + @Test + public void testServletBad() throws IOException, ServletException { + HelpYangSchemaHttpServlet servlet = new HelpYangSchemaHttpServlet(); + HttpServletRequest req = mock(HttpServletRequest.class); + HttpServletResponse resp = mock(HttpServletResponse.class); + + when(req.getRequestURI()).thenReturn("/yang-schema/module1/2020-01-01"); + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + when(resp.getOutputStream()).thenReturn(printOut); + servlet.doGet(req, resp); + verify(resp).sendError(HttpServletResponse.SC_NOT_FOUND); + + } + + @Test + public void testServletNear() throws IOException, ServletException { + HelpYangSchemaHttpServlet servlet = new HelpYangSchemaHttpServlet(); + HttpServletRequest req = mock(HttpServletRequest.class); + HttpServletResponse resp = mock(HttpServletResponse.class); + + when(req.getRequestURI()).thenReturn("/yang-schema/module2/2010-03-01"); + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + when(resp.getOutputStream()).thenReturn(printOut); + servlet.doGet(req, resp); + verify(resp).setStatus(200); + verify(resp).setContentType("text/plain"); + + } + + private static class HelpYangSchemaHttpServlet extends YangSchemaHttpServlet { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doGet(req, resp); + } + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderImpl.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderImpl.java index a336c0f6f..821e3ec1e 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderImpl.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderImpl.java @@ -62,14 +62,15 @@ import org.slf4j.LoggerFactory; public class DataMigrationProviderImpl implements DataMigrationProviderService { - + private static final Logger LOG = LoggerFactory.getLogger(DataMigrationProviderImpl.class); private final HtDatabaseClient dbClient; - public DataMigrationProviderImpl(HostInfo[] hosts, String username, String password, boolean trustAll, long timeoutms) { + public DataMigrationProviderImpl(HostInfo[] hosts, String username, String password, boolean trustAll, + long timeoutms) { - if(timeoutms>0) { - Portstatus.waitSecondsTillAvailable(timeoutms/1000, hosts); + if (timeoutms > 0) { + Portstatus.waitSecondsTillAvailable(timeoutms / 1000, hosts); } this.dbClient = new HtDatabaseClient(hosts, username, password, trustAll); } @@ -148,8 +149,7 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { /** - * export data - * if file exists .1 (.n) will be created + * export data if file exists .1 (.n) will be created * */ @Override @@ -162,17 +162,17 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { LOG.info("output will be written to {}", filename); //autodetect version Release dbRelease = this.autoDetectRelease(); - if(dbRelease==null) { + if (dbRelease == null) { report.error("unbable to detect db release. is database initialized?"); return report; } ReleaseInformation ri = ReleaseInformation.getInstance(dbRelease); boolean componentsSucceeded = true; - for(ComponentName c: ri.getComponents()) { + for (ComponentName c : ri.getComponents()) { ComponentData data = new ComponentData(c); - SearchResult result = this.dbClient.doReadAllJsonData(ri.getAlias(c),ri.getDataType(c),false); + SearchResult result = this.dbClient.doReadAllJsonData(ri.getAlias(c), ri.getDataType(c), false); data.addAll(result.getHits()); - container.addComponent(c, data ); + container.addComponent(c, data); } try { Files.write(new File(filename).toPath(), Arrays.asList(container.toJSON()), StandardCharsets.UTF_8); @@ -192,7 +192,7 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { } private String checkFilenameForWrite(String filename, int apdx) { - File f = new File(String.format("$s.$d",filename,apdx)); + File f = new File(String.format("$s.$d", filename, apdx)); if (!f.exists()) { return filename; } @@ -209,18 +209,18 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { EsVersion dbVersion = this.readActualVersion(); AliasesEntryList aliases = this.readAliases(); IndicesEntryList indices = this.readIndices(); - if(indices==null) { + if (indices == null) { return null; } List foundReleases = new ArrayList<>(); //if there are active aliases reduce indices to the active ones - if(aliases!=null && aliases.size()>0) { + if (aliases != null && aliases.size() > 0) { indices = indices.subList(aliases.getLinkedIndices()); } - for(Release r:Release.values()) { - if(r.isDbInRange(dbVersion)) { + for (Release r : Release.values()) { + if (r.isDbInRange(dbVersion)) { ReleaseInformation ri = ReleaseInformation.getInstance(r); - if(ri!=null && ri.containsIndices(indices)) { + if (ri != null && ri.containsIndices(indices)) { foundReleases.add(r); } } @@ -228,9 +228,11 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { if (foundReleases.size() == 1) { return foundReleases.get(0); } - LOG.error("detect {} releases: {}. unable to detect for which one to do sth.",foundReleases.size(), foundReleases); + LOG.error("detect {} releases: {}. unable to detect for which one to do sth.", foundReleases.size(), + foundReleases); return null; } + private EsVersion readActualVersion() { try { GetInfoResponse response = this.dbClient.getInfo(); @@ -264,9 +266,9 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { } @Override - public boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, - boolean forceRecreate,long timeoutms) { - if(timeoutms>0) { + public boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, boolean forceRecreate, + long timeoutms) { + if (timeoutms > 0) { this.dbClient.waitForYellowStatus(timeoutms); } EsVersion dbVersion = this.readActualVersion(); @@ -278,7 +280,7 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { return false; } if (forceRecreate) { - this.clearDatabase(release, dbPrefix,0); + this.clearDatabase(release, dbPrefix, 0); } ReleaseInformation ri = ReleaseInformation.getInstance(release); AliasesEntryList aliases = this.readAliases(); @@ -287,7 +289,7 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { return false; } AcknowledgedResponse response = null; - if(!ri.runPreInitCommands(this.dbClient)) { + if (!ri.runPreInitCommands(this.dbClient)) { return false; } for (ComponentName component : ri.getComponents()) { @@ -320,7 +322,7 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { return false; } } - if(!ri.runPostInitCommands(this.dbClient)) { + if (!ri.runPostInitCommands(this.dbClient)) { return false; } return true; @@ -329,7 +331,7 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { @Override public boolean clearDatabase(Release release, String dbPrefix, long timeoutms) { - if(timeoutms>0) { + if (timeoutms > 0) { this.dbClient.waitForYellowStatus(timeoutms); } //check aliases @@ -349,9 +351,9 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { if (entryToDelete != null) { try { LOG.info("deleting alias {} for index {}", entryToDelete.getAlias(), entryToDelete.getIndex()); - response=this.dbClient.deleteAlias( + response = this.dbClient.deleteAlias( new DeleteAliasRequest(entryToDelete.getIndex(), entryToDelete.getAlias())); - LOG.info(response.isResponseSucceeded()?"succeeded":"failed"); + LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed"); } catch (IOException e) { LOG.error(e.getMessage()); return false; @@ -373,8 +375,8 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { if (entryToDelete != null) { try { LOG.info("deleting index {}", entryToDelete.getName()); - response=this.dbClient.deleteIndex(new DeleteIndexRequest(entryToDelete.getName())); - LOG.info(response.isResponseSucceeded()?"succeeded":"failed"); + response = this.dbClient.deleteIndex(new DeleteIndexRequest(entryToDelete.getName())); + LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed"); } catch (IOException e) { LOG.error(e.getMessage()); return false; @@ -386,39 +388,39 @@ public class DataMigrationProviderImpl implements DataMigrationProviderService { return true; } - /** - * @param timeoutms - * @return - */ - public boolean clearCompleteDatabase(long timeoutms) { - if(timeoutms>0) { + /** + * @param timeoutms + * @return + */ + public boolean clearCompleteDatabase(long timeoutms) { + if (timeoutms > 0) { this.dbClient.waitForYellowStatus(timeoutms); } //check aliases and indices - AliasesEntryList aliases = this.readAliases(); + AliasesEntryList aliases = this.readAliases(); IndicesEntryList indices = this.readIndices(); if (aliases == null || indices == null) { return false; } - for(AliasesEntry alias:aliases) { - try { - LOG.info("deleting alias {} for index {}",alias.getAlias(),alias.getIndex()); - this.dbClient.deleteAlias(new DeleteAliasRequest(alias.getIndex(), alias.getAlias())); - } catch (IOException e) { - LOG.error("problem deleting alias {}: {}",alias.getAlias(),e); - return false; - } - } - for(IndicesEntry index : indices) { - try { - LOG.info("deleting index {}",index.getName()); - this.dbClient.deleteIndex(new DeleteIndexRequest(index.getName())); - } catch (IOException e) { - LOG.error("problem deleting index {}: {}",index.getName(),e); - return false; - } + for (AliasesEntry alias : aliases) { + try { + LOG.info("deleting alias {} for index {}", alias.getAlias(), alias.getIndex()); + this.dbClient.deleteAlias(new DeleteAliasRequest(alias.getIndex(), alias.getAlias())); + } catch (IOException e) { + LOG.error("problem deleting alias {}: {}", alias.getAlias(), e); + return false; + } + } + for (IndicesEntry index : indices) { + try { + LOG.info("deleting index {}", index.getName()); + this.dbClient.deleteIndex(new DeleteIndexRequest(index.getName())); + } catch (IOException e) { + LOG.error("problem deleting index {}: {}", index.getName(), e); + return false; + } } return true; - } + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderService.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderService.java index 5a0ec3b6a..0f1fc6c73 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderService.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/DataMigrationProviderService.java @@ -29,43 +29,46 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release; public interface DataMigrationProviderService { - /** - * import data from file and write these to database - * @param filename source - * @param dryrun only loading file and check consistency, not pushing into database - * @return report - * @throws FileNotFoundException - * @throws Exception - */ - DataMigrationReport importData(String filename,boolean dryrun) throws FileNotFoundException, Exception; - /** - * export current data to file - * @param filename - */ - DataMigrationReport exportData(String filename); - - /** - * - * @return - */ - Release getCurrentVersion(); - - /** - * @param release - * @param numShards - * @param numReplicas - * @param dbPrefix - * @param forceRecreate - * @param timeoutms - * @return - */ - boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, boolean forceRecreate, - long timeoutms); - /** - * clean up the database - * all data will be removed - * complete structure will be destroyed - * @return - */ - boolean clearDatabase(Release release, String dbPrefix, long timeoutms); + /** + * import data from file and write these to database + * + * @param filename source + * @param dryrun only loading file and check consistency, not pushing into database + * @return report + * @throws FileNotFoundException + * @throws Exception + */ + DataMigrationReport importData(String filename, boolean dryrun) throws FileNotFoundException, Exception; + + /** + * export current data to file + * + * @param filename + */ + DataMigrationReport exportData(String filename); + + /** + * + * @return + */ + Release getCurrentVersion(); + + /** + * @param release + * @param numShards + * @param numReplicas + * @param dbPrefix + * @param forceRecreate + * @param timeoutms + * @return + */ + boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, boolean forceRecreate, + long timeoutms); + + /** + * clean up the database all data will be removed complete structure will be destroyed + * + * @return + */ + boolean clearDatabase(Release release, String dbPrefix, long timeoutms); } 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 d06ffe1ee..c7775a96b 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 @@ -43,7 +43,7 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release; */ public class Program { - // constants + // constants private static final String CMD_INITDB = "init"; private static final String CMD_CLEAR_DB = "delete"; private static final String CMD_CLEAR_DB_COMPLETE = "clear"; @@ -59,11 +59,11 @@ public class Program { private static final String CMD_EXPORT_DESCRIPTION = "export data from database"; private static final String CMD_LIST_VERSION_DESCRIPTION = "list release versions"; - private static final List commands = Arrays.asList(new String[] { CMD_INITDB, CMD_INITDB_DESCRIPTION }, - new String[] { CMD_CLEAR_DB, CMD_CLEAR_DB_DESCRIPTION }, - new String[] { CMD_CREATE_PLUGIN_INIT_FILE, CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION }, - new String[] { CMD_IMPORT, CMD_IMPORT_DESCRIPTION }, new String[] { CMD_EXPORT, CMD_EXPORT_DESCRIPTION }, - new String[] { CMD_LIST_VERSION, CMD_LIST_VERSION_DESCRIPTION }); + private static final List commands = Arrays.asList(new String[] {CMD_INITDB, CMD_INITDB_DESCRIPTION}, + new String[] {CMD_CLEAR_DB, CMD_CLEAR_DB_DESCRIPTION}, + new String[] {CMD_CREATE_PLUGIN_INIT_FILE, CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION}, + new String[] {CMD_IMPORT, CMD_IMPORT_DESCRIPTION}, new String[] {CMD_EXPORT, CMD_EXPORT_DESCRIPTION}, + new String[] {CMD_LIST_VERSION, CMD_LIST_VERSION_DESCRIPTION}); private static final String APPLICATION_NAME = "SDNR DataMigrationTool"; private static final int DEFAULT_SHARDS = 5; private static final int DEFAULT_REPLICAS = 1; @@ -81,24 +81,24 @@ public class Program { private static final String OPTION_TRUSTINSECURESSL_SHORT = "k"; private static final String OPTION_DATABASE_SHORT = "db"; private static final String OPTION_COMMAND_SHORT = "c"; - private static final String OPTION_DATABASEUSER_SHORT = "dbu"; - private static final String OPTION_DATABASEPASSWORD_SHORT = "dbp"; - private static final String OPTION_DATABASEPREFIX_SHORT = "p"; - private static final String OPTION_DATABASEWAIT_SHORT = "w"; - private static final String OPTION_HELP_SHORT = "h"; + private static final String OPTION_DATABASEUSER_SHORT = "dbu"; + private static final String OPTION_DATABASEPASSWORD_SHORT = "dbp"; + private static final String OPTION_DATABASEPREFIX_SHORT = "p"; + private static final String OPTION_DATABASEWAIT_SHORT = "w"; + private static final String OPTION_HELP_SHORT = "h"; // end of constants - - // variables + + // variables private static Options options = init(); private static Log LOG = null; // end of variables - + // public methods public static void main(String[] args) { - System.exit( main2(args) ); + System.exit(main2(args)); } // end of public methods - + // private methods @SuppressWarnings("unchecked") private static T getOptionOrDefault(CommandLine cmd, String option, T def) throws ParseException { @@ -156,7 +156,7 @@ public class Program { CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; - + try { cmd = parser.parse(options, args); } catch (ParseException e) { @@ -175,72 +175,72 @@ public class Program { } try { - if(getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) { - printHelp(formatter); - return 0; - } - } catch (ParseException e2) { - return exit(e2); - } + if (getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) { + printHelp(formatter); + return 0; + } + } catch (ParseException e2) { + return exit(e2); + } final String command = cmd.getOptionValue(OPTION_COMMAND_SHORT); - if(command==null) { - printHelp(formatter); + if (command == null) { + printHelp(formatter); return 1; } switch (command) { - case CMD_INITDB: - try { - cmd_init_db(cmd); - } catch (Exception e1) { - return exit(e1); - } - break; - case CMD_CLEAR_DB: - try { - cmd_clear_db(cmd); - } catch (Exception e1) { - return exit(e1); - } - break; - case CMD_CLEAR_DB_COMPLETE: - try { - cmd_clear_db_complete(cmd); - } catch (Exception e1) { - return exit(e1); - } - break; - case CMD_CREATE_PLUGIN_INIT_FILE: - try { - String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null); - if (of == null) { - throw new Exception("please add the parameter output-file"); + case CMD_INITDB: + try { + cmd_init_db(cmd); + } catch (Exception e1) { + return exit(e1); } - MavenDatabasePluginInitFile.create(Release.CURRENT_RELEASE, of); - } catch (Exception e) { - return exit(e); - } - break; - case CMD_IMPORT: - try { - cmd_dbimport(cmd); - } catch (Exception e1) { - return exit(e1); - } - break; - case CMD_EXPORT: - try { - cmd_dbexport(cmd); - } catch (Exception e) { - return exit(e); - } - break; - case CMD_LIST_VERSION: - cmd_listversion(); - break; + break; + case CMD_CLEAR_DB: + try { + cmd_clear_db(cmd); + } catch (Exception e1) { + return exit(e1); + } + break; + case CMD_CLEAR_DB_COMPLETE: + try { + cmd_clear_db_complete(cmd); + } catch (Exception e1) { + return exit(e1); + } + break; + case CMD_CREATE_PLUGIN_INIT_FILE: + try { + String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null); + if (of == null) { + throw new Exception("please add the parameter output-file"); + } + MavenDatabasePluginInitFile.create(Release.CURRENT_RELEASE, of); + } catch (Exception e) { + return exit(e); + } + break; + case CMD_IMPORT: + try { + cmd_dbimport(cmd); + } catch (Exception e1) { + return exit(e1); + } + break; + case CMD_EXPORT: + try { + cmd_dbexport(cmd); + } catch (Exception e) { + return exit(e); + } + break; + case CMD_LIST_VERSION: + cmd_listversion(); + break; - default: - printHelp(formatter); - return 1; + default: + printHelp(formatter); + return 1; } return 0; } @@ -266,7 +266,7 @@ public class Program { } - private static void cmd_dbimport(CommandLine cmd) throws Exception { + private static void cmd_dbimport(CommandLine cmd) throws Exception { String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL); String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null); String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null); @@ -275,12 +275,12 @@ public class Program { if (filename == null) { throw new Exception("please add output file parameter"); } - long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000; - DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) }, + long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30) * 1000; + DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)}, username, password, trustAll, timeoutms); DataMigrationReport report = service.importData(filename, false); LOG.info(report); - if(!report.completed()) { + if (!report.completed()) { throw new Exception("db import seems to be not executed completed"); } } @@ -294,12 +294,12 @@ public class Program { if (filename == null) { throw new Exception("please add output file parameter"); } - long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000; - DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) }, + long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30) * 1000; + DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)}, username, password, trustAll, timeoutms); DataMigrationReport report = service.exportData(filename); LOG.info(report); - if(!report.completed()) { + if (!report.completed()) { throw new Exception("db export seems to be not executed completed"); } @@ -321,23 +321,24 @@ public class Program { String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null); String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null); boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false); - long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000; - DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) }, + long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30) * 1000; + DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)}, username, password, trustAll, timeoutms); - if (!service.clearDatabase(r, dbPrefix,timeoutms)) { + if (!service.clearDatabase(r, dbPrefix, timeoutms)) { throw new Exception("failed to init database"); } } + private static void cmd_clear_db_complete(CommandLine cmd) throws Exception { String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL); String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null); String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null); boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false); - long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000; - DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) }, + long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30) * 1000; + DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)}, username, password, trustAll, timeoutms); if (!service.clearCompleteDatabase(timeoutms)) { - throw new Exception("failed to init database"); + throw new Exception("failed to init database"); } } @@ -348,13 +349,13 @@ public class Program { String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL); String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX); String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null); - String password = getOptionOrDefault(cmd,OPTION_DATABASEPASSWORD_SHORT, null); + String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null); boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false); - long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000; - DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) }, + long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30) * 1000; + DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)}, username, password, trustAll, timeoutms); boolean forceRecreate = cmd.hasOption(OPTION_FORCE_RECREATE_SHORT); - if (!service.initDatabase(r, numShards, numReplicas, dbPrefix, forceRecreate,timeoutms)) { + if (!service.initDatabase(r, numShards, numReplicas, dbPrefix, forceRecreate, timeoutms)) { throw new Exception("failed to init database"); } @@ -364,8 +365,10 @@ public class Program { Options result = new Options(); result.addOption(createOption(OPTION_COMMAND_SHORT, "cmd", true, "command to execute", false)); result.addOption(createOption(OPTION_DATABASE_SHORT, "dburl", true, "database url", false)); - result.addOption(createOption(OPTION_DATABASEUSER_SHORT, "db-username", true, "database basic auth username", false)); - result.addOption(createOption(OPTION_DATABASEPASSWORD_SHORT, "db-password", true, "database basic auth password", false)); + result.addOption( + createOption(OPTION_DATABASEUSER_SHORT, "db-username", true, "database basic auth username", false)); + result.addOption(createOption(OPTION_DATABASEPASSWORD_SHORT, "db-password", true, + "database basic auth password", false)); result.addOption(createOption(OPTION_REPLICAS_SHORT, "replicas", true, "amount of replicas", false)); result.addOption(createOption(OPTION_SHARDS_SHORT, "shards", true, "amount of shards", false)); result.addOption(createOption(OPTION_DATABASEPREFIX_SHORT, "prefix", true, "prefix for db indices", false)); @@ -373,13 +376,14 @@ public class Program { result.addOption(createOption(OPTION_DEBUG_SHORT, "verbose", false, "verbose mode", false)); result.addOption(createOption(OPTION_TRUSTINSECURESSL_SHORT, "trust-insecure", false, "trust insecure ssl certs", false)); - result.addOption(createOption(OPTION_DATABASEWAIT_SHORT, "wait", true, "wait for yellow status with timeout in seconds", false)); + result.addOption(createOption(OPTION_DATABASEWAIT_SHORT, "wait", true, + "wait for yellow status with timeout in seconds", false)); result.addOption( createOption(OPTION_FORCE_RECREATE_SHORT, "force-recreate", false, "delete if sth exists", false)); result.addOption(createOption(OPTION_SILENT_SHORT, OPTION_SILENT, false, "prevent console output", false)); result.addOption(createOption(OPTION_OUTPUTFILE_SHORT, "output-file", true, "file to write into", false)); result.addOption(createOption(OPTION_INPUTFILE_SHORT, "input-file", true, "file to read from", false)); - result.addOption(createOption(OPTION_HELP_SHORT,"help",false,"show help",false)); + result.addOption(createOption(OPTION_HELP_SHORT, "help", false, "show help", false)); return result; } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/ReleaseInformation.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/ReleaseInformation.java index ccae07c0e..cb20025ff 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/ReleaseInformation.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/ReleaseInformation.java @@ -37,152 +37,159 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.guilin.GuilinReleaseIn public abstract class ReleaseInformation { - // variables - private final Release release; - private final Map dbMap; - // end of variables - - // constructors - public ReleaseInformation(Release r, Map dbMap) { - this.release = r; - this.dbMap = dbMap; - } - // end of constructors - - /** - * get database alias for component - * @param name - * @return alias or null if not exists - */ - public String getAlias(ComponentName name) { - return this.getAlias(name, ""); - } - - public String getAlias(ComponentName name, String prefix) { - return dbMap.get(name) == null ? null : prefix + dbMap.get(name).alias; - } - - /** - * get index name for component - * @param comp - * @return null if component does not exists in this release, otherwise index name - */ - public String getIndex(ComponentName comp) { - return this.getIndex(comp, ""); - } - - /** - * get index name for component with prefix - * @param comp - * @param prefix - * @return null if component does not exists in this release, otherwise index name - */ - public String getIndex(ComponentName comp, String prefix) { - return dbMap.get(comp) == null ? null : (prefix + dbMap.get(comp).getIndex(this.release.getDBSuffix())); - } - - /** - * get database datatype (doctype) for component - * @param name - * @return datatype or null if not exists - */ - public String getDataType(ComponentName name) { - return dbMap.get(name) == null ? null : dbMap.get(name).doctype; - } - - public String getDatabaseMapping(ComponentName name) { - return dbMap.get(name) == null ? null : dbMap.get(name).getMapping(); - } - - /** - * get database doctype definition for component - * @param name - * @return mappings or null if not exists - */ - public String getDatabaseMapping(ComponentName name, boolean useStrict) { - return dbMap.get(name) == null ? null : dbMap.get(name).getMapping(useStrict); - } - - /** - * get database settings definition for component - * @param name - * @return settings or null if not exists - */ - public String getDatabaseSettings(ComponentName name, int shards, int replicas) { - return dbMap.get(name) == null ? null : dbMap.get(name).getSettings(shards, replicas); - } - - /** - * get converter for component data - * @param dst destination release - * @param comp component to convert - * @return - */ - public SearchHitConverter getConverter(Release dst, ComponentName comp) { - if (dst == this.release && this.getComponents().contains(comp)) { - return new KeepDataSearchHitConverter(comp); - } - return null; - } - - public static ReleaseInformation getInstance(Release r) { - switch (r) { - case EL_ALTO: - return new ElAltoReleaseInformation(); - case FRANKFURT_R1: - return new FrankfurtReleaseInformation(); - case GUILIN: - return new GuilinReleaseInformation(); - default: - return null; - } - } - - /** - * @return - */ - public Set getComponents() { - return dbMap.keySet(); - } - - /** - * @param component - * @return - */ - public boolean hasOwnDbIndex(ComponentName component) { - return this.getDatabaseMapping(component) != null; - } - - /** - * @param indices - * @return true if components of this release are covered by the given indices - */ - protected boolean containsIndices(IndicesEntryList indices) { - - if (this.dbMap.size() <= 0) { - return false; - } - for (DatabaseInfo entry : this.dbMap.values()) { - String dbIndexName = entry.getIndex(this.release.getDBSuffix()); - if (indices.findByIndex(dbIndexName) == null) { - return false; - } - } - return true; - - } - - /** - * @param dbClient - * @return if succeeded or not - */ - protected abstract boolean runPreInitCommands(HtDatabaseClient dbClient); - - /** - * - * @param dbClient - * @return if succeeded or not - */ - protected abstract boolean runPostInitCommands(HtDatabaseClient dbClient); + // variables + private final Release release; + private final Map dbMap; + // end of variables + + // constructors + public ReleaseInformation(Release r, Map dbMap) { + this.release = r; + this.dbMap = dbMap; + } + // end of constructors + + /** + * get database alias for component + * + * @param name + * @return alias or null if not exists + */ + public String getAlias(ComponentName name) { + return this.getAlias(name, ""); + } + + public String getAlias(ComponentName name, String prefix) { + return dbMap.get(name) == null ? null : prefix + dbMap.get(name).alias; + } + + /** + * get index name for component + * + * @param comp + * @return null if component does not exists in this release, otherwise index name + */ + public String getIndex(ComponentName comp) { + return this.getIndex(comp, ""); + } + + /** + * get index name for component with prefix + * + * @param comp + * @param prefix + * @return null if component does not exists in this release, otherwise index name + */ + public String getIndex(ComponentName comp, String prefix) { + return dbMap.get(comp) == null ? null : (prefix + dbMap.get(comp).getIndex(this.release.getDBSuffix())); + } + + /** + * get database datatype (doctype) for component + * + * @param name + * @return datatype or null if not exists + */ + public String getDataType(ComponentName name) { + return dbMap.get(name) == null ? null : dbMap.get(name).doctype; + } + + public String getDatabaseMapping(ComponentName name) { + return dbMap.get(name) == null ? null : dbMap.get(name).getMapping(); + } + + /** + * get database doctype definition for component + * + * @param name + * @return mappings or null if not exists + */ + public String getDatabaseMapping(ComponentName name, boolean useStrict) { + return dbMap.get(name) == null ? null : dbMap.get(name).getMapping(useStrict); + } + + /** + * get database settings definition for component + * + * @param name + * @return settings or null if not exists + */ + public String getDatabaseSettings(ComponentName name, int shards, int replicas) { + return dbMap.get(name) == null ? null : dbMap.get(name).getSettings(shards, replicas); + } + + /** + * get converter for component data + * + * @param dst destination release + * @param comp component to convert + * @return + */ + public SearchHitConverter getConverter(Release dst, ComponentName comp) { + if (dst == this.release && this.getComponents().contains(comp)) { + return new KeepDataSearchHitConverter(comp); + } + return null; + } + + public static ReleaseInformation getInstance(Release r) { + switch (r) { + case EL_ALTO: + return new ElAltoReleaseInformation(); + case FRANKFURT_R1: + return new FrankfurtReleaseInformation(); + case GUILIN: + return new GuilinReleaseInformation(); + default: + return null; + } + } + + /** + * @return + */ + public Set getComponents() { + return dbMap.keySet(); + } + + /** + * @param component + * @return + */ + public boolean hasOwnDbIndex(ComponentName component) { + return this.getDatabaseMapping(component) != null; + } + + /** + * @param indices + * @return true if components of this release are covered by the given indices + */ + protected boolean containsIndices(IndicesEntryList indices) { + + if (this.dbMap.size() <= 0) { + return false; + } + for (DatabaseInfo entry : this.dbMap.values()) { + String dbIndexName = entry.getIndex(this.release.getDBSuffix()); + if (indices.findByIndex(dbIndexName) == null) { + return false; + } + } + return true; + + } + + /** + * @param dbClient + * @return if succeeded or not + */ + protected abstract boolean runPreInitCommands(HtDatabaseClient dbClient); + + /** + * + * @param dbClient + * @return if succeeded or not + */ + protected abstract boolean runPostInitCommands(HtDatabaseClient dbClient); } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/BaseSearchHitConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/BaseSearchHitConverter.java index 2f4f067bd..c58c3cdf7 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/BaseSearchHitConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/BaseSearchHitConverter.java @@ -26,26 +26,28 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; public abstract class BaseSearchHitConverter implements SearchHitConverter { - private ComponentName name; - public BaseSearchHitConverter(ComponentName name) { - this.name = name; - } - - protected SearchHit getSearchHit(String index, String type, String id, JSONObject data) { - JSONObject o = new JSONObject(); - o.put("_index", index); - o.put("_type", type); - o.put("_id", id); - o.put("_source", data); - return new SearchHit(o); - } - @Override - public ComponentData convert(DataContainer container) { - ComponentData srcData = container.getComponents().get(this.name); - ComponentData dstData = new ComponentData(srcData.getName()); - for(SearchHit sh:srcData) { - dstData.add(this.convert(sh)); - } - return dstData; - } + private ComponentName name; + + public BaseSearchHitConverter(ComponentName name) { + this.name = name; + } + + protected SearchHit getSearchHit(String index, String type, String id, JSONObject data) { + JSONObject o = new JSONObject(); + o.put("_index", index); + o.put("_type", type); + o.put("_id", id); + o.put("_source", data); + return new SearchHit(o); + } + + @Override + public ComponentData convert(DataContainer container) { + ComponentData srcData = container.getComponents().get(this.name); + ComponentData dstData = new ComponentData(srcData.getName()); + for (SearchHit sh : srcData) { + dstData.add(this.convert(sh)); + } + return dstData; + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentData.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentData.java index fd361843c..5d6f0079f 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentData.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentData.java @@ -25,38 +25,38 @@ import java.util.ArrayList; import org.json.JSONArray; import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; -public class ComponentData extends ArrayList{ - - /** - * - */ - private static final long serialVersionUID = 1L; - private final ComponentName name; - - public ComponentData(ComponentName name) { - this(name,null); - } - - public ComponentData(ComponentName name,JSONArray a) { - this.name = name; - if(a!=null) { - for(int i=0;i { + + /** + * + */ + private static final long serialVersionUID = 1L; + private final ComponentName name; + + public ComponentData(ComponentName name) { + this(name, null); + } + + public ComponentData(ComponentName name, JSONArray a) { + this.name = name; + if (a != null) { + for (int i = 0; i < a.length(); i++) { + this.add(new SearchHit(a.getJSONObject(i))); + } + } + + } + + public ComponentName getName() { + return this.name; + } + + public JSONArray toJsonArray() { + JSONArray a = new JSONArray(); + for (SearchHit h : this) { + a.put(h.getRaw()); + } + return a; + } + } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentName.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentName.java index 9c5ef5c53..ab3f311a1 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentName.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ComponentName.java @@ -23,37 +23,34 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data; public enum ComponentName { - CONNECTIONLOG("connectionlog"), - EVENTLOG("eventlog"), - FAULTLOG("faultlog"), - FAULTCURRENT("faultcurrent"), - HISTORICAL_PERFORMANCE_15M("historicalperformance15m"), - HISTORICAL_PERFORMANCE_24H("historicalperformance24h"), - INVENTORY("inventory"), - INVENTORYTOPLEVEL("inventorytoplevel"), - MAINTENANCE("maintenance"), - MEDIATOR_SERVER("mediator-server"), - REQUIRED_NETWORKELEMENT("required-networkelement"); - - private final String value; + CONNECTIONLOG("connectionlog"), EVENTLOG("eventlog"), FAULTLOG("faultlog"), FAULTCURRENT( + "faultcurrent"), HISTORICAL_PERFORMANCE_15M("historicalperformance15m"), HISTORICAL_PERFORMANCE_24H( + "historicalperformance24h"), INVENTORY("inventory"), INVENTORYTOPLEVEL( + "inventorytoplevel"), MAINTENANCE("maintenance"), MEDIATOR_SERVER( + "mediator-server"), REQUIRED_NETWORKELEMENT("required-networkelement"); - private ComponentName(String s) { - this.value = s; - } - @Override - public String toString() { - return this.value; - } - public String getValue() { - return value; - } - public static ComponentName getValueOf(String s) throws Exception { - s = s.toLowerCase(); - for(ComponentName p:ComponentName.values()) { - if(p.value.equals(s)) { - return p; - } - } - throw new Exception("value not found for "+s); - } -} \ No newline at end of file + private final String value; + + private ComponentName(String s) { + this.value = s; + } + + @Override + public String toString() { + return this.value; + } + + public String getValue() { + return value; + } + + public static ComponentName getValueOf(String s) throws Exception { + s = s.toLowerCase(); + for (ComponentName p : ComponentName.values()) { + if (p.value.equals(s)) { + return p; + } + } + throw new Exception("value not found for " + s); + } +} diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigData.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigData.java index 95c483736..49600320f 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigData.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigData.java @@ -23,13 +23,14 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data; public class ConfigData { - private final String[] lines; + private final String[] lines; - public String[] getLines() { - return this.lines; - } - public ConfigData(String content) { - this.lines = content.split("\n"); - } + public String[] getLines() { + return this.lines; + } + + public ConfigData(String content) { + this.lines = content.split("\n"); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigName.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigName.java index 181fe2006..da00cb24a 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigName.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/ConfigName.java @@ -23,30 +23,31 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data; public enum ConfigName { - APIGATEWAY("apigateway"), - DEVICEMANAGER("devicemanager"), - DATAPROVIDER("dataprovider"); - - - private final String value; - - private ConfigName(String s) { - this.value = s; - } - @Override - public String toString() { - return this.value; - } - public String getValue() { - return value; - } - public static ConfigName getValueOf(String s) throws Exception { - s = s.toLowerCase(); - for(ConfigName p:ConfigName.values()) { - if(p.value.equals(s)) { - return p; - } - } - throw new Exception("value not found"); - } -} \ No newline at end of file + APIGATEWAY("apigateway"), DEVICEMANAGER("devicemanager"), DATAPROVIDER("dataprovider"); + + + private final String value; + + private ConfigName(String s) { + this.value = s; + } + + @Override + public String toString() { + return this.value; + } + + public String getValue() { + return value; + } + + public static ConfigName getValueOf(String s) throws Exception { + s = s.toLowerCase(); + for (ConfigName p : ConfigName.values()) { + if (p.value.equals(s)) { + return p; + } + } + throw new Exception("value not found"); + } +} diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataContainer.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataContainer.java index f50969ed6..f23723773 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataContainer.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataContainer.java @@ -41,101 +41,101 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types.NetconfTimeStamp */ public class DataContainer { - private final Release release; - private final Date created; - private final Map components; - private final Map configs; - - public Release getRelease() { - return this.release; - } - - public boolean isCurrentRelease() { - return this.release.equals(Release.CURRENT_RELEASE); - } - - public Date getCreated() { - return this.created; - } - - public Map getComponents() { - return this.components; - } - - public Map getConfigs() { - return this.configs; - } - - public DataContainer() { - this(Release.CURRENT_RELEASE); - } - - public DataContainer(Release release) { - this(release, new Date()); - } - - public DataContainer(Release release, Date dt) { - this.release = release; - this.created = dt; - this.components = new HashMap<>(); - this.configs = new HashMap<>(); - } - - public void addComponent(ComponentName name, ComponentData data) { - this.components.put(name, data); - } - - public void addConfig(ConfigName name, ConfigData data) { - this.configs.put(name, data); - } - - public static DataContainer load(File file) throws Exception { - if(!file.exists()) { - throw new FileNotFoundException(); - } - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"); - JSONObject o = new JSONObject(new String(Files.readAllBytes(file.toPath()))); - DataContainer c = new DataContainer(Release.getValueOf(o.getString("release")), - format.parse(o.getString("created"))); - JSONObject comps = o.getJSONObject("components"); - - String k; - ComponentName compKey; - JSONArray compData; - for (Object key : comps.keySet()) { - k = String.valueOf(key); - // check component if exists - compKey = ComponentName.getValueOf(k); - compData = comps.getJSONArray(k); - c.addComponent(compKey, new ComponentData(compKey, compData)); - } - ConfigName confKey; - ConfigData confData; - JSONObject confs = o.getJSONObject("configs"); - for (Object key : confs.keySet()) { - k = String.valueOf(key); - confKey = ConfigName.getValueOf(k); - confData = new ConfigData(confs.getString(k)); - c.addConfig(confKey, confData); - } - return c; - } - - public String toJSON() { - JSONObject o = new JSONObject(); - o.put("release", this.release.getValue()); - o.put("created", NetconfTimeStampImpl.getConverter().getTimeStampAsNetconfString(this.created)); - JSONObject compsJson = new JSONObject(); - JSONObject confsJson = new JSONObject(); - for (Entry entry : this.components.entrySet()) { - compsJson.put(entry.getKey().getValue(), entry.getValue().toJsonArray()); - } - for (Entry entry : this.configs.entrySet()) { - confsJson.put(entry.getKey().getValue(), entry.getValue().toString()); - } - o.put("components", compsJson); - o.put("configs", confsJson); - return o.toString(); - } - -} \ No newline at end of file + private final Release release; + private final Date created; + private final Map components; + private final Map configs; + + public Release getRelease() { + return this.release; + } + + public boolean isCurrentRelease() { + return this.release.equals(Release.CURRENT_RELEASE); + } + + public Date getCreated() { + return this.created; + } + + public Map getComponents() { + return this.components; + } + + public Map getConfigs() { + return this.configs; + } + + public DataContainer() { + this(Release.CURRENT_RELEASE); + } + + public DataContainer(Release release) { + this(release, new Date()); + } + + public DataContainer(Release release, Date dt) { + this.release = release; + this.created = dt; + this.components = new HashMap<>(); + this.configs = new HashMap<>(); + } + + public void addComponent(ComponentName name, ComponentData data) { + this.components.put(name, data); + } + + public void addConfig(ConfigName name, ConfigData data) { + this.configs.put(name, data); + } + + public static DataContainer load(File file) throws Exception { + if (!file.exists()) { + throw new FileNotFoundException(); + } + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"); + JSONObject o = new JSONObject(new String(Files.readAllBytes(file.toPath()))); + DataContainer c = + new DataContainer(Release.getValueOf(o.getString("release")), format.parse(o.getString("created"))); + JSONObject comps = o.getJSONObject("components"); + + String k; + ComponentName compKey; + JSONArray compData; + for (Object key : comps.keySet()) { + k = String.valueOf(key); + // check component if exists + compKey = ComponentName.getValueOf(k); + compData = comps.getJSONArray(k); + c.addComponent(compKey, new ComponentData(compKey, compData)); + } + ConfigName confKey; + ConfigData confData; + JSONObject confs = o.getJSONObject("configs"); + for (Object key : confs.keySet()) { + k = String.valueOf(key); + confKey = ConfigName.getValueOf(k); + confData = new ConfigData(confs.getString(k)); + c.addConfig(confKey, confData); + } + return c; + } + + public String toJSON() { + JSONObject o = new JSONObject(); + o.put("release", this.release.getValue()); + o.put("created", NetconfTimeStampImpl.getConverter().getTimeStampAsNetconfString(this.created)); + JSONObject compsJson = new JSONObject(); + JSONObject confsJson = new JSONObject(); + for (Entry entry : this.components.entrySet()) { + compsJson.put(entry.getKey().getValue(), entry.getValue().toJsonArray()); + } + for (Entry entry : this.configs.entrySet()) { + confsJson.put(entry.getKey().getValue(), entry.getValue().toString()); + } + o.put("components", compsJson); + o.put("configs", confsJson); + return o.toString(); + } + +} diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataMigrationReport.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataMigrationReport.java index c8270bad6..9e0831631 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataMigrationReport.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DataMigrationReport.java @@ -26,29 +26,35 @@ import java.util.List; public class DataMigrationReport { - private boolean completed; - private final List logs; - private final List errors; - public void setCompleted(boolean s) { - this.completed = s; - } - public boolean completed() { - return this.completed; - } - public void log(String format,Object ...params) { - this.logs.add(String.format(format, params)); - } - public void error(String format,Object ...params) { - this.errors.add(String.format(format, params)); - } - public DataMigrationReport() { - this.completed = false; - this.logs = new ArrayList<>(); - this.errors = new ArrayList<>(); - } - @Override - public String toString() { - return "DataMigrationReport [completed=" + completed + ", logs=" + logs + ", errors=" + errors + "]"; - } + private boolean completed; + private final List logs; + private final List errors; + + public void setCompleted(boolean s) { + this.completed = s; + } + + public boolean completed() { + return this.completed; + } + + public void log(String format, Object... params) { + this.logs.add(String.format(format, params)); + } + + public void error(String format, Object... params) { + this.errors.add(String.format(format, params)); + } + + public DataMigrationReport() { + this.completed = false; + this.logs = new ArrayList<>(); + this.errors = new ArrayList<>(); + } + + @Override + public String toString() { + return "DataMigrationReport [completed=" + completed + ", logs=" + logs + ", errors=" + errors + "]"; + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DatabaseInfo.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DatabaseInfo.java index 4d82a0901..4c38b5032 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DatabaseInfo.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/DatabaseInfo.java @@ -26,43 +26,45 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data; * */ public class DatabaseInfo { - public final String doctype; - public final String alias; - private final String mapping; - private final String settingsFormat; - private final String index; + public final String doctype; + public final String alias; + private final String mapping; + private final String settingsFormat; + private final String index; - public String getIndex(String version) { - return this.index + version; - } + public String getIndex(String version) { + return this.index + version; + } - public DatabaseInfo(String alias, String doctype, String mapping) { - this(alias, alias, doctype, mapping); - } + public DatabaseInfo(String alias, String doctype, String mapping) { + this(alias, alias, doctype, mapping); + } - public DatabaseInfo(String index, String alias, String doctype, String mapping) { - this(index, alias, doctype, mapping, - "{\"index\":{\"number_of_shards\":%d,\"number_of_replicas\":%d},\"analysis\":{\"analyzer\":{\"content\":" - + "{\"type\":\"custom\",\"tokenizer\":\"whitespace\"}}}}"); - } + public DatabaseInfo(String index, String alias, String doctype, String mapping) { + this(index, alias, doctype, mapping, + "{\"index\":{\"number_of_shards\":%d,\"number_of_replicas\":%d},\"analysis\":{\"analyzer\":{\"content\":" + + "{\"type\":\"custom\",\"tokenizer\":\"whitespace\"}}}}"); + } - public DatabaseInfo(String index, String alias, String doctype, String mapping, String settingsformat) { - this.index = index; - this.alias = alias; - this.doctype = doctype; - this.mapping = mapping; - this.settingsFormat = settingsformat; - } - - public String getMapping() { - return this.getMapping(false); - } - public String getMapping(boolean useStrict) { - return this.mapping == null ? null - : String.format("{\"%s\":{%s\"properties\":%s}}", this.doctype,useStrict?"\"dynamic\": \"strict\",":"", this.mapping); - } + public DatabaseInfo(String index, String alias, String doctype, String mapping, String settingsformat) { + this.index = index; + this.alias = alias; + this.doctype = doctype; + this.mapping = mapping; + this.settingsFormat = settingsformat; + } - public String getSettings(int shards, int replicas) { - return String.format(this.settingsFormat, shards, replicas); - } -} \ No newline at end of file + public String getMapping() { + return this.getMapping(false); + } + + public String getMapping(boolean useStrict) { + return this.mapping == null ? null + : String.format("{\"%s\":{%s\"properties\":%s}}", this.doctype, + useStrict ? "\"dynamic\": \"strict\"," : "", this.mapping); + } + + public String getSettings(int shards, int replicas) { + return String.format(this.settingsFormat, shards, replicas); + } +} diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/KeepDataSearchHitConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/KeepDataSearchHitConverter.java index fa86c90e2..04bdfd38f 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/KeepDataSearchHitConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/KeepDataSearchHitConverter.java @@ -25,19 +25,20 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; public class KeepDataSearchHitConverter implements SearchHitConverter { - - private final ComponentName name; - public KeepDataSearchHitConverter(ComponentName name) { - this.name = name; - } - @Override - public SearchHit convert(SearchHit source) { - return source; - } + private final ComponentName name; - @Override - public ComponentData convert(DataContainer container) { - return container.getComponents().get(this.name); - } + public KeepDataSearchHitConverter(ComponentName name) { + this.name = name; + } + + @Override + public SearchHit convert(SearchHit source) { + return source; + } + + @Override + public ComponentData convert(DataContainer container) { + return container.getComponents().get(this.name); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/MavenDatabasePluginInitFile.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/MavenDatabasePluginInitFile.java index e923b2728..66a5e16d0 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/MavenDatabasePluginInitFile.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/MavenDatabasePluginInitFile.java @@ -38,27 +38,29 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.ReleaseInformation; * */ public class MavenDatabasePluginInitFile { - private static final int replicas=1; - private static final int shards=5; - private static final String mappings="\"mappings\":%s"; - private static final String settings="\"settings\":{\"index\":{\"number_of_shards\":%d,\"number_of_replicas\":%d},\"analysis\":{\"analyzer\":{\"content\":"+ - "{\"type\":\"custom\",\"tokenizer\":\"whitespace\"}}}}"; + private static final int replicas = 1; + private static final int shards = 5; + private static final String mappings = "\"mappings\":%s"; + private static final String settings = + "\"settings\":{\"index\":{\"number_of_shards\":%d,\"number_of_replicas\":%d},\"analysis\":{\"analyzer\":{\"content\":" + + "{\"type\":\"custom\",\"tokenizer\":\"whitespace\"}}}}"; - public static void create(Release release, String filename) throws IOException { + public static void create(Release release, String filename) throws IOException { - ReleaseInformation ri = ReleaseInformation.getInstance(release); - Set comps=ri.getComponents(); - List lines = new ArrayList<>(); - for(ComponentName c:comps) { - lines.add(String.format("PUT:%s/:{"+settings+","+mappings+"}",ri.getIndex(c),shards,replicas,ri.getDatabaseMapping(c))); - lines.add(String.format("PUT:%s/_alias/%s/:{}", ri.getIndex(c),ri.getAlias(c))); - } + ReleaseInformation ri = ReleaseInformation.getInstance(release); + Set comps = ri.getComponents(); + List lines = new ArrayList<>(); + for (ComponentName c : comps) { + lines.add(String.format("PUT:%s/:{" + settings + "," + mappings + "}", ri.getIndex(c), shards, replicas, + ri.getDatabaseMapping(c))); + lines.add(String.format("PUT:%s/_alias/%s/:{}", ri.getIndex(c), ri.getAlias(c))); + } - File filePath = new File(filename); - if (filePath.getParentFile() != null && !filePath.getParentFile().exists()){ - //Crate Directory if missing - filePath.getParentFile().mkdirs(); - } - Files.write(filePath.toPath(), lines); - } + File filePath = new File(filename); + if (filePath.getParentFile() != null && !filePath.getParentFile().exists()) { + //Crate Directory if missing + filePath.getParentFile().mkdirs(); + } + Files.write(filePath.toPath(), lines); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/Release.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/Release.java index ae4522dc5..13c604716 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/Release.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/Release.java @@ -25,74 +25,82 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntry; import org.onap.ccsdk.features.sdnr.wt.common.database.data.EsVersion; public enum Release { - - EL_ALTO("el alto","_v1",new EsVersion(2,2,0),new EsVersion(2,2,0)), - FRANKFURT_R1("frankfurt-R1","-v2",new EsVersion(6,4,3),new EsVersion(6,8,6)), - FRANKFURT_R2("frankfurt-R2","",new EsVersion(6,4,3),new EsVersion(6,8,6)), - FRANKFURT_R3("frankfurt-R3","",new EsVersion(6,4,3),new EsVersion(6,8,6)), - - GUILIN("guilin","",new EsVersion(6,4,3),new EsVersion(6,8,6)); - - public static final Release CURRENT_RELEASE = Release.FRANKFURT_R1; - - private final String value; - private final String dbSuffix; - private final EsVersion minDbVersion; - private final EsVersion maxDbVersion; - - private Release(String s,String dbsuffix,EsVersion minDbVersion,EsVersion maxDbVersion) { - this.value = s; - this.dbSuffix=dbsuffix; - this.minDbVersion = minDbVersion; - this.maxDbVersion = maxDbVersion; - } - @Override - public String toString() { - return this.value; - } - public String getValue() { - return value; - } - public static Release getValueOf(String s) throws Exception { - //s = s.toLowerCase(); - for(Release p:Release.values()) { - if(p.value.equals(s)) { - return p; - } - } - throw new Exception("value not found"); - } - public static Release getValueBySuffix(String suffix) { - for(Release r:Release.values()) { - if(r.dbSuffix.equals(suffix)) - return r; - } - return null; - } - public static String getDbSuffix(AliasesEntry entry) throws Exception { - ComponentName comp = ComponentName.getValueOf(entry.getAlias()); - if(comp!=null) { - return entry.getIndex().substring(entry.getAlias().length()); - } - return null; - } - /** - * @return - */ - public String getDBSuffix() { - return this.dbSuffix; - } - /** - * @return - */ - public EsVersion getDBVersion() { - return this.minDbVersion; - } - /** - * @param dbVersion2 - * @return - */ - public boolean isDbInRange(EsVersion dbVersion) { - return dbVersion.isNewerOrEqualThan(minDbVersion) && dbVersion.isOlderOrEqualThan(maxDbVersion); - } + + EL_ALTO("el alto", "_v1", new EsVersion(2, 2, 0), new EsVersion(2, 2, 0)), FRANKFURT_R1("frankfurt-R1", "-v2", + new EsVersion(6, 4, 3), new EsVersion(6, 8, 6)), FRANKFURT_R2("frankfurt-R2", "", new EsVersion(6, 4, 3), + new EsVersion(6, 8, 6)), FRANKFURT_R3("frankfurt-R3", "", new EsVersion(6, 4, 3), + new EsVersion(6, 8, 6)), + + GUILIN("guilin", "", new EsVersion(6, 4, 3), new EsVersion(6, 8, 6)); + + public static final Release CURRENT_RELEASE = Release.FRANKFURT_R1; + + private final String value; + private final String dbSuffix; + private final EsVersion minDbVersion; + private final EsVersion maxDbVersion; + + private Release(String s, String dbsuffix, EsVersion minDbVersion, EsVersion maxDbVersion) { + this.value = s; + this.dbSuffix = dbsuffix; + this.minDbVersion = minDbVersion; + this.maxDbVersion = maxDbVersion; + } + + @Override + public String toString() { + return this.value; + } + + public String getValue() { + return value; + } + + public static Release getValueOf(String s) throws Exception { + //s = s.toLowerCase(); + for (Release p : Release.values()) { + if (p.value.equals(s)) { + return p; + } + } + throw new Exception("value not found"); + } + + public static Release getValueBySuffix(String suffix) { + for (Release r : Release.values()) { + if (r.dbSuffix.equals(suffix)) + return r; + } + return null; + } + + public static String getDbSuffix(AliasesEntry entry) throws Exception { + ComponentName comp = ComponentName.getValueOf(entry.getAlias()); + if (comp != null) { + return entry.getIndex().substring(entry.getAlias().length()); + } + return null; + } + + /** + * @return + */ + public String getDBSuffix() { + return this.dbSuffix; + } + + /** + * @return + */ + public EsVersion getDBVersion() { + return this.minDbVersion; + } + + /** + * @param dbVersion2 + * @return + */ + public boolean isDbInRange(EsVersion dbVersion) { + return dbVersion.isNewerOrEqualThan(minDbVersion) && dbVersion.isOlderOrEqualThan(maxDbVersion); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/SearchHitConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/SearchHitConverter.java index 7a549ca86..a95a405d6 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/SearchHitConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/data/SearchHitConverter.java @@ -28,37 +28,38 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.guilin.GuilinReleaseIn public interface SearchHitConverter { - /** - * convert single entry of database - * @param source - * @return - */ - public SearchHit convert(SearchHit source); - - /** - * @param component destination component - * @param container source data - * @return data for destination component - */ - public ComponentData convert(DataContainer container); + /** + * convert single entry of database + * + * @param source + * @return + */ + public SearchHit convert(SearchHit source); + + /** + * @param component destination component + * @param container source data + * @return data for destination component + */ + public ComponentData convert(DataContainer container); + + + public static class Factory { + public static SearchHitConverter getInstance(Release src, Release dst, ComponentName component) { + switch (src) { + case EL_ALTO: + return new ElAltoReleaseInformation().getConverter(dst, component); + case FRANKFURT_R1: + return new FrankfurtReleaseInformation().getConverter(dst, component); + case GUILIN: + return new GuilinReleaseInformation().getConverter(dst, component); + default: + return null; + + } + } + } - - public static class Factory{ - public static SearchHitConverter getInstance(Release src,Release dst, ComponentName component) { - switch(src) { - case EL_ALTO: - return new ElAltoReleaseInformation().getConverter(dst, component); - case FRANKFURT_R1: - return new FrankfurtReleaseInformation().getConverter(dst, component); - case GUILIN: - return new GuilinReleaseInformation().getConverter(dst, component); - default: - return null; - - } - } - } - } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/ElAltoReleaseInformation.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/ElAltoReleaseInformation.java index 1236bd8e5..739afaf0e 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/ElAltoReleaseInformation.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/ElAltoReleaseInformation.java @@ -33,70 +33,76 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.ReleaseInformation; public class ElAltoReleaseInformation extends ReleaseInformation { - - private Map> converters; - public ElAltoReleaseInformation() { - super(Release.EL_ALTO, createDbInfos()); - this.converters = generateConverters(); - } + private Map> converters; - private static Map createDbInfos() { - Map map = new HashMap<>(); - map.put(ComponentName.EVENTLOG, new DatabaseInfo("sdnevents","eventlog","")); - map.put(ComponentName.FAULTCURRENT, new DatabaseInfo("sdnevents","faultcurrent","")); - map.put(ComponentName.FAULTLOG, new DatabaseInfo("sdnevents","faultlog","")); - map.put(ComponentName.INVENTORY, new DatabaseInfo("sdnevents","inventoryequipment","")); - map.put(ComponentName.INVENTORYTOPLEVEL, new DatabaseInfo("sdnevents","inventorytoplevel","")); - map.put(ComponentName.HISTORICAL_PERFORMANCE_15M, new DatabaseInfo("sdnperformance","historicalperformance15min","")); - map.put(ComponentName.HISTORICAL_PERFORMANCE_24H, new DatabaseInfo("sdnperformance","historicalperformance24h","")); - map.put(ComponentName.REQUIRED_NETWORKELEMENT, new DatabaseInfo("mwtn","required-networkelement","{\"required-networkelement\": {\"date_detection\": false }}")); - map.put(ComponentName.MEDIATOR_SERVER, new DatabaseInfo("mwtn","mediator-server","")); - map.put(ComponentName.MAINTENANCE, new DatabaseInfo("mwtn","maintenancemode","")); - return map; - } + public ElAltoReleaseInformation() { + super(Release.EL_ALTO, createDbInfos()); + this.converters = generateConverters(); + } - /** - * @return components used in el alto - */ - - - private static Map> generateConverters() { - Map> c = new HashMap<>(); - Map frankfurtConverters = new HashMap<>(); - frankfurtConverters.put(ComponentName.EVENTLOG, new FrankfurtEventlogConverter()); - frankfurtConverters.put(ComponentName.FAULTCURRENT, new FrankfurtFaultcurrentConverter()); - frankfurtConverters.put(ComponentName.FAULTLOG, new FrankfurtFaultlogConverter()); - frankfurtConverters.put(ComponentName.INVENTORY, new KeepDataSearchHitConverter(ComponentName.INVENTORY)); - //obsolete in frankfurt - //frankfurtConverters.put(ComponentName.INVENTORYTOPLEVEL, new KeepDataSearchHitConverter(ComponentName.INVENTORYTOPLEVEL)); - frankfurtConverters.put(ComponentName.HISTORICAL_PERFORMANCE_15M, new KeepDataSearchHitConverter(ComponentName.HISTORICAL_PERFORMANCE_15M)); - frankfurtConverters.put(ComponentName.HISTORICAL_PERFORMANCE_24H, new KeepDataSearchHitConverter(ComponentName.HISTORICAL_PERFORMANCE_24H)); - frankfurtConverters.put(ComponentName.MAINTENANCE, new FrankfurtMaintenanceConverter()); - frankfurtConverters.put(ComponentName.MEDIATOR_SERVER, new KeepDataSearchHitConverter(ComponentName.MEDIATOR_SERVER)); - frankfurtConverters.put(ComponentName.REQUIRED_NETWORKELEMENT, new FrankfurtRequiredNetworkElementConverter()); - frankfurtConverters.put(ComponentName.CONNECTIONLOG,new FrankfurtConnectionlogConverter()); - c.put(Release.FRANKFURT_R1,frankfurtConverters); - return c; - } + private static Map createDbInfos() { + Map map = new HashMap<>(); + map.put(ComponentName.EVENTLOG, new DatabaseInfo("sdnevents", "eventlog", "")); + map.put(ComponentName.FAULTCURRENT, new DatabaseInfo("sdnevents", "faultcurrent", "")); + map.put(ComponentName.FAULTLOG, new DatabaseInfo("sdnevents", "faultlog", "")); + map.put(ComponentName.INVENTORY, new DatabaseInfo("sdnevents", "inventoryequipment", "")); + map.put(ComponentName.INVENTORYTOPLEVEL, new DatabaseInfo("sdnevents", "inventorytoplevel", "")); + map.put(ComponentName.HISTORICAL_PERFORMANCE_15M, + new DatabaseInfo("sdnperformance", "historicalperformance15min", "")); + map.put(ComponentName.HISTORICAL_PERFORMANCE_24H, + new DatabaseInfo("sdnperformance", "historicalperformance24h", "")); + map.put(ComponentName.REQUIRED_NETWORKELEMENT, new DatabaseInfo("mwtn", "required-networkelement", + "{\"required-networkelement\": {\"date_detection\": false }}")); + map.put(ComponentName.MEDIATOR_SERVER, new DatabaseInfo("mwtn", "mediator-server", "")); + map.put(ComponentName.MAINTENANCE, new DatabaseInfo("mwtn", "maintenancemode", "")); + return map; + } - @Override - public SearchHitConverter getConverter(Release dst, ComponentName comp) { - SearchHitConverter c=this.converters.containsKey(dst)?this.converters.get(dst).get(comp):null; - if(c==null) { - c=super.getConverter(dst, comp); - } - return c; - } + /** + * @return components used in el alto + */ - @Override - protected boolean runPreInitCommands(HtDatabaseClient dbClient) { - return true; - } - @Override - protected boolean runPostInitCommands(HtDatabaseClient dbClient) { - return true; - } - + private static Map> generateConverters() { + Map> c = new HashMap<>(); + Map frankfurtConverters = new HashMap<>(); + frankfurtConverters.put(ComponentName.EVENTLOG, new FrankfurtEventlogConverter()); + frankfurtConverters.put(ComponentName.FAULTCURRENT, new FrankfurtFaultcurrentConverter()); + frankfurtConverters.put(ComponentName.FAULTLOG, new FrankfurtFaultlogConverter()); + frankfurtConverters.put(ComponentName.INVENTORY, new KeepDataSearchHitConverter(ComponentName.INVENTORY)); + //obsolete in frankfurt + //frankfurtConverters.put(ComponentName.INVENTORYTOPLEVEL, new KeepDataSearchHitConverter(ComponentName.INVENTORYTOPLEVEL)); + frankfurtConverters.put(ComponentName.HISTORICAL_PERFORMANCE_15M, + new KeepDataSearchHitConverter(ComponentName.HISTORICAL_PERFORMANCE_15M)); + frankfurtConverters.put(ComponentName.HISTORICAL_PERFORMANCE_24H, + new KeepDataSearchHitConverter(ComponentName.HISTORICAL_PERFORMANCE_24H)); + frankfurtConverters.put(ComponentName.MAINTENANCE, new FrankfurtMaintenanceConverter()); + frankfurtConverters.put(ComponentName.MEDIATOR_SERVER, + new KeepDataSearchHitConverter(ComponentName.MEDIATOR_SERVER)); + frankfurtConverters.put(ComponentName.REQUIRED_NETWORKELEMENT, new FrankfurtRequiredNetworkElementConverter()); + frankfurtConverters.put(ComponentName.CONNECTIONLOG, new FrankfurtConnectionlogConverter()); + c.put(Release.FRANKFURT_R1, frankfurtConverters); + return c; + } + + @Override + public SearchHitConverter getConverter(Release dst, ComponentName comp) { + SearchHitConverter c = this.converters.containsKey(dst) ? this.converters.get(dst).get(comp) : null; + if (c == null) { + c = super.getConverter(dst, comp); + } + return c; + } + + @Override + protected boolean runPreInitCommands(HtDatabaseClient dbClient) { + return true; + } + + @Override + protected boolean runPostInitCommands(HtDatabaseClient dbClient) { + return true; + } + } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtConnectionlogConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtConnectionlogConverter.java index d68373199..55fa0d88a 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtConnectionlogConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtConnectionlogConverter.java @@ -35,86 +35,73 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.frankfurt.data.Connect * * @author Michael Dürre * - * Convert data from el alto to frankfurt + * Convert data from el alto to frankfurt * - * src: eventlog - * dst: connectionlog + * src: eventlog dst: connectionlog * * - * { - * "event": { - * "nodeName": "SDN-Controller-5a150173d678", - * "counter": "48", - * "timeStamp": "2019-10-07T09:57:08.2Z", - * "objectId": "Sim2230", - * "attributeName": "ConnectionStatus", - * "newValue": "connecting", - * "type": "AttributeValueChangedNotificationXml" - * } - * } + * { "event": { "nodeName": "SDN-Controller-5a150173d678", "counter": "48", "timeStamp": + * "2019-10-07T09:57:08.2Z", "objectId": "Sim2230", "attributeName": "ConnectionStatus", "newValue": + * "connecting", "type": "AttributeValueChangedNotificationXml" } } * - * => + * => * - * { - * "timestamp": "2020-01-28T12:00:10.2Z", - * "status": "Connected", - * "node-id": "sim1" - * } + * { "timestamp": "2020-01-28T12:00:10.2Z", "status": "Connected", "node-id": "sim1" } * */ public class FrankfurtConnectionlogConverter extends BaseSearchHitConverter { - public FrankfurtConnectionlogConverter() { - super(ComponentName.CONNECTIONLOG); - } + public FrankfurtConnectionlogConverter() { + super(ComponentName.CONNECTIONLOG); + } - /** - * @source eventlog searchhit converted to connectionlog entry - */ - @Override - public SearchHit convert(SearchHit source) { + /** + * @source eventlog searchhit converted to connectionlog entry + */ + @Override + public SearchHit convert(SearchHit source) { - JSONObject data = new JSONObject(); - JSONObject inner = source.getSource().getJSONObject("event"); - String eventType = inner.getString("type"); - String eventSource = inner.getString("nodeName"); - if (!eventSource.startsWith("SDN-Controller")) { - return null; - } - data.put("node-id", inner.getString("objectId")); - data.put("timestamp", inner.getString("timeStamp")); - if (eventType.equals("AttributeValueChangedNotificationXml")) { - String event = inner.getString("newValue").toLowerCase(); - if (event.equals("connected")) { - data.put("status", ConnectionLogStatus.Connected.getName()); - } else if (event.equals("connecting")) { - data.put("status", ConnectionLogStatus.Connecting.getName()); - } else { - data.put("status", ConnectionLogStatus.UnableToConnect.getName()); - } + JSONObject data = new JSONObject(); + JSONObject inner = source.getSource().getJSONObject("event"); + String eventType = inner.getString("type"); + String eventSource = inner.getString("nodeName"); + if (!eventSource.startsWith("SDN-Controller")) { + return null; + } + data.put("node-id", inner.getString("objectId")); + data.put("timestamp", inner.getString("timeStamp")); + if (eventType.equals("AttributeValueChangedNotificationXml")) { + String event = inner.getString("newValue").toLowerCase(); + if (event.equals("connected")) { + data.put("status", ConnectionLogStatus.Connected.getName()); + } else if (event.equals("connecting")) { + data.put("status", ConnectionLogStatus.Connecting.getName()); + } else { + data.put("status", ConnectionLogStatus.UnableToConnect.getName()); + } - } else if (eventType.equals("ObjectCreationNotificationXml")) { - data.put("status", ConnectionLogStatus.Mounted.getName()); + } else if (eventType.equals("ObjectCreationNotificationXml")) { + data.put("status", ConnectionLogStatus.Mounted.getName()); - } else if (eventType.equals("ObjectDeletionNotificationXml")) { - data.put("status", ConnectionLogStatus.Unmounted.getName()); - } + } else if (eventType.equals("ObjectDeletionNotificationXml")) { + data.put("status", ConnectionLogStatus.Unmounted.getName()); + } - return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); - } + return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); + } - @Override - public ComponentData convert(DataContainer container) { - Map src = container.getComponents(); - if (!src.containsKey(ComponentName.EVENTLOG)) { - return null; - } - ComponentData eventData = src.get(ComponentName.EVENTLOG); - ComponentData dstData = new ComponentData(ComponentName.CONNECTIONLOG); - for (SearchHit sh : eventData) { - dstData.add(this.convert(sh)); - } - return dstData; - } + @Override + public ComponentData convert(DataContainer container) { + Map src = container.getComponents(); + if (!src.containsKey(ComponentName.EVENTLOG)) { + return null; + } + ComponentData eventData = src.get(ComponentName.EVENTLOG); + ComponentData dstData = new ComponentData(ComponentName.CONNECTIONLOG); + for (SearchHit sh : eventData) { + dstData.add(this.convert(sh)); + } + return dstData; + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtEventlogConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtEventlogConverter.java index e04378bbe..3bd70dd95 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtEventlogConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtEventlogConverter.java @@ -32,24 +32,23 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataContainer; * @author Michael Dürre * * - * Cannot be converted from el alto to frankfurt - * most of the entries are in connectionlog + * Cannot be converted from el alto to frankfurt most of the entries are in connectionlog * */ -public class FrankfurtEventlogConverter extends BaseSearchHitConverter{ +public class FrankfurtEventlogConverter extends BaseSearchHitConverter { - public FrankfurtEventlogConverter() { - super(ComponentName.EVENTLOG); - } + public FrankfurtEventlogConverter() { + super(ComponentName.EVENTLOG); + } - @Override - public SearchHit convert(SearchHit source) { - return null; - } + @Override + public SearchHit convert(SearchHit source) { + return null; + } - @Override - public ComponentData convert(DataContainer container) { - return null; - } + @Override + public ComponentData convert(DataContainer container) { + return null; + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultcurrentConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultcurrentConverter.java index 060434fe9..40541dcae 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultcurrentConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultcurrentConverter.java @@ -30,51 +30,36 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentName; * * @author Michael Dürre * - * { - * "faultCurrent": { - * "nodeName": "sim9090", - * "counter": "50443", - * "timeStamp": "2017-07-27T13:33:49.0Z", - * "objectId": "a2.module-1.1.5.6", - * "problem": "Ais", - * "severity": "Major", - * "type": "ProblemNotificationXml" - * } - * } + * { "faultCurrent": { "nodeName": "sim9090", "counter": "50443", "timeStamp": "2017-07-27T13:33:49.0Z", + * "objectId": "a2.module-1.1.5.6", "problem": "Ais", "severity": "Major", "type": "ProblemNotificationXml" } } * - * => + * => * - * { - * "timestamp": "2017-01-01T00:00:00.0Z", - * "object-id": "LP-MWS-TTP-01", - * "severity": "Warning", - * "counter": 2, - * "node-id": "sim1", - * "problem": "unknownProblem2" - * } + * { "timestamp": "2017-01-01T00:00:00.0Z", "object-id": "LP-MWS-TTP-01", "severity": "Warning", "counter": 2, + * "node-id": "sim1", "problem": "unknownProblem2" } */ public class FrankfurtFaultcurrentConverter extends BaseSearchHitConverter { - /** - * @param name - */ - public FrankfurtFaultcurrentConverter() { - super(ComponentName.FAULTCURRENT); - } + /** + * @param name + */ + public FrankfurtFaultcurrentConverter() { + super(ComponentName.FAULTCURRENT); + } - @Override - public SearchHit convert(SearchHit source) { - - JSONObject data = new JSONObject(); - JSONObject src = source.getSource(); - JSONObject srcInner = src.getJSONObject("faultCurrent"); - data.put("node-id", srcInner.getString("nodeName")); - data.put("severity", srcInner.getString("severity")); - data.put("counter", Long.parseLong(srcInner.getString("counter"))); - data.put("timestamp", srcInner.getString("timeStamp")); - data.put("object-id",srcInner.getString("objectId")); - data.put("problem", srcInner.getString("problem")); - - return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data ); - } + @Override + public SearchHit convert(SearchHit source) { + + JSONObject data = new JSONObject(); + JSONObject src = source.getSource(); + JSONObject srcInner = src.getJSONObject("faultCurrent"); + data.put("node-id", srcInner.getString("nodeName")); + data.put("severity", srcInner.getString("severity")); + data.put("counter", Long.parseLong(srcInner.getString("counter"))); + data.put("timestamp", srcInner.getString("timeStamp")); + data.put("object-id", srcInner.getString("objectId")); + data.put("problem", srcInner.getString("problem")); + + return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultlogConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultlogConverter.java index 87e71c612..f8319020d 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultlogConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtFaultlogConverter.java @@ -28,51 +28,34 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentName; /** * - * @author Michael Dürre - *{ - * "fault": { - * "nodeName": "SDN-Controller-5a150173d678", - * "counter": "380", - * "timeStamp": "2019-10-18T18:40:25.0Z", - * "objectId": "ADVA-DTAG-Nuernberg-3", - * "problem": "connectionLossOAM", - * "severity": "Major", - * "type": "ProblemNotificationXml" - * } - *} + * @author Michael Dürre { "fault": { "nodeName": "SDN-Controller-5a150173d678", "counter": "380", "timeStamp": + * "2019-10-18T18:40:25.0Z", "objectId": "ADVA-DTAG-Nuernberg-3", "problem": "connectionLossOAM", "severity": + * "Major", "type": "ProblemNotificationXml" } } * - * => - *{ - * "timestamp": "2017-01-01T00:00:00.0Z", - * "object-id": "LP-MWPS-RADIO", - * "severity": "Critical", - * "counter": -1, - * "node-id": "sim1", - * "source-type": "Netconf", - * "problem": "signalIsLost" - *} + * => { "timestamp": "2017-01-01T00:00:00.0Z", "object-id": "LP-MWPS-RADIO", "severity": "Critical", "counter": + * -1, "node-id": "sim1", "source-type": "Netconf", "problem": "signalIsLost" } * */ -public class FrankfurtFaultlogConverter extends BaseSearchHitConverter{ +public class FrankfurtFaultlogConverter extends BaseSearchHitConverter { - public FrankfurtFaultlogConverter() { - super(ComponentName.FAULTLOG); - } + public FrankfurtFaultlogConverter() { + super(ComponentName.FAULTLOG); + } - @Override - public SearchHit convert(SearchHit source) { - - JSONObject data = new JSONObject(); - JSONObject src = source.getSource(); - JSONObject srcInner = src.getJSONObject("fault"); - data.put("node-id", srcInner.getString("nodeName")); - data.put("severity", srcInner.getString("severity")); - data.put("counter", Long.parseLong(srcInner.getString("counter"))); - data.put("timestamp", srcInner.getString("timeStamp")); - data.put("object-id",srcInner.getString("objectId")); - data.put("problem", srcInner.getString("problem")); - data.put("type", "Netconf"); - return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data ); - } + @Override + public SearchHit convert(SearchHit source) { + + JSONObject data = new JSONObject(); + JSONObject src = source.getSource(); + JSONObject srcInner = src.getJSONObject("fault"); + data.put("node-id", srcInner.getString("nodeName")); + data.put("severity", srcInner.getString("severity")); + data.put("counter", Long.parseLong(srcInner.getString("counter"))); + data.put("timestamp", srcInner.getString("timeStamp")); + data.put("object-id", srcInner.getString("objectId")); + data.put("problem", srcInner.getString("problem")); + data.put("type", "Netconf"); + return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtMaintenanceConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtMaintenanceConverter.java index 16be5d97b..69b9a9934 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtMaintenanceConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtMaintenanceConverter.java @@ -31,56 +31,37 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentName; * * @author jack * - *{ - * "node": "ddd", - * "filter": [ - * { - * "definition": { - * "object-id-ref": "", - * "problem": "" - * }, - * "description": "", - * "start": "2019-11-26T15:37+00:00", - * "end": "2019-11-26T23:37+00:00" - * }], - * "active": false - *} - * => - *{ - * "id": "sim1" - * "node-id": "sim1", - * "description": "", - * "start": "2020-01-28T12:00:17.6Z", - * "end": "2020-01-28T12:00:17.6Z", - * "active": false, - * "object-id-ref": "", - * "problem": "" + * { "node": "ddd", "filter": [ { "definition": { "object-id-ref": "", "problem": "" }, "description": "", + * "start": "2019-11-26T15:37+00:00", "end": "2019-11-26T23:37+00:00" }], "active": false } => { "id": "sim1" + * "node-id": "sim1", "description": "", "start": "2020-01-28T12:00:17.6Z", "end": "2020-01-28T12:00:17.6Z", + * "active": false, "object-id-ref": "", "problem": "" * */ public class FrankfurtMaintenanceConverter extends BaseSearchHitConverter { - public FrankfurtMaintenanceConverter() { - super(ComponentName.MAINTENANCE); - } + public FrankfurtMaintenanceConverter() { + super(ComponentName.MAINTENANCE); + } - @Override - public SearchHit convert(SearchHit source) { + @Override + public SearchHit convert(SearchHit source) { - JSONObject src = source.getSource(); - JSONObject data = new JSONObject(); - data.put("id", src.getString("node")); - data.put("node-id", src.getString("node")); - data.put("active", src.getBoolean("active")); - JSONObject filter = null; - if (src.has("filter")) { - filter = src.getJSONArray("filter").length() > 0 ? src.getJSONArray("filter").getJSONObject(0) : null; - } - data.put("start", filter != null ? filter.getString("start") : ""); - data.put("end", filter != null ? filter.getString("end") : ""); - data.put("description", filter != null ? filter.getString("description") : ""); - JSONObject definition = filter!=null?filter.has("definition")?filter.getJSONObject("definition"):null:null; - data.put("problem", definition!=null?definition.getString("problem"):""); - data.put("object-id-ref", definition!=null?definition.getString("object-id-ref"):""); - return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); - } + JSONObject src = source.getSource(); + JSONObject data = new JSONObject(); + data.put("id", src.getString("node")); + data.put("node-id", src.getString("node")); + data.put("active", src.getBoolean("active")); + JSONObject filter = null; + if (src.has("filter")) { + filter = src.getJSONArray("filter").length() > 0 ? src.getJSONArray("filter").getJSONObject(0) : null; + } + data.put("start", filter != null ? filter.getString("start") : ""); + data.put("end", filter != null ? filter.getString("end") : ""); + data.put("description", filter != null ? filter.getString("description") : ""); + JSONObject definition = + filter != null ? filter.has("definition") ? filter.getJSONObject("definition") : null : null; + data.put("problem", definition != null ? definition.getString("problem") : ""); + data.put("object-id-ref", definition != null ? definition.getString("object-id-ref") : ""); + return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtRequiredNetworkElementConverter.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtRequiredNetworkElementConverter.java index ef6de907e..7cf18dd43 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtRequiredNetworkElementConverter.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/elalto/FrankfurtRequiredNetworkElementConverter.java @@ -31,48 +31,35 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.frankfurt.data.Connect * * @author Michael Dürre * - * { - * "mountId":"nts-manager-dev-micha", - * "host":"10.20.5.2", - * "port":8300, - * "username":"netconf", - * "password":"netconf" - * } + * { "mountId":"nts-manager-dev-micha", "host":"10.20.5.2", "port":8300, "username":"netconf", + * "password":"netconf" } * - * => + * => * - * { - * "node-id": "sim1", - * "is-required": true, - * "password": "ads", - * "port": 12600, - * "host": "10.20.5.2", - * "id": "sim1", - * "username": "ad", - * "status": "Connected" - * } + * { "node-id": "sim1", "is-required": true, "password": "ads", "port": 12600, "host": "10.20.5.2", "id": + * "sim1", "username": "ad", "status": "Connected" } * */ -public class FrankfurtRequiredNetworkElementConverter extends BaseSearchHitConverter{ +public class FrankfurtRequiredNetworkElementConverter extends BaseSearchHitConverter { - public FrankfurtRequiredNetworkElementConverter() { - super(ComponentName.REQUIRED_NETWORKELEMENT); - } + public FrankfurtRequiredNetworkElementConverter() { + super(ComponentName.REQUIRED_NETWORKELEMENT); + } - @Override - public SearchHit convert(SearchHit source) { - - JSONObject data = new JSONObject(); - JSONObject src = source.getSource(); - data.put("id", src.getString("mountId")); - data.put("node-id", src.getString("mountId")); - data.put("username", src.getString("username")); - data.put("password", src.getString("password")); - data.put("host", src.getString("host")); - data.put("port", src.getInt("port")); - data.put("status", ConnectionLogStatus.Undefined.getName()); - data.put("is-required", true); - return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data ); - } + @Override + public SearchHit convert(SearchHit source) { + + JSONObject data = new JSONObject(); + JSONObject src = source.getSource(); + data.put("id", src.getString("mountId")); + data.put("node-id", src.getString("mountId")); + data.put("username", src.getString("username")); + data.put("password", src.getString("password")); + data.put("host", src.getString("host")); + data.put("port", src.getInt("port")); + data.put("status", ConnectionLogStatus.Undefined.getName()); + data.put("is-required", true); + return this.getSearchHit(source.getIndex(), source.getType(), source.getId(), data); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/FrankfurtReleaseInformation.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/FrankfurtReleaseInformation.java index bbbde1f22..ad0abee89 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/FrankfurtReleaseInformation.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/FrankfurtReleaseInformation.java @@ -37,65 +37,65 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.ReleaseInformation; public class FrankfurtReleaseInformation extends ReleaseInformation { - private final Logger LOG = LoggerFactory.getLogger(FrankfurtReleaseInformation.class); - private final Map> converters = new HashMap<>(); + private final Logger LOG = LoggerFactory.getLogger(FrankfurtReleaseInformation.class); + private final Map> converters = new HashMap<>(); - public FrankfurtReleaseInformation() { - super(Release.FRANKFURT_R1, createDBMap()); - } + public FrankfurtReleaseInformation() { + super(Release.FRANKFURT_R1, createDBMap()); + } - private static Map createDBMap() { - Map map = new HashMap<>(); - map.put(ComponentName.CONNECTIONLOG, new DatabaseInfo("connectionlog", "connectionlog", - "{\"node-id\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"status\": {\"type\": \"keyword\"}}")); - map.put(ComponentName.EVENTLOG, new DatabaseInfo("eventlog", "eventlog", - "{\"node-id\": {\"type\": \"keyword\"},\"source-type\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"new-value\": {\"type\": \"keyword\"},\"attribute-name\": {\"type\": \"keyword\"},\"counter\": {\"type\": \"long\"},\"object-id\": {\"type\": \"keyword\"}}")); - map.put(ComponentName.FAULTCURRENT, new DatabaseInfo("faultcurrent", "faultcurrent", - "{\"node-id\": {\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"problem\": {\"type\": \"keyword\"},\"counter\": {\"type\": \"long\"},\"object-id\":{\"type\": \"keyword\"}}")); - map.put(ComponentName.FAULTLOG, new DatabaseInfo("faultlog", "faultlog", - "{\"node-id\": {\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"problem\": {\"type\": \"keyword\"},\"counter\": {\"type\": \"long\"},\"object-id\":{\"type\": \"keyword\"},\"source-type\":{\"type\": \"keyword\"}}")); - map.put(ComponentName.INVENTORY, new DatabaseInfo("inventoryequipment", "inventoryequipment", - "{\"date\": {\"type\": \"keyword\"},\"model-identifier\": {\"type\": \"keyword\"},\"manufacturer-identifier\": {\"type\": \"keyword\"},\"type-name\": {\"type\": \"keyword\"},\"description\": {\"type\": \"keyword\"},\"uuid\": {\"type\": \"keyword\"},\"version\": {\"type\": \"keyword\"},\"parent-uuid\": {\"type\": \"keyword\"},\"contained-holder\": {\"type\": \"keyword\"},\"node-id\": {\"type\": \"keyword\"},\"tree-level\": {\"type\": \"long\"},\"part-type-id\": {\"type\": \"keyword\"},\"serial\": {\"type\": \"keyword\"}}")); - map.put(ComponentName.HISTORICAL_PERFORMANCE_15M, new DatabaseInfo("historicalperformance15min", - "historicalperformance15min", - "{\"node-name\":{\"type\": \"keyword\"},\"timestamp\":{\"type\": \"date\"},\"suspect-interval-flag\":{\"type\":\"boolean\"},\"scanner-id\":{\"type\": \"keyword\"},\"uuid-interface\":{\"type\": \"keyword\"},\"layer-protocol-name\":{\"type\": \"keyword\"},\"granularity-period\":{\"type\": \"keyword\"},\"radio-signal-id\":{\"type\": \"keyword\"}}")); - map.put(ComponentName.HISTORICAL_PERFORMANCE_24H, new DatabaseInfo("historicalperformance24h", - "historicalperformance24h", - "{\"node-name\":{\"type\": \"keyword\"},\"timestamp\":{\"type\": \"date\"},\"suspect-interval-flag\":{\"type\":\"boolean\"},\"scanner-id\":{\"type\": \"keyword\"},\"uuid-interface\":{\"type\": \"keyword\"},\"layer-protocol-name\":{\"type\": \"keyword\"},\"granularity-period\":{\"type\": \"keyword\"},\"radio-signal-id\":{\"type\": \"keyword\"}}")); - map.put(ComponentName.REQUIRED_NETWORKELEMENT, new DatabaseInfo("networkelement-connection", - "networkelement-connection", - "{\"node-id\": {\"type\": \"keyword\"},\"host\": {\"type\": \"keyword\"},\"port\": {\"type\": \"long\"},\"username\": {\"type\": \"keyword\"},\"password\": {\"type\": \"keyword\"},\"core-model-capability\": {\"type\": \"keyword\"},\"device-type\": {\"type\": \"keyword\"},\"is-required\": {\"type\": \"boolean\"},\"status\": {\"type\": \"keyword\"}}")); - map.put(ComponentName.MEDIATOR_SERVER, new DatabaseInfo("mediator-server", "mediator-server", - "{\"url\":{\"type\": \"keyword\"},\"name\":{\"type\": \"keyword\"}}")); - map.put(ComponentName.MAINTENANCE, new DatabaseInfo("maintenancemode", "maintenancemode", - "{\"node-id\": {\"type\": \"keyword\"},\"start\": {\"type\": \"date\"},\"end\": {\"type\": \"date\"},\"description\": {\"type\": \"keyword\"},\"active\": {\"type\": \"boolean\"}},\"date_detection\":false}}")); - return map; - } + private static Map createDBMap() { + Map map = new HashMap<>(); + map.put(ComponentName.CONNECTIONLOG, new DatabaseInfo("connectionlog", "connectionlog", + "{\"node-id\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"status\": {\"type\": \"keyword\"}}")); + map.put(ComponentName.EVENTLOG, new DatabaseInfo("eventlog", "eventlog", + "{\"node-id\": {\"type\": \"keyword\"},\"source-type\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"new-value\": {\"type\": \"keyword\"},\"attribute-name\": {\"type\": \"keyword\"},\"counter\": {\"type\": \"long\"},\"object-id\": {\"type\": \"keyword\"}}")); + map.put(ComponentName.FAULTCURRENT, new DatabaseInfo("faultcurrent", "faultcurrent", + "{\"node-id\": {\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"problem\": {\"type\": \"keyword\"},\"counter\": {\"type\": \"long\"},\"object-id\":{\"type\": \"keyword\"}}")); + map.put(ComponentName.FAULTLOG, new DatabaseInfo("faultlog", "faultlog", + "{\"node-id\": {\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"},\"timestamp\": {\"type\": \"date\"},\"problem\": {\"type\": \"keyword\"},\"counter\": {\"type\": \"long\"},\"object-id\":{\"type\": \"keyword\"},\"source-type\":{\"type\": \"keyword\"}}")); + map.put(ComponentName.INVENTORY, new DatabaseInfo("inventoryequipment", "inventoryequipment", + "{\"date\": {\"type\": \"keyword\"},\"model-identifier\": {\"type\": \"keyword\"},\"manufacturer-identifier\": {\"type\": \"keyword\"},\"type-name\": {\"type\": \"keyword\"},\"description\": {\"type\": \"keyword\"},\"uuid\": {\"type\": \"keyword\"},\"version\": {\"type\": \"keyword\"},\"parent-uuid\": {\"type\": \"keyword\"},\"contained-holder\": {\"type\": \"keyword\"},\"node-id\": {\"type\": \"keyword\"},\"tree-level\": {\"type\": \"long\"},\"part-type-id\": {\"type\": \"keyword\"},\"serial\": {\"type\": \"keyword\"}}")); + map.put(ComponentName.HISTORICAL_PERFORMANCE_15M, new DatabaseInfo("historicalperformance15min", + "historicalperformance15min", + "{\"node-name\":{\"type\": \"keyword\"},\"timestamp\":{\"type\": \"date\"},\"suspect-interval-flag\":{\"type\":\"boolean\"},\"scanner-id\":{\"type\": \"keyword\"},\"uuid-interface\":{\"type\": \"keyword\"},\"layer-protocol-name\":{\"type\": \"keyword\"},\"granularity-period\":{\"type\": \"keyword\"},\"radio-signal-id\":{\"type\": \"keyword\"}}")); + map.put(ComponentName.HISTORICAL_PERFORMANCE_24H, new DatabaseInfo("historicalperformance24h", + "historicalperformance24h", + "{\"node-name\":{\"type\": \"keyword\"},\"timestamp\":{\"type\": \"date\"},\"suspect-interval-flag\":{\"type\":\"boolean\"},\"scanner-id\":{\"type\": \"keyword\"},\"uuid-interface\":{\"type\": \"keyword\"},\"layer-protocol-name\":{\"type\": \"keyword\"},\"granularity-period\":{\"type\": \"keyword\"},\"radio-signal-id\":{\"type\": \"keyword\"}}")); + map.put(ComponentName.REQUIRED_NETWORKELEMENT, new DatabaseInfo("networkelement-connection", + "networkelement-connection", + "{\"node-id\": {\"type\": \"keyword\"},\"host\": {\"type\": \"keyword\"},\"port\": {\"type\": \"long\"},\"username\": {\"type\": \"keyword\"},\"password\": {\"type\": \"keyword\"},\"core-model-capability\": {\"type\": \"keyword\"},\"device-type\": {\"type\": \"keyword\"},\"is-required\": {\"type\": \"boolean\"},\"status\": {\"type\": \"keyword\"}}")); + map.put(ComponentName.MEDIATOR_SERVER, new DatabaseInfo("mediator-server", "mediator-server", + "{\"url\":{\"type\": \"keyword\"},\"name\":{\"type\": \"keyword\"}}")); + map.put(ComponentName.MAINTENANCE, new DatabaseInfo("maintenancemode", "maintenancemode", + "{\"node-id\": {\"type\": \"keyword\"},\"start\": {\"type\": \"date\"},\"end\": {\"type\": \"date\"},\"description\": {\"type\": \"keyword\"},\"active\": {\"type\": \"boolean\"}},\"date_detection\":false}}")); + return map; + } - @Override - public SearchHitConverter getConverter(Release dst, ComponentName comp) { - SearchHitConverter c = this.converters.containsKey(dst) ? this.converters.get(dst).get(comp) : null; - if (c == null) { - c = super.getConverter(dst, comp); - } - return c; - } + @Override + public SearchHitConverter getConverter(Release dst, ComponentName comp) { + SearchHitConverter c = this.converters.containsKey(dst) ? this.converters.get(dst).get(comp) : null; + if (c == null) { + c = super.getConverter(dst, comp); + } + return c; + } - @Override - protected boolean runPreInitCommands(HtDatabaseClient dbClient) { + @Override + protected boolean runPreInitCommands(HtDatabaseClient dbClient) { - ClusterSettingsResponse response = null; - try { - response = dbClient.setupClusterSettings(new ClusterSettingsRequest(false)); - } catch (IOException e) { - LOG.warn("problem setting up cluster: {}", e); - } - return response == null ? false : response.isAcknowledged(); - } + ClusterSettingsResponse response = null; + try { + response = dbClient.setupClusterSettings(new ClusterSettingsRequest(false)); + } catch (IOException e) { + LOG.warn("problem setting up cluster: {}", e); + } + return response == null ? false : response.isAcknowledged(); + } - @Override - protected boolean runPostInitCommands(HtDatabaseClient dbClient) { - return true; - } + @Override + protected boolean runPostInitCommands(HtDatabaseClient dbClient) { + return true; + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/data/ConnectionLogStatus.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/data/ConnectionLogStatus.java index 7615c4452..1ecae6782 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/data/ConnectionLogStatus.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/frankfurt/data/ConnectionLogStatus.java @@ -26,13 +26,13 @@ package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.frankfurt.data; * */ public enum ConnectionLogStatus { - Connected, Connecting, UnableToConnect, Mounted, Unmounted, Undefined; + Connected, Connecting, UnableToConnect, Mounted, Unmounted, Undefined; - /** - * @return - */ - public String getName() { - return this.name(); - } + /** + * @return + */ + public String getName() { + return this.name(); + } } diff --git a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/guilin/GuilinReleaseInformation.java b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/guilin/GuilinReleaseInformation.java index 7b5e38116..a81a6f0fd 100644 --- a/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/guilin/GuilinReleaseInformation.java +++ b/sdnr/wt/data-provider/setup/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/guilin/GuilinReleaseInformation.java @@ -35,48 +35,48 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DatabaseInfo; public class GuilinReleaseInformation extends ReleaseInformation { - /** - * @param r - * @param dbMap - */ - public GuilinReleaseInformation() { - super(Release.GUILIN, createDBMap()); + /** + * @param r + * @param dbMap + */ + public GuilinReleaseInformation() { + super(Release.GUILIN, createDBMap()); - } + } - private static Map createDBMap() { - Map map = new HashMap<>(); - map.put(ComponentName.EVENTLOG, new DatabaseInfo("eventlog", "eventlog", "")); - map.put(ComponentName.FAULTCURRENT, new DatabaseInfo("faultcurrent", "faultcurrent", "")); - map.put(ComponentName.FAULTLOG, new DatabaseInfo("faultlog", "faultlog", "")); - map.put(ComponentName.INVENTORY, new DatabaseInfo("inventoryequipment", "inventoryequipment", "")); - map.put(ComponentName.HISTORICAL_PERFORMANCE_15M, - new DatabaseInfo("historicalperformance15min", "historicalperformance15min", "")); - map.put(ComponentName.HISTORICAL_PERFORMANCE_24H, - new DatabaseInfo("historicalperformance24h", "historicalperformance24h", "")); - map.put(ComponentName.REQUIRED_NETWORKELEMENT, - new DatabaseInfo("networkelement-connection", "networkelement-connection", "")); - map.put(ComponentName.MEDIATOR_SERVER, new DatabaseInfo("mediator-server", "mediator-server", "")); - map.put(ComponentName.MAINTENANCE, new DatabaseInfo("maintenancemode", "maintenancemode", "")); - return map; - } + private static Map createDBMap() { + Map map = new HashMap<>(); + map.put(ComponentName.EVENTLOG, new DatabaseInfo("eventlog", "eventlog", "")); + map.put(ComponentName.FAULTCURRENT, new DatabaseInfo("faultcurrent", "faultcurrent", "")); + map.put(ComponentName.FAULTLOG, new DatabaseInfo("faultlog", "faultlog", "")); + map.put(ComponentName.INVENTORY, new DatabaseInfo("inventoryequipment", "inventoryequipment", "")); + map.put(ComponentName.HISTORICAL_PERFORMANCE_15M, + new DatabaseInfo("historicalperformance15min", "historicalperformance15min", "")); + map.put(ComponentName.HISTORICAL_PERFORMANCE_24H, + new DatabaseInfo("historicalperformance24h", "historicalperformance24h", "")); + map.put(ComponentName.REQUIRED_NETWORKELEMENT, + new DatabaseInfo("networkelement-connection", "networkelement-connection", "")); + map.put(ComponentName.MEDIATOR_SERVER, new DatabaseInfo("mediator-server", "mediator-server", "")); + map.put(ComponentName.MAINTENANCE, new DatabaseInfo("maintenancemode", "maintenancemode", "")); + return map; + } - @Override - public SearchHitConverter getConverter(Release dst, ComponentName comp) { - if (dst == Release.GUILIN) { - return new KeepDataSearchHitConverter(comp); - } - return null; - } + @Override + public SearchHitConverter getConverter(Release dst, ComponentName comp) { + if (dst == Release.GUILIN) { + return new KeepDataSearchHitConverter(comp); + } + return null; + } - @Override - protected boolean runPreInitCommands(HtDatabaseClient dbClient) { - return true; - } + @Override + protected boolean runPreInitCommands(HtDatabaseClient dbClient) { + return true; + } - @Override - protected boolean runPostInitCommands(HtDatabaseClient dbClient) { - return true; - } + @Override + protected boolean runPostInitCommands(HtDatabaseClient dbClient) { + return true; + } } diff --git a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestData.java b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestData.java index 03629edaa..c7864560b 100644 --- a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestData.java +++ b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestData.java @@ -48,128 +48,111 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release; * */ public class TestData { - private static final JSONObject EVENTLOG_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" - + "\"_type\": \"eventlog\",\n" + "\"_id\": \"AXB7cJHlZ_FApnwi29xq\",\n" + "\"_version\": 1,\n" - + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"event\": {\n" - + "\"nodeName\": \"SDN-Controller-465e2ae306ca\",\n" + "\"counter\": \"1\",\n" - + "\"timeStamp\": \"2020-02-25T08:22:19.8Z\",\n" + "\"objectId\": \"sim2230\",\n" - + "\"attributeName\": \"ConnectionStatus\",\n" + "\"newValue\": \"connecting\",\n" - + "\"type\": \"AttributeValueChangedNotificationXml\"\n" + "}\n" + "}\n" + "}"); - private static final JSONObject EVENTLOG_SEARCHHIT2= new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" - + "\"_type\": \"eventlog\",\n" + "\"_id\": \"AXB7cJHlZ_FApnwi29xq\",\n" + "\"_version\": 1,\n" - + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"event\": {\n" - + "\"nodeName\": \"SDN-Controller-465e2ae306ca\",\n" + "\"counter\": \"3\",\n" - + "\"timeStamp\": \"2020-02-22T08:22:19.8Z\",\n" + "\"objectId\": \"sim2230\",\n" - + "\"attributeName\": \"ConnectionStatus\",\n" + "\"newValue\": \"connected\",\n" - + "\"type\": \"AttributeValueChangedNotificationXml\"\n" + "}\n" + "}\n" + "}"); - private static final String CONFIG_CONTENT = "[dcae]\n" + - "dcaeUserCredentials=admin:admin\n" + - "dcaeUrl=off\n" + - "dcaeHeartbeatPeriodSeconds=120\n" + - "dcaeTestCollector=no\n" + - "\n" + - "[es]\n" + - "esCluster=sendateodl5\n" + - "#time limit to keep increasing data in database [in seconds]\n" + - "#60*60*24*30 (30days)\n" + - "esArchiveLimit=2592000\n" + - "#folder where removed data will be stored\n" + - "esArchiveFolder=./backup\n" + - "#interval to archive database [in seconds]\n" + - "#60*60*24 (1day)\n" + - "esArchiveInterval=86400\n" + - "\n" + - "[aai]\n" + - "#keep comment\n" + - "aaiHeaders=[\"X-TransactionId: 9999\"]\n" + - "aaiUrl=http://localhost:81\n" + - "aaiUserCredentials=AAI:AAI\n" + - "aaiDeleteOnMountpointRemove=false\n" + - "aaiTrustAllCerts=false\n" + - "aaiApiVersion=aai/v13\n" + - "aaiPropertiesFile=aaiclient.properties\n" + - "aaiApplicationId=SDNR\n" + - "aaiPcks12ClientCertFile=/opt/logs/externals/data/stores/keystore.client.p12\n" + - "aaiPcks12ClientCertPassphrase=adminadmin\n" + - "aaiClientConnectionTimeout=30000\n" + - "\n" + - "[pm]\n" + - "pmCluster=sendateodl5\n" + - "pmEnabled=true\n" + - ""; - @Test - public void testComponentData() { - JSONArray hits = new JSONArray(); - hits.put(EVENTLOG_SEARCHHIT); - hits.put(EVENTLOG_SEARCHHIT2); - ComponentData data = new ComponentData(ComponentName.EVENTLOG,hits); - JSONArray out = data.toJsonArray(); - assertEquals(ComponentName.EVENTLOG, data.getName()); - JSONAssert.assertEquals(EVENTLOG_SEARCHHIT.toString(),out.getJSONObject(0).toString(),false); - JSONAssert.assertEquals(EVENTLOG_SEARCHHIT2.toString(),out.getJSONObject(1).toString(),false); - - } - @Test - public void testConfigData() { - ConfigData data = new ConfigData(CONFIG_CONTENT); - assertTrue(data.getLines().length>10); - } - @Test - public void testConfigName() { - ConfigName name = ConfigName.APIGATEWAY; - assertEquals("apigateway", name.getValue()); - try { - assertEquals(ConfigName.APIGATEWAY,ConfigName.getValueOf("apigateway")); - } catch (Exception e) { - fail(e.getMessage()); - } - - } - @Test - public void testDataContainer() { - DataContainer container = new DataContainer(); - assertEquals(Release.CURRENT_RELEASE,container.getRelease()); - assertNotNull(container.getCreated()); - - try { - container = DataContainer.load(new File("src/test/resources/test.bak.json")); - } catch (Exception e) { - fail(e.getMessage()); - } - assertNotNull(container); - assertEquals(Release.EL_ALTO,container.getRelease()); - assertNotNull(container.getCreated()); - assertTrue(container.getComponents().size()>0); - assertTrue(container.getConfigs().size()==0); - } - @Test - public void testReport() { - DataMigrationReport report = new DataMigrationReport(); - - assertFalse(report.completed()); - long myvar = 42; - String myvar2 = "come"; - report.log("%d was wrong",myvar); - report.error("%s to me",myvar2); - assertTrue(report.toString().contains("42 was wrong")); - assertTrue(report.toString().contains("come to me")); - report.setCompleted(true); - assertTrue(report.completed()); - - } - @Test - public void TestPluginFileCreation() { - - final String TESTFILE = "asi324po.sa"; - try { - MavenDatabasePluginInitFile.create(Release.FRANKFURT_R1, TESTFILE); - } catch (IOException e) { - fail(e.getMessage()); - } - File f = new File(TESTFILE); - if(f.exists()) { - f.delete(); - } - } - + private static final JSONObject EVENTLOG_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" + + "\"_type\": \"eventlog\",\n" + "\"_id\": \"AXB7cJHlZ_FApnwi29xq\",\n" + "\"_version\": 1,\n" + + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"event\": {\n" + + "\"nodeName\": \"SDN-Controller-465e2ae306ca\",\n" + "\"counter\": \"1\",\n" + + "\"timeStamp\": \"2020-02-25T08:22:19.8Z\",\n" + "\"objectId\": \"sim2230\",\n" + + "\"attributeName\": \"ConnectionStatus\",\n" + "\"newValue\": \"connecting\",\n" + + "\"type\": \"AttributeValueChangedNotificationXml\"\n" + "}\n" + "}\n" + "}"); + private static final JSONObject EVENTLOG_SEARCHHIT2 = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" + + "\"_type\": \"eventlog\",\n" + "\"_id\": \"AXB7cJHlZ_FApnwi29xq\",\n" + "\"_version\": 1,\n" + + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"event\": {\n" + + "\"nodeName\": \"SDN-Controller-465e2ae306ca\",\n" + "\"counter\": \"3\",\n" + + "\"timeStamp\": \"2020-02-22T08:22:19.8Z\",\n" + "\"objectId\": \"sim2230\",\n" + + "\"attributeName\": \"ConnectionStatus\",\n" + "\"newValue\": \"connected\",\n" + + "\"type\": \"AttributeValueChangedNotificationXml\"\n" + "}\n" + "}\n" + "}"); + private static final String CONFIG_CONTENT = "[dcae]\n" + "dcaeUserCredentials=admin:admin\n" + "dcaeUrl=off\n" + + "dcaeHeartbeatPeriodSeconds=120\n" + "dcaeTestCollector=no\n" + "\n" + "[es]\n" + + "esCluster=sendateodl5\n" + "#time limit to keep increasing data in database [in seconds]\n" + + "#60*60*24*30 (30days)\n" + "esArchiveLimit=2592000\n" + "#folder where removed data will be stored\n" + + "esArchiveFolder=./backup\n" + "#interval to archive database [in seconds]\n" + "#60*60*24 (1day)\n" + + "esArchiveInterval=86400\n" + "\n" + "[aai]\n" + "#keep comment\n" + + "aaiHeaders=[\"X-TransactionId: 9999\"]\n" + "aaiUrl=http://localhost:81\n" + + "aaiUserCredentials=AAI:AAI\n" + "aaiDeleteOnMountpointRemove=false\n" + "aaiTrustAllCerts=false\n" + + "aaiApiVersion=aai/v13\n" + "aaiPropertiesFile=aaiclient.properties\n" + "aaiApplicationId=SDNR\n" + + "aaiPcks12ClientCertFile=/opt/logs/externals/data/stores/keystore.client.p12\n" + + "aaiPcks12ClientCertPassphrase=adminadmin\n" + "aaiClientConnectionTimeout=30000\n" + "\n" + "[pm]\n" + + "pmCluster=sendateodl5\n" + "pmEnabled=true\n" + ""; + + @Test + public void testComponentData() { + JSONArray hits = new JSONArray(); + hits.put(EVENTLOG_SEARCHHIT); + hits.put(EVENTLOG_SEARCHHIT2); + ComponentData data = new ComponentData(ComponentName.EVENTLOG, hits); + JSONArray out = data.toJsonArray(); + assertEquals(ComponentName.EVENTLOG, data.getName()); + JSONAssert.assertEquals(EVENTLOG_SEARCHHIT.toString(), out.getJSONObject(0).toString(), false); + JSONAssert.assertEquals(EVENTLOG_SEARCHHIT2.toString(), out.getJSONObject(1).toString(), false); + + } + + @Test + public void testConfigData() { + ConfigData data = new ConfigData(CONFIG_CONTENT); + assertTrue(data.getLines().length > 10); + } + + @Test + public void testConfigName() { + ConfigName name = ConfigName.APIGATEWAY; + assertEquals("apigateway", name.getValue()); + try { + assertEquals(ConfigName.APIGATEWAY, ConfigName.getValueOf("apigateway")); + } catch (Exception e) { + fail(e.getMessage()); + } + + } + + @Test + public void testDataContainer() { + DataContainer container = new DataContainer(); + assertEquals(Release.CURRENT_RELEASE, container.getRelease()); + assertNotNull(container.getCreated()); + + try { + container = DataContainer.load(new File("src/test/resources/test.bak.json")); + } catch (Exception e) { + fail(e.getMessage()); + } + assertNotNull(container); + assertEquals(Release.EL_ALTO, container.getRelease()); + assertNotNull(container.getCreated()); + assertTrue(container.getComponents().size() > 0); + assertTrue(container.getConfigs().size() == 0); + } + + @Test + public void testReport() { + DataMigrationReport report = new DataMigrationReport(); + + assertFalse(report.completed()); + long myvar = 42; + String myvar2 = "come"; + report.log("%d was wrong", myvar); + report.error("%s to me", myvar2); + assertTrue(report.toString().contains("42 was wrong")); + assertTrue(report.toString().contains("come to me")); + report.setCompleted(true); + assertTrue(report.completed()); + + } + + @Test + public void TestPluginFileCreation() { + + final String TESTFILE = "asi324po.sa"; + try { + MavenDatabasePluginInitFile.create(Release.FRANKFURT_R1, TESTFILE); + } catch (IOException e) { + fail(e.getMessage()); + } + File f = new File(TESTFILE); + if (f.exists()) { + f.delete(); + } + } + } diff --git a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoReleaseInformation.java b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoReleaseInformation.java index 4d5ebaa4a..05a2ffe7a 100644 --- a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoReleaseInformation.java +++ b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoReleaseInformation.java @@ -42,9 +42,9 @@ public class TestElAltoReleaseInformation { Set components = ri.getComponents(); assertFalse(components.contains(ComponentName.CONNECTIONLOG)); assertTrue(components.contains(ComponentName.EVENTLOG)); - assertEquals("sdnevents",ri.getAlias(ComponentName.FAULTLOG)); - assertEquals("sdnevents_v1",ri.getIndex(ComponentName.FAULTLOG)); - assertNull(ri.getConverter(Release.EL_ALTO,ComponentName.CONNECTIONLOG)); + assertEquals("sdnevents", ri.getAlias(ComponentName.FAULTLOG)); + assertEquals("sdnevents_v1", ri.getIndex(ComponentName.FAULTLOG)); + assertNull(ri.getConverter(Release.EL_ALTO, ComponentName.CONNECTIONLOG)); assertNotNull(ri.getConverter(Release.EL_ALTO, ComponentName.FAULTCURRENT)); } diff --git a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoToFrankfurtConversion.java b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoToFrankfurtConversion.java index 07a60a0f1..d515e2a6b 100644 --- a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoToFrankfurtConversion.java +++ b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestElAltoToFrankfurtConversion.java @@ -38,100 +38,85 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.elalto.ElAltoReleaseIn */ public class TestElAltoToFrankfurtConversion { - private static final JSONObject FAULTLOG_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" - + "\"_type\": \"faultlog\",\n" + "\"_id\": \"sim12600/LP-MWS-TTP-01/unknownProblem1\",\n" - + "\"_version\": 1,\n" + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"fault\": {\n" - + "\"nodeName\": \"sim12600\",\n" + "\"counter\": \"1\",\n" + "\"timeStamp\": \"2017-01-01T00:00:00.0Z\",\n" - + "\"objectId\": \"LP-MWS-TTP-01\",\n" + "\"problem\": \"unknownProblem1\",\n" - + "\"severity\": \"Critical\",\n" + "\"type\": \"ProblemNotificationXml\"\n" + "}\n" + "}\n" + "}"); - private static final JSONObject FAULTCURRENT_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" - + "\"_type\": \"faultcurrent\",\n" + "\"_id\": \"sim12600/LP-MWS-TTP-01/unknownProblem1\",\n" - + "\"_version\": 1,\n" + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"faultCurrent\": {\n" - + "\"nodeName\": \"sim12600\",\n" + "\"counter\": \"1\",\n" + "\"timeStamp\": \"2017-01-01T00:00:00.0Z\",\n" - + "\"objectId\": \"LP-MWS-TTP-01\",\n" + "\"problem\": \"unknownProblem1\",\n" - + "\"severity\": \"Critical\",\n" + "\"type\": \"ProblemNotificationXml\"\n" + "}\n" + "}\n" + "}"); - private static final JSONObject INVENTORY_SEARCHHIT = new JSONObject( - "{\n" + "\"_index\": \"sdnevents_v1\",\n" + "\"_type\": \"inventoryequipment\",\n" - + "\"_id\": \"sim12600/a2.module-1.1.5.5\",\n" + "\"_version\": 1,\n" + "\"_score\": 1,\n" - + "\"_source\": {\n" + "\"treeLevel\": 2,\n" + "\"parentUuid\": \"CARD-1.1.5.0\",\n" - + "\"mountpoint\": \"sim12600\",\n" + "\"uuid\": \"a2.module-1.1.5.5\",\n" - + "\"containedHolder\": [\n" + "\"SUBRACK-1.55.0.0\"\n" + "],\n" + "\"manufacturerName\": null,\n" - + "\"manufacturerIdentifier\": \"ONF-Wireless-Transport\",\n" + "\"serial\": \"310330015\",\n" - + "\"date\": \"2013-04-13T00:00:00.0Z\",\n" + "\"version\": \"a2.module-newest\",\n" - + "\"description\": \"WS/p8.module/a2.module#5\",\n" + "\"partTypeId\": \"3EM23141AD01\",\n" - + "\"modelIdentifier\": \"CRPQABVFAA\",\n" + "\"typeName\": \"a2.module\"\n" + "}\n" + "}"); - private static final JSONObject REQUIREDNE_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"mwtn_v1\",\n" - + "\"_type\": \"required-networkelement\",\n" + "\"_id\": \"sim2230\",\n" + "\"_version\": 1,\n" - + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"mountId\": \"sim2230\",\n" + "\"host\": \"10.20.5.2\",\n" - + "\"port\": 2230,\n" + "\"username\": \"adsa\",\n" + "\"password\": \"asda\"\n" + "}\n" + "}"); - private static final JSONObject EVENTLOG_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" - + "\"_type\": \"eventlog\",\n" + "\"_id\": \"AXB7cJHlZ_FApnwi29xq\",\n" + "\"_version\": 1,\n" - + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"event\": {\n" - + "\"nodeName\": \"SDN-Controller-465e2ae306ca\",\n" + "\"counter\": \"1\",\n" - + "\"timeStamp\": \"2020-02-25T08:22:19.8Z\",\n" + "\"objectId\": \"sim2230\",\n" - + "\"attributeName\": \"ConnectionStatus\",\n" + "\"newValue\": \"connecting\",\n" - + "\"type\": \"AttributeValueChangedNotificationXml\"\n" + "}\n" + "}\n" + "}"); - private static final JSONObject MAINTENANCE_SEARCHHIT = new JSONObject("{\n" + - "\"_index\": \"mwtn_v1\",\n" + - "\"_type\": \"maintenancemode\",\n" + - "\"_id\": \"sim2230\",\n" + - "\"_version\": 1,\n" + - "\"_score\": 1,\n" + - "\"_source\": {\n" + - "\"node\": \"sim2230\",\n" + - "\"filter\": [\n" + - "{\n" + - "\"definition\": {\n" + - "\"object-id-ref\": \"\",\n" + - "\"problem\": \"\"\n" + - "},\n" + - "\"description\": \"\",\n" + - "\"start\": \"\",\n" + - "\"end\": \"\"\n" + - "}\n" + - "],\n" + - "\"active\": false\n" + - "}\n" + - "}"); - @Test - public void test() { - ElAltoReleaseInformation ri = new ElAltoReleaseInformation(); - //faultlog - SearchHitConverter faultlogConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.FAULTLOG); - assertNotNull(faultlogConverter); - SearchHit frankfurtFaultlogEntry = faultlogConverter.convert(new SearchHit(FAULTLOG_SEARCHHIT)); - assertNotNull(frankfurtFaultlogEntry); - //faultcurrent - SearchHitConverter faultcurrentConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.FAULTCURRENT); - assertNotNull(faultcurrentConverter); - SearchHit frankfurtFaultcurrentEntry = faultcurrentConverter.convert(new SearchHit(FAULTCURRENT_SEARCHHIT)); - assertNotNull(frankfurtFaultcurrentEntry); - //inventory - SearchHitConverter inventoryConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.INVENTORY); - assertNotNull(inventoryConverter); - SearchHit frankfurtInventory = inventoryConverter.convert(new SearchHit(INVENTORY_SEARCHHIT)); - assertNotNull(frankfurtInventory); - //inventory - SearchHitConverter neConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.REQUIRED_NETWORKELEMENT); - assertNotNull(neConverter); - SearchHit frankfurtNE = neConverter.convert(new SearchHit(REQUIREDNE_SEARCHHIT)); - assertNotNull(frankfurtNE); - //eventlog - SearchHitConverter eventlogConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.EVENTLOG); - assertNotNull(eventlogConverter); - SearchHit frankfurtEvent = eventlogConverter.convert(new SearchHit(EVENTLOG_SEARCHHIT)); - assertNull(frankfurtEvent); - //eventlog->connectionlog - SearchHitConverter conlogConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.CONNECTIONLOG); - assertNotNull(conlogConverter); - SearchHit frankfurtconlog = conlogConverter.convert(new SearchHit(EVENTLOG_SEARCHHIT)); - assertNotNull(frankfurtconlog); - //maintenance - SearchHitConverter maintenanceConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.MAINTENANCE); - assertNotNull(maintenanceConverter); - SearchHit frankfurtmaint = maintenanceConverter.convert(new SearchHit(MAINTENANCE_SEARCHHIT)); - assertNotNull(frankfurtmaint); + private static final JSONObject FAULTLOG_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" + + "\"_type\": \"faultlog\",\n" + "\"_id\": \"sim12600/LP-MWS-TTP-01/unknownProblem1\",\n" + + "\"_version\": 1,\n" + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"fault\": {\n" + + "\"nodeName\": \"sim12600\",\n" + "\"counter\": \"1\",\n" + "\"timeStamp\": \"2017-01-01T00:00:00.0Z\",\n" + + "\"objectId\": \"LP-MWS-TTP-01\",\n" + "\"problem\": \"unknownProblem1\",\n" + + "\"severity\": \"Critical\",\n" + "\"type\": \"ProblemNotificationXml\"\n" + "}\n" + "}\n" + "}"); + private static final JSONObject FAULTCURRENT_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" + + "\"_type\": \"faultcurrent\",\n" + "\"_id\": \"sim12600/LP-MWS-TTP-01/unknownProblem1\",\n" + + "\"_version\": 1,\n" + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"faultCurrent\": {\n" + + "\"nodeName\": \"sim12600\",\n" + "\"counter\": \"1\",\n" + "\"timeStamp\": \"2017-01-01T00:00:00.0Z\",\n" + + "\"objectId\": \"LP-MWS-TTP-01\",\n" + "\"problem\": \"unknownProblem1\",\n" + + "\"severity\": \"Critical\",\n" + "\"type\": \"ProblemNotificationXml\"\n" + "}\n" + "}\n" + "}"); + private static final JSONObject INVENTORY_SEARCHHIT = + new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" + "\"_type\": \"inventoryequipment\",\n" + + "\"_id\": \"sim12600/a2.module-1.1.5.5\",\n" + "\"_version\": 1,\n" + "\"_score\": 1,\n" + + "\"_source\": {\n" + "\"treeLevel\": 2,\n" + "\"parentUuid\": \"CARD-1.1.5.0\",\n" + + "\"mountpoint\": \"sim12600\",\n" + "\"uuid\": \"a2.module-1.1.5.5\",\n" + + "\"containedHolder\": [\n" + "\"SUBRACK-1.55.0.0\"\n" + "],\n" + "\"manufacturerName\": null,\n" + + "\"manufacturerIdentifier\": \"ONF-Wireless-Transport\",\n" + "\"serial\": \"310330015\",\n" + + "\"date\": \"2013-04-13T00:00:00.0Z\",\n" + "\"version\": \"a2.module-newest\",\n" + + "\"description\": \"WS/p8.module/a2.module#5\",\n" + "\"partTypeId\": \"3EM23141AD01\",\n" + + "\"modelIdentifier\": \"CRPQABVFAA\",\n" + "\"typeName\": \"a2.module\"\n" + "}\n" + "}"); + private static final JSONObject REQUIREDNE_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"mwtn_v1\",\n" + + "\"_type\": \"required-networkelement\",\n" + "\"_id\": \"sim2230\",\n" + "\"_version\": 1,\n" + + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"mountId\": \"sim2230\",\n" + "\"host\": \"10.20.5.2\",\n" + + "\"port\": 2230,\n" + "\"username\": \"adsa\",\n" + "\"password\": \"asda\"\n" + "}\n" + "}"); + private static final JSONObject EVENTLOG_SEARCHHIT = new JSONObject("{\n" + "\"_index\": \"sdnevents_v1\",\n" + + "\"_type\": \"eventlog\",\n" + "\"_id\": \"AXB7cJHlZ_FApnwi29xq\",\n" + "\"_version\": 1,\n" + + "\"_score\": 1,\n" + "\"_source\": {\n" + "\"event\": {\n" + + "\"nodeName\": \"SDN-Controller-465e2ae306ca\",\n" + "\"counter\": \"1\",\n" + + "\"timeStamp\": \"2020-02-25T08:22:19.8Z\",\n" + "\"objectId\": \"sim2230\",\n" + + "\"attributeName\": \"ConnectionStatus\",\n" + "\"newValue\": \"connecting\",\n" + + "\"type\": \"AttributeValueChangedNotificationXml\"\n" + "}\n" + "}\n" + "}"); + private static final JSONObject MAINTENANCE_SEARCHHIT = + new JSONObject("{\n" + "\"_index\": \"mwtn_v1\",\n" + "\"_type\": \"maintenancemode\",\n" + + "\"_id\": \"sim2230\",\n" + "\"_version\": 1,\n" + "\"_score\": 1,\n" + "\"_source\": {\n" + + "\"node\": \"sim2230\",\n" + "\"filter\": [\n" + "{\n" + "\"definition\": {\n" + + "\"object-id-ref\": \"\",\n" + "\"problem\": \"\"\n" + "},\n" + "\"description\": \"\",\n" + + "\"start\": \"\",\n" + "\"end\": \"\"\n" + "}\n" + "],\n" + "\"active\": false\n" + "}\n" + "}"); - } + @Test + public void test() { + ElAltoReleaseInformation ri = new ElAltoReleaseInformation(); + //faultlog + SearchHitConverter faultlogConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.FAULTLOG); + assertNotNull(faultlogConverter); + SearchHit frankfurtFaultlogEntry = faultlogConverter.convert(new SearchHit(FAULTLOG_SEARCHHIT)); + assertNotNull(frankfurtFaultlogEntry); + //faultcurrent + SearchHitConverter faultcurrentConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.FAULTCURRENT); + assertNotNull(faultcurrentConverter); + SearchHit frankfurtFaultcurrentEntry = faultcurrentConverter.convert(new SearchHit(FAULTCURRENT_SEARCHHIT)); + assertNotNull(frankfurtFaultcurrentEntry); + //inventory + SearchHitConverter inventoryConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.INVENTORY); + assertNotNull(inventoryConverter); + SearchHit frankfurtInventory = inventoryConverter.convert(new SearchHit(INVENTORY_SEARCHHIT)); + assertNotNull(frankfurtInventory); + //inventory + SearchHitConverter neConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.REQUIRED_NETWORKELEMENT); + assertNotNull(neConverter); + SearchHit frankfurtNE = neConverter.convert(new SearchHit(REQUIREDNE_SEARCHHIT)); + assertNotNull(frankfurtNE); + //eventlog + SearchHitConverter eventlogConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.EVENTLOG); + assertNotNull(eventlogConverter); + SearchHit frankfurtEvent = eventlogConverter.convert(new SearchHit(EVENTLOG_SEARCHHIT)); + assertNull(frankfurtEvent); + //eventlog->connectionlog + SearchHitConverter conlogConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.CONNECTIONLOG); + assertNotNull(conlogConverter); + SearchHit frankfurtconlog = conlogConverter.convert(new SearchHit(EVENTLOG_SEARCHHIT)); + assertNotNull(frankfurtconlog); + //maintenance + SearchHitConverter maintenanceConverter = ri.getConverter(Release.FRANKFURT_R1, ComponentName.MAINTENANCE); + assertNotNull(maintenanceConverter); + SearchHit frankfurtmaint = maintenanceConverter.convert(new SearchHit(MAINTENANCE_SEARCHHIT)); + assertNotNull(frankfurtmaint); + + } } diff --git a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestFrankfurtReleaseInformation.java b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestFrankfurtReleaseInformation.java index 47a3a8f74..1d7a6eb6d 100644 --- a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestFrankfurtReleaseInformation.java +++ b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestFrankfurtReleaseInformation.java @@ -42,9 +42,9 @@ public class TestFrankfurtReleaseInformation { Set components = ri.getComponents(); assertFalse(components.contains(ComponentName.INVENTORYTOPLEVEL)); assertTrue(components.contains(ComponentName.EVENTLOG)); - assertEquals("faultlog",ri.getAlias(ComponentName.FAULTLOG)); - assertEquals("faultlog-v2",ri.getIndex(ComponentName.FAULTLOG)); - assertNull(ri.getConverter(Release.FRANKFURT_R1,ComponentName.INVENTORYTOPLEVEL)); + assertEquals("faultlog", ri.getAlias(ComponentName.FAULTLOG)); + assertEquals("faultlog-v2", ri.getIndex(ComponentName.FAULTLOG)); + assertNull(ri.getConverter(Release.FRANKFURT_R1, ComponentName.INVENTORYTOPLEVEL)); assertNotNull(ri.getConverter(Release.FRANKFURT_R1, ComponentName.FAULTCURRENT)); } diff --git a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestMigrationProvider.java b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestMigrationProvider.java index 1ec19117b..02877f0c8 100644 --- a/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestMigrationProvider.java +++ b/sdnr/wt/data-provider/setup/src/test/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/setup/TestMigrationProvider.java @@ -37,17 +37,17 @@ import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release; */ public class TestMigrationProvider { - private static final String FRANKFURT_BACKUP_FILE = "src/test/resources/test2.bak.json"; - public static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer - .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; + private static final String FRANKFURT_BACKUP_FILE = "src/test/resources/test2.bak.json"; + public static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))}; @Test public void testCreateImport() { - DataMigrationProviderImpl provider = new DataMigrationProviderImpl(hosts, null, null,true,5000); + DataMigrationProviderImpl provider = new DataMigrationProviderImpl(hosts, null, null, true, 5000); try { //create el alto db infrastructure - provider.initDatabase(Release.FRANKFURT_R1, 5, 1, "", true,10000); + provider.initDatabase(Release.FRANKFURT_R1, 5, 1, "", true, 10000); //import data into database DataMigrationReport report = provider.importData(FRANKFURT_BACKUP_FILE, false, Release.FRANKFURT_R1); assertTrue(report.completed()); -- cgit 1.2.3-korg