From 45cfee1861924b4a8086d38079ce8cbd320386d6 Mon Sep 17 00:00:00 2001 From: Robert Varga Date: Thu, 12 Oct 2017 14:33:55 +0200 Subject: [PATCH] Adjust to yangtools-2.0.0/odlparent-3.0.0 changes This also bumps sshd-core to 1.6.0, as that is what karaf ships by default. Change-Id: I064b1621bfa729c58e3b3ef6646787a6112301aa Signed-off-by: Robert Varga Signed-off-by: Stephen Kitt --- .../src/main/feature/feature.xml | 1 + features/netconf/odl-netconf-util/pom.xml | 2 +- .../src/main/feature/feature.xml | 14 ++ .../src/main/feature/feature.xml | 2 + features/yanglib/odl-yanglib/pom.xml | 2 +- .../odl-yanglib/src/main/feature/feature.xml | 13 ++ .../protocol/AuthorizedKeysDecoder.java | 28 ++- .../protocol/CallHomeAuthorization.java | 18 +- .../protocol/CallHomeSessionContext.java | 34 ++-- .../protocol/MinaSshNettyChannel.java | 28 +-- .../protocol/NetconfCallHomeServer.java | 49 +++--- .../NetconfCallHomeServerBuilder.java | 22 +-- .../protocol/CallHomeAuthorizationTest.java | 2 +- .../protocol/CallHomeSessionContextTest.java | 28 +-- .../protocol/MinaSshNettyChannelTest.java | 6 +- .../protocol/NetconfCallHomeServerTest.java | 19 +- .../mount/CallHomeAuthProviderImpl.java | 37 ++-- .../mount/CallhomeStatusReporter.java | 48 +++--- .../netconf/callhome/mount/Configuration.java | 34 ++-- .../IetfZeroTouchCallHomeServerProvider.java | 15 +- .../NetconfMappingTest.java | 56 ++---- .../MdsalNetconfOperationServiceFactory.java | 15 +- .../mdsal/connector/TransactionProvider.java | 2 +- .../mdsal/connector/ops/EditConfig.java | 54 +++--- ...itOperationNormalizedNodeStreamWriter.java | 2 +- .../mdsal/connector/ops/RuntimeRpc.java | 8 +- .../mdsal/connector/ops/get/AbstractGet.java | 6 +- .../ops/get/FilterContentValidator.java | 28 +-- .../ops/NetconfMDSalMappingTest.java | 32 +--- .../mdsal/connector/ops/RuntimeRpcTest.java | 42 ++--- .../mdsal/connector/ops/get/Bug8084.java | 11 +- .../ops/get/FilterContentValidatorTest.java | 22 +-- .../library/SchemaServiceToMdsalWriter.java | 23 +-- .../SchemaServiceToMdsalWriterTest.java | 14 +- .../netconf/NetconfEventSource.java | 5 +- .../NetconfEventSourceRegistration.java | 2 +- .../NotificationTopicRegistration.java | 15 +- .../netconf/NetconfEventSourceMountTest.java | 8 +- .../netconf/NetconfEventSourceTest.java | 8 +- .../netconf/api/monitoring/SessionEvent.java | 2 +- .../netconf/api/util/NetconfConstants.java | 4 + ...tconfHelloMessageAdditionalHeaderTest.java | 6 +- .../SimpleNetconfClientSessionListener.java | 3 + .../NetconfClientConfigurationBuilder.java | 7 + ...econnectingClientConfigurationBuilder.java | 4 +- .../NetconfClientSessionNegotiatorTest.java | 18 +- netconf/netconf-console/pom.xml | 16 -- .../console/commands/NetconfCommandUtils.java | 6 +- .../utils/NetconfConsoleConstants.java | 2 +- .../console/utils/NetconfConsoleUtils.java | 2 +- .../console/utils/NetconfIidFactory.java | 4 +- .../console/impl/NetconfCommandsImplTest.java | 50 ++---- .../operations/DefaultCloseSession.java | 2 +- .../NetconfCapabilityMonitoringService.java | 4 +- .../impl/osgi/NetconfOperationRouterImpl.java | 7 +- ...NetconfOperationServiceFactoryTracker.java | 11 +- .../util/DeserializerExceptionHandler.java | 2 +- .../NetconfServerSessionNegotiatorTest.java | 2 +- .../impl/NetconfServerSessionTest.java | 22 +-- .../operations/DefaultCloseSessionTest.java | 26 +-- ...etconfCapabilityMonitoringServiceTest.java | 20 +-- .../netconf/mapping/api/HandlingPriority.java | 13 +- .../opendaylight/netconf/monitoring/Get.java | 2 +- .../netconf/monitoring/GetSchema.java | 2 +- netconf/netconf-netty-util/pom.xml | 2 +- .../AbstractNetconfSessionNegotiator.java | 2 + .../nettyutil/handler/BufferedWriter.java | 1 + .../authentication/AuthenticationHandler.java | 2 +- .../authentication/LoginPasswordHandler.java | 2 +- .../ssh/authentication/PublicKeyAuth.java | 4 +- .../handler/ssh/client/AsyncSshHandler.java | 105 ++++-------- .../ssh/client/AsyncSshHandlerReader.java | 7 +- .../ssh/client/AsyncSshHandlerWriter.java | 75 ++++---- .../nettyutil/AbstractNetconfSessionTest.java | 8 +- .../LoginPasswordHandlerTest.java | 2 +- .../ssh/client/AsyncSshHandlerTest.java | 24 ++- .../ssh/NetconfNorthboundSshServer.java | 7 +- .../netconf/ssh/RemoteNetconfCommand.java | 5 + .../netconf/ssh/SshProxyServer.java | 28 ++- .../ssh/SshProxyServerConfiguration.java | 4 +- .../SshProxyServerConfigurationBuilder.java | 16 +- .../netconf/ssh/osgi/NetconfSSHActivator.java | 12 +- .../netconf/netty/EchoClientHandler.java | 12 +- .../opendaylight/netconf/netty/SSHTest.java | 5 +- .../ssh/authentication/SSHServerTest.java | 9 +- .../singleton/impl/MasterSalFacade.java | 22 ++- .../impl/NetconfTopologyManager.java | 11 +- .../impl/actors/NetconfNodeActor.java | 19 +- .../impl/actors/ReadTransactionActor.java | 2 +- .../actors/ReadWriteTransactionActor.java | 2 +- .../impl/actors/WriteTransactionActor.java | 2 +- .../impl/utils/NetconfTopologySetup.java | 2 +- .../impl/utils/NetconfTopologyUtils.java | 8 +- .../singleton/impl/NetconfNodeActorTest.java | 25 +-- .../impl/RemoteDeviceConnectorImplTest.java | 2 - .../impl/actors/ReadTransactionActorTest.java | 2 +- .../actors/ReadWriteTransactionActorTest.java | 16 +- .../actors/WriteTransactionActorTest.java | 10 +- .../impl/tx/ProxyReadTransactionTest.java | 2 +- .../tx/ProxyReadWriteTransactionTest.java | 2 +- .../impl/tx/ProxyWriteTransactionTest.java | 14 +- .../impl/tx/ReadOnlyTransactionTest.java | 6 +- .../impl/tx/ReadWriteTransactionTest.java | 15 +- .../impl/tx/WriteOnlyTransactionTest.java | 11 +- .../topology/AbstractNetconfTopology.java | 12 +- .../netconf/util/CloseableUtil.java | 6 +- .../netconf/util/messages/SubtreeFilter.java | 6 +- .../netconf/util/test/XmlFileLoader.java | 6 +- .../netconf/util/test/XmlUnitUtil.java | 2 +- .../netconf/LibraryModulesSchemas.java | 36 ++-- .../sal/connect/netconf/NetconfDevice.java | 49 +++--- .../connect/netconf/NetconfStateSchemas.java | 20 +-- .../connect/netconf/NotificationHandler.java | 10 +- .../auth/DatastoreBackedPublicKeyAuth.java | 4 +- .../listener/NetconfDeviceCommunicator.java | 16 +- .../listener/NetconfSessionPreferences.java | 16 +- .../connect/netconf/sal/NetconfDeviceRpc.java | 11 +- .../netconf/sal/NetconfDeviceSalProvider.java | 8 +- .../sal/SchemalessNetconfDeviceRpc.java | 6 +- .../netconf/sal/tx/WriteCandidateTx.java | 2 +- .../netconf/sal/tx/WriteRunningTx.java | 7 +- ...NetconfRemoteSchemaYangSourceProvider.java | 35 +--- .../YangLibrarySchemaYangSourceProvider.java | 14 +- .../mapping/NetconfMessageTransformer.java | 8 +- .../mapping/SchemalessMessageTransformer.java | 5 +- .../connect/netconf/util/NetconfBaseOps.java | 26 ++- .../util/NetconfMessageTransformUtil.java | 9 +- .../util/NetconfRpcStructureTransformer.java | 4 +- .../netconf/util/NodeContainerProxy.java | 53 ++++-- .../SchemalessRpcStructureTransformer.java | 2 +- .../util/NetconfTopologyRPCProvider.java | 4 +- .../netconf/LibraryModulesSchemasTest.java | 9 +- .../connect/netconf/NetconfDeviceTest.java | 40 ++--- .../netconf/NetconfStateSchemasTest.java | 2 +- .../netconf/NetconfToNotificationTest.java | 17 +- .../netconf/NetconfToRpcRequestTest.java | 17 +- .../NetconfDeviceCommunicatorTest.java | 32 ++-- .../netconf/sal/KeepaliveSalFacadeTest.java | 12 +- .../NetconfDeviceNotificationServiceTest.java | 4 +- .../sal/NetconfDeviceTopologyAdapterTest.java | 47 ++--- .../connect/netconf/sal/tx/TxChainTest.java | 3 +- .../connect/netconf/sal/tx/TxTestUtils.java | 6 +- .../sal/tx/WriteCandidateRunningTxTest.java | 6 +- .../netconf/sal/tx/WriteCandidateTxTest.java | 2 +- .../netconf/sal/tx/WriteRunningTxTest.java | 2 +- ...onfRemoteSchemaYangSourceProviderTest.java | 12 +- ...ngLibrarySchemaYangSourceProviderTest.java | 31 ++-- .../BaseRpcSchemalessTransformerTest.java | 8 +- .../NetconfMessageTransformerTest.java | 9 +- .../netconf/util/NetconfBaseOpsTest.java | 6 +- .../util/NetconfTopologyRPCProviderTest.java | 4 +- .../netconf/util/NodeContainerProxyTest.java | 15 +- .../opendaylight/netconf/test/tool/Main.java | 5 +- .../test/tool/MdsalOperationProvider.java | 23 ++- .../test/tool/NetconfDeviceSimulator.java | 78 ++++----- .../netconf/test/tool/TestToolUtils.java | 3 + .../netconf/test/tool/TesttoolParameters.java | 2 +- .../tool/client/http/perf/RestPerfClient.java | 8 +- .../stress/ConfigurableClientDispatcher.java | 2 +- .../test/tool/client/stress/StressClient.java | 12 +- .../test/tool/config/Configuration.java | 50 +++--- .../tool/config/ConfigurationBuilder.java | 79 +++++---- .../test/tool/customrpc/RpcMapping.java | 2 +- .../customrpc/SettableOperationProvider.java | 2 +- .../test/tool/customrpc/SettableRpc.java | 2 +- .../operations/DefaultOperationsCreator.java | 2 +- .../tool/rpc/SimulatedCreateSubscription.java | 27 ++- .../test/tool/rpc/SimulatedGetConfig.java | 2 +- .../SettableOperationRpcProvider.java | 2 +- .../test/tool/rpchandler/SettableRpc.java | 4 +- .../tool/schemacache/SchemaSourceCache.java | 33 ++-- .../yanglib/impl/YangLibProvider.java | 11 +- .../yanglib/impl/YangLibServiceImpl.java | 20 +-- .../yanglib/impl/YangLibProviderTest.java | 7 +- .../yanglib/impl/YangLibServiceImplTest.java | 12 +- .../errors/RestconfDocumentedException.java | 2 +- .../common/util/RestconfSchemaUtilTest.java | 4 +- .../SchemaExportContentYangBodyWriter.java | 8 +- .../schema/SchemaRetrievalServiceImpl.java | 11 +- .../impl/DepthAwareNormalizedNodeWriter.java | 2 +- ...estconfDelegatingNormalizedNodeWriter.java | 2 +- .../StringModuleInstanceIdentifierCodec.java | 7 +- .../impl/XmlNormalizedNodeBodyReader.java | 21 +-- .../sal/rest/impl/XmlToPatchBodyReader.java | 9 +- .../sal/restconf/impl/BrokerFacade.java | 18 +- .../sal/restconf/impl/ControllerContext.java | 162 ++++++++++-------- .../impl/FakeContainerSchemaNode.java | 43 +++-- .../sal/restconf/impl/FakeImportedModule.java | 46 ++--- .../sal/restconf/impl/FakeLeafSchemaNode.java | 22 +-- .../sal/restconf/impl/FakeModuleImport.java | 23 ++- .../sal/restconf/impl/FakeRestconfModule.java | 48 ++---- .../restconf/impl/QueryParametersParser.java | 8 +- .../netconf/sal/restconf/impl/RestCodec.java | 4 +- .../sal/restconf/impl/RestconfImpl.java | 81 ++++----- .../StatisticsRestconfServiceWrapper.java | 4 +- .../listeners/AbstractQueryParams.java | 1 + .../streams/listeners/ListenerAdapter.java | 37 ++-- .../NotificationListenerAdapter.java | 10 +- .../sal/streams/listeners/Notificator.java | 2 +- .../streams/websockets/WebSocketServer.java | 2 +- .../md/sal/rest/common/TestRestconfUtils.java | 8 +- .../impl/InstanceIdentifierTypeLeafTest.java | 2 +- .../test/providers/TestJsonBodyReader.java | 25 +-- .../TestJsonBodyReaderMountPoint.java | 25 +-- .../test/providers/TestJsonBodyWriter.java | 2 +- .../test/providers/TestXmlBodyReader.java | 30 ++-- .../TestXmlBodyReaderMountPoint.java | 27 +-- .../test/providers/TestXmlBodyWriter.java | 2 +- .../test/CnSnToJsonBasicDataTypesTest.java | 3 +- .../to/cnsn/test/RestPutListDataTest.java | 3 +- .../impl/json/to/nn/test/JsonToNnTest.java | 8 +- .../test/NnInstanceIdentifierToXmlTest.java | 1 - .../impl/nn/to/xml/test/NnToXmlTest.java | 24 +-- ...NnToXmlWithDataFromSeveralModulesTest.java | 4 +- .../sal/restconf/impl/test/Bug3595Test.java | 6 +- .../sal/restconf/impl/test/Bug8072Test.java | 3 +- ...nSnToXmlAndJsonInstanceIdentifierTest.java | 19 +- .../impl/test/CutDataToCorrectDepthTest.java | 6 +- .../sal/restconf/impl/test/DummyFuture.java | 16 +- .../restconf/impl/test/DummyRpcResult.java | 12 +- .../sal/restconf/impl/test/DummyType.java | 22 +-- .../impl/test/ExpressionParserTest.java | 2 +- .../impl/test/InvokeRpcMethodTest.java | 6 +- .../test/JSONRestconfServiceImplTest.java | 9 +- .../impl/test/RestGetOperationTest.java | 15 +- .../impl/test/RestOperationUtils.java | 2 +- ...stconfImplNotificationSubscribingTest.java | 6 +- .../restconf/impl/test/RestconfImplTest.java | 2 +- .../sal/restconf/impl/test/TestUtils.java | 19 +- .../impl/test/URIParametersParsing.java | 45 ++--- .../test/YangAndXmlAndDataSchemaLoader.java | 5 +- .../DepthAwareNormalizedNodeWriterTest.java | 2 +- .../impl/InstanceIdentifierCodecImplTest.java | 2 +- .../listeners/ListenerAdapterTest.java | 17 +- .../listeners/NotificationListenerTest.java | 16 +- .../sal-remote-augment.yang | 4 +- .../invoke-rpc/invoke-rpc-module.yang | 4 +- .../identityref/identity-module.yang | 4 +- .../identityref/identityref-module.yang | 14 +- .../test/resources/modules/nested-module.yang | 2 +- .../identityref/identity-module.yang | 4 +- .../identityref/identityref-module.yang | 6 +- .../leafref/cont-augment-module.yang | 6 +- .../nn-to-json/leafref/main-module.yang | 2 +- .../aug-referenced-elements-module.yang | 6 +- .../eferenced-elements-module.yang | 4 +- .../rinstance-identifier-module.yang | 4 +- .../nn-to-xml/yang/basic-module.yang | 4 +- .../nn-to-xml/yang/referenced-module.yang | 4 +- .../identityref/identity-module.yang | 4 +- .../identityref/identityref-module.yang | 6 +- .../yang-augments/identity-module.yang | 4 +- .../yang-augments/identityref-module.yang | 6 +- .../restconf/nb/rfc8040/Rfc8040.java | 50 +----- .../restconf/nb/rfc8040/codecs/RestCodec.java | 23 +-- .../StringModuleInstanceIdentifierCodec.java | 12 +- .../handlers/SchemaContextHandler.java | 5 +- .../handlers/TransactionChainHandler.java | 1 + .../ParameterAwareNormalizedNodeWriter.java | 2 +- .../XmlNormalizedNodeBodyReader.java | 19 +- .../providers/patch/XmlToPatchBodyReader.java | 9 +- .../SchemaExportContentYangBodyWriter.java | 8 +- .../rfc8040/references/SchemaContextRef.java | 15 +- .../impl/RestconfDataServiceImpl.java | 9 +- .../transactions/TransactionVarsWrapper.java | 6 +- .../rfc8040/rests/utils/CreateStreamUtil.java | 2 +- .../rfc8040/rests/utils/ParametersUtil.java | 2 +- .../rests/utils/PutDataTransactionUtil.java | 4 + .../rests/utils/ReadDataTransactionUtil.java | 24 +-- .../utils/RestconfDataServiceConstant.java | 18 +- .../utils/RestconfInvokeOperationsUtil.java | 4 +- .../rests/utils/RestconfStreamsConstants.java | 28 +-- .../rests/utils/SubscribeToStreamUtil.java | 10 +- .../simple/impl/FakeContainerSchemaNode.java | 43 +++-- .../simple/impl/FakeImportedModule.java | 40 +++-- .../simple/impl/FakeLeafSchemaNode.java | 25 +-- .../simple/impl/FakeModuleImport.java | 21 ++- .../simple/impl/FakeRestconfModule.java | 48 ++---- .../services/simple/impl/RestconfImpl.java | 6 +- .../impl/RestconfOperationsServiceImpl.java | 3 +- .../services/wrapper/ServicesWrapperImpl.java | 2 +- .../listeners/AbstractNotificationsData.java | 2 + .../listeners/AbstractQueryParams.java | 1 + .../streams/listeners/ListenerAdapter.java | 37 ++-- .../NotificationListenerAdapter.java | 6 +- .../streams/listeners/Notificator.java | 2 +- .../streams/websockets/WebSocketServer.java | 2 +- .../mapping/RestconfMappingNodeUtil.java | 34 ++-- .../utils/parser/ParserFieldsParameter.java | 15 +- .../utils/parser/ParserIdentifier.java | 36 ++-- .../YangInstanceIdentifierDeserializer.java | 26 +-- .../YangInstanceIdentifierSerializer.java | 5 +- .../utils/validations/RestconfValidation.java | 10 +- .../nb/rfc8040/TestRestconfUtils.java | 8 +- .../restconf/nb/rfc8040/TestUtils.java | 17 +- .../handlers/SchemaContextHandlerTest.java | 4 +- ...terAwareNormalizedNodeWriterDepthTest.java | 2 +- ...erAwareNormalizedNodeWriterFieldsTest.java | 2 +- .../XmlBodyReaderMountPointTest.java | 25 +-- .../providers/test/JsonBodyReaderTest.java | 23 +-- .../providers/test/XmlBodyReaderTest.java | 21 +-- .../JSONRestconfServiceRfc8040ImplTest.java | 9 +- .../impl/RestconfDataServiceImplTest.java | 5 +- ...stconfInvokeOperationsServiceImplTest.java | 4 +- ...onfStreamsSubscriptionServiceImplTest.java | 2 +- .../rests/utils/CreateStreamUtilTest.java | 9 +- .../utils/PatchDataTransactionUtilTest.java | 23 ++- .../utils/PostDataTransactionUtilTest.java | 2 +- .../utils/PutDataTransactionUtilTest.java | 2 +- .../simple/impl/RestconfImplTest.java | 2 +- .../impl/RestconfOperationsServiceTest.java | 10 +- .../impl/RestconfSchemaServiceTest.java | 14 +- .../listeners/NotificationListenerTest.java | 16 +- .../mapping/RestconfMappingNodeUtilTest.java | 31 ++-- .../utils/parser/IdentifierCodecTest.java | 5 +- .../parser/ParserFieldsParameterTest.java | 8 +- .../utils/parser/ParserIdentifierTest.java | 28 ++- ...angInstanceIdentifierDeserializerTest.java | 5 +- .../YangInstanceIdentifierSerializerTest.java | 2 +- .../validations/RestconfValidationTest.java | 13 +- .../invoke-rpc/invoke-rpc-module.yang | 4 +- .../test/resources/modules/nested-module.yang | 2 +- .../rest/doc/maven/StaticDocGenerator.java | 30 ++-- .../doc/impl/BaseYangSwaggerGenerator.java | 60 +++---- .../sal/rest/doc/impl/ModelGenerator.java | 122 +++++++------ .../doc/model/builder/OperationBuilder.java | 6 +- .../sal/rest/doc/util/RestDocgenUtil.java | 13 +- .../sal/rest/doc/impl/DocGenTestHelper.java | 65 +++---- .../rest/doc/impl/MountPointSwaggerTest.java | 6 +- .../resources/yang/toaster_augmented.yang | 4 +- 330 files changed, 2256 insertions(+), 2570 deletions(-) create mode 100644 features/restconf/odl-restconf-nb-rfc8040-noauth/src/main/feature/feature.xml create mode 100644 features/yanglib/odl-yanglib/src/main/feature/feature.xml diff --git a/features/netconf/odl-netconf-netty-util/src/main/feature/feature.xml b/features/netconf/odl-netconf-netty-util/src/main/feature/feature.xml index b02171eac3..c89db48614 100644 --- a/features/netconf/odl-netconf-netty-util/src/main/feature/feature.xml +++ b/features/netconf/odl-netconf-netty-util/src/main/feature/feature.xml @@ -9,5 +9,6 @@ ssh + odl-netty-4 diff --git a/features/netconf/odl-netconf-util/pom.xml b/features/netconf/odl-netconf-util/pom.xml index 41c66684c4..c3e555dfdd 100644 --- a/features/netconf/odl-netconf-util/pom.xml +++ b/features/netconf/odl-netconf-util/pom.xml @@ -33,7 +33,7 @@ org.opendaylight.yangtools - odl-yangtools-yang-data + odl-yangtools-data 2.0.0 xml features diff --git a/features/restconf/odl-restconf-nb-rfc8040-noauth/src/main/feature/feature.xml b/features/restconf/odl-restconf-nb-rfc8040-noauth/src/main/feature/feature.xml new file mode 100644 index 0000000000..a190dfc48d --- /dev/null +++ b/features/restconf/odl-restconf-nb-rfc8040-noauth/src/main/feature/feature.xml @@ -0,0 +1,14 @@ + + + + + odl-karaf-feat-jetty + odl-netty-4 + + diff --git a/features/restconf/odl-restconf-noauth/src/main/feature/feature.xml b/features/restconf/odl-restconf-noauth/src/main/feature/feature.xml index 2b246c9d9b..341cd50769 100644 --- a/features/restconf/odl-restconf-noauth/src/main/feature/feature.xml +++ b/features/restconf/odl-restconf-noauth/src/main/feature/feature.xml @@ -11,5 +11,7 @@ mvn:org.opendaylight.netconf/sal-rest-connector-config/${project.version}/cfg/restconf + odl-karaf-feat-jetty + odl-netty-4 diff --git a/features/yanglib/odl-yanglib/pom.xml b/features/yanglib/odl-yanglib/pom.xml index 492e6bacca..65d02262e4 100644 --- a/features/yanglib/odl-yanglib/pom.xml +++ b/features/yanglib/odl-yanglib/pom.xml @@ -33,7 +33,7 @@ org.opendaylight.yangtools - odl-yangtools-yang-data + odl-yangtools-data 2.0.0 xml features diff --git a/features/yanglib/odl-yanglib/src/main/feature/feature.xml b/features/yanglib/odl-yanglib/src/main/feature/feature.xml new file mode 100644 index 0000000000..2093186670 --- /dev/null +++ b/features/yanglib/odl-yanglib/src/main/feature/feature.xml @@ -0,0 +1,13 @@ + + + + + odl-karaf-feat-jetty + + diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java index ac476c6c91..e544195fd8 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java @@ -11,9 +11,8 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.math.BigInteger; +import java.security.GeneralSecurityException; import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPublicKey; @@ -21,13 +20,12 @@ import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPublicKeySpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; -import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import java.util.Arrays; +import java.util.Base64; import java.util.HashMap; import java.util.Map; -import org.apache.sshd.common.util.Base64; -import org.apache.sshd.common.util.SecurityUtils; +import org.apache.sshd.common.util.security.SecurityUtils; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.ECPointUtil; @@ -61,12 +59,11 @@ public class AuthorizedKeysDecoder { private byte[] bytes = new byte[0]; private int pos = 0; - public PublicKey decodePublicKey(String keyLine) - throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException { + public PublicKey decodePublicKey(final String keyLine) throws GeneralSecurityException { // look for the Base64 encoded part of the line to decode // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes - bytes = Base64.decodeBase64(keyLine.getBytes()); + bytes = Base64.getDecoder().decode(keyLine.getBytes()); if (bytes.length == 0) { throw new IllegalArgumentException("No Base64 part to decode in " + keyLine); } @@ -89,8 +86,7 @@ public class AuthorizedKeysDecoder { throw new IllegalArgumentException("Unknown decode key type " + type + " in " + keyLine); } - private PublicKey decodeAsEcDSA() - throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { + private PublicKey decodeAsEcDSA() throws GeneralSecurityException { KeyFactory ecdsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_ECDSA); ECNamedCurveParameterSpec spec256r1 = ECNamedCurveTable.getParameterSpec(ECDSA_SUPPORTED_CURVE_NAME_SPEC); @@ -103,7 +99,7 @@ public class AuthorizedKeysDecoder { return ecdsaFactory.generatePublic(pubKeySpec); } - private PublicKey decodeAsDSA() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { + private PublicKey decodeAsDSA() throws GeneralSecurityException { KeyFactory dsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_DSA); BigInteger prime = decodeBigInt(); BigInteger subPrime = decodeBigInt(); @@ -114,7 +110,7 @@ public class AuthorizedKeysDecoder { return dsaFactory.generatePublic(spec); } - private PublicKey decodeAsRSA() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { + private PublicKey decodeAsRSA() throws GeneralSecurityException { KeyFactory rsaFactory = SecurityUtils.getKeyFactory(KEY_FACTORY_TYPE_RSA); BigInteger exponent = decodeBigInt(); BigInteger modulus = decodeBigInt(); @@ -131,8 +127,8 @@ public class AuthorizedKeysDecoder { } private int decodeInt() { - return ((bytes[pos++] & 0xFF) << 24) | ((bytes[pos++] & 0xFF) << 16) - | ((bytes[pos++] & 0xFF) << 8) | (bytes[pos++] & 0xFF); + return (bytes[pos++] & 0xFF) << 24 | (bytes[pos++] & 0xFF) << 16 + | (bytes[pos++] & 0xFF) << 8 | bytes[pos++] & 0xFF; } private BigInteger decodeBigInt() { @@ -143,7 +139,7 @@ public class AuthorizedKeysDecoder { return new BigInteger(bigIntBytes); } - public static String encodePublicKey(PublicKey publicKey) throws IOException { + public static String encodePublicKey(final PublicKey publicKey) throws IOException { String publicKeyEncoded; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA)) { @@ -186,7 +182,7 @@ public class AuthorizedKeysDecoder { } else { throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm()); } - publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray())); + publicKeyEncoded = new String(Base64.getEncoder().encodeToString(byteOs.toByteArray())); return publicKeyEncoded; } } diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeAuthorization.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeAuthorization.java index 1896b2b005..886021ed3c 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeAuthorization.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeAuthorization.java @@ -13,7 +13,7 @@ import java.security.KeyPair; import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.apache.sshd.ClientSession; +import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.session.ClientSessionImpl; /** @@ -35,7 +35,7 @@ public abstract class CallHomeAuthorization { } @Override - protected void applyTo(ClientSession session) { + protected void applyTo(final ClientSession session) { throw new IllegalStateException("Server is not allowed."); } }; @@ -69,7 +69,7 @@ public abstract class CallHomeAuthorization { * @param username Username to be used for authorization * @return Builder which allows to specify credentials. */ - public static final Builder serverAccepted(String sessionName, String username) { + public static final Builder serverAccepted(final String sessionName, final String username) { return new Builder(sessionName, username); } @@ -103,7 +103,7 @@ public abstract class CallHomeAuthorization { private final Set passwords = new HashSet<>(); private final Set clientKeys = new HashSet<>(); - private Builder(String nodeId, String username) { + Builder(final String nodeId, final String username) { this.nodeId = Preconditions.checkNotNull(nodeId); this.username = Preconditions.checkNotNull(username); } @@ -114,7 +114,7 @@ public abstract class CallHomeAuthorization { * @param password Password to be used for password-based authorization. * @return this builder. */ - public Builder addPassword(String password) { + public Builder addPassword(final String password) { this.passwords.add(password); return this; } @@ -125,7 +125,7 @@ public abstract class CallHomeAuthorization { * @param clientKey Keys to be used for authorization. * @return this builder. */ - public Builder addClientKeys(KeyPair clientKey) { + public Builder addClientKeys(final KeyPair clientKey) { this.clientKeys.add(clientKey); return this; } @@ -144,8 +144,8 @@ public abstract class CallHomeAuthorization { private final Set passwords; private final Set clientKeyPair; - ServerAllowed(String nodeId, String username, Collection passwords, - Collection clientKeyPairs) { + ServerAllowed(final String nodeId, final String username, final Collection passwords, + final Collection clientKeyPairs) { this.username = Preconditions.checkNotNull(username); this.passwords = ImmutableSet.copyOf(passwords); this.clientKeyPair = ImmutableSet.copyOf(clientKeyPairs); @@ -163,7 +163,7 @@ public abstract class CallHomeAuthorization { } @Override - protected void applyTo(ClientSession session) { + protected void applyTo(final ClientSession session) { Preconditions.checkArgument(session instanceof ClientSessionImpl); ((ClientSessionImpl) session).setUsername(username); diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeSessionContext.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeSessionContext.java index 05c9991677..c1bb615ff2 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeSessionContext.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/CallHomeSessionContext.java @@ -21,13 +21,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; -import org.apache.sshd.ClientChannel; -import org.apache.sshd.ClientSession; +import org.apache.sshd.client.channel.ClientChannel; import org.apache.sshd.client.future.AuthFuture; import org.apache.sshd.client.future.OpenFuture; +import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.session.ClientSessionImpl; -import org.apache.sshd.common.Session; import org.apache.sshd.common.future.SshFutureListener; +import org.apache.sshd.common.session.Session; import org.opendaylight.netconf.client.NetconfClientSession; import org.opendaylight.netconf.client.NetconfClientSessionListener; import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory; @@ -51,8 +51,8 @@ class CallHomeSessionContext implements CallHomeProtocolSessionContext { private final InetSocketAddress remoteAddress; private final PublicKey serverKey; - CallHomeSessionContext(ClientSession sshSession, CallHomeAuthorization authorization, - SocketAddress remoteAddress, Factory factory) { + CallHomeSessionContext(final ClientSession sshSession, final CallHomeAuthorization authorization, + final SocketAddress remoteAddress, final Factory factory) { this.authorization = Preconditions.checkNotNull(authorization, "authorization"); Preconditions.checkArgument(this.authorization.isServerAllowed(), "Server was not allowed."); Preconditions.checkArgument(sshSession instanceof ClientSessionImpl, @@ -64,7 +64,7 @@ class CallHomeSessionContext implements CallHomeProtocolSessionContext { this.serverKey = this.sshSession.getKex().getServerKey(); } - static CallHomeSessionContext getFrom(ClientSession sshSession) { + static CallHomeSessionContext getFrom(final ClientSession sshSession) { return sshSession.getAttribute(SESSION_KEY); } @@ -94,19 +94,19 @@ class CallHomeSessionContext implements CallHomeProtocolSessionContext { }; } - private void channelOpenFailed(Throwable throwable) { + private void channelOpenFailed(final Throwable throwable) { LOG.error("Unable to open netconf subsystem, disconnecting.", throwable); sshSession.close(false); } - private void netconfChannelOpened(ClientChannel netconfChannel) { + private void netconfChannelOpened(final ClientChannel netconfChannel) { nettyChannel = newMinaSshNettyChannel(netconfChannel); factory.getChannelOpenListener().onNetconfSubsystemOpened( CallHomeSessionContext.this, this::doActivate); } @GuardedBy("this") - private synchronized Promise doActivate(NetconfClientSessionListener listener) { + private synchronized Promise doActivate(final NetconfClientSessionListener listener) { if (activated) { return newSessionPromise().setFailure(new IllegalStateException("Session already activated.")); } @@ -118,11 +118,11 @@ class CallHomeSessionContext implements CallHomeProtocolSessionContext { return activationPromise; } - protected MinaSshNettyChannel newMinaSshNettyChannel(ClientChannel netconfChannel) { + protected MinaSshNettyChannel newMinaSshNettyChannel(final ClientChannel netconfChannel) { return new MinaSshNettyChannel(this, sshSession, netconfChannel); } - private Promise newSessionPromise() { + private static Promise newSessionPromise() { return GlobalEventExecutor.INSTANCE.newPromise(); } @@ -157,18 +157,18 @@ class CallHomeSessionContext implements CallHomeProtocolSessionContext { private final CallHomeNetconfSubsystemListener subsystemListener; private final ConcurrentMap sessions = new ConcurrentHashMap<>(); - Factory(EventLoopGroup nettyGroup, NetconfClientSessionNegotiatorFactory negotiatorFactory, - CallHomeNetconfSubsystemListener subsystemListener) { + Factory(final EventLoopGroup nettyGroup, final NetconfClientSessionNegotiatorFactory negotiatorFactory, + final CallHomeNetconfSubsystemListener subsystemListener) { this.nettyGroup = Preconditions.checkNotNull(nettyGroup, "nettyGroup"); this.negotiatorFactory = Preconditions.checkNotNull(negotiatorFactory, "negotiatorFactory"); this.subsystemListener = Preconditions.checkNotNull(subsystemListener); } - void remove(CallHomeSessionContext session) { + void remove(final CallHomeSessionContext session) { sessions.remove(session.getSessionName(), session); } - ReverseSshChannelInitializer getChannelInitializer(NetconfClientSessionListener listener) { + ReverseSshChannelInitializer getChannelInitializer(final NetconfClientSessionListener listener) { return ReverseSshChannelInitializer.create(negotiatorFactory, listener); } @@ -177,8 +177,8 @@ class CallHomeSessionContext implements CallHomeProtocolSessionContext { } @Nullable - CallHomeSessionContext createIfNotExists(ClientSession sshSession, CallHomeAuthorization authorization, - SocketAddress remoteAddress) { + CallHomeSessionContext createIfNotExists(final ClientSession sshSession, + final CallHomeAuthorization authorization, final SocketAddress remoteAddress) { CallHomeSessionContext session = new CallHomeSessionContext(sshSession, authorization, remoteAddress, this); CallHomeSessionContext preexisting = sessions.putIfAbsent(session.getSessionName(), session); diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/MinaSshNettyChannel.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/MinaSshNettyChannel.java index 9975c94962..02b9d3d0da 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/MinaSshNettyChannel.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/MinaSshNettyChannel.java @@ -20,8 +20,8 @@ import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelConfig; import io.netty.channel.EventLoop; import java.net.SocketAddress; -import org.apache.sshd.ClientChannel; -import org.apache.sshd.ClientSession; +import org.apache.sshd.client.channel.ClientChannel; +import org.apache.sshd.client.session.ClientSession; import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerReader; import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerReader.ReadMsgHandler; import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter; @@ -41,7 +41,8 @@ class MinaSshNettyChannel extends AbstractServerChannel { private volatile boolean nettyClosed = false; - MinaSshNettyChannel(CallHomeSessionContext context, ClientSession session, ClientChannel sshChannel) { + MinaSshNettyChannel(final CallHomeSessionContext context, final ClientSession session, + final ClientChannel sshChannel) { this.context = Preconditions.checkNotNull(context); this.session = Preconditions.checkNotNull(session); this.sshChannel = Preconditions.checkNotNull(sshChannel); @@ -53,12 +54,11 @@ class MinaSshNettyChannel extends AbstractServerChannel { private ChannelOutboundHandlerAdapter createChannelAdapter() { return new ChannelOutboundHandlerAdapter() { - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) + throws Exception { sshWriteAsyncHandler.write(ctx, msg, promise); } - }; } @@ -67,7 +67,7 @@ class MinaSshNettyChannel extends AbstractServerChannel { return config; } - private boolean notClosing(org.apache.sshd.common.Closeable sshCloseable) { + private static boolean notClosing(final org.apache.sshd.common.Closeable sshCloseable) { return !sshCloseable.isClosing() && !sshCloseable.isClosed(); } @@ -92,7 +92,7 @@ class MinaSshNettyChannel extends AbstractServerChannel { } @Override - protected boolean isCompatible(EventLoop loop) { + protected boolean isCompatible(final EventLoop loop) { return true; } @@ -107,11 +107,11 @@ class MinaSshNettyChannel extends AbstractServerChannel { } @Override - protected void doBind(SocketAddress localAddress) throws Exception { + protected void doBind(final SocketAddress localAddress) throws Exception { throw new UnsupportedOperationException("Bind not supported."); } - void doMinaDisconnect(boolean blocking) { + void doMinaDisconnect(final boolean blocking) { if (notClosing(session)) { sshChannel.close(blocking); session.close(blocking); @@ -149,13 +149,13 @@ class MinaSshNettyChannel extends AbstractServerChannel { } @Override - protected void doWrite(ChannelOutboundBuffer in) throws Exception { + protected void doWrite(final ChannelOutboundBuffer in) throws Exception { throw new IllegalStateException("Outbound writes to SSH should be done by SSH Write handler"); } private final class FireReadMessage implements ReadMsgHandler { @Override - public void onMessageRead(ByteBuf msg) { + public void onMessageRead(final ByteBuf msg) { pipeline().fireChannelRead(msg); } } @@ -172,9 +172,9 @@ class MinaSshNettyChannel extends AbstractServerChannel { } private class SshUnsafe extends AbstractUnsafe { - @Override - public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + public void connect(final SocketAddress remoteAddress, final SocketAddress localAddress, + final ChannelPromise promise) { throw new UnsupportedOperationException("Unsafe is not supported."); } } diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServer.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServer.java index 723273a763..6b88df3987 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServer.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServer.java @@ -13,20 +13,20 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.PublicKey; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; -import org.apache.sshd.client.ServerKeyVerifier; -import org.apache.sshd.client.SessionFactory; +import org.apache.sshd.client.SshClient; import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.keyverifier.ServerKeyVerifier; +import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.session.ClientSessionImpl; -import org.apache.sshd.common.KeyExchange; -import org.apache.sshd.common.Session; -import org.apache.sshd.common.SessionListener; +import org.apache.sshd.client.session.SessionFactory; import org.apache.sshd.common.future.SshFutureListener; import org.apache.sshd.common.io.IoAcceptor; import org.apache.sshd.common.io.IoServiceFactory; import org.apache.sshd.common.io.mina.MinaServiceFactory; import org.apache.sshd.common.io.nio2.Nio2ServiceFactory; +import org.apache.sshd.common.kex.KeyExchange; +import org.apache.sshd.common.session.Session; +import org.apache.sshd.common.session.SessionListener; import org.opendaylight.netconf.callhome.protocol.CallHomeSessionContext.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,8 +42,8 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { private final InetSocketAddress bindAddress; private final StatusRecorder recorder; - NetconfCallHomeServer(SshClient sshClient, CallHomeAuthorizationProvider authProvider, Factory factory, - InetSocketAddress socketAddress, StatusRecorder recorder) { + NetconfCallHomeServer(final SshClient sshClient, final CallHomeAuthorizationProvider authProvider, + final Factory factory, final InetSocketAddress socketAddress, final StatusRecorder recorder) { this.client = Preconditions.checkNotNull(sshClient); this.authProvider = Preconditions.checkNotNull(authProvider); this.sessionFactory = Preconditions.checkNotNull(factory); @@ -51,32 +51,28 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { this.recorder = recorder; sshClient.setServerKeyVerifier(this); + sshClient.addSessionListener(createSessionListener()); - SessionFactory clientSessions = new SessionFactory(); - clientSessions.setClient(sshClient); - clientSessions.addListener(createSessionListener()); - - IoServiceFactory minaFactory = createServiceFactory(sshClient); - this.acceptor = minaFactory.createAcceptor(clientSessions); + this.acceptor = createServiceFactory(sshClient).createAcceptor(new SessionFactory(sshClient)); } - private IoServiceFactory createServiceFactory(SshClient sshClient) { + private IoServiceFactory createServiceFactory(final SshClient sshClient) { try { return createMinaServiceFactory(sshClient); } catch (NoClassDefFoundError e) { LOG.warn("Mina is not available, defaulting to NIO."); - return new Nio2ServiceFactory(sshClient); + return new Nio2ServiceFactory(sshClient, sshClient.getScheduledExecutorService(), false); } } - protected IoServiceFactory createMinaServiceFactory(SshClient sshClient) { - return new MinaServiceFactory(sshClient); + protected IoServiceFactory createMinaServiceFactory(final SshClient sshClient) { + return new MinaServiceFactory(sshClient, sshClient.getScheduledExecutorService(), false); } SessionListener createSessionListener() { return new SessionListener() { @Override - public void sessionEvent(Session session, Event event) { + public void sessionEvent(final Session session, final Event event) { ClientSession clientSession = (ClientSession) session; LOG.debug("SSH session {} event {}", session, event); switch (event) { @@ -92,12 +88,12 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { } @Override - public void sessionCreated(Session session) { + public void sessionCreated(final Session session) { LOG.debug("SSH session {} created", session); } @Override - public void sessionClosed(Session session) { + public void sessionClosed(final Session session) { CallHomeSessionContext ctx = CallHomeSessionContext.getFrom((ClientSession) session); if (ctx != null) { ctx.removeSelf(); @@ -107,7 +103,7 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { }; } - private void doPostAuth(final ClientSession session) { + private static void doPostAuth(final ClientSession session) { CallHomeSessionContext.getFrom(session).openNetconfChannel(); } @@ -123,7 +119,7 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { private SshFutureListener newAuthSshFutureListener(final ClientSession session) { return new SshFutureListener() { @Override - public void operationComplete(AuthFuture authFuture) { + public void operationComplete(final AuthFuture authFuture) { if (authFuture.isSuccess()) { onSuccess(); } else if (authFuture.isFailure()) { @@ -138,7 +134,7 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { LOG.debug("Authorize success"); } - private void onFailure(Throwable throwable) { + private void onFailure(final Throwable throwable) { ClientSessionImpl impl = (ClientSessionImpl) session; LOG.error("Authorize failed for session {}", session, throwable); @@ -157,7 +153,8 @@ public class NetconfCallHomeServer implements AutoCloseable, ServerKeyVerifier { } @Override - public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress, PublicKey serverKey) { + public boolean verifyServerKey(final ClientSession sshClientSession, final SocketAddress remoteAddress, + final PublicKey serverKey) { final CallHomeAuthorization authorization = authProvider.provideAuth(remoteAddress, serverKey); // server is not authorized if (!authorization.isServerAllowed()) { diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServerBuilder.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServerBuilder.java index de8eb106d0..decb759689 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServerBuilder.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/NetconfCallHomeServerBuilder.java @@ -14,7 +14,7 @@ import io.netty.channel.local.LocalEventLoopGroup; import io.netty.util.HashedWheelTimer; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; -import org.apache.sshd.SshClient; +import org.apache.sshd.client.SshClient; import org.opendaylight.netconf.callhome.protocol.CallHomeSessionContext.Factory; import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory; import org.opendaylight.yangtools.concepts.Builder; @@ -33,8 +33,8 @@ public class NetconfCallHomeServerBuilder implements Builder byPublicKey = new ConcurrentHashMap<>(); @Override - public void onDataTreeChanged(@Nonnull Collection> mods) { + public void onDataTreeChanged(@Nonnull final Collection> mods) { for (DataTreeModification dataTreeModification : mods) { DataObjectModification rootNode = dataTreeModification.getRootNode(); process(rootNode); } } - private void process(DataObjectModification deviceMod) { + private void process(final DataObjectModification deviceMod) { Device before = deviceMod.getDataBefore(); Device after = deviceMod.getDataAfter(); @@ -159,7 +158,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, } } - private void putDevice(Device device) { + private void putDevice(final Device device) { PublicKey key = publicKey(device); if (key == null) { return; @@ -167,7 +166,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, byPublicKey.put(key, device); } - private void removeDevice(Device device) { + private void removeDevice(final Device device) { PublicKey key = publicKey(device); if (key == null) { return; @@ -175,17 +174,17 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, byPublicKey.remove(key); } - private PublicKey publicKey(Device device) { + private PublicKey publicKey(final Device device) { String hostKey = device.getSshHostKey(); try { return keyDecoder.decodePublicKey(hostKey); - } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) { + } catch (GeneralSecurityException e) { LOG.error("Unable to decode SSH key for {}. Ignoring update for this device", device.getUniqueId(), e); return null; } } - private Device get(PublicKey key) { + private Device get(final PublicKey key) { return byPublicKey.get(key); } } @@ -195,14 +194,14 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, private final ConcurrentMap byPublicKey = new ConcurrentHashMap<>(); @Override - public void onDataTreeChanged(@Nonnull Collection> mods) { + public void onDataTreeChanged(@Nonnull final Collection> mods) { for (DataTreeModification dataTreeModification : mods) { DataObjectModification rootNode = dataTreeModification.getRootNode(); process(rootNode); } } - private void process(DataObjectModification deviceMod) { + private void process(final DataObjectModification deviceMod) { Device before = deviceMod.getDataBefore(); Device after = deviceMod.getDataAfter(); @@ -220,17 +219,17 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, } } - private void putDevice(Device device) { + private void putDevice(final Device device) { String key = device.getSshHostKey(); byPublicKey.put(key, device); } - private void removeDevice(Device device) { + private void removeDevice(final Device device) { String key = device.getSshHostKey(); byPublicKey.remove(key); } - Device get(PublicKey serverKey) { + Device get(final PublicKey serverKey) { String skey = ""; try { @@ -248,7 +247,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, private volatile Global current = null; @Override - public void onDataTreeChanged(@Nonnull Collection> mods) { + public void onDataTreeChanged(@Nonnull final Collection> mods) { for (DataTreeModification dataTreeModification : mods) { current = dataTreeModification.getRootNode().getDataAfter(); } diff --git a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallhomeStatusReporter.java b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallhomeStatusReporter.java index 6f547f885c..226fd27d78 100644 --- a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallhomeStatusReporter.java +++ b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallhomeStatusReporter.java @@ -11,10 +11,8 @@ package org.opendaylight.netconf.callhome.mount; import com.google.common.base.Optional; import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; +import java.security.GeneralSecurityException; import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -63,14 +61,14 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco private final DataBroker dataBroker; private final ListenerRegistration reg; - CallhomeStatusReporter(DataBroker broker) { + CallhomeStatusReporter(final DataBroker broker) { this.dataBroker = broker; this.reg = dataBroker.registerDataTreeChangeListener(new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, NETCONF_TOPO_IID.child(Node.class)), this); } @Override - public void onDataTreeChanged(@Nonnull Collection> changes) { + public void onDataTreeChanged(@Nonnull final Collection> changes) { for (DataTreeModification change: changes) { final DataObjectModification rootNode = change.getRootNode(); final InstanceIdentifier identifier = change.getRootPath().getRootIdentifier(); @@ -99,16 +97,16 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } } - private boolean isNetconfNode(Node node) { + private static boolean isNetconfNode(final Node node) { return node.getAugmentation(NetconfNode.class) != null; } - private NodeId getNodeId(final InstanceIdentifier path) { + private static NodeId getNodeId(final InstanceIdentifier path) { NodeKey key = path.firstKeyOf(Node.class); return key != null ? key.getNodeId() : null; } - private void handledNetconfNode(NodeId nodeId, NetconfNode nnode) { + private void handledNetconfNode(final NodeId nodeId, final NetconfNode nnode) { NetconfNodeConnectionStatus.ConnectionStatus csts = nnode.getConnectionStatus(); switch (csts) { @@ -124,7 +122,7 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } } - private void handleConnectedNetconfNode(NodeId nodeId) { + private void handleConnectedNetconfNode(final NodeId nodeId) { // Fully connected, all services for remote device are // available from the MountPointService. LOG.debug("NETCONF Node: {} is fully connected", nodeId.getValue()); @@ -142,7 +140,7 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } } - private void handleDisconnectedNetconfNode(NodeId nodeId) { + private void handleDisconnectedNetconfNode(final NodeId nodeId) { LOG.debug("NETCONF Node: {} disconnected", nodeId.getValue()); Device opDev = readAndGetDevice(nodeId); @@ -158,7 +156,7 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } } - private void handleUnableToConnectNetconfNode(NodeId nodeId) { + private void handleUnableToConnectNetconfNode(final NodeId nodeId) { // The maximum configured number of reconnect attempts // have been reached. No more reconnects will be // attempted by the Netconf Connector. @@ -177,19 +175,19 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } } - void asForceListedDevice(String id, PublicKey serverKey) { + void asForceListedDevice(final String id, final PublicKey serverKey) { NodeId nid = new NodeId(id); Device device = newDevice(id, serverKey, Device1.DeviceStatus.DISCONNECTED); writeDevice(nid, device); } - void asUnlistedDevice(String id, PublicKey serverKey) { + void asUnlistedDevice(final String id, final PublicKey serverKey) { NodeId nid = new NodeId(id); Device device = newDevice(id, serverKey, Device1.DeviceStatus.FAILEDNOTALLOWED); writeDevice(nid, device); } - private Device newDevice(String id, PublicKey serverKey, Device1.DeviceStatus status) { + private static Device newDevice(final String id, final PublicKey serverKey, final Device1.DeviceStatus status) { String sshEncodedKey = serverKey.toString(); try { sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey); @@ -206,12 +204,12 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco return builder.build(); } - private Device readAndGetDevice(NodeId nodeId) { + private Device readAndGetDevice(final NodeId nodeId) { return readDevice(nodeId).orNull(); } @Nonnull - private Optional readDevice(NodeId nodeId) { + private Optional readDevice(final NodeId nodeId) { ReadOnlyTransaction opTx = dataBroker.newReadOnlyTransaction(); InstanceIdentifier deviceIID = buildDeviceInstanceIdentifier(nodeId); @@ -223,43 +221,43 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } } - private void writeDevice(NodeId nodeId, Device modifiedDevice) { + private void writeDevice(final NodeId nodeId, final Device modifiedDevice) { ReadWriteTransaction opTx = dataBroker.newReadWriteTransaction(); opTx.merge(LogicalDatastoreType.OPERATIONAL, buildDeviceInstanceIdentifier(nodeId), modifiedDevice); opTx.submit(); } - private InstanceIdentifier buildDeviceInstanceIdentifier(NodeId nodeId) { + private static InstanceIdentifier buildDeviceInstanceIdentifier(final NodeId nodeId) { return InstanceIdentifier.create(NetconfCallhomeServer.class) .child(AllowedDevices.class) .child(Device.class, new DeviceKey(nodeId.getValue())); } - private Device withConnectedStatus(Device opDev) { + private static Device withConnectedStatus(final Device opDev) { Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.CONNECTED).build(); return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId()) .setSshHostKey(opDev.getSshHostKey()).build(); } - private Device withFailedStatus(Device opDev) { + private static Device withFailedStatus(final Device opDev) { Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.FAILED).build(); return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId()) .setSshHostKey(opDev.getSshHostKey()).build(); } - private Device withDisconnectedStatus(Device opDev) { + private static Device withDisconnectedStatus(final Device opDev) { Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.DISCONNECTED).build(); return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId()) .setSshHostKey(opDev.getSshHostKey()).build(); } - private Device withFailedAuthStatus(Device opDev) { + private static Device withFailedAuthStatus(final Device opDev) { Device1 status = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.FAILEDAUTHFAILURE).build(); return new DeviceBuilder().addAugmentation(Device1.class, status).setUniqueId(opDev.getUniqueId()) .setSshHostKey(opDev.getSshHostKey()).build(); } - private void setDeviceStatus(Device device) { + private void setDeviceStatus(final Device device) { WriteTransaction tx = dataBroker.newWriteOnlyTransaction(); InstanceIdentifier deviceIId = InstanceIdentifier.create(NetconfCallhomeServer.class) @@ -288,7 +286,7 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco } @Override - public void reportFailedAuth(PublicKey sshKey) { + public void reportFailedAuth(final PublicKey sshKey) { AuthorizedKeysDecoder decoder = new AuthorizedKeysDecoder(); for (Device device : getDevicesAsList()) { @@ -305,7 +303,7 @@ class CallhomeStatusReporter implements DataTreeChangeListener, StatusReco setDeviceStatus(failedDevice); return; } - } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchProviderException e) { + } catch (GeneralSecurityException e) { LOG.error("Failed decoding a device key with host key: {} {}", keyString, e); return; } diff --git a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java index cb83bc9deb..713b7ec4a5 100644 --- a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java +++ b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java @@ -16,17 +16,17 @@ import java.util.Properties; public class Configuration { public abstract static class ConfigurationException extends RuntimeException { - ConfigurationException(String msg) { + ConfigurationException(final String msg) { super(msg); } - ConfigurationException(String msg, Exception cause) { + ConfigurationException(final String msg, final Exception cause) { super(msg, cause); } } public static class ReadException extends ConfigurationException { - ReadException(String msg, Exception exc) { + ReadException(final String msg, final Exception exc) { super(msg, exc); } } @@ -34,7 +34,7 @@ public class Configuration { public static class MissingException extends ConfigurationException { private final String key; - MissingException(String key) { + MissingException(final String key) { super("Key not found: " + key); this.key = key; } @@ -48,12 +48,18 @@ public class Configuration { private final String key; private final String value; - IllegalValueException(String key, String value) { + IllegalValueException(final String key, final String value) { super("Key has an illegal value. Key: " + key + ", Value: " + value); this.key = key; this.value = value; } + IllegalValueException(final String key, final String value, final Exception cause) { + super("Key has an illegal value. Key: " + key + ", Value: " + value, cause); + this.key = key; + this.value = value; + } + public String getKey() { return key; } @@ -71,7 +77,7 @@ public class Configuration { properties = new Properties(); } - public Configuration(String path) throws ConfigurationException { + public Configuration(final String path) throws ConfigurationException { this.path = path; try { this.properties = readFromPath(path); @@ -80,27 +86,27 @@ public class Configuration { } } - private Properties readFromPath(String path) throws IOException { - return readFromFile(new File(path)); + private Properties readFromPath(final String filePath) throws IOException { + return readFromFile(new File(filePath)); } - private Properties readFromFile(File file) throws IOException { + private Properties readFromFile(final File file) throws IOException { FileInputStream stream = new FileInputStream(file); properties = readFrom(stream); return properties; } - private Properties readFrom(InputStream stream) throws IOException { + private static Properties readFrom(final InputStream stream) throws IOException { Properties properties = new Properties(); properties.load(stream); return properties; } - public void set(String key, String value) { + public void set(final String key, final String value) { properties.setProperty(key, value); } - String get(String key) { + String get(final String key) { String result = (String) properties.get(key); if (result == null) { throw new MissingException(key); @@ -108,7 +114,7 @@ public class Configuration { return result; } - public int getAsPort(String key) { + public int getAsPort(final String key) { String keyValue = get(key); try { int newPort = Integer.parseInt(keyValue); @@ -117,7 +123,7 @@ public class Configuration { } return newPort; } catch (NumberFormatException e) { - throw new IllegalValueException(key, keyValue); + throw new IllegalValueException(key, keyValue, e); } } } diff --git a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/IetfZeroTouchCallHomeServerProvider.java b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/IetfZeroTouchCallHomeServerProvider.java index e8b96e671b..987fcc0364 100644 --- a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/IetfZeroTouchCallHomeServerProvider.java +++ b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/IetfZeroTouchCallHomeServerProvider.java @@ -62,7 +62,8 @@ public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataT private int port = 0; // 0 = use default in NetconfCallHomeBuilder private final CallhomeStatusReporter statusReporter; - public IetfZeroTouchCallHomeServerProvider(DataBroker dataBroker, CallHomeMountDispatcher mountDispacher) { + public IetfZeroTouchCallHomeServerProvider(final DataBroker dataBroker, + final CallHomeMountDispatcher mountDispacher) { this.dataBroker = dataBroker; this.mountDispacher = mountDispacher; this.authProvider = new CallHomeAuthProviderImpl(dataBroker); @@ -82,7 +83,7 @@ public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataT } } - public void setPort(String portStr) { + public void setPort(final String portStr) { try { Configuration configuration = new Configuration(); configuration.set(CALL_HOME_PORT_KEY, portStr); @@ -112,7 +113,7 @@ public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataT } @VisibleForTesting - void assertValid(Object obj, String description) { + void assertValid(final Object obj, final String description) { if (obj == null) { throw new RuntimeException( String.format("Failed to find %s in IetfZeroTouchCallHomeProvider.initialize()", description)); @@ -136,7 +137,7 @@ public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataT } @Override - public void onDataTreeChanged(@Nonnull Collection> changes) { + public void onDataTreeChanged(@Nonnull final Collection> changes) { // In case of any changes to the devices datatree, register the changed values with callhome server // As of now, no way to add a new callhome client key to the CallHomeAuthorization instance since // its created under CallHomeAuthorizationProvider. @@ -169,7 +170,7 @@ public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataT } } - private void handleDeletedDevices(Set> deletedDevices) { + private void handleDeletedDevices(final Set> deletedDevices) { if (deletedDevices.isEmpty()) { return; } @@ -188,8 +189,8 @@ public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataT } } - private List getReadDevices( - ListenableFuture> devicesFuture) throws InterruptedException, ExecutionException { + private static List getReadDevices(final ListenableFuture> devicesFuture) + throws InterruptedException, ExecutionException { Optional opt = devicesFuture.get(); return opt.isPresent() ? opt.get().getDevice() : Collections.emptyList(); } diff --git a/netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/NetconfMappingTest.java b/netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/NetconfMappingTest.java index fe79771724..923141f8a6 100644 --- a/netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/NetconfMappingTest.java +++ b/netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/NetconfMappingTest.java @@ -33,19 +33,14 @@ import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.netty.channel.Channel; import java.io.IOException; -import java.io.InputStream; import java.math.BigInteger; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -117,9 +112,7 @@ import org.opendaylight.netconf.util.test.XmlFileLoader; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; import org.osgi.framework.Filter; import org.osgi.framework.ServiceListener; @@ -260,12 +253,7 @@ public class NetconfMappingTest extends AbstractConfigTest { final BindingRuntimeContext ret = super.getBindingRuntimeContext(); doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME); doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME); - final List streams = getYangs(); - try { - doReturn(YangParserTestUtils.parseYangStreams(streams)).when(ret).getSchemaContext(); - } catch (final ReactorException e) { - throw new RuntimeException("Unable to build schema context from " + streams, e); - } + doReturn(getSchemaContext()).when(ret).getSchemaContext(); return ret; } @@ -754,22 +742,16 @@ public class NetconfMappingTest extends AbstractConfigTest { } } - private Map> getMbes() throws Exception { - final List yangDependencies = getYangs(); - - final Map> mBeanEntries = Maps.newHashMap(); + private static Map> getMbes() { - final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(yangDependencies); - final YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() { - @Override - public SchemaContext getSchemaContext() { - return schemaContext; - } - }, mock(SchemaSourceProvider.class)); + final SchemaContext schemaContext = getSchemaContext(); + final YangStoreService yangStoreService = new YangStoreService(() -> schemaContext, + mock(SchemaSourceProvider.class)); final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class); doReturn(schemaContext).when(bindingRuntimeContext).getSchemaContext(); doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class)); yangStoreService.refresh(bindingRuntimeContext); + final Map> mBeanEntries = new HashMap<>(); mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap()); return mBeanEntries; @@ -785,9 +767,8 @@ public class NetconfMappingTest extends AbstractConfigTest { return enumBiMap; } - private Set getModules() throws Exception { - final SchemaContext resolveSchemaContext = YangParserTestUtils.parseYangStreams(getYangs()); - return resolveSchemaContext.getModules(); + private static Set getModules() { + return getSchemaContext().getModules(); } @Test @@ -865,19 +846,12 @@ public class NetconfMappingTest extends AbstractConfigTest { return response; } - private List getYangs() { - final List paths = Arrays.asList("/META-INF/yang/config@2013-04-05.yang", - "/META-INF/yang/rpc-context@2013-06-17.yang", - "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", - "/META-INF/yang/test-types.yang", "/META-INF/yang/test-groups.yang", - "/META-INF/yang/ietf-inet-types@2013-07-15.yang"); - final Collection yangDependencies = new ArrayList<>(); - for (final String path : paths) { - final InputStream is = Preconditions - .checkNotNull(getClass().getResourceAsStream(path), path + " not found"); - yangDependencies.add(is); - } - return Lists.newArrayList(yangDependencies); + private static SchemaContext getSchemaContext() { + return YangParserTestUtils.parseYangResources(NetconfMappingTest.class, + "/META-INF/yang/config@2013-04-05.yang", "/META-INF/yang/rpc-context@2013-06-17.yang", + "/META-INF/yang/config-test@2013-06-13.yang", "/META-INF/yang/config-test-impl@2013-04-03.yang", + "/META-INF/yang/test-types@2013-11-27.yang", "/META-INF/yang/test-groups@2014-12-08.yang", + "/META-INF/yang/ietf-inet-types@2013-07-15.yang"); } private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/MdsalNetconfOperationServiceFactory.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/MdsalNetconfOperationServiceFactory.java index 273709db1c..d957097ae8 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/MdsalNetconfOperationServiceFactory.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/MdsalNetconfOperationServiceFactory.java @@ -8,7 +8,6 @@ package org.opendaylight.netconf.mdsal.connector; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.io.CharStreams; import java.io.IOException; @@ -16,7 +15,9 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashSet; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.ExecutionException; import org.opendaylight.controller.config.util.capability.Capability; import org.opendaylight.controller.config.util.capability.YangModuleCapability; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; @@ -25,11 +26,9 @@ import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.netconf.api.monitoring.CapabilityListener; import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory; import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactoryListener; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; @@ -118,16 +117,14 @@ public class MdsalNetconfOperationServiceFactory implements NetconfOperationServ final Module module, final SchemaSourceProvider rootSchemaSourceProviderDependency) { final SourceIdentifier moduleSourceIdentifier = RevisionSourceIdentifier.create(module.getName(), - SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() : - Optional.of(module.getQNameModule().getFormattedRevision())); + module.getRevision()); InputStream sourceStream = null; String source; try { - sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).checkedGet() - .openStream(); + sourceStream = rootSchemaSourceProviderDependency.getSource(moduleSourceIdentifier).get().openStream(); source = CharStreams.toString(new InputStreamReader(sourceStream, StandardCharsets.UTF_8)); - } catch (IOException | SchemaSourceException e) { + } catch (ExecutionException | InterruptedException | IOException e) { LOG.warn("Ignoring source for module {}. Unable to read content", moduleSourceIdentifier, e); source = null; } @@ -146,7 +143,7 @@ public class MdsalNetconfOperationServiceFactory implements NetconfOperationServ LOG.warn("Missing source for module {}. This module will not be available from netconf server", moduleSourceIdentifier); - return Optional.absent(); + return Optional.empty(); } @Override diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/TransactionProvider.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/TransactionProvider.java index 8e5119a886..78680e00ba 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/TransactionProvider.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/TransactionProvider.java @@ -83,7 +83,7 @@ public class TransactionProvider implements AutoCloseable { LOG.debug("Transaction {} failed on", candidateTransaction, e); final String cause = e.getCause() != null ? (" Cause: " + e.getCause().getMessage()) : ""; throw new DocumentedException( - "Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting + cause, + "Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting + cause, e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR); } finally { allOpenReadWriteTransactions.remove(candidateTransaction); diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java index 7c86dd26b4..cfb59b871f 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java @@ -15,9 +15,11 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import java.net.URI; import java.net.URISyntaxException; +import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; +import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.xml.transform.dom.DOMSource; import org.opendaylight.controller.config.util.xml.DocumentedException; @@ -27,7 +29,6 @@ import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType import org.opendaylight.controller.config.util.xml.XmlElement; import org.opendaylight.controller.config.util.xml.XmlUtil; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; import org.opendaylight.netconf.api.NetconfDocumentedException; import org.opendaylight.netconf.api.xml.XmlNetconfConstants; @@ -129,14 +130,14 @@ public class EditConfig extends AbstractSingletonNetconfOperation { case CREATE: try { final Optional> readResult = - rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet(); + rwtx.read(LogicalDatastoreType.CONFIGURATION, path).get(); if (readResult.isPresent()) { throw new DocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR); } mergeParentMixin(rwtx, path, changeData); rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData); - } catch (final ReadFailedException e) { + } catch (final InterruptedException | ExecutionException e) { LOG.warn("Read from datastore failed when trying to read data for create operation", change, e); } break; @@ -147,13 +148,13 @@ public class EditConfig extends AbstractSingletonNetconfOperation { case DELETE: try { final Optional> readResult = - rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet(); + rwtx.read(LogicalDatastoreType.CONFIGURATION, path).get(); if (!readResult.isPresent()) { throw new DocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR); } rwtx.delete(LogicalDatastoreType.CONFIGURATION, path); - } catch (final ReadFailedException e) { + } catch (final InterruptedException | ExecutionException e) { LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e); } break; @@ -166,7 +167,7 @@ public class EditConfig extends AbstractSingletonNetconfOperation { } private void mergeParentMixin(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path, - final NormalizedNode change) { + final NormalizedNode change) { final YangInstanceIdentifier parentNodeYid = path.getParent(); if (change instanceof MapEntryNode) { final SchemaNode schemaNode = SchemaContextUtil.findNodeInSchemaContext( @@ -232,33 +233,36 @@ public class EditConfig extends AbstractSingletonNetconfOperation { private Optional getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws DocumentedException { - Optional dataSchemaNode = Optional.absent(); + final Iterator it; try { // returns module with newest revision since findModuleByNamespace returns a set of modules and we only // need the newest one - final Module module = - schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null); - if (module == null) { - // no module is present with this namespace - throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace, - ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR); - } - final DataSchemaNode schemaNode = - module.getDataChildByName(QName.create(module.getQNameModule(), element.getName())); + it = schemaContext.getCurrentContext().findModules(new URI(namespace)).iterator(); + } catch (final URISyntaxException e) { + LOG.debug("Unable to create URI for namespace : {}", namespace); + return Optional.absent(); + } + + if (!it.hasNext()) { + // no module is present with this namespace + throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace, + ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR); + } + + final Module module = it.next(); + final java.util.Optional schemaNode = + module.findDataChildByName(QName.create(module.getQNameModule(), element.getName())); + if (!schemaNode.isPresent()) { if (schemaNode != null) { - dataSchemaNode = Optional.of(schemaNode); - } else { throw new DocumentedException( - "Unable to find node with namespace: " + namespace + "in module: " + module.toString(), - ErrorType.APPLICATION, - ErrorTag.UNKNOWN_NAMESPACE, - ErrorSeverity.ERROR); + "Unable to find node with namespace: " + namespace + "in module: " + module.toString(), + ErrorType.APPLICATION, + ErrorTag.UNKNOWN_NAMESPACE, + ErrorSeverity.ERROR); } - } catch (final URISyntaxException e) { - LOG.debug("Unable to create URI for namespace : {}", namespace); } - return dataSchemaNode; + return Optional.fromJavaUtil(schemaNode); } private static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException { diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditOperationNormalizedNodeStreamWriter.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditOperationNormalizedNodeStreamWriter.java index 7a983428df..d64375a887 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditOperationNormalizedNodeStreamWriter.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditOperationNormalizedNodeStreamWriter.java @@ -33,7 +33,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNo final class EditOperationNormalizedNodeStreamWriter extends ImmutableNormalizedNodeStreamWriter implements NormalizedNodeStreamAttributeWriter { - private static final QName OPERATION_ATTRIBUTE = QName.create(EditConfigInput.QNAME.getNamespace(), null, + private static final QName OPERATION_ATTRIBUTE = QName.create(EditConfigInput.QNAME.getNamespace(), XmlNetconfConstants.OPERATION_ATTR_KEY); private final DataTreeChangeTracker dataTreeChangeTracker; diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java index 00d9b81e4a..6d4ba4305a 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java @@ -9,7 +9,6 @@ package org.opendaylight.netconf.mdsal.connector.ops; import com.google.common.base.Optional; -import com.google.common.base.Throwables; import com.google.common.util.concurrent.CheckedFuture; import java.io.IOException; import java.net.URI; @@ -107,8 +106,7 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation { //this returns module with the newest revision if more then 1 module with same namespace is found private Optional getModule(final URI namespaceURI) { - return Optional.fromNullable( - schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null)); + return Optional.fromJavaUtil(schemaContext.getCurrentContext().findModule(namespaceURI)); } private static Optional getRpcDefinitionFromModule(final Module module, final URI namespaceURI, @@ -132,7 +130,7 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation { netconfOperationNamespace = operationElement.getNamespace(); } catch (final DocumentedException e) { LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e); - throw new DocumentedException("Cannot retrieve netconf operation namespace from message", + throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR); } @@ -246,7 +244,7 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation { nnWriter.flush(); xmlWriter.flush(); } catch (XMLStreamException | IOException e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/AbstractGet.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/AbstractGet.java index e04766a1d7..4fa0baa805 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/AbstractGet.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/AbstractGet.java @@ -161,7 +161,7 @@ public abstract class AbstractGet extends AbstractSingletonNetconfOperation { try { validateInputRpc(xml, operationName); } catch (final DocumentedException e) { - throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), + throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e, e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo()); } @@ -169,8 +169,8 @@ public abstract class AbstractGet extends AbstractSingletonNetconfOperation { try { sourceDatastore = parseSource(xml); } catch (final DocumentedException e) { - throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e.getErrorType(), - e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo()); + throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e, + e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo()); } return new GetConfigExecution(sourceDatastore); diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidator.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidator.java index c6f5714e1f..d104fddb96 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidator.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidator.java @@ -32,7 +32,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceI import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory; import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec; import org.opendaylight.yangtools.yang.data.util.codec.TypeAwareCodec; -import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; +import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; @@ -65,16 +65,16 @@ public class FilterContentValidator { public YangInstanceIdentifier validate(final XmlElement filterContent) throws DocumentedException { try { final URI namespace = new URI(filterContent.getNamespace()); - final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null); + final Module module = schemaContext.getCurrentContext().findModules(namespace).iterator().next(); final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName()); final FilterTree filterTree = validateNode( filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER, schema)); return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder()); } catch (final URISyntaxException e) { - throw new RuntimeException("Wrong namespace in element + " + filterContent.toString()); + throw new RuntimeException("Wrong namespace in element + " + filterContent.toString(), e); } catch (final ValidationException e) { LOG.debug("Filter content isn't valid", e); - throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), + throw new DocumentedException("Validation failed. Cause: " + e.getMessage(), e, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.UNKNOWN_NAMESPACE, DocumentedException.ErrorSeverity.ERROR); @@ -132,7 +132,7 @@ public class FilterContentValidator { final DataSchemaNode childSchema = path.getLast(); validateNode(childElement, childSchema, subtree); } catch (URISyntaxException | MissingNameSpaceException e) { - throw new RuntimeException("Wrong namespace in element + " + childElement.toString()); + throw new RuntimeException("Wrong namespace in element + " + childElement.toString(), e); } } return tree; @@ -249,20 +249,20 @@ public class FilterContentValidator { } FilterTree addChild(final DataSchemaNode data) { - final Type type; - if (data instanceof ChoiceCaseNode) { - type = Type.CHOICE_CASE; + final Type childType; + if (data instanceof CaseSchemaNode) { + childType = Type.CHOICE_CASE; } else if (data instanceof ListSchemaNode) { - type = Type.LIST; + childType = Type.LIST; } else { - type = Type.OTHER; + childType = Type.OTHER; } - final QName name = data.getQName(); - FilterTree childTree = children.get(name); + final QName childName = data.getQName(); + FilterTree childTree = children.get(childName); if (childTree == null) { - childTree = new FilterTree(name, type, data); + childTree = new FilterTree(childName, childType, data); } - children.put(name, childTree); + children.put(childName, childTree); return childTree; } diff --git a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/NetconfMDSalMappingTest.java b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/NetconfMDSalMappingTest.java index c23155a2b3..ad35b0dfa5 100644 --- a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/NetconfMDSalMappingTest.java +++ b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/NetconfMDSalMappingTest.java @@ -17,12 +17,8 @@ import static org.mockito.Mockito.doAnswer; import com.google.common.io.ByteSource; import com.google.common.util.concurrent.Futures; -import java.io.InputStream; import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; import java.util.EnumMap; -import java.util.List; import java.util.concurrent.ExecutorService; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; @@ -133,7 +129,8 @@ public class NetconfMDSalMappingTest { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); - this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas()); + this.schemaContext = YangParserTestUtils.parseYangResources(NetconfMDSalMappingTest.class, + "/META-INF/yang/config@2013-04-05.yang", "/yang/mdsal-netconf-mapping-test.yang"); schemaContext.getModules(); final SchemaService schemaService = createSchemaService(); @@ -145,7 +142,7 @@ public class NetconfMDSalMappingTest { datastores.put(LogicalDatastoreType.OPERATIONAL, operStore); final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool( - 16, 16, "CommitFutures"); + 16, 16, "CommitFutures", NetconfMDSalMappingTest.class); final ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor); this.transactionProvider = new TransactionProvider(cdb, SESSION_ID_FOR_REPORTING); @@ -154,7 +151,7 @@ public class NetconfMDSalMappingTest { final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0]; final YangTextSchemaSource yangTextSchemaSource = YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes())); - return Futures.immediateCheckedFuture(yangTextSchemaSource); + return Futures.immediateFuture(yangTextSchemaSource); }).when(sourceProvider).getSource(any(SourceIdentifier.class)); @@ -556,7 +553,7 @@ public class NetconfMDSalMappingTest { + " \n" + ""; XmlElement xe = getXmlElement(stringWithoutPrefix); - NodeList nodeList = editConfig.getElementsByTagName(xe, TARGET_KEY); + NodeList nodeList = EditConfig.getElementsByTagName(xe, TARGET_KEY); Assert.assertEquals(1, nodeList.getLength()); String stringWithPrefix = @@ -569,7 +566,7 @@ public class NetconfMDSalMappingTest { + ""; xe = getXmlElement(stringWithPrefix); - nodeList = editConfig.getElementsByTagName(xe, TARGET_KEY); + nodeList = EditConfig.getElementsByTagName(xe, TARGET_KEY); Assert.assertEquals(1, nodeList.getLength()); String stringWithoutTarget = @@ -582,7 +579,7 @@ public class NetconfMDSalMappingTest { xe = getXmlElement(stringWithoutTarget); try { - nodeList = editConfig.getElementsByTagName(xe, TARGET_KEY); + nodeList = EditConfig.getElementsByTagName(xe, TARGET_KEY); XmlElement.fromDomElement((Element) nodeList.item(0)).getOnlyChildElement(); Assert.fail("Not specified target, we should fail"); } catch (DocumentedException documentedException) { @@ -591,7 +588,7 @@ public class NetconfMDSalMappingTest { } - private XmlElement getXmlElement(final String elementAsString) throws Exception { + private static XmlElement getXmlElement(final String elementAsString) throws Exception { Document document = XmlUtil.readXmlToDocument(elementAsString); Element element = document.getDocumentElement(); return XmlElement.fromDomElement(element); @@ -824,19 +821,6 @@ public class NetconfMDSalMappingTest { return response; } - private List getYangSchemas() { - final List schemaPaths = Arrays.asList("/META-INF/yang/config@2013-04-05.yang", - "/yang/mdsal-netconf-mapping-test.yang"); - final List schemas = new ArrayList<>(); - - for (final String schemaPath : schemaPaths) { - final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath); - schemas.add(resourceAsStream); - } - - return schemas; - } - private SchemaService createSchemaService() { return new SchemaService() { diff --git a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpcTest.java b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpcTest.java index 7df0ff59e0..60ac65ab68 100644 --- a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpcTest.java +++ b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpcTest.java @@ -20,12 +20,9 @@ import com.google.common.base.Preconditions; import com.google.common.io.ByteSource; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; -import java.io.InputStream; import java.net.URI; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.custommonkey.xmlunit.DetailedDiff; @@ -88,7 +85,7 @@ public class RuntimeRpcTest { return doc; } - private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() { + private static final DOMRpcService RPC_SERVICE_VOID_INVOKER = new DOMRpcService() { @Nonnull @Override public CheckedFuture invokeRpc( @@ -104,7 +101,7 @@ public class RuntimeRpcTest { } }; - private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() { + private static final DOMRpcService RPC_SERVICE_FAILED_INVOCATION = new DOMRpcService() { @Nonnull @Override public CheckedFuture invokeRpc( @@ -122,15 +119,14 @@ public class RuntimeRpcTest { } }; - private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() { + private final DOMRpcService rpcServiceSuccessfulInvocation = new DOMRpcService() { @Nonnull @Override public CheckedFuture invokeRpc( @Nonnull final SchemaPath type, @Nullable final NormalizedNode input) { final Collection> children = (Collection>) input.getValue(); - final Module module = schemaContext.findModuleByNamespaceAndRevision( - type.getLastComponent().getNamespace(), null); + final Module module = schemaContext.findModule(type.getLastComponent().getNamespace()).orElse(null); final RpcDefinition rpcDefinition = getRpcDefinitionFromModule( module, module.getNamespace(), type.getLastComponent().getLocalName()); final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput(); @@ -144,7 +140,7 @@ public class RuntimeRpcTest { @Nonnull @Override public ListenerRegistration registerRpcListener( - @Nonnull final T listener) { + @Nonnull final T lsnr) { return null; } }; @@ -186,13 +182,13 @@ public class RuntimeRpcTest { }).when(sourceProvider).getSource(any(SourceIdentifier.class)); - this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas()); + this.schemaContext = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang"); this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider); } @Test public void testVoidOutputRpc() throws Exception { - final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke); + final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER); final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml"); final HandlingPriority priority = rpc.canHandle(rpcDocument); @@ -206,7 +202,7 @@ public class RuntimeRpcTest { @Test public void testSuccesfullNonVoidInvocation() throws Exception { final RuntimeRpc rpc = new RuntimeRpc( - SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation); + SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation); final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml"); final HandlingPriority priority = rpc.canHandle(rpcDocument); @@ -219,7 +215,7 @@ public class RuntimeRpcTest { @Test public void testSuccesfullContainerInvocation() throws Exception { final RuntimeRpc rpc = new RuntimeRpc( - SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation); + SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation); final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml"); final HandlingPriority priority = rpc.canHandle(rpcDocument); @@ -232,7 +228,7 @@ public class RuntimeRpcTest { @Test public void testFailedInvocation() throws Exception { final RuntimeRpc rpc = new RuntimeRpc( - SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceFailedInvocation); + SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION); final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml"); final HandlingPriority priority = rpc.canHandle(rpcDocument); @@ -250,7 +246,7 @@ public class RuntimeRpcTest { @Test public void testVoidInputOutputRpc() throws Exception { - final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke); + final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER); final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml"); final HandlingPriority priority = rpc.canHandle(rpcDocument); @@ -263,7 +259,7 @@ public class RuntimeRpcTest { @Test public void testBadNamespaceInRpc() throws Exception { - final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke); + final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER); final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml"); try { @@ -294,16 +290,4 @@ public class RuntimeRpcTest { return null; } - - private List getYangSchemas() { - final List schemaPaths = Collections.singletonList("/yang/mdsal-netconf-rpc-test.yang"); - final List schemas = new ArrayList<>(); - - for (final String schemaPath : schemaPaths) { - final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath); - schemas.add(resourceAsStream); - } - - return schemas; - } -} \ No newline at end of file +} diff --git a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java index 466c7dbc02..d90e31b071 100644 --- a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java +++ b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java @@ -11,12 +11,9 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.junit.Test; import org.opendaylight.controller.config.util.xml.XmlElement; @@ -35,11 +32,9 @@ public class Bug8084 { @Test public void testValidateTypes() throws Exception { - final List sources = new ArrayList<>(); - sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang")); - sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang")); - sources.add(getClass().getResourceAsStream("/yang/mdsal-netconf-mapping-test.yang")); - final SchemaContext context = YangParserTestUtils.parseYangStreams(sources); + final SchemaContext context = YangParserTestUtils.parseYangResources(Bug8084.class, + "/yang/filter-validator-test-mod-0.yang", "/yang/filter-validator-test-augment.yang", + "/yang/mdsal-netconf-mapping-test.yang"); final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class); doReturn(context).when(currentContext).getCurrentContext(); final FilterContentValidator validator = new FilterContentValidator(currentContext); diff --git a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidatorTest.java b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidatorTest.java index 8ee3e38a33..cec6855c46 100644 --- a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidatorTest.java +++ b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidatorTest.java @@ -11,7 +11,6 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import com.google.common.base.Preconditions; -import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -73,11 +72,10 @@ public class FilterContentValidatorTest { @Before public void setUp() throws Exception { - final List sources = new ArrayList<>(); - sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang")); - sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang")); - sources.add(getClass().getResourceAsStream("/yang/mdsal-netconf-mapping-test.yang")); - final SchemaContext context = YangParserTestUtils.parseYangStreams(sources); + final SchemaContext context = YangParserTestUtils.parseYangResources(FilterContentValidatorTest.class, + "/yang/filter-validator-test-mod-0.yang", "/yang/filter-validator-test-augment.yang", + "/yang/mdsal-netconf-mapping-test.yang"); + final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class); doReturn(context).when(currentContext).getCurrentContext(); validator = new FilterContentValidator(currentContext); @@ -89,8 +87,7 @@ public class FilterContentValidatorTest { if (expected.startsWith("success")) { final String expId = expected.replace("success=", ""); final YangInstanceIdentifier actual = validator.validate(filterContent); - final YangInstanceIdentifier expected = fromString(expId); - Assert.assertEquals(expected, actual); + Assert.assertEquals(fromString(expId), actual); } else if (expected.startsWith("error")) { try { validator.validate(filterContent); @@ -142,11 +139,10 @@ public class FilterContentValidatorTest { } private static QName createNodeQName(final QName prev, final String input) { - final QName qName = QName.create(input); - if (qName.getModule().getNamespace() != null) { - return qName; + try { + return QName.create(input); + } catch (IllegalArgumentException e) { + return QName.create(Preconditions.checkNotNull(prev), input); } - - return QName.create(Preconditions.checkNotNull(prev), input); } } diff --git a/netconf/mdsal-netconf-yang-library/src/main/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriter.java b/netconf/mdsal-netconf-yang-library/src/main/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriter.java index d0d383a2bb..918e71d13f 100644 --- a/netconf/mdsal-netconf-yang-library/src/main/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriter.java +++ b/netconf/mdsal-netconf-yang-library/src/main/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriter.java @@ -115,21 +115,24 @@ public class SchemaServiceToMdsalWriter implements SchemaContextListener, AutoCl // TODO Conformance type is always set to Implement value, but it should it really be like this? // TODO Add also deviations and features lists to module entries - moduleBuilder.setName(new YangIdentifier(module.getName())) - .setRevision(new OptionalRevision(module.getQNameModule().getFormattedRevision())) - .setNamespace(new Uri(module.getNamespace().toString())) - .setConformanceType(ConformanceType.Implement) - .setSubmodules(createSubmodulesForModule(module)); + moduleBuilder.setName(new YangIdentifier(module.getName())); + + module.getQNameModule().getRevision().ifPresent(rev -> moduleBuilder.setRevision( + new OptionalRevision(rev.toString()))); - return moduleBuilder.build(); + return moduleBuilder.setNamespace(new Uri(module.getNamespace().toString())) + .setConformanceType(ConformanceType.Implement) + .setSubmodules(createSubmodulesForModule(module)) + .build(); } - private Submodules createSubmodulesForModule(final Module module) { + private static Submodules createSubmodulesForModule(final Module module) { final List submodulesList = Lists.newArrayList(); for (final Module subModule : module.getSubmodules()) { - final SubmoduleBuilder subModuleEntryBuilder = new SubmoduleBuilder(); - subModuleEntryBuilder.setName(new YangIdentifier(subModule.getName())) - .setRevision(new OptionalRevision(subModule.getQNameModule().getFormattedRevision())); + final SubmoduleBuilder subModuleEntryBuilder = new SubmoduleBuilder() + .setName(new YangIdentifier(subModule.getName())); + subModule.getQNameModule().getRevision().ifPresent( + rev -> subModuleEntryBuilder.setRevision(new OptionalRevision(rev.toString()))); submodulesList.add(subModuleEntryBuilder.build()); } diff --git a/netconf/mdsal-netconf-yang-library/src/test/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriterTest.java b/netconf/mdsal-netconf-yang-library/src/test/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriterTest.java index 5e6457ac8e..1b8b6dd6a3 100644 --- a/netconf/mdsal-netconf-yang-library/src/test/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriterTest.java +++ b/netconf/mdsal-netconf-yang-library/src/test/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriterTest.java @@ -16,8 +16,6 @@ import static org.mockito.Mockito.when; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; -import java.io.InputStream; -import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @@ -91,17 +89,13 @@ public class SchemaServiceToMdsalWriterTest { eq(MODULES_STATE_INSTANCE_IDENTIFIER), eq(createTestModuleState())); } - private SchemaContext getSchema() throws Exception { - final List modelsToParse = Lists.newArrayList( - SchemaServiceToMdsalWriterTest.class.getResourceAsStream("/test-module.yang"), - SchemaServiceToMdsalWriterTest.class.getResourceAsStream("/test-submodule.yang") - ); - return YangParserTestUtils.parseYangStreams(modelsToParse); + private static SchemaContext getSchema() { + return YangParserTestUtils.parseYangResources(SchemaServiceToMdsalWriterTest.class, "/test-module.yang", + "/test-submodule.yang"); } - private ModulesState createTestModuleState() { + private static ModulesState createTestModuleState() { Submodule sub = new SubmoduleBuilder().setName(new YangIdentifier("test-submodule")) - .setRevision(new OptionalRevision("1970-01-01")) .build(); Module module = new ModuleBuilder().setName(new YangIdentifier("test-module")) diff --git a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java index 69abbad23f..26609d21e3 100644 --- a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java +++ b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java @@ -12,7 +12,6 @@ import static com.google.common.util.concurrent.Futures.immediateFuture; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; @@ -235,7 +234,7 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener try { domPublish.putNotification(new TopicDOMNotification(topicNotification)); } catch (final InterruptedException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -254,7 +253,7 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG).withValue(new DOMSource(element)).build(); } catch (IOException | XMLStreamException e) { LOG.error("Unable to encapsulate notification.", e); - throw Throwables.propagate(e); + throw new RuntimeException(e); } } diff --git a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceRegistration.java b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceRegistration.java index 9089e92ee1..649454ef11 100644 --- a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceRegistration.java +++ b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceRegistration.java @@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory; /** * Helper class to keep connection status of netconf node and event source registration object. */ -public class NetconfEventSourceRegistration implements AutoCloseable { +public final class NetconfEventSourceRegistration implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSourceRegistration.class); private static final YangInstanceIdentifier NETCONF_DEVICE_DOM_PATH = YangInstanceIdentifier.builder() diff --git a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NotificationTopicRegistration.java b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NotificationTopicRegistration.java index d10ce66249..d9b3543167 100644 --- a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NotificationTopicRegistration.java +++ b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NotificationTopicRegistration.java @@ -37,8 +37,8 @@ abstract class NotificationTopicRegistration implements AutoCloseable { private Date lastEventTime; protected final ConcurrentHashMap> notificationTopicMap = new ConcurrentHashMap<>(); - protected NotificationTopicRegistration(NotificationSourceType notificationSourceType, String sourceName, - String notificationUrnPrefix) { + protected NotificationTopicRegistration(final NotificationSourceType notificationSourceType, + final String sourceName, final String notificationUrnPrefix) { this.notificationSourceType = notificationSourceType; this.sourceName = sourceName; this.notificationUrnPrefix = notificationUrnPrefix; @@ -50,7 +50,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable { return active; } - protected void setActive(boolean active) { + protected void setActive(final boolean active) { this.active = active; } @@ -72,7 +72,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable { * @param notificationPath path * @return topicIds */ - Set getTopicsForNotification(SchemaPath notificationPath) { + Set getTopicsForNotification(final SchemaPath notificationPath) { final Set topicIds = notificationTopicMap.get(notificationPath); return topicIds != null ? topicIds : Sets.newHashSet(); } @@ -83,7 +83,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable { * @param notificationPath path * @return true, if notification belongs to registration namespace */ - boolean checkNotificationPath(SchemaPath notificationPath) { + boolean checkNotificationPath(final SchemaPath notificationPath) { if (notificationPath == null) { return false; } @@ -97,7 +97,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable { return Optional.fromNullable(lastEventTime); } - void setLastEventTime(Date lastEventTime) { + void setLastEventTime(final Date lastEventTime) { this.lastEventTime = lastEventTime; } @@ -120,7 +120,6 @@ abstract class NotificationTopicRegistration implements AutoCloseable { * Registers associated event source notification to topic. * * @param topicId topic id - * @return true, if successful */ abstract void unRegisterNotificationTopic(TopicId topicId); @@ -128,7 +127,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable { return replaySupported; } - protected void setReplaySupported(boolean replaySupported) { + protected void setReplaySupported(final boolean replaySupported) { this.replaySupported = replaySupported; } diff --git a/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceMountTest.java b/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceMountTest.java index d64e1a6415..04be595ed2 100644 --- a/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceMountTest.java +++ b/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceMountTest.java @@ -135,7 +135,7 @@ public class NetconfEventSourceMountTest { final List streamNames = Lists.transform(availableStreams, new Function() { @Nullable @Override - public String apply(@Nullable Stream input) { + public String apply(@Nullable final Stream input) { return input.getName().getValue(); } }); @@ -143,15 +143,15 @@ public class NetconfEventSourceMountTest { streamNames.contains(STREAM_2); } - private String getStreamName(ContainerNode value) { + private static String getStreamName(final ContainerNode value) { YangInstanceIdentifier.NodeIdentifier stream = new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "stream")); return (String) value.getChild(stream).get().getValue(); } - private Optional getDate(ContainerNode value) { + private static Optional getDate(final ContainerNode value) { YangInstanceIdentifier.NodeIdentifier startTime = new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "startTime")); - return value.getChild(startTime); + return Optional.fromJavaUtil(value.getChild(startTime)); } } \ No newline at end of file diff --git a/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceTest.java b/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceTest.java index 56ce4ee61a..7e94e23486 100644 --- a/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceTest.java +++ b/netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceTest.java @@ -98,6 +98,7 @@ public class NetconfEventSourceTest { final Node nodeId1 = NetconfTestUtils.getNetconfNode("NodeId1", "node.test.local", ConnectionStatus .Connected, NetconfTestUtils.NOTIFICATION_CAPABILITY_PREFIX); doReturn(nodeId1).when(mount).getNode(); + doReturn(nodeId1.getNodeId().getValue()).when(mount).getNodeId(); Map streamMap = new HashMap<>(); streamMap.put(NOTIFICATION_1_PATH.getLastComponent().getNamespace().toString(), "stream-1"); @@ -126,8 +127,7 @@ public class NetconfEventSourceTest { final TopicDOMNotification value = (TopicDOMNotification) captor.getValue(); final QName qname = TopicNotification.QNAME; final YangInstanceIdentifier.NodeIdentifier topicIdNode = - new YangInstanceIdentifier.NodeIdentifier(QName.create(qname.getNamespace().toString(), qname - .getFormattedRevision(), "topic-id")); + new YangInstanceIdentifier.NodeIdentifier(QName.create(qname, "topic-id")); final Object actualTopicId = value.getBody().getChild(topicIdNode).get().getValue(); Assert.assertEquals(topic1.getTopicId(), actualTopicId); } @@ -151,14 +151,14 @@ public class NetconfEventSourceTest { verify(domNotificationPublishServiceMock, only()).putNotification(any()); } - private Stream createStream(String name) { + private static Stream createStream(final String name) { return new StreamBuilder() .setName(new StreamNameType(name)) .setReplaySupport(true) .build(); } - private NotificationDefinition getNotificationDefinitionMock(QName qualifiedName) { + private static NotificationDefinition getNotificationDefinitionMock(final QName qualifiedName) { NotificationDefinition notification = mock(NotificationDefinition.class); doReturn(qualifiedName).when(notification).getQName(); doReturn(SchemaPath.create(true, qualifiedName)).when(notification).getPath(); diff --git a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/SessionEvent.java b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/SessionEvent.java index d6c87c3ed8..6918335e5b 100644 --- a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/SessionEvent.java +++ b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/SessionEvent.java @@ -10,7 +10,7 @@ package org.opendaylight.netconf.api.monitoring; /** * Class represents change in netconf session. */ -public class SessionEvent { +public final class SessionEvent { private final NetconfManagementSession session; private final Type type; diff --git a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java index e3ffdd0ae5..3abeeea40c 100644 --- a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java +++ b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java @@ -27,4 +27,8 @@ public final class NetconfConstants { public static final Set CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR, NETCONF_MONITORING, NETCONF_NOTIFICATION); + + private NetconfConstants() { + + } } diff --git a/netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageAdditionalHeaderTest.java b/netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageAdditionalHeaderTest.java index b7b2b2db20..5de0f0a35c 100644 --- a/netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageAdditionalHeaderTest.java +++ b/netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageAdditionalHeaderTest.java @@ -35,8 +35,8 @@ public class NetconfHelloMessageAdditionalHeaderTest { @Test public void testStaticConstructor() throws Exception { - NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(customHeader); - assertEquals(header.toString(), this.header.toString()); - assertEquals(header.toFormattedString(), this.header.toFormattedString()); + NetconfHelloMessageAdditionalHeader hdr = NetconfHelloMessageAdditionalHeader.fromString(customHeader); + assertEquals(hdr.toString(), this.header.toString()); + assertEquals(hdr.toFormattedString(), this.header.toFormattedString()); } } diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java index 654210a4a0..82e72045d4 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java @@ -55,6 +55,7 @@ public class SimpleNetconfClientSessionListener implements NetconfClientSessionL } @Override + @SuppressWarnings("checkstyle:hiddenField") public final synchronized void onSessionUp(NetconfClientSession clientSession) { this.clientSession = Preconditions.checkNotNull(clientSession); LOG.debug("Client session {} went up", clientSession); @@ -71,12 +72,14 @@ public class SimpleNetconfClientSessionListener implements NetconfClientSessionL } @Override + @SuppressWarnings("checkstyle:hiddenField") public final void onSessionDown(NetconfClientSession clientSession, Exception exception) { LOG.debug("Client Session {} went down unexpectedly", clientSession, exception); tearDown(exception); } @Override + @SuppressWarnings("checkstyle:hiddenField") public final void onSessionTerminated(NetconfClientSession clientSession, NetconfTerminationReason netconfTerminationReason) { LOG.debug("Client Session {} terminated, reason: {}", clientSession, diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfigurationBuilder.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfigurationBuilder.java index 8047d60f1c..73f664cdce 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfigurationBuilder.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfigurationBuilder.java @@ -34,38 +34,45 @@ public class NetconfClientConfigurationBuilder { return new NetconfClientConfigurationBuilder(); } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withAddress(final InetSocketAddress address) { this.address = address; return this; } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withConnectionTimeoutMillis(final long connectionTimeoutMillis) { this.connectionTimeoutMillis = connectionTimeoutMillis; return this; } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withProtocol( final NetconfClientConfiguration.NetconfClientProtocol clientProtocol) { this.clientProtocol = clientProtocol; return this; } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withAdditionalHeader( final NetconfHelloMessageAdditionalHeader additionalHeader) { this.additionalHeader = additionalHeader; return this; } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withSessionListener(final NetconfClientSessionListener sessionListener) { this.sessionListener = sessionListener; return this; } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withReconnectStrategy(final ReconnectStrategy reconnectStrategy) { this.reconnectStrategy = reconnectStrategy; return this; } + @SuppressWarnings("checkstyle:hiddenField") public NetconfClientConfigurationBuilder withAuthHandler(final AuthenticationHandler authHandler) { this.authHandler = authHandler; return this; diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfReconnectingClientConfigurationBuilder.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfReconnectingClientConfigurationBuilder.java index 4597dca75e..e705d3cca6 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfReconnectingClientConfigurationBuilder.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfReconnectingClientConfigurationBuilder.java @@ -14,7 +14,7 @@ import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.Authenticat import org.opendaylight.protocol.framework.ReconnectStrategy; import org.opendaylight.protocol.framework.ReconnectStrategyFactory; -public class NetconfReconnectingClientConfigurationBuilder extends NetconfClientConfigurationBuilder { +public final class NetconfReconnectingClientConfigurationBuilder extends NetconfClientConfigurationBuilder { private ReconnectStrategyFactory connectStrategyFactory; @@ -25,7 +25,7 @@ public class NetconfReconnectingClientConfigurationBuilder extends NetconfClient return new NetconfReconnectingClientConfigurationBuilder(); } - + @SuppressWarnings("checkstyle:hiddenField") public NetconfReconnectingClientConfigurationBuilder withConnectStrategyFactory( final ReconnectStrategyFactory connectStrategyFactory) { this.connectStrategyFactory = connectStrategyFactory; diff --git a/netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorTest.java b/netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorTest.java index 8ca1d8c811..63c24c2419 100644 --- a/netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorTest.java +++ b/netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorTest.java @@ -80,17 +80,17 @@ public class NetconfClientSessionNegotiatorTest { } private Channel mockChannel() { - Channel channel = mock(Channel.class); + Channel ret = mock(Channel.class); ChannelHandler channelHandler = mockChannelHandler(); - doReturn("").when(channel).toString(); - doReturn(future).when(channel).close(); - doReturn(future).when(channel).writeAndFlush(anyObject()); - doReturn(true).when(channel).isOpen(); - doReturn(pipeline).when(channel).pipeline(); + doReturn("").when(ret).toString(); + doReturn(future).when(ret).close(); + doReturn(future).when(ret).writeAndFlush(anyObject()); + doReturn(true).when(ret).isOpen(); + doReturn(pipeline).when(ret).pipeline(); doReturn("").when(pipeline).toString(); doReturn(pipeline).when(pipeline).remove(any(ChannelHandler.class)); doReturn(channelHandler).when(pipeline).remove(anyString()); - return channel; + return ret; } private static ChannelFuture mockChannelFuture() { @@ -178,7 +178,7 @@ public class NetconfClientSessionNegotiatorTest { negotiator.channelActive(null); Set caps = Sets.newSet("exi:1.0"); - NetconfHelloMessage helloMessage = NetconfHelloMessage.createServerHello(caps, 10); + NetconfHelloMessage message = NetconfHelloMessage.createServerHello(caps, 10); doAnswer(new Answer() { @Override @@ -190,7 +190,7 @@ public class NetconfClientSessionNegotiatorTest { ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class); doReturn(pipeline).when(handlerContext).pipeline(); - negotiator.handleMessage(helloMessage); + negotiator.handleMessage(message); Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml"); channelInboundHandlerAdapter.channelRead(handlerContext, new NetconfMessage(expectedResult)); diff --git a/netconf/netconf-console/pom.xml b/netconf/netconf-console/pom.xml index 32c335ad14..60b69733d4 100644 --- a/netconf/netconf-console/pom.xml +++ b/netconf/netconf-console/pom.xml @@ -99,22 +99,6 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL - - org.apache.felix - maven-bundle-plugin - true - - - - - org.apache.karaf.shell.commands;version="[3.0.0,4.1)", - org.apache.karaf.shell.console;version="[3.0.0,4.1)", - org.apache.karaf.shell.table;version="[3.0.0,4.1)", - * - - - - org.apache.maven.plugins maven-checkstyle-plugin diff --git a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfCommandUtils.java b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfCommandUtils.java index e7c9eda71f..f705c94062 100644 --- a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfCommandUtils.java +++ b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfCommandUtils.java @@ -12,7 +12,7 @@ import com.google.common.base.Strings; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class NetconfCommandUtils { +public final class NetconfCommandUtils { private static final Pattern IP_PATTERN = Pattern.compile( "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." @@ -20,6 +20,10 @@ public class NetconfCommandUtils { + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + private NetconfCommandUtils() { + + } + public static boolean isPortValid(final String devicePort) { if (Strings.isNullOrEmpty(devicePort)) { return false; diff --git a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleConstants.java b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleConstants.java index ea7741cbbd..4d24bbb6bb 100644 --- a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleConstants.java +++ b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleConstants.java @@ -8,7 +8,7 @@ package org.opendaylight.netconf.console.utils; -public class NetconfConsoleConstants { +public final class NetconfConsoleConstants { private NetconfConsoleConstants() { throw new IllegalStateException("Instantiating utility class."); diff --git a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleUtils.java b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleUtils.java index 385f0f9e82..560ddcae4a 100644 --- a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleUtils.java +++ b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleUtils.java @@ -23,7 +23,7 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class NetconfConsoleUtils { +public final class NetconfConsoleUtils { private static final Logger LOG = LoggerFactory.getLogger(NetconfConsoleUtils.class); diff --git a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfIidFactory.java b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfIidFactory.java index 8df16c6642..1ea1f715f8 100644 --- a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfIidFactory.java +++ b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfIidFactory.java @@ -18,7 +18,7 @@ import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology. import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -public class NetconfIidFactory { +public final class NetconfIidFactory { private NetconfIidFactory() { throw new IllegalStateException("Instantiating utility class."); @@ -29,7 +29,7 @@ public class NetconfIidFactory { .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))) .build(); - public static final InstanceIdentifier netconfNodeIid(final String nodeId) { + public static InstanceIdentifier netconfNodeIid(final String nodeId) { return NETCONF_TOPOLOGY_IID.child(Node.class, new NodeKey(new NodeId(nodeId))); } } diff --git a/netconf/netconf-console/src/test/java/org/opendaylight/netconf/console/impl/NetconfCommandsImplTest.java b/netconf/netconf-console/src/test/java/org/opendaylight/netconf/console/impl/NetconfCommandsImplTest.java index 9cd1981285..8301b0fe00 100644 --- a/netconf/netconf-console/src/test/java/org/opendaylight/netconf/console/impl/NetconfCommandsImplTest.java +++ b/netconf/netconf-console/src/test/java/org/opendaylight/netconf/console/impl/NetconfCommandsImplTest.java @@ -15,9 +15,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.google.common.collect.ImmutableList; -import java.io.InputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.EnumMap; import java.util.HashMap; import java.util.List; @@ -90,7 +88,9 @@ public class NetconfCommandsImplTest { @Before public void setUp() throws Exception { - schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas()); + schemaContext = YangParserTestUtils.parseYangResources(NetconfCommandsImplTest.class, + "/schemas/network-topology@2013-10-21.yang", "/schemas/ietf-inet-types@2013-07-15.yang", + "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang"); schemaContext.getModules(); final SchemaService schemaService = createSchemaService(); @@ -102,7 +102,7 @@ public class NetconfCommandsImplTest { datastores.put(LogicalDatastoreType.OPERATIONAL, operStore); final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool( - 16, 16, "CommitFutures"); + 16, 16, "CommitFutures", NetconfCommandsImplTest.class); final ConcurrentDOMDataBroker cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor); @@ -127,11 +127,11 @@ public class NetconfCommandsImplTest { public void testListDevice() throws TimeoutException, TransactionCommitFailedException { createTopology(LogicalDatastoreType.OPERATIONAL); - final Map map = netconfCommands.listDevices(); + final Map map = netconfCommands.listDevices(); map.containsKey(NetconfConsoleConstants.NETCONF_ID); assertTrue(map.containsKey(NODE_ID)); - final Map mapNode = (Map) map.get(NODE_ID); + final Map mapNode = (Map) map.get(NODE_ID); assertBaseNodeAttributes(mapNode); } @@ -139,19 +139,19 @@ public class NetconfCommandsImplTest { public void testShowDevice() throws TimeoutException, TransactionCommitFailedException { createTopology(LogicalDatastoreType.OPERATIONAL); - final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT)); + final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT)); mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID); assertTrue(mapCorrect.containsKey(NODE_ID)); - assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID)); + assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID)); - final Map mapWrongPort = netconfCommands.showDevice(IP, "1"); + final Map mapWrongPort = netconfCommands.showDevice(IP, "1"); assertFalse(mapWrongPort.containsKey(NODE_ID)); - final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT)); + final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT)); assertFalse(mapWrongIP.containsKey(NODE_ID)); - final Map mapId = netconfCommands.showDevice(NODE_ID); + final Map mapId = netconfCommands.showDevice(NODE_ID); assertTrue(mapId.containsKey(NODE_ID)); assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID)); } @@ -230,7 +230,7 @@ public class NetconfCommandsImplTest { assertEquals(1, nodes.size()); } - private void createTopology(LogicalDatastoreType dataStoreType) + private void createTopology(final LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException { final List nodes = new ArrayList<>(); final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX); @@ -245,8 +245,8 @@ public class NetconfCommandsImplTest { writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS); } - private Node getNetconfNode(String nodeIdent, String ip, int portNumber, - NetconfNodeConnectionStatus.ConnectionStatus cs, String notificationCapabilityPrefix) { + private static Node getNetconfNode(final String nodeIdent, final String ip, final int portNumber, + final NetconfNodeConnectionStatus.ConnectionStatus cs, final String notificationCapabilityPrefix) { final Host host = HostBuilder.getDefaultInstance(ip); final PortNumber port = new PortNumber(portNumber); @@ -269,8 +269,7 @@ public class NetconfCommandsImplTest { return nb.build(); } - private void assertBaseNodeAttributes(Map mapNode) { - + private static void assertBaseNodeAttributes(final Map mapNode) { assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID)); assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP)); assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT)); @@ -282,7 +281,7 @@ public class NetconfCommandsImplTest { assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS)); } - private void assertBaseNodeAttributesImmutableList(Map mapNode) { + private static void assertBaseNodeAttributesImmutableList(final Map mapNode) { assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID)); assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP)); assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT)); @@ -294,28 +293,15 @@ public class NetconfCommandsImplTest { assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS)); } - private List getYangSchemas() { - final List schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang", - "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang", - "/schemas/netconf-node-topology.yang"); - - final List schemas = new ArrayList<>(); - for (String schemaPath : schemaPaths) { - final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath); - schemas.add(resourceAsStream); - } - return schemas; - } - private SchemaService createSchemaService() { return new SchemaService() { @Override - public void addModule(Module module) { + public void addModule(final Module module) { } @Override - public void removeModule(Module module) { + public void removeModule(final Module module) { } diff --git a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSession.java b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSession.java index d98f07b069..1cf2d41c08 100644 --- a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSession.java +++ b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSession.java @@ -55,7 +55,7 @@ public class DefaultCloseSession extends AbstractSingletonNetconfOperation imple LOG.info("Session {} closing", session.getSessionId()); } catch (final Exception e) { throw new DocumentedException("Unable to properly close session " - + getNetconfSessionIdForReporting(), DocumentedException.ErrorType.APPLICATION, + + getNetconfSessionIdForReporting(), e, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR, Collections.singletonMap( DocumentedException.ErrorSeverity.ERROR.toString(), e.getMessage())); diff --git a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringService.java b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringService.java index f48a477a58..78041d00ba 100644 --- a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringService.java +++ b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringService.java @@ -223,9 +223,9 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos } } - private void notifyCapabilityChanged(final Capabilities capabilities) { + private void notifyCapabilityChanged(final Capabilities newCapabilities) { for (NetconfMonitoringService.CapabilitiesListener listener : listeners) { - listener.onCapabilitiesChanged(capabilities); + listener.onCapabilitiesChanged(newCapabilities); listener.onSchemasChanged(getSchemas()); } } diff --git a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationRouterImpl.java b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationRouterImpl.java index b7db507ca5..bc1618b0d4 100644 --- a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationRouterImpl.java +++ b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationRouterImpl.java @@ -104,9 +104,8 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter { Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), exception.toString())); } - private Document executeOperationWithHighestPriority(final Document message, - final NetconfOperationExecution netconfOperationExecution) - throws DocumentedException { + private static Document executeOperationWithHighestPriority(final Document message, + final NetconfOperationExecution netconfOperationExecution) throws DocumentedException { if (LOG.isDebugEnabled()) { LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution .netconfOperation); @@ -154,7 +153,7 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter { return sortedPriority; } - private static class NetconfOperationExecution implements NetconfOperationChainedExecution { + private static final class NetconfOperationExecution implements NetconfOperationChainedExecution { private final NetconfOperation netconfOperation; private final NetconfOperationChainedExecution subsequentExecution; diff --git a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationServiceFactoryTracker.java b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationServiceFactoryTracker.java index b1a084424c..f1845b1038 100644 --- a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationServiceFactoryTracker.java +++ b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationServiceFactoryTracker.java @@ -18,14 +18,15 @@ class NetconfOperationServiceFactoryTracker extends ServiceTracker { private final NetconfOperationServiceFactoryListener factoriesListener; - NetconfOperationServiceFactoryTracker(BundleContext context, + NetconfOperationServiceFactoryTracker(final BundleContext context, final NetconfOperationServiceFactoryListener factoriesListener) { super(context, NetconfOperationServiceFactory.class, null); this.factoriesListener = factoriesListener; } @Override - public NetconfOperationServiceFactory addingService(ServiceReference reference) { + public NetconfOperationServiceFactory addingService( + final ServiceReference reference) { Object property = reference.getProperty(NetconfConstants.SERVICE_NAME); if (property != null && isMarkedForConfig(property)) { NetconfOperationServiceFactory netconfOperationServiceFactory = super.addingService(reference); @@ -37,14 +38,14 @@ class NetconfOperationServiceFactoryTracker extends } @Override - public void removedService(ServiceReference reference, - NetconfOperationServiceFactory netconfOperationServiceFactory) { + public void removedService(final ServiceReference reference, + final NetconfOperationServiceFactory netconfOperationServiceFactory) { if (netconfOperationServiceFactory != null) { factoriesListener.onRemoveNetconfOperationServiceFactory(netconfOperationServiceFactory); } } - private boolean isMarkedForConfig(Object property) { + private static boolean isMarkedForConfig(final Object property) { return NetconfConstants.CONFIG_SERVICE_MARKERS.contains(property); } diff --git a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/util/DeserializerExceptionHandler.java b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/util/DeserializerExceptionHandler.java index d02fe98480..ad99674856 100644 --- a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/util/DeserializerExceptionHandler.java +++ b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/util/DeserializerExceptionHandler.java @@ -37,7 +37,7 @@ public final class DeserializerExceptionHandler implements ChannelHandler { handleDeserializerException(ctx, cause); } - private void handleDeserializerException(final ChannelHandlerContext ctx, final Throwable cause) { + private static void handleDeserializerException(final ChannelHandlerContext ctx, final Throwable cause) { final Map info = Maps.newHashMap(); info.put("cause", cause.getMessage()); diff --git a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiatorTest.java b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiatorTest.java index 78931f19bc..36a5d25a4c 100644 --- a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiatorTest.java +++ b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiatorTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertNotNull; import io.netty.channel.local.LocalAddress; import java.net.InetSocketAddress; -import org.apache.sshd.common.SshdSocketAddress; +import org.apache.sshd.common.util.net.SshdSocketAddress; import org.junit.Test; public class NetconfServerSessionNegotiatorTest { diff --git a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionTest.java b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionTest.java index 84603bc511..01320b4ec1 100644 --- a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionTest.java +++ b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionTest.java @@ -92,12 +92,12 @@ public class NetconfServerSessionTest { public void testSendNotification() throws Exception { doNothing().when(listener).onNotification(any(), any()); final Document msgDoc = XmlUtil.readXmlToDocument(""); - final NetconfNotification msg = new NetconfNotification(msgDoc); - session.sendMessage(msg); + final NetconfNotification notif = new NetconfNotification(msgDoc); + session.sendMessage(notif); channel.runPendingTasks(); final Object o = channel.readOutbound(); - Assert.assertEquals(msg, o); - verify(listener).onNotification(session, msg); + Assert.assertEquals(notif, o); + verify(listener).onNotification(session, notif); } @Test @@ -134,8 +134,8 @@ public class NetconfServerSessionTest { public void testToManagementSession() throws Exception { final NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader(USER, HOST, PORT, TCP_TRANSPORT, SESSION_ID); - final EmbeddedChannel channel = new EmbeddedChannel(); - final NetconfServerSession tcpSession = new NetconfServerSession(listener, channel, 1L, header); + final EmbeddedChannel ch = new EmbeddedChannel(); + final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header); tcpSession.sessionUp(); final Session managementSession = tcpSession.toManagementSession(); Assert.assertEquals(new String(managementSession.getSourceHost().getValue()), HOST); @@ -148,8 +148,8 @@ public class NetconfServerSessionTest { public void testToManagementSessionUnknownTransport() throws Exception { final NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader(USER, HOST, PORT, "http", SESSION_ID); - final EmbeddedChannel channel = new EmbeddedChannel(); - final NetconfServerSession tcpSession = new NetconfServerSession(listener, channel, 1L, header); + final EmbeddedChannel ch = new EmbeddedChannel(); + final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header); tcpSession.sessionUp(); tcpSession.toManagementSession(); } @@ -158,8 +158,8 @@ public class NetconfServerSessionTest { public void testToManagementSessionIpv6() throws Exception { final NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader(USER, "::1", PORT, SSH_TRANSPORT, SESSION_ID); - final EmbeddedChannel channel = new EmbeddedChannel(); - final NetconfServerSession tcpSession = new NetconfServerSession(listener, channel, 1L, header); + final EmbeddedChannel ch = new EmbeddedChannel(); + final NetconfServerSession tcpSession = new NetconfServerSession(listener, ch, 1L, header); tcpSession.sessionUp(); final Session managementSession = tcpSession.toManagementSession(); Assert.assertEquals(new String(managementSession.getSourceHost().getValue()), "::1"); @@ -201,4 +201,4 @@ public class NetconfServerSessionTest { Assert.assertTrue(NetconfMessageToXMLEncoder.class.equals(encoder.getClass())); } -} \ No newline at end of file +} diff --git a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSessionTest.java b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSessionTest.java index 068ebf6eb4..2566e07022 100644 --- a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSessionTest.java +++ b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSessionTest.java @@ -22,8 +22,6 @@ import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoop; import io.netty.util.concurrent.GenericFutureListener; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.opendaylight.controller.config.util.xml.DocumentedException; import org.opendaylight.controller.config.util.xml.XmlElement; import org.opendaylight.controller.config.util.xml.XmlUtil; @@ -37,17 +35,14 @@ import org.w3c.dom.Document; public class DefaultCloseSessionTest { - private void mockEventLoop(final Channel channel) { + private static void mockEventLoop(final Channel channel) { final EventLoop eventLoop = mock(EventLoop.class); doReturn(eventLoop).when(channel).eventLoop(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - final Object[] args = invocation.getArguments(); - final Runnable runnable = (Runnable) args[0]; - runnable.run(); - return null; - } + doAnswer(invocation -> { + final Object[] args = invocation.getArguments(); + final Runnable runnable = (Runnable) args[0]; + runnable.run(); + return null; }).when(eventLoop).execute(any(Runnable.class)); doReturn(true).when(eventLoop).inEventLoop(); } @@ -67,12 +62,9 @@ public class DefaultCloseSessionTest { doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class)); final ChannelFuture sendFuture = mock(ChannelFuture.class); - doAnswer(new Answer() { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable { - ((GenericFutureListener) invocation.getArguments()[0]).operationComplete(sendFuture); - return null; - } + doAnswer(invocation -> { + ((GenericFutureListener) invocation.getArguments()[0]).operationComplete(sendFuture); + return null; }).when(sendFuture).addListener(any(GenericFutureListener.class)); doReturn(sendFuture).when(channel).writeAndFlush(anyObject()); doReturn(true).when(sendFuture).isSuccess(); diff --git a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringServiceTest.java b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringServiceTest.java index 7acef9165f..c322737993 100644 --- a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringServiceTest.java +++ b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringServiceTest.java @@ -17,13 +17,11 @@ import com.google.common.base.Optional; import java.net.URI; import java.util.ArrayList; import java.util.Collections; -import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; @@ -44,7 +42,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.mon import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionBuilder; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; public class NetconfCapabilityMonitoringServiceTest { @@ -55,8 +53,8 @@ public class NetconfCapabilityMonitoringServiceTest { private static final String TEST_MODULE_REV2 = "1970-01-02"; private static final Uri TEST_MODULE_NAMESPACE = new Uri("testModuleNamespace"); private static final String TEST_MODULE_NAME = "testModule"; - private static Date TEST_MODULE_DATE; - private static Date TEST_MODULE_DATE2; + private static final Revision TEST_MODULE_DATE = Revision.of(TEST_MODULE_REV); + private static final Revision TEST_MODULE_DATE2 = Revision.of(TEST_MODULE_REV2); private YangModuleCapability moduleCapability1; private YangModuleCapability moduleCapability2; @@ -84,26 +82,20 @@ public class NetconfCapabilityMonitoringServiceTest { private NetconfCapabilityMonitoringService monitoringService; - @BeforeClass - public static void suiteSetUp() throws Exception { - TEST_MODULE_DATE = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV); - TEST_MODULE_DATE2 = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV2); - } - @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); doReturn(new URI(TEST_MODULE_NAMESPACE.getValue())).when(moduleMock).getNamespace(); doReturn(TEST_MODULE_NAME).when(moduleMock).getName(); - doReturn(TEST_MODULE_DATE).when(moduleMock).getRevision(); + doReturn(java.util.Optional.of(TEST_MODULE_DATE)).when(moduleMock).getRevision(); moduleCapability1 = new YangModuleCapability(moduleMock, TEST_MODULE_CONTENT); capabilities.add(moduleCapability1); doReturn(new URI(TEST_MODULE_NAMESPACE.getValue())).when(moduleMock2).getNamespace(); doReturn(TEST_MODULE_NAME).when(moduleMock2).getName(); - doReturn(TEST_MODULE_DATE2).when(moduleMock2).getRevision(); + doReturn(java.util.Optional.of(TEST_MODULE_DATE2)).when(moduleMock2).getRevision(); moduleCapability2 = new YangModuleCapability(moduleMock2, TEST_MODULE_CONTENT2); capabilities.add(new BasicCapability("urn:ietf:params:netconf:base:1.0")); @@ -200,7 +192,7 @@ public class NetconfCapabilityMonitoringServiceTest { //remove capability monitoringService.onCapabilitiesChanged(Collections.emptySet(), testCaps); - verify(listener, times(3)).onCapabilitiesChanged((monitoringListenerCaptor.capture())); + verify(listener, times(3)).onCapabilitiesChanged(monitoringListenerCaptor.capture()); verify(notificationPublisher, times(2)).onCapabilityChanged(capabilityChangeCaptor.capture()); //verify listener calls diff --git a/netconf/netconf-mapping-api/src/main/java/org/opendaylight/netconf/mapping/api/HandlingPriority.java b/netconf/netconf-mapping-api/src/main/java/org/opendaylight/netconf/mapping/api/HandlingPriority.java index c308aa8e7b..4d3e025ebe 100644 --- a/netconf/netconf-mapping-api/src/main/java/org/opendaylight/netconf/mapping/api/HandlingPriority.java +++ b/netconf/netconf-mapping-api/src/main/java/org/opendaylight/netconf/mapping/api/HandlingPriority.java @@ -54,24 +54,25 @@ public final class HandlingPriority implements Comparable { } @Override - public int compareTo(HandlingPriority priority) { - if (this == priority) { + @SuppressWarnings("checkstyle:parameterName") + public int compareTo(HandlingPriority o) { + if (this == o) { return 0; } if (isCannotHandle()) { return -1; } - if (priority.isCannotHandle()) { + if (o.isCannotHandle()) { return 1; } - if (this.priority > priority.priority) { + if (priority > o.priority) { return 1; } - if (this.priority.equals(priority.priority)) { + if (priority.equals(o.priority)) { return 0; } - if (this.priority < priority.priority) { + if (priority < o.priority) { return -1; } diff --git a/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/Get.java b/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/Get.java index a3601fe7b6..9e122e36c3 100644 --- a/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/Get.java +++ b/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/Get.java @@ -77,7 +77,7 @@ public class Get extends AbstractNetconfOperation { final String errorMessage = "Get operation for netconf-state subtree failed"; LOG.warn(errorMessage, e); - throw new DocumentedException(errorMessage, DocumentedException.ErrorType.APPLICATION, + throw new DocumentedException(errorMessage, e, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR, Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), e.getMessage())); diff --git a/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/GetSchema.java b/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/GetSchema.java index 84801b1476..c3527a29be 100644 --- a/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/GetSchema.java +++ b/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/GetSchema.java @@ -59,7 +59,7 @@ public class GetSchema extends AbstractSingletonNetconfOperation { final Map errorInfo = Maps.newHashMap(); errorInfo.put(DocumentedException.ErrorTag.OPERATION_FAILED.toString(), e.getMessage()); LOG.warn("Rpc error: {}", DocumentedException.ErrorTag.OPERATION_FAILED, e); - throw new DocumentedException(e.getMessage(), DocumentedException.ErrorType.APPLICATION, + throw new DocumentedException(e.getMessage(), e, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR, errorInfo); } diff --git a/netconf/netconf-netty-util/pom.xml b/netconf/netconf-netty-util/pom.xml index 7774691705..37779348d6 100644 --- a/netconf/netconf-netty-util/pom.xml +++ b/netconf/netconf-netty-util/pom.xml @@ -76,7 +76,7 @@ org.apache.sshd sshd-core - 0.14.0 + 1.6.0 openexi diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java index 1a548f41da..a9adf2a668 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java @@ -117,6 +117,7 @@ public abstract class AbstractNetconfSessionNegotiator

buffer.length) || (length < 0) || ((offset + length) > buffer.length) || ((offset + length) < 0)) { diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java index aed43347d8..72d9fb7fbc 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java @@ -9,7 +9,7 @@ package org.opendaylight.netconf.nettyutil.handler.ssh.authentication; import java.io.IOException; -import org.apache.sshd.ClientSession; +import org.apache.sshd.client.session.ClientSession; /** * Class providing authentication facility to SSH handler. diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandler.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandler.java index 84682226aa..f824084c13 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandler.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandler.java @@ -9,8 +9,8 @@ package org.opendaylight.netconf.nettyutil.handler.ssh.authentication; import java.io.IOException; -import org.apache.sshd.ClientSession; import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.session.ClientSession; /** * Class Providing username/password authentication option to diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/PublicKeyAuth.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/PublicKeyAuth.java index 70367c04ce..7bc7935cf2 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/PublicKeyAuth.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/PublicKeyAuth.java @@ -10,8 +10,8 @@ package org.opendaylight.netconf.nettyutil.handler.ssh.authentication; import com.google.common.base.Strings; import java.io.IOException; import java.security.KeyPair; -import org.apache.sshd.ClientSession; import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.session.ClientSession; import org.opendaylight.aaa.encrypt.PKIUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,7 +23,7 @@ public class PublicKeyAuth extends LoginPasswordHandler { private KeyPair keyPair = null; private static final Logger LOG = LoggerFactory.getLogger(PublicKeyAuth.class); - public PublicKeyAuth(String username, String password, String keyPath, + public PublicKeyAuth(final String username, final String password, final String keyPath, String passPhrase) { super(username, password); try { diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java index 44444683c4..c3ff349662 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java @@ -9,7 +9,6 @@ package org.opendaylight.netconf.nettyutil.handler.ssh.client; import com.google.common.base.Preconditions; -import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; @@ -17,16 +16,11 @@ import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import java.io.IOException; import java.net.SocketAddress; -import java.util.HashMap; -import java.util.Map; -import org.apache.sshd.ClientChannel; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.channel.ClientChannel; import org.apache.sshd.client.future.AuthFuture; import org.apache.sshd.client.future.ConnectFuture; -import org.apache.sshd.client.future.OpenFuture; -import org.apache.sshd.common.future.CloseFuture; -import org.apache.sshd.common.future.SshFutureListener; +import org.apache.sshd.client.session.ClientSession; import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,13 +40,10 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { public static final SshClient DEFAULT_CLIENT; static { - final Map props = new HashMap<>(); - props.put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT)); - props.put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT)); - final SshClient c = SshClient.setUpDefaultClient(); + c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT)); + c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT)); - c.setProperties(props); // TODO make configurable, or somehow reuse netty threadpool c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS); c.start(); @@ -109,18 +100,15 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture); } - private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) { + private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException { LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel()); final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address); - sshConnectionFuture.addListener(new SshFutureListener() { - @Override - public void operationComplete(final ConnectFuture future) { - if (future.isConnected()) { - handleSshSessionCreated(future, ctx); - } else { - handleSshSetupFailure(ctx, future.getException()); - } + sshConnectionFuture.addListener(future -> { + if (future.isConnected()) { + handleSshSessionCreated(future, ctx); + } else { + handleSshSetupFailure(ctx, future.getException()); } }); } @@ -131,17 +119,14 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { session = future.getSession(); final AuthFuture authenticateFuture = authenticationHandler.authenticate(session); - authenticateFuture.addListener(new SshFutureListener() { - @Override - public void operationComplete(final AuthFuture future) { - if (future.isSuccess()) { - handleSshAuthenticated(session, ctx); - } else { - // Exception does not have to be set in the future, add simple exception in such case - final Throwable exception = future.getException() == null - ? new IllegalStateException("Authentication failed") : future.getException(); - handleSshSetupFailure(ctx, exception); - } + authenticateFuture.addListener(future1 -> { + if (future1.isSuccess()) { + handleSshAuthenticated(session, ctx); + } else { + // Exception does not have to be set in the future, add simple exception in such case + final Throwable exception = future1.getException() == null + ? new IllegalStateException("Authentication failed") : future1.getException(); + handleSshSetupFailure(ctx, exception); } }); } catch (final IOException e) { @@ -149,21 +134,18 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { } } - private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) { + private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) { try { LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), - session.getServerVersion()); + newSession.getServerVersion()); - channel = session.createSubsystemChannel(SUBSYSTEM); + channel = newSession.createSubsystemChannel(SUBSYSTEM); channel.setStreaming(ClientChannel.Streaming.Async); - channel.open().addListener(new SshFutureListener() { - @Override - public void operationComplete(final OpenFuture future) { - if (future.isOpened()) { - handleSshChanelOpened(ctx); - } else { - handleSshSetupFailure(ctx, future.getException()); - } + channel.open().addListener(future -> { + if (future.isOpened()) { + handleSshChanelOpened(ctx); + } else { + handleSshSetupFailure(ctx, future.getException()); } }); @@ -182,17 +164,8 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { // TODO we should also read from error stream and at least log from that - sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() { - @Override - public void close() throws Exception { - AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()); - } - }, new AsyncSshHandlerReader.ReadMsgHandler() { - @Override - public void onMessageRead(final ByteBuf msg) { - ctx.fireChannelRead(msg); - } - }, channel.toString(), channel.getAsyncOut()); + sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()), + msg -> ctx.fireChannelRead(msg), channel.toString(), channel.getAsyncOut()); // if readAsyncListener receives immediate close, // it will close this handler and closing this handler sets channel variable to null @@ -226,12 +199,9 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { if (negotiationFuture != null) { - negotiationFutureListener = new GenericFutureListener>() { - @Override - public void operationComplete(final Future future) { - if (future.isSuccess()) { - connectPromise.setSuccess(); - } + negotiationFutureListener = future -> { + if (future.isSuccess()) { + connectPromise.setSuccess(); } }; //complete connection promise with netconf negotiation future @@ -278,14 +248,11 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { } if (session != null && !session.isClosed() && !session.isClosing()) { - session.close(false).addListener(new SshFutureListener() { - @Override - public void operationComplete(final CloseFuture future) { - if (!future.isClosed()) { - session.close(true); - } - session = null; + session.close(false).addListener(future -> { + if (!future.isClosed()) { + session.close(true); } + session = null; }); } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java index c79b71308a..b905f7ad21 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java @@ -13,7 +13,8 @@ import io.netty.buffer.Unpooled; import org.apache.sshd.common.future.SshFutureListener; import org.apache.sshd.common.io.IoInputStream; import org.apache.sshd.common.io.IoReadFuture; -import org.apache.sshd.common.util.Buffer; +import org.apache.sshd.common.util.buffer.Buffer; +import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +42,7 @@ public final class AsyncSshHandlerReader implements SshFutureListener() { - - @Override - public void operationComplete(final IoWriteFuture future) { - // synchronized block due to deadlock that happens on ssh window resize - // writes and pending writes would lock the underlyinch channel session - // window resize write would try to write the message on an already locked channelSession, - // while the pending write was in progress from the write callback - synchronized (asyncInLock) { - if (LOG.isTraceEnabled()) { - LOG.trace( - "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}", - ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg)); - } - - // Notify success or failure - if (future.isWritten()) { - promise.setSuccess(); - } else { - LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(), - byteBufToString(byteBufMsg), future.getException()); - promise.setFailure(future.getException()); - } - - // Not needed anymore, release - byteBufMsg.release(); - - //rescheduling message from queue after successfully sent - if (wasPending) { - byteBufMsg.resetReaderIndex(); - pending.remove(); - } + asyncIn.write(toBuffer(byteBufMsg)).addListener(future -> { + // synchronized block due to deadlock that happens on ssh window resize + // writes and pending writes would lock the underlyinch channel session + // window resize write would try to write the message on an already locked channelSession, + // while the pending write was in progress from the write callback + synchronized (asyncInLock) { + if (LOG.isTraceEnabled()) { + LOG.trace( + "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}", + ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg)); } - // Check pending queue and schedule next - // At this time we are guaranteed that we are not in pending state anymore - // so the next request should succeed - writePendingIfAny(); + // Notify success or failure + if (future.isWritten()) { + promise.setSuccess(); + } else { + LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(), + byteBufToString(byteBufMsg), future.getException()); + promise.setFailure(future.getException()); + } + + // Not needed anymore, release + byteBufMsg.release(); + + //rescheduling message from queue after successfully sent + if (wasPending) { + byteBufMsg.resetReaderIndex(); + pending.remove(); + } } + + // Check pending queue and schedule next + // At this time we are guaranteed that we are not in pending state anymore + // so the next request should succeed + writePendingIfAny(); }); } catch (final WritePendingException e) { @@ -183,7 +178,7 @@ public final class AsyncSshHandlerWriter implements AutoCloseable { msg.resetReaderIndex(); final byte[] temp = new byte[msg.readableBytes()]; msg.readBytes(temp, 0, msg.readableBytes()); - return new Buffer(temp); + return new ByteArrayBuffer(temp); } private static final class PendingWriteRequest { diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionTest.java index 7dda1cdac8..f1dad80c6c 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionTest.java @@ -159,10 +159,10 @@ public class AbstractNetconfSessionTest { @Test public void testSendMessage() throws Exception { final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L); - final NetconfHelloMessage clientHello = NetconfHelloMessage.createClientHello(Collections.emptySet(), + final NetconfHelloMessage hello = NetconfHelloMessage.createClientHello(Collections.emptySet(), Optional.absent()); - testingNetconfSession.sendMessage(clientHello); - verify(channel).writeAndFlush(clientHello); + testingNetconfSession.sendMessage(hello); + verify(channel).writeAndFlush(hello); } -} \ No newline at end of file +} diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandlerTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandlerTest.java index 905c0c03da..d2ce899e0a 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandlerTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPasswordHandlerTest.java @@ -14,8 +14,8 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import org.apache.sshd.ClientSession; import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.session.ClientSession; import org.junit.Test; public class LoginPasswordHandlerTest { diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java index df9ece7dd9..bc57f3c7a1 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java @@ -37,13 +37,13 @@ import io.netty.channel.DefaultChannelPromise; import io.netty.channel.EventLoop; import java.io.IOException; import java.net.SocketAddress; -import org.apache.sshd.ClientChannel; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; +import org.apache.sshd.client.SshClient; import org.apache.sshd.client.channel.ChannelSubsystem; +import org.apache.sshd.client.channel.ClientChannel; import org.apache.sshd.client.future.AuthFuture; import org.apache.sshd.client.future.ConnectFuture; import org.apache.sshd.client.future.OpenFuture; +import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.future.CloseFuture; import org.apache.sshd.common.future.SshFuture; import org.apache.sshd.common.future.SshFutureListener; @@ -51,7 +51,8 @@ import org.apache.sshd.common.io.IoInputStream; import org.apache.sshd.common.io.IoOutputStream; import org.apache.sshd.common.io.IoReadFuture; import org.apache.sshd.common.io.IoWriteFuture; -import org.apache.sshd.common.util.Buffer; +import org.apache.sshd.common.util.buffer.Buffer; +import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -59,8 +60,6 @@ import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; public class AsyncSshHandlerTest { @@ -129,12 +128,9 @@ public class AsyncSshHandlerTest { private static > ListenableFuture> stubAddListener(final T future) { final SettableFuture> listenerSettableFuture = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable { - listenerSettableFuture.set((SshFutureListener) invocation.getArguments()[0]); - return null; - } + doAnswer(invocation -> { + listenerSettableFuture.set((SshFutureListener) invocation.getArguments()[0]); + return null; }).when(future).addListener(any(SshFutureListener.class)); return listenerSettableFuture; @@ -162,7 +158,7 @@ public class AsyncSshHandlerTest { doReturn(Boolean.TRUE).when(eventLoop).inEventLoop(); } - private void stubSshClient() { + private void stubSshClient() throws IOException { doNothing().when(sshClient).start(); final ConnectFuture connectFuture = mock(ConnectFuture.class); Futures.addCallback(stubAddListener(connectFuture), new SuccessFutureListener() { @@ -519,7 +515,7 @@ public class AsyncSshHandlerTest { doReturn(null).when(ioReadFuture).getException(); doReturn(ioReadFuture).when(ioReadFuture).removeListener(Matchers.>any()); doReturn(5).when(ioReadFuture).getRead(); - doReturn(new Buffer(new byte[]{0, 1, 2, 3, 4})).when(ioReadFuture).getBuffer(); + doReturn(new ByteArrayBuffer(new byte[]{0, 1, 2, 3, 4})).when(ioReadFuture).getBuffer(); doReturn(ioReadFuture).when(ioReadFuture).addListener(Matchers.>any()); // Always success for read diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java index 65de77be96..f478029323 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java @@ -15,7 +15,7 @@ import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.concurrent.Executors; -import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.opendaylight.netconf.api.NetconfServerDispatcher; import org.opendaylight.netconf.auth.AuthProvider; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil; @@ -55,8 +55,7 @@ public class NetconfNorthboundSshServer { sshProxyServerConfigurationBuilder.setLocalAddress(localAddress); sshProxyServerConfigurationBuilder.setAuthenticator(authProvider); sshProxyServerConfigurationBuilder.setIdleTimeout(Integer.MAX_VALUE); - sshProxyServerConfigurationBuilder.setKeyPairProvider(new PEMGeneratorHostKeyProvider(DEFAULT_PRIVATE_KEY_PATH, - DEFAULT_ALGORITHM, DEFAULT_KEY_SIZE)); + sshProxyServerConfigurationBuilder.setKeyPairProvider(new SimpleGeneratorHostKeyProvider()); localServer.addListener(future -> { if (future.isDone() && !future.isCancelled()) { @@ -79,7 +78,7 @@ public class NetconfNorthboundSshServer { return new InetSocketAddress(inetAd, Integer.parseInt(portNumber)); } - public void close() { + public void close() throws IOException { sshProxyServer.close(); if (localServer.isDone()) { diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java index d8d4148a9e..3d91f3aeb4 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java @@ -63,11 +63,13 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { } @Override + @SuppressWarnings("checkstyle:hiddenField") public void setIoInputStream(final IoInputStream in) { this.in = in; } @Override + @SuppressWarnings("checkstyle:hiddenField") public void setIoOutputStream(final IoOutputStream out) { this.out = out; } @@ -78,11 +80,13 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { } @Override + @SuppressWarnings("checkstyle:hiddenField") public void setInputStream(final InputStream in) { throw new UnsupportedOperationException("Synchronous IO is unsupported"); } @Override + @SuppressWarnings("checkstyle:hiddenField") public void setOutputStream(final OutputStream out) { throw new UnsupportedOperationException("Synchronous IO is unsupported"); @@ -95,6 +99,7 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { } @Override + @SuppressWarnings("checkstyle:hiddenField") public void setExitCallback(final ExitCallback callback) { this.callback = callback; } diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java index f525674436..406a28aee4 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java @@ -18,13 +18,11 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.apache.sshd.SshServer; -import org.apache.sshd.common.Cipher; import org.apache.sshd.common.FactoryManager; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.RuntimeSshException; -import org.apache.sshd.common.cipher.ARCFOUR128; -import org.apache.sshd.common.cipher.ARCFOUR256; +import org.apache.sshd.common.cipher.BuiltinCiphers; +import org.apache.sshd.common.cipher.Cipher; import org.apache.sshd.common.io.IoAcceptor; import org.apache.sshd.common.io.IoConnector; import org.apache.sshd.common.io.IoHandler; @@ -33,17 +31,15 @@ import org.apache.sshd.common.io.IoServiceFactoryFactory; import org.apache.sshd.common.io.nio2.Nio2Acceptor; import org.apache.sshd.common.io.nio2.Nio2Connector; import org.apache.sshd.common.io.nio2.Nio2ServiceFactoryFactory; -import org.apache.sshd.common.util.CloseableUtils; +import org.apache.sshd.common.util.closeable.AbstractCloseable; import org.apache.sshd.server.ServerFactoryManager; +import org.apache.sshd.server.SshServer; /** * Proxy SSH server that just delegates decrypted content to a delegate server within same VM. * Implemented using Apache Mina SSH lib. */ public class SshProxyServer implements AutoCloseable { - - private static final ARCFOUR128.Factory DEFAULT_ARCFOUR128_FACTORY = new ARCFOUR128.Factory(); - private static final ARCFOUR256.Factory DEFAULT_ARCFOUR256_FACTORY = new ARCFOUR256.Factory(); private final SshServer sshServer; private final ScheduledExecutorService minaTimerExecutor; private final EventLoopGroup clientGroup; @@ -64,8 +60,8 @@ public class SshProxyServer implements AutoCloseable { //remove rc4 ciphers final List> cipherFactories = sshServer.getCipherFactories(); - cipherFactories.removeIf(factory -> factory.getName().contains(DEFAULT_ARCFOUR128_FACTORY.getName()) - || factory.getName().contains(DEFAULT_ARCFOUR256_FACTORY.getName())); + cipherFactories.removeIf(factory -> factory.getName().contains(BuiltinCiphers.arcfour128.getName()) + || factory.getName().contains(BuiltinCiphers.arcfour256.getName())); sshServer.setPasswordAuthenticator( (username, password, session) -> sshProxyServerConfiguration.getAuthenticator().authenticated(username, password)); @@ -76,7 +72,10 @@ public class SshProxyServer implements AutoCloseable { sshServer.setIoServiceFactoryFactory(nioServiceWithPoolFactoryFactory); sshServer.setScheduledExecutorService(minaTimerExecutor); - sshServer.setProperties(getProperties(sshProxyServerConfiguration)); + sshServer.getProperties().put(ServerFactoryManager.IDLE_TIMEOUT, + String.valueOf(sshProxyServerConfiguration.getIdleTimeout())); + sshServer.getProperties().put(ServerFactoryManager.AUTH_TIMEOUT, + String.valueOf(sshProxyServerConfiguration.getIdleTimeout())); final RemoteNetconfCommand.NetconfCommandFactory netconfCommandFactory = new RemoteNetconfCommand.NetconfCommandFactory(clientGroup, @@ -95,11 +94,9 @@ public class SshProxyServer implements AutoCloseable { } @Override - public void close() { + public void close() throws IOException { try { sshServer.stop(true); - } catch (final InterruptedException e) { - throw new RuntimeException("Interrupted while stopping sshServer", e); } finally { sshServer.close(true); } @@ -108,8 +105,7 @@ public class SshProxyServer implements AutoCloseable { /** * Based on Nio2ServiceFactory with one addition: injectable executor. */ - private static final class NioServiceWithPoolFactory - extends CloseableUtils.AbstractCloseable implements IoServiceFactory { + private static final class NioServiceWithPoolFactory extends AbstractCloseable implements IoServiceFactory { private final FactoryManager manager; private final AsynchronousChannelGroup group; diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java index 75692ba575..935241a390 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java @@ -12,8 +12,8 @@ import com.google.common.base.Preconditions; import io.netty.channel.local.LocalAddress; import java.net.InetSocketAddress; import java.util.Optional; -import org.apache.sshd.common.KeyPairProvider; -import org.apache.sshd.server.PublickeyAuthenticator; +import org.apache.sshd.common.keyprovider.KeyPairProvider; +import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.opendaylight.netconf.auth.AuthProvider; public final class SshProxyServerConfiguration { diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java index 6d9a364af9..11706a823d 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java @@ -5,13 +5,12 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ - package org.opendaylight.netconf.ssh; import io.netty.channel.local.LocalAddress; import java.net.InetSocketAddress; -import org.apache.sshd.common.KeyPairProvider; -import org.apache.sshd.server.PublickeyAuthenticator; +import org.apache.sshd.common.keyprovider.KeyPairProvider; +import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.opendaylight.netconf.auth.AuthProvider; public final class SshProxyServerConfigurationBuilder { @@ -20,7 +19,7 @@ public final class SshProxyServerConfigurationBuilder { private AuthProvider authenticator; private KeyPairProvider keyPairProvider; private int idleTimeout; - private PublickeyAuthenticator publicKeyAuthenticator = null; + private PublickeyAuthenticator publickeyAuthenticator = null; public SshProxyServerConfigurationBuilder setBindingAddress(final InetSocketAddress bindingAddress) { this.bindingAddress = bindingAddress; @@ -37,8 +36,9 @@ public final class SshProxyServerConfigurationBuilder { return this; } - public SshProxyServerConfigurationBuilder setPublickeyAuthenticator(final PublickeyAuthenticator authenticator) { - this.publicKeyAuthenticator = authenticator; + public SshProxyServerConfigurationBuilder setPublickeyAuthenticator( + final PublickeyAuthenticator publickeyAuthenticator) { + this.publickeyAuthenticator = publickeyAuthenticator; return this; } @@ -53,11 +53,11 @@ public final class SshProxyServerConfigurationBuilder { } public SshProxyServerConfiguration createSshProxyServerConfiguration() { - return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, publicKeyAuthenticator, + return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, publickeyAuthenticator, keyPairProvider, idleTimeout); } public static SshProxyServerConfigurationBuilder create() { return new SshProxyServerConfigurationBuilder(); } -} \ No newline at end of file +} diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java index e498b56e73..0a15fdb608 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java @@ -9,13 +9,15 @@ package org.opendaylight.netconf.ssh.osgi; import io.netty.channel.local.LocalAddress; import io.netty.channel.nio.NioEventLoopGroup; +import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import org.apache.sshd.common.util.ThreadUtils; -import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.common.util.security.SecurityUtils; +import org.apache.sshd.common.util.threads.ThreadUtils; +import org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider; import org.opendaylight.netconf.ssh.SshProxyServer; import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder; import org.opendaylight.netconf.util.osgi.NetconfConfigUtil; @@ -88,12 +90,16 @@ public class NetconfSSHActivator implements BundleActivator { LOG.trace("Starting netconf SSH server with path to ssh private key {}", path); final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerExecutor, clientGroup, nioExecutor); + final AbstractGeneratorHostKeyProvider keyPairProvider = SecurityUtils.createGeneratorHostKeyProvider(null); + keyPairProvider.setAlgorithm(ALGORITHM); + keyPairProvider.setKeySize(KEY_SIZE); + keyPairProvider.setFile(new File(path)); sshProxyServer.bind( new SshProxyServerConfigurationBuilder() .setBindingAddress(sshSocketAddress) .setLocalAddress(localAddress) .setAuthenticator(authProviderTracker) - .setKeyPairProvider(new PEMGeneratorHostKeyProvider(path, ALGORITHM, KEY_SIZE)) + .setKeyPairProvider(keyPairProvider) .setIdleTimeout(DEFAULT_IDLE_TIMEOUT) .createSshProxyServerConfiguration()); return sshProxyServer; diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java index 2a94d38161..8f990380a3 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java @@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory; public class EchoClientHandler extends ChannelInboundHandlerAdapter implements ChannelFutureListener { private static final Logger LOG = LoggerFactory.getLogger(EchoClientHandler.class); - private ChannelHandlerContext ctx; + private ChannelHandlerContext context; private final StringBuilder fromServer = new StringBuilder(); public enum State { @@ -40,9 +40,9 @@ public class EchoClientHandler extends ChannelInboundHandlerAdapter implements C @Override public synchronized void channelActive(ChannelHandlerContext ctx) { - checkState(this.ctx == null); + checkState(context == null); LOG.info("channelActive"); - this.ctx = ctx; + context = ctx; state = State.CONNECTED; } @@ -64,14 +64,14 @@ public class EchoClientHandler extends ChannelInboundHandlerAdapter implements C public synchronized void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. LOG.warn("Unexpected exception from downstream.", cause); - checkState(this.ctx.equals(ctx)); + checkState(context.equals(ctx)); ctx.close(); - this.ctx = null; + context = null; } public synchronized void write(String message) { ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes()); - ctx.writeAndFlush(byteBuf); + context.writeAndFlush(byteBuf); } public synchronized boolean isConnected() { diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java index a2da0dafb7..38907bcf50 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java @@ -26,7 +26,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.common.util.security.SecurityUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -75,8 +75,7 @@ public class SSHTest { sshProxyServer.bind(new SshProxyServerConfigurationBuilder() .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS) .setAuthenticator((username, password) -> true) - .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString(), - "RSA", 4096)) + .setKeyPairProvider(SecurityUtils.createGeneratorHostKeyProvider(sshKeyPair.toPath())) .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); final EchoClientHandler echoClientHandler = connectClient(addr); diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java index 1d31f6b77a..e660628a67 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java @@ -21,11 +21,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.apache.sshd.ClientSession; -import org.apache.sshd.SshClient; +import org.apache.sshd.client.SshClient; import org.apache.sshd.client.future.AuthFuture; import org.apache.sshd.client.future.ConnectFuture; -import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.util.security.SecurityUtils; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @@ -74,8 +74,7 @@ public class SSHServerTest { server.bind(new SshProxyServerConfigurationBuilder() .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS) .setAuthenticator((username, password) -> true) - .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString(), - "RSA", 4096)) + .setKeyPairProvider(SecurityUtils.createGeneratorHostKeyProvider(sshKeyPair.toPath())) .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); LOG.info("SSH server started on {}", PORT); } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/MasterSalFacade.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/MasterSalFacade.java index 2e683734da..1ebbad0700 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/MasterSalFacade.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/MasterSalFacade.java @@ -14,7 +14,6 @@ import akka.cluster.Cluster; import akka.dispatch.OnComplete; import akka.pattern.Patterns; import akka.util.Timeout; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.List; import java.util.stream.Collectors; @@ -31,10 +30,10 @@ import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceNotificatio import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalProvider; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; +import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.Future; @@ -49,7 +48,7 @@ class MasterSalFacade implements AutoCloseable, RemoteDeviceHandler sendInitialDataToActor() { final List sourceIdentifiers = - remoteSchemaContext.getAllModuleIdentifiers().stream().map(mi -> - RevisionSourceIdentifier.create(mi.getName(), - (SimpleDateFormatUtil.DEFAULT_DATE_REV == mi.getRevision() ? Optional.absent() : - Optional.of(mi.getQNameModule().getFormattedRevision())))) - .collect(Collectors.toList()); + SchemaContextUtil.getConstituentModuleIdentifiers(currentSchemaContext).stream() + .map(mi -> RevisionSourceIdentifier.create(mi.getName(), mi.getRevision())) + .collect(Collectors.toList()); // send initial data to master actor and create actor for providing it return Patterns.ask(masterActorRef, new CreateInitialMasterActorData(deviceDataBroker, sourceIdentifiers, diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java index 48f063e920..82e340d917 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java @@ -108,7 +108,7 @@ public class NetconfTopologyManager // Blueprint init method public void init() { - dataChangeListenerRegistration = registerDataTreeChangeListener(topologyId); + dataChangeListenerRegistration = registerDataTreeChangeListener(); } @Override @@ -242,10 +242,10 @@ public class NetconfTopologyManager this.privateKeyPassphrase = privateKeyPassphrase; } - private ListenerRegistration registerDataTreeChangeListener(final String topologyId) { + private ListenerRegistration registerDataTreeChangeListener() { final WriteTransaction wtx = dataBroker.newWriteOnlyTransaction(); - initTopology(wtx, LogicalDatastoreType.CONFIGURATION, topologyId); - initTopology(wtx, LogicalDatastoreType.OPERATIONAL, topologyId); + initTopology(wtx, LogicalDatastoreType.CONFIGURATION); + initTopology(wtx, LogicalDatastoreType.OPERATIONAL); Futures.addCallback(wtx.submit(), new FutureCallback() { @Override public void onSuccess(final Void result) { @@ -264,8 +264,7 @@ public class NetconfTopologyManager NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this); } - private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType, - final String topologyId) { + private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType) { final NetworkTopology networkTopology = new NetworkTopologyBuilder().build(); final InstanceIdentifier networkTopologyId = InstanceIdentifier.builder(NetworkTopology.class).build(); diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java index 2e46cd4a1b..89547421c7 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java @@ -15,12 +15,14 @@ import akka.util.Timeout; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider; import org.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProvider; import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy; @@ -60,8 +62,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; @@ -72,7 +72,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.duration.Duration; -public class NetconfNodeActor extends UntypedActor { +public final class NetconfNodeActor extends UntypedActor { private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeActor.class); @@ -168,7 +168,7 @@ public class NetconfNodeActor extends UntypedActor { } } else if (message instanceof InvokeRpcMessage) { // master - final InvokeRpcMessage invokeRpcMessage = ((InvokeRpcMessage) message); + final InvokeRpcMessage invokeRpcMessage = (InvokeRpcMessage) message; invokeSlaveRpc(invokeRpcMessage.getSchemaPath(), invokeRpcMessage.getNormalizedNodeMessage(), sender()); } else if (message instanceof RegisterMountPoint) { //slaves @@ -198,7 +198,7 @@ public class NetconfNodeActor extends UntypedActor { } private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) { - final CheckedFuture yangTextSchemaSource = + final ListenableFuture<@NonNull YangTextSchemaSource> yangTextSchemaSource = schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class); Futures.addCallback(yangTextSchemaSource, new FutureCallback() { @@ -254,15 +254,14 @@ public class NetconfNodeActor extends UntypedActor { slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime, mountPointService); - final CheckedFuture remoteSchemaContext = - getSchemaContext(masterReference); - final DOMRpcService deviceRpc = getDOMRpcService(masterReference); + final ListenableFuture remoteSchemaContext = getSchemaContext(masterReference); + final DOMRpcService deviceRpcService = getDOMRpcService(masterReference); Futures.addCallback(remoteSchemaContext, new FutureCallback() { @Override public void onSuccess(final SchemaContext result) { LOG.info("{}: Schema context resolved: {}", id, result.getModules()); - slaveSalManager.registerSlaveMountPoint(result, deviceRpc, masterReference); + slaveSalManager.registerSlaveMountPoint(result, deviceRpcService, masterReference); } @Override @@ -276,7 +275,7 @@ public class NetconfNodeActor extends UntypedActor { return new ProxyDOMRpcService(setup.getActorSystem(), masterReference, id, actorResponseWaitTime); } - private CheckedFuture getSchemaContext(final ActorRef masterReference) { + private ListenableFuture getSchemaContext(final ActorRef masterReference) { final RemoteYangTextSourceProvider remoteYangTextSourceProvider = new ProxyYangTextSourceProvider(masterReference, getContext(), actorResponseWaitTime); diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActor.java index 777140cd4f..efa4713608 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActor.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActor.java @@ -16,7 +16,7 @@ import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadAct /** * ReadTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes. */ -public class ReadTransactionActor extends UntypedActor { +public final class ReadTransactionActor extends UntypedActor { private final ReadAdapter readAdapter; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java index 1c263c0191..229cdf528c 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java @@ -18,7 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.duration.Duration; -public class ReadWriteTransactionActor extends UntypedActor { +public final class ReadWriteTransactionActor extends UntypedActor { private static final Logger LOG = LoggerFactory.getLogger(ReadWriteTransactionActor.class); diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActor.java index 8a1f53af52..a1305dbab2 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActor.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActor.java @@ -21,7 +21,7 @@ import scala.concurrent.duration.Duration; /** * WriteTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes. */ -public class WriteTransactionActor extends UntypedActor { +public final class WriteTransactionActor extends UntypedActor { private static final Logger LOG = LoggerFactory.getLogger(WriteTransactionActor.class); diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologySetup.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologySetup.java index 6eb78007af..65daa1544e 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologySetup.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologySetup.java @@ -41,7 +41,7 @@ public class NetconfTopologySetup { private final String privateKeyPassphrase; private final AAAEncryptionService encryptionService; - private NetconfTopologySetup(final NetconfTopologySetupBuilder builder) { + NetconfTopologySetup(final NetconfTopologySetupBuilder builder) { this.clusterSingletonServiceProvider = builder.getClusterSingletonServiceProvider(); this.rpcProviderRegistry = builder.getRpcProviderRegistry(); this.dataBroker = builder.getDataBroker(); diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologyUtils.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologyUtils.java index 1324e8ad44..dae2c40d80 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologyUtils.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologyUtils.java @@ -37,11 +37,11 @@ import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache; import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository; -import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class NetconfTopologyUtils { +public final class NetconfTopologyUtils { private static Logger LOG = LoggerFactory.getLogger(NetconfTopologyUtils.class); private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector"; @@ -102,6 +102,10 @@ public class NetconfTopologyUtils { TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY)); } + private NetconfTopologyUtils() { + + } + public static NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final Node node) { final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class); final String moduleSchemaCacheDirectory = netconfNode.getSchemaCacheDirectory(); diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeActorTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeActorTest.java index 4e50b34943..485f3c506b 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeActorTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeActorTest.java @@ -29,12 +29,12 @@ import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import akka.util.Timeout; import com.google.common.base.MoreObjects; -import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.net.InetAddresses; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -81,6 +81,7 @@ import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; +import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource; @@ -166,7 +167,7 @@ public class NetconfNodeActorTest { final DOMDataBroker domDataBroker = mock(DOMDataBroker.class); final List sourceIdentifiers = - Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent())); + Lists.newArrayList(RevisionSourceIdentifier.create("testID")); // init master data @@ -198,12 +199,12 @@ public class NetconfNodeActorTest { final RevisionSourceIdentifier yang2 = RevisionSourceIdentifier.create("yang2"); final SchemaSourceRegistry registry = mock(SchemaSourceRegistry.class); final SchemaRepository schemaRepository = mock(SchemaRepository.class); - final SchemaSourceRegistration regYang1 = mock(SchemaSourceRegistration.class); - final SchemaSourceRegistration regYang2 = mock(SchemaSourceRegistration.class); + final SchemaSourceRegistration regYang1 = mock(SchemaSourceRegistration.class); + final SchemaSourceRegistration regYang2 = mock(SchemaSourceRegistration.class); doReturn(regYang1).when(registry).registerSchemaSource(any(), withSourceId(yang1)); doReturn(regYang2).when(registry).registerSchemaSource(any(), withSourceId(yang2)); final SchemaContextFactory schemaContextFactory = mock(SchemaContextFactory.class); - doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any()); + doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any(SchemaSourceFilter.class)); final SettableFuture schemaContextFuture = SettableFuture.create(); final CheckedFuture checkedFuture = Futures.makeChecked(schemaContextFuture, e -> new SchemaResolutionException("fail", e)); @@ -227,7 +228,7 @@ public class NetconfNodeActorTest { @Test public void testYangTextSchemaSourceRequestMessage() throws Exception { final SchemaRepository schemaRepository = mock(SchemaRepository.class); - final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID", Optional.absent()); + final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID"); final Props props = NetconfNodeActor.props(mock(NetconfTopologySetup.class), remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT, mountPointService); @@ -253,8 +254,7 @@ public class NetconfNodeActorTest { }; - final CheckedFuture result = - Futures.immediateCheckedFuture(yangTextSchemaSource); + final ListenableFuture result = Futures.immediateFuture(yangTextSchemaSource); doReturn(result).when(schemaRepository).getSchemaSource(sourceIdentifier, YangTextSchemaSource.class); @@ -290,7 +290,7 @@ public class NetconfNodeActorTest { final DOMDataBroker domDataBroker = mock(DOMDataBroker.class); final List sourceIdentifiers = - Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent())); + Lists.newArrayList(RevisionSourceIdentifier.create("testID")); // init master data @@ -307,10 +307,11 @@ public class NetconfNodeActorTest { final ProxyDOMRpcService slaveDomRPCService = new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT); - final SchemaPath schemaPath = SchemaPath.create(true, QName.create("TestQname")); + final QName testQName = QName.create("", "TestQname"); + final SchemaPath schemaPath = SchemaPath.create(true, testQName); final NormalizedNode outputNode = ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname"))) - .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build(); + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(testQName)) + .withChild(ImmutableNodes.leafNode(testQName, "foo")).build(); final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, null, "Rpc invocation failed."); // EmptyResultResponse message diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImplTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImplTest.java index 5855dd44b9..d4432d185d 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImplTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImplTest.java @@ -219,8 +219,6 @@ public class RemoteDeviceConnectorImplTest { .setKeepaliveDelay(1L) .build(); - final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(TOPOLOGY_ID, - new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999)); final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build(); builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node)); diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActorTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActorTest.java index 30d279aef4..d41e6955f8 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActorTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActorTest.java @@ -61,7 +61,7 @@ public class ReadTransactionActorTest { @Test public void testRead() throws Exception { final ContainerNode node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont"))) .build(); when(deviceReadTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node))); actorRef.tell(new ReadRequest(STORE, PATH), probe.ref()); diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java index e9eee1851a..2ccf874449 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java @@ -47,7 +47,6 @@ import org.opendaylight.yangtools.yang.common.RpcError; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import scala.concurrent.Await; import scala.concurrent.Future; @@ -64,7 +63,7 @@ public class ReadWriteTransactionActorTest { private TestProbe probe; private ActorSystem system; private TestActorRef actorRef; - private NormalizedNode node; + private ContainerNode node; @Before public void setUp() throws Exception { @@ -72,7 +71,7 @@ public class ReadWriteTransactionActorTest { system = ActorSystem.apply(); probe = TestProbe.apply(system); node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont"))) .build(); actorRef = TestActorRef.create(system, ReadWriteTransactionActor.props(deviceReadWriteTx, Duration.apply(2, TimeUnit.SECONDS)), "testA"); @@ -85,9 +84,6 @@ public class ReadWriteTransactionActorTest { @Test public void testRead() throws Exception { - final ContainerNode node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) - .build(); when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node))); actorRef.tell(new ReadRequest(STORE, PATH), probe.ref()); verify(deviceReadWriteTx).read(STORE, PATH); @@ -182,9 +178,9 @@ public class ReadWriteTransactionActorTest { @Test public void testIdleTimeout() throws Exception { - final TestProbe probe = new TestProbe(system); - probe.watch(actorRef); + final TestProbe testProbe = new TestProbe(system); + testProbe.watch(actorRef); verify(deviceReadWriteTx, timeout(3000)).cancel(); - probe.expectTerminated(actorRef, TIMEOUT.duration()); + testProbe.expectTerminated(actorRef, TIMEOUT.duration()); } -} \ No newline at end of file +} diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActorTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActorTest.java index cd2b982914..e21ec46e9c 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActorTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActorTest.java @@ -65,7 +65,7 @@ public class WriteTransactionActorTest { system = ActorSystem.apply(); probe = TestProbe.apply(system); node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont"))) .build(); actorRef = TestActorRef.create(system, WriteTransactionActor.props(deviceWriteTx, Duration.apply(2, TimeUnit.SECONDS)), "testA"); @@ -130,10 +130,10 @@ public class WriteTransactionActorTest { @Test public void testIdleTimeout() throws Exception { - final TestProbe probe = new TestProbe(system); - probe.watch(actorRef); + final TestProbe testProbe = new TestProbe(system); + testProbe.watch(actorRef); verify(deviceWriteTx, timeout(3000)).cancel(); - probe.expectTerminated(actorRef, TIMEOUT.duration()); + testProbe.expectTerminated(actorRef, TIMEOUT.duration()); } -} \ No newline at end of file +} diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadTransactionTest.java index df4be27b77..b9a1bad196 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadTransactionTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadTransactionTest.java @@ -49,7 +49,7 @@ public class ProxyReadTransactionTest { masterActor = new TestProbe(system); final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830)); node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont"))) .build(); tx = new ProxyReadTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS)); } diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java index a24f2b124a..30a6867f1a 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java @@ -61,7 +61,7 @@ public class ProxyReadWriteTransactionTest { masterActor = new TestProbe(system); final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830)); node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont"))) .build(); tx = new ProxyReadWriteTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS)); } diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteTransactionTest.java index 05ad6be8dd..b51375b145 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteTransactionTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteTransactionTest.java @@ -53,7 +53,7 @@ public class ProxyWriteTransactionTest { masterActor = new TestProbe(system); final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830)); node = Builders.containerBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont"))) + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont"))) .build(); tx = new ProxyWriteTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS)); } @@ -73,10 +73,10 @@ public class ProxyWriteTransactionTest { @Test public void testCancelSubmitted() throws Exception { - final CheckedFuture submitFuture = tx.submit(); + final ListenableFuture submitFuture = tx.submit(); masterActor.expectMsgClass(SubmitRequest.class); masterActor.reply(new SubmitReply()); - submitFuture.checkedGet(); + submitFuture.get(); final Future submit = Executors.newSingleThreadExecutor().submit(() -> tx.cancel()); masterActor.expectNoMsg(); Assert.assertFalse(submit.get()); @@ -84,18 +84,18 @@ public class ProxyWriteTransactionTest { @Test public void testSubmit() throws Exception { - final CheckedFuture submitFuture = tx.submit(); + final ListenableFuture submitFuture = tx.submit(); masterActor.expectMsgClass(SubmitRequest.class); masterActor.reply(new SubmitReply()); - submitFuture.checkedGet(); + submitFuture.get(); } @Test public void testDoubleSubmit() throws Exception { - final CheckedFuture submitFuture = tx.submit(); + final ListenableFuture submitFuture = tx.submit(); masterActor.expectMsgClass(SubmitRequest.class); masterActor.reply(new SubmitReply()); - submitFuture.checkedGet(); + submitFuture.get(); try { tx.submit().checkedGet(); Assert.fail("Should throw IllegalStateException"); diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadOnlyTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadOnlyTransactionTest.java index 366a75b267..825a812f03 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadOnlyTransactionTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadOnlyTransactionTest.java @@ -119,8 +119,8 @@ public class ReadOnlyTransactionTest { public void testRead() throws Exception { // Message: NormalizedNodeMessage final NormalizedNode outputNode = ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname"))) - .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build(); + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname"))) + .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build(); final CheckedFuture>, ReadFailedException> resultNormalizedNodeMessage = Futures.immediateCheckedFuture(Optional.of(outputNode)); doReturn(resultNormalizedNodeMessage).when(readTx).read(storeType, instanceIdentifier); @@ -147,7 +147,7 @@ public class ReadOnlyTransactionTest { instanceIdentifier); final Optional> resultEmptyMessage = - resultEmptyResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS); + resultEmptyResponse.get(TIMEOUT_SEC, TimeUnit.SECONDS); assertEquals(resultEmptyMessage, Optional.absent()); } diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java index ccf2d59660..441a4caaa3 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java @@ -115,8 +115,8 @@ public class ReadWriteTransactionTest { new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS)); initializeDataTest(); testNode = ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname"))) - .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build(); + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname"))) + .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build(); instanceIdentifier = YangInstanceIdentifier.EMPTY; storeType = LogicalDatastoreType.CONFIGURATION; } @@ -151,15 +151,12 @@ public class ReadWriteTransactionTest { @Test public void testDelete() throws Exception { - final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY; - final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION; - // Test of invoking delete on master through slave proxy final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction(); - wTx.delete(storeType, instanceIdentifier); + wTx.delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY); wTx.cancel(); - verify(readWriteTx, timeout(2000)).delete(storeType, instanceIdentifier); + verify(readWriteTx, timeout(2000)).delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY); } @Test @@ -240,8 +237,8 @@ public class ReadWriteTransactionTest { public void testRead() throws Exception { // Message: NormalizedNodeMessage final NormalizedNode outputNode = ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname"))) - .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build(); + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname"))) + .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build(); final CheckedFuture>, ReadFailedException> resultNormalizedNodeMessage = Futures.immediateCheckedFuture(Optional.of(outputNode)); doReturn(resultNormalizedNodeMessage).when(readWriteTx).read(storeType, instanceIdentifier); diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/WriteOnlyTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/WriteOnlyTransactionTest.java index 6267e73dbc..a13c953625 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/WriteOnlyTransactionTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/WriteOnlyTransactionTest.java @@ -116,8 +116,8 @@ public class WriteOnlyTransactionTest { new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS)); initializeDataTest(); testNode = ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname"))) - .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build(); + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "TestQname"))) + .withChild(ImmutableNodes.leafNode(QName.create("", "NodeQname"), "foo")).build(); instanceIdentifier = YangInstanceIdentifier.EMPTY; storeType = LogicalDatastoreType.CONFIGURATION; } @@ -152,15 +152,12 @@ public class WriteOnlyTransactionTest { @Test public void testDelete() throws Exception { - final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY; - final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION; - // Test of invoking delete on master through slave proxy final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction(); - wTx.delete(storeType, instanceIdentifier); + wTx.delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY); wTx.cancel(); - verify(writeTx, timeout(2000)).delete(storeType, instanceIdentifier); + verify(writeTx, timeout(2000)).delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY); } @Test diff --git a/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java b/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java index ebd5795821..df3eff0976 100644 --- a/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java +++ b/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java @@ -82,7 +82,7 @@ import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache; import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository; -import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -389,14 +389,14 @@ public abstract class AbstractNetconfTopology implements NetconfTopology { */ private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) { final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory); - final SchemaContextFactory schemaContextFactory + final SchemaContextFactory contextFactory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT); setSchemaRegistry(repository); - setSchemaContextFactory(schemaContextFactory); + setSchemaContextFactory(contextFactory); final FilesystemSchemaSourceCache deviceCache = createDeviceFilesystemCache(moduleSchemaCacheDirectory); repository.registerSchemaSourceListener(deviceCache); - return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory, + return new NetconfDevice.SchemaResourcesDTO(repository, repository, contextFactory, new NetconfStateSchemasResolverImpl()); } @@ -416,14 +416,14 @@ public abstract class AbstractNetconfTopology implements NetconfTopology { /** * Sets the private key path from location specified in configuration file using blueprint. */ - public void setPrivateKeyPath(String privateKeyPath) { + public void setPrivateKeyPath(final String privateKeyPath) { this.privateKeyPath = privateKeyPath; } /** * Sets the private key passphrase from location specified in configuration file using blueprint. */ - public void setPrivateKeyPassphrase(String privateKeyPassphrase) { + public void setPrivateKeyPassphrase(final String privateKeyPassphrase) { this.privateKeyPassphrase = privateKeyPassphrase; } diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java index 1067da9d91..f9dab60182 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java @@ -5,10 +5,12 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ - package org.opendaylight.netconf.util; -public class CloseableUtil { +public final class CloseableUtil { + private CloseableUtil() { + + } @SuppressWarnings("checkstyle:IllegalCatch") public static void closeAll(Iterable autoCloseables) throws Exception { diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java index 4f6d852e69..373d7095b5 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java @@ -25,9 +25,13 @@ import org.w3c.dom.Node; /** * See rfc6241 for details. */ -public class SubtreeFilter { +public final class SubtreeFilter { private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class); + private SubtreeFilter() { + + } + public static Document applyRpcSubtreeFilter(Document requestDocument, Document rpcReply) throws DocumentedException { OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument); diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlFileLoader.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlFileLoader.java index ed51ae000e..d62d40df5e 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlFileLoader.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlFileLoader.java @@ -20,7 +20,11 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; -public class XmlFileLoader { +public final class XmlFileLoader { + + private XmlFileLoader() { + + } public static NetconfMessage xmlFileToNetconfMessage(final String fileName) throws IOException, SAXException, ParserConfigurationException { diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java index 9ce2be2013..6677a42c8f 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java @@ -22,7 +22,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; -public class XmlUnitUtil { +public final class XmlUnitUtil { private XmlUnitUtil() {} diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java index a3e258248d..68fb36018b 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java @@ -13,7 +13,6 @@ import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTr import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId; import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; @@ -30,6 +29,7 @@ import java.net.URLConnection; import java.util.AbstractMap; import java.util.Collections; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; @@ -45,6 +45,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.librar import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; @@ -71,7 +72,7 @@ import org.w3c.dom.Node; * Holds URLs with YANG schema resources for all yang modules reported in * ietf-netconf-yang-library/modules-state/modules node. */ -public class LibraryModulesSchemas implements NetconfDeviceSchemas { +public final class LibraryModulesSchemas implements NetconfDeviceSchemas { private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class); private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})"); @@ -106,7 +107,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { final Map result = Maps.newHashMap(); for (final Map.Entry entry : availableModels.entrySet()) { final SourceIdentifier sId = RevisionSourceIdentifier - .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision())); + .create(entry.getKey().getLocalName(), entry.getKey().getRevision()); result.put(sId, entry.getValue()); } @@ -170,11 +171,11 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { if (modulesStateNode.isPresent()) { Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode, "Expecting container containing schemas, but was %s", modulesStateNode.get()); - return create(((ContainerNode) modulesStateNode.get())); - } else { - LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME)); - return new LibraryModulesSchemas(Collections.emptyMap()); + return create((ContainerNode) modulesStateNode.get()); } + + LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME)); + return new LibraryModulesSchemas(Collections.emptyMap()); } private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) { @@ -224,12 +225,12 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { private static Optional> findModulesStateNode(final NormalizedNode result) { if (result == null) { - return Optional.absent(); + return Optional.empty(); } final Optional> dataNode = ((DataContainerNode) result).getChild(toId(NETCONF_DATA_QNAME)); if (dataNode.isPresent() == false) { - return Optional.absent(); + return Optional.empty(); } return ((DataContainerNode) dataNode.get()).getChild(toId(ModulesState.QNAME)); @@ -305,8 +306,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { jsonParser.parse(reader); - return resultHolder.isFinished() - ? Optional.of(resultHolder.getResult()) : Optional.>absent(); + return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty(); } @SuppressWarnings("checkstyle:IllegalCatch") @@ -342,7 +342,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { LOG.warn("Unable to parse yang library xml content", e); } - return Optional.>absent(); + return Optional.empty(); } private static Optional> createFromEntry(final MapEntryNode moduleNode) { @@ -356,9 +356,9 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision")); final Optional revision = getSingleChildNodeValue(moduleNode, childNodeId); if (revision.isPresent()) { - if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) { + if (!Revision.STRING_FORMAT_PATTERN.matcher(revision.get()).matches()) { LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get()); - return Optional.>absent(); + return Optional.empty(); } } @@ -372,7 +372,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { final QName moduleQName = revision.isPresent() ? QName.create(moduleNameSpace, revision.get(), moduleName) - : QName.create(URI.create(moduleNameSpace), null, moduleName); + : QName.create(URI.create(moduleNameSpace), moduleName); try { return Optional.>of(new AbstractMap.SimpleImmutableEntry<>( @@ -380,7 +380,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { } catch (final MalformedURLException e) { LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid", moduleNode, schemaUriAsString.get()); - return Optional.>absent(); + return Optional.empty(); } } @@ -395,8 +395,8 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { private static Optional getValueOfSimpleNode( final NormalizedNode node) { final Object value = node.getValue(); - return value == null || Strings.isNullOrEmpty(value.toString()) - ? Optional.absent() : Optional.of(value.toString().trim()); + return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.empty() + : Optional.of(value.toString().trim()); } @Override diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java index 22fa4cb92e..2dc1633172 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java @@ -26,6 +26,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; import javax.annotation.concurrent.GuardedBy; @@ -60,7 +61,6 @@ import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; @@ -68,7 +68,7 @@ import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; -import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -431,8 +431,7 @@ public class NetconfDevice } private static SourceIdentifier toSourceId(final QName input) { - return RevisionSourceIdentifier.create(input.getLocalName(), - Optional.fromNullable(input.getFormattedRevision())); + return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision()); } } @@ -467,15 +466,13 @@ public class NetconfDevice } private Collection filterMissingSources(final Collection requiredSources) { - return requiredSources.parallelStream().filter(sourceIdentifier -> { - boolean remove = false; try { - schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet(); - } catch (SchemaSourceException e) { - remove = true; + schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).get(); + return false; + } catch (InterruptedException | ExecutionException e) { + return true; } - return remove; }).collect(Collectors.toList()); } @@ -487,9 +484,9 @@ public class NetconfDevice while (!requiredSources.isEmpty()) { LOG.trace("{}: Trying to build schema context from {}", id, requiredSources); try { - final CheckedFuture schemaBuilderFuture = - schemaContextFactory.createSchemaContext(requiredSources); - final SchemaContext result = schemaBuilderFuture.checkedGet(); + final ListenableFuture schemaBuilderFuture = schemaContextFactory + .createSchemaContext(requiredSources); + final SchemaContext result = schemaBuilderFuture.get(); LOG.debug("{}: Schema context built successfully from {}", id, requiredSources); final Collection filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet()); @@ -506,16 +503,24 @@ public class NetconfDevice handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result)); return; - } catch (final SchemaResolutionException e) { + } catch (final ExecutionException e) { // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException // that might be wrapping a MissingSchemaSourceException so we need to look // at the cause of the exception to make sure we don't misinterpret it. - if (e.getCause() instanceof MissingSchemaSourceException) { + final Throwable cause = e.getCause(); + + if (cause instanceof MissingSchemaSourceException) { requiredSources = handleMissingSchemaSourceException( requiredSources, (MissingSchemaSourceException) e.getCause()); continue; } - requiredSources = handleSchemaResolutionException(requiredSources, e); + if (cause instanceof SchemaResolutionException) { + requiredSources = handleSchemaResolutionException(requiredSources, + (SchemaResolutionException) cause); + } else { + handleSalInitializationFailure(e, listener); + return; + } } catch (final Exception e) { // unknown error, fail handleSalInitializationFailure(e, listener); @@ -602,12 +607,7 @@ public class NetconfDevice continue; } - final String rev = getNullableRev(identifier); - if (rev == null) { - if (qname.getRevision() == null) { - return qname; - } - } else if (qname.getFormattedRevision().equals(rev)) { + if (identifier.getRevision().equals(qname.getRevision())) { return qname; } } @@ -617,10 +617,5 @@ public class NetconfDevice // this capability will be removed from required sources and not reported as unresolved-capability return null; } - - private String getNullableRev(final SourceIdentifier identifier) { - final String rev = identifier.getRevision(); - return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? null : rev; - } } } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java index f5ae6935b5..6ce2d0f145 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java @@ -14,13 +14,13 @@ import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTr import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import java.net.URI; import java.util.Collections; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; @@ -154,18 +154,18 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { private static Optional> findSchemasNode(final NormalizedNode result) { if (result == null) { - return Optional.absent(); + return Optional.empty(); } final Optional> dataNode = ((DataContainerNode) result).getChild(toId(NETCONF_DATA_QNAME)); if (!dataNode.isPresent()) { - return Optional.absent(); + return Optional.empty(); } final Optional> nStateNode = ((DataContainerNode) dataNode.get()).getChild(toId(NetconfState.QNAME)); if (!nStateNode.isPresent()) { - return Optional.absent(); + return Optional.empty(); } return ((DataContainerNode) nStateNode.get()).getChild(toId(Schemas.QNAME)); @@ -193,21 +193,21 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { if (!formatAsString.equals(Yang.QNAME.toString())) { LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString); - return Optional.absent(); + return Optional.empty(); } childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION; final Set locationsAsString = getAllChildNodeValues(schemaNode, childNode); if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) { LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString); - return Optional.absent(); + return Optional.empty(); } childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE; final Optional namespaceValue = getSingleChildNodeValue(schemaNode, childNode); if (!namespaceValue.isPresent()) { LOG.warn("{}: Ignoring schema due to missing namespace", id); - return Optional.absent(); + return Optional.empty(); } final String namespaceAsString = namespaceValue.get(); @@ -220,7 +220,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { final QName moduleQName = revisionAsString.isPresent() ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString) - : QName.create(URI.create(namespaceAsString), null, moduleNameAsString); + : QName.create(URI.create(namespaceAsString), moduleNameAsString); return Optional.of(new RemoteYangSchema(moduleQName)); } @@ -250,7 +250,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { return getValueOfSimpleNode(node.get()); } else { LOG.debug("Child node {} not present", childNode); - return Optional.absent(); + return Optional.empty(); } } @@ -258,7 +258,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { final NormalizedNode node) { final Object value = node.getValue(); return value == null || Strings.isNullOrEmpty(value.toString()) - ? Optional.absent() : Optional.of(value.toString().trim()); + ? Optional.empty() : Optional.of(value.toString().trim()); } @Override diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java index 7db88e0d04..28dc94ed49 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java @@ -50,10 +50,10 @@ final class NotificationHandler { /** * Forward all cached notifications and pass all notifications from this point directly to sal facade. - * @param messageTransformer Message transformer + * @param transformer Message transformer */ - synchronized void onRemoteSchemaUp(final MessageTransformer messageTransformer) { - this.messageTransformer = Preconditions.checkNotNull(messageTransformer); + synchronized void onRemoteSchemaUp(final MessageTransformer transformer) { + this.messageTransformer = Preconditions.checkNotNull(transformer); passNotifications = true; @@ -90,8 +90,8 @@ final class NotificationHandler { } } - synchronized void addNotificationFilter(final NotificationFilter filter) { - this.filter = filter; + synchronized void addNotificationFilter(final NotificationFilter newFilter) { + this.filter = newFilter; } synchronized void onRemoteSchemaDown() { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/auth/DatastoreBackedPublicKeyAuth.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/auth/DatastoreBackedPublicKeyAuth.java index 7c750cc67f..a33115e465 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/auth/DatastoreBackedPublicKeyAuth.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/auth/DatastoreBackedPublicKeyAuth.java @@ -13,8 +13,8 @@ import java.io.IOException; import java.io.StringReader; import java.security.KeyPair; import java.util.Optional; -import org.apache.sshd.ClientSession; import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.session.ClientSession; import org.opendaylight.aaa.encrypt.AAAEncryptionService; import org.opendaylight.aaa.encrypt.PKIUtil; import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; @@ -52,7 +52,7 @@ public class DatastoreBackedPublicKeyAuth extends AuthenticationHandler { } @Override - public AuthFuture authenticate(ClientSession session) throws IOException { + public AuthFuture authenticate(final ClientSession session) throws IOException { // if we have keypair set the identity, otherwise retry the retrieval from the adapter // if successful set the identity. if (keyPair.isPresent() || tryToSetKeyPair()) { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java index b55b42f669..d8eace1fc9 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java @@ -59,7 +59,7 @@ public class NetconfDeviceCommunicator private final int concurentRpcMsgs; private final Queue requests = new ArrayDeque<>(); - private NetconfClientSession session; + private NetconfClientSession currentSession; private Future initFuture; private final SettableFuture firstConnectionFuture; @@ -106,7 +106,7 @@ public class NetconfDeviceCommunicator sessionLock.lock(); try { LOG.debug("{}: Session established", id); - this.session = session; + currentSession = session; NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromNetconfSession(session); @@ -167,8 +167,8 @@ public class NetconfDeviceCommunicator public void disconnect() { // If session is already in closing, no need to close it again - if (session != null && isSessionClosing.compareAndSet(false, true)) { - session.close(); + if (currentSession != null && isSessionClosing.compareAndSet(false, true)) { + currentSession.close(); } } @@ -180,8 +180,8 @@ public class NetconfDeviceCommunicator final List>> futuresToCancel = Lists.newArrayList(); sessionLock.lock(); try { - if (session != null) { - session = null; + if (currentSession != null) { + currentSession = null; /* * Walk all requests, check if they have been executing * or cancelled and remove them from the queue. @@ -367,7 +367,7 @@ public class NetconfDeviceCommunicator LOG.trace("{}: Sending message {}", id, msgToS(message)); } - if (session == null) { + if (currentSession == null) { LOG.warn("{}: Session is disconnected, failing RPC request {}", id, message); return Futures.immediateFuture(createSessionDownRpcResult()); @@ -376,7 +376,7 @@ public class NetconfDeviceCommunicator final Request req = new Request(new UncancellableFuture<>(true), message); requests.add(req); - session.sendMessage(req.request).addListener(future -> { + currentSession.sendMessage(req.request).addListener(future -> { if (!future.isSuccess()) { // We expect that a session down will occur at this point LOG.debug("{}: Failed to send request {}", id, diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java index a08996da90..d5383afda7 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java @@ -37,12 +37,7 @@ public final class NetconfSessionPreferences { private final int skipLength; ParameterMatcher(final String name) { - predicate = new Predicate() { - @Override - public boolean apply(final String input) { - return input.startsWith(name); - } - }; + predicate = input -> input.startsWith(name); this.skipLength = name.length(); } @@ -62,12 +57,7 @@ public final class NetconfSessionPreferences { private static final ParameterMatcher REVISION_PARAM = new ParameterMatcher("revision="); private static final ParameterMatcher BROKEN_REVISON_PARAM = new ParameterMatcher("amp;revision="); private static final Splitter AMP_SPLITTER = Splitter.on('&'); - private static final Predicate CONTAINS_REVISION = new Predicate() { - @Override - public boolean apply(final String input) { - return input.contains("revision="); - } - }; + private static final Predicate CONTAINS_REVISION = input -> input.contains("revision="); private final Map moduleBasedCaps; private final Map nonModuleCaps; @@ -218,7 +208,7 @@ public final class NetconfSessionPreferences { } private static QName cachedQName(final String namespace, final String moduleName) { - return QName.create(URI.create(namespace), null, moduleName).withoutRevision().intern(); + return QName.create(URI.create(namespace), moduleName).withoutRevision().intern(); } public static NetconfSessionPreferences fromStrings(final Collection capabilities) { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java index e34b885787..1b5ae10ec4 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java @@ -37,13 +37,14 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath; */ public final class NetconfDeviceRpc implements DOMRpcService { - private final RemoteDeviceCommunicator listener; + private final RemoteDeviceCommunicator communicator; private final MessageTransformer transformer; private final Collection availableRpcs; - public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator listener, - final MessageTransformer transformer) { - this.listener = listener; + public NetconfDeviceRpc(final SchemaContext schemaContext, + final RemoteDeviceCommunicator communicator, + final MessageTransformer transformer) { + this.communicator = communicator; this.transformer = transformer; availableRpcs = Collections2.transform(schemaContext.getOperations(), @@ -56,7 +57,7 @@ public final class NetconfDeviceRpc implements DOMRpcService { @Nullable final NormalizedNode input) { final NetconfMessage message = transformer.toRpcRequest(type, input); final ListenableFuture> delegateFutureWithPureResult = - listener.sendRequest(message, type.getLastComponent()); + communicator.sendRequest(message, type.getLastComponent()); final ListenableFuture transformed = Futures.transform(delegateFutureWithPureResult, input1 -> { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java index 4ad1dde5fe..e4d16e9394 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java @@ -115,8 +115,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable { } public synchronized void onTopologyDeviceConnected(final SchemaContext initialCtx, - final DOMDataBroker broker, final DOMRpcService rpc, - final NetconfDeviceNotificationService notificationService) { + final DOMDataBroker broker, final DOMRpcService rpc, + final NetconfDeviceNotificationService newNotificationService) { Preconditions.checkNotNull(mountService, "Closed"); Preconditions.checkState(topologyRegistration == null, "Already initialized"); @@ -126,8 +126,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable { mountBuilder.addService(DOMDataBroker.class, broker); mountBuilder.addService(DOMRpcService.class, rpc); - mountBuilder.addService(DOMNotificationService.class, notificationService); - this.notificationService = notificationService; + mountBuilder.addService(DOMNotificationService.class, newNotificationService); + this.notificationService = newNotificationService; topologyRegistration = mountBuilder.register(); LOG.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java index 84b824000e..9701c98410 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java @@ -11,6 +11,7 @@ import com.google.common.base.Function; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener; @@ -82,7 +83,7 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService { } else { return new DefaultDOMRpcResult(input1.getErrors()); } - }); + }, MoreExecutors.directExecutor()); return Futures.makeChecked(transformed, e -> new DOMRpcImplementationNotAvailableException(e, @@ -95,8 +96,7 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService { @Nonnull @Override - public ListenerRegistration registerRpcListener( - @Nonnull final T listener) { + public ListenerRegistration registerRpcListener(@Nonnull final T lsnr) { throw new UnsupportedOperationException("Not available for netconf 1.0"); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java index 1d429022c1..d3f5b1e94d 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java @@ -101,7 +101,7 @@ public class WriteCandidateTx extends AbstractWriteTx { Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(), "Submit failed with errors: %s", input.getErrors()); return null; - }); + }, MoreExecutors.directExecutor()); return Futures.makeChecked(commitFutureAsVoid, input -> new TransactionCommitFailedException( "Submit of transaction " + getIdentifier() + " failed", input)); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTx.java index af51c824ef..ddc66fb5f1 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTx.java @@ -13,6 +13,7 @@ import com.google.common.base.Optional; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import java.util.ArrayList; import java.util.List; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; @@ -73,7 +74,7 @@ public class WriteRunningTx extends AbstractWriteTx { @Override public synchronized CheckedFuture submit() { final ListenableFuture commmitFutureAsVoid = Futures.transform(commit(), - (Function, Void>) input -> null); + (Function, Void>) input -> null, MoreExecutors.directExecutor()); return Futures.makeChecked(commmitFutureAsVoid, input -> new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", @@ -102,12 +103,12 @@ public class WriteRunningTx extends AbstractWriteTx { netOps.unlockRunning(new NetconfRpcFutureCallback("Unlock running", id)); } - private static class Change { + private static final class Change { private final DataContainerChild editStructure; private final Optional defaultOperation; - private Change(final DataContainerChild editStructure, final Optional defaultOperation) { + Change(final DataContainerChild editStructure, final Optional defaultOperation) { this.editStructure = editStructure; this.defaultOperation = defaultOperation; } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java index 6bb12e7e4b..068fc10a51 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java @@ -15,9 +15,9 @@ import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -28,8 +28,8 @@ import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang; -import org.opendaylight.yangtools.util.concurrent.ExceptionMapper; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode; @@ -40,7 +40,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; @@ -52,14 +51,6 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource private static final Logger LOG = LoggerFactory.getLogger(NetconfRemoteSchemaYangSourceProvider.class); - private static final ExceptionMapper MAPPER = new ExceptionMapper( - "schemaDownload", SchemaSourceException.class) { - @Override - protected SchemaSourceException newWithCause(final String message, final Throwable throwable) { - return new SchemaSourceException(message, throwable); - } - }; - private final DOMRpcService rpc; private final RemoteDeviceId id; @@ -103,7 +94,7 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource return Optional.absent(); } - final Optional> child = + final java.util.Optional> child = ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG); Preconditions.checkState(child.isPresent() && child.get() instanceof AnyXmlNode, @@ -118,27 +109,19 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource } @Override - public CheckedFuture getSource( - final SourceIdentifier sourceIdentifier) { + public ListenableFuture getSource(final SourceIdentifier sourceIdentifier) { final String moduleName = sourceIdentifier.getName(); - // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request - final String badRev = sourceIdentifier.getRevision(); - final String formattedRevision = SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(badRev) ? null : badRev; - final Optional revision = Optional.fromNullable(formattedRevision); + final Optional revision = Optional.fromJavaUtil(sourceIdentifier.getRevision().map(Revision::toString)); final NormalizedNode getSchemaRequest = createGetSchemaRequest(moduleName, revision); LOG.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision); - final ListenableFuture transformed = Futures.transform( - rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest), - new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision)); - - final CheckedFuture checked = - Futures.makeChecked(transformed, MAPPER); - - return checked; + return Futures.transform( + rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest), + new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision), + MoreExecutors.directExecutor()); } /** diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java index 33af8ec298..d7d4948e4c 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java @@ -10,8 +10,8 @@ package org.opendaylight.netconf.sal.connect.netconf.schema; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; -import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -41,15 +41,14 @@ public final class YangLibrarySchemaYangSourceProvider implements SchemaSourcePr } @Override - public CheckedFuture getSource( + public ListenableFuture getSource( final SourceIdentifier sourceIdentifier) { Preconditions.checkNotNull(sourceIdentifier); Preconditions.checkArgument(availableSources.containsKey(sourceIdentifier)); return download(sourceIdentifier); } - private CheckedFuture download( - final SourceIdentifier sourceIdentifier) { + private ListenableFuture download(final SourceIdentifier sourceIdentifier) { final URL url = availableSources.get(sourceIdentifier); try (InputStream in = url.openStream()) { final String schemaContent = new String(ByteStreams.toByteArray(in)); @@ -57,12 +56,11 @@ public final class YangLibrarySchemaYangSourceProvider implements SchemaSourcePr new NetconfRemoteSchemaYangSourceProvider .NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent)); LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url); - return Futures.immediateCheckedFuture(yangSource); + return Futures.immediateFuture(yangSource); } catch (IOException e) { LOG.warn("Unable to download source {} from a yang library's url {}", sourceIdentifier, url, e); - return Futures.immediateFailedCheckedFuture( - new SchemaSourceException( - "Unable to download remote schema for " + sourceIdentifier + " from " + url, e)); + return Futures.immediateFailedFuture(new SchemaSourceException( + "Unable to download remote schema for " + sourceIdentifier + " from " + url, e)); } } } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java index fc31a256aa..8428a48df6 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java @@ -18,7 +18,6 @@ import com.google.common.collect.Multimaps; import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.Map; import javax.annotation.Nonnull; @@ -36,6 +35,7 @@ import org.opendaylight.netconf.sal.connect.api.MessageTransformer; import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil; import org.opendaylight.netconf.sal.connect.util.MessageCounter; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; @@ -121,10 +121,8 @@ public class NetconfMessageTransformer implements MessageTransformer notificationDefinitions) { - Comparator cmp = (o1, o2) -> - o1.getQName().getRevision().compareTo(o2.getQName().getRevision()); - - return Collections.max(notificationDefinitions, cmp); + return Collections.max(notificationDefinitions, (o1, o2) -> + Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision())); } @Override diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/SchemalessMessageTransformer.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/SchemalessMessageTransformer.java index d2cb8d5226..21835b5903 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/SchemalessMessageTransformer.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/SchemalessMessageTransformer.java @@ -39,7 +39,8 @@ public class SchemalessMessageTransformer implements MessageTransformer input) { final DOMSource payload = (DOMSource) input.getValue(); wrapPayload((Document) payload.getNode()); - return new NetconfMessage(((Document) ((AnyXmlNode) input).getValue().getNode())); + return new NetconfMessage((Document) ((AnyXmlNode) input).getValue().getNode()); } /** diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOps.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOps.java index 3dee33869e..71a60bb18e 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOps.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOps.java @@ -27,7 +27,6 @@ import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTr import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId; import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; @@ -41,6 +40,7 @@ import org.opendaylight.netconf.sal.connect.netconf.sal.SchemalessNetconfDeviceR import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.get.config.input.source.ConfigSource; +import org.opendaylight.yangtools.yang.common.Empty; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.ModifyAction; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; @@ -66,8 +66,8 @@ public final class NetconfBaseOps { this.rpc = rpc; this.schemaContext = schemaContext; - if ((rpc instanceof KeepaliveDOMRpcService) - && (((KeepaliveDOMRpcService) rpc).getDeviceRpc() instanceof SchemalessNetconfDeviceRpc)) { + if (rpc instanceof KeepaliveDOMRpcService + && ((KeepaliveDOMRpcService) rpc).getDeviceRpc() instanceof SchemalessNetconfDeviceRpc) { this.transformer = new SchemalessRpcStructureTransformer(); } else { this.transformer = new NetconfRpcStructureTransformer(schemaContext); @@ -208,14 +208,14 @@ public final class NetconfBaseOps { private ListenableFuture>> extractData( final Optional path, final ListenableFuture configRunning) { - return Futures.transform(configRunning, (Function>>) result -> { + return Futures.transform(configRunning, result -> { Preconditions.checkArgument( result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors()); final DataContainerChild dataNode = ((ContainerNode) result.getResult()).getChild( NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get(); return transformer.selectFromDataStructure(dataNode, path.get()); - }); + }, MoreExecutors.directExecutor()); } public ListenableFuture getConfigRunning(final FutureCallback callback, @@ -239,7 +239,7 @@ public final class NetconfBaseOps { NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext))) : rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT); - Futures.addCallback(future, callback); + Futures.addCallback(future, callback, MoreExecutors.directExecutor()); return future; } @@ -322,10 +322,9 @@ public final class NetconfBaseOps { public static DataContainerChild getSourceNode(final QName datastore) { return Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_SOURCE_QNAME)) - .withChild( - Builders.choiceBuilder().withNodeIdentifier(toId(ConfigSource.QNAME)).withChild( - Builders.leafBuilder().withNodeIdentifier(toId(datastore)).build()).build() - ).build(); + .withChild(Builders.choiceBuilder().withNodeIdentifier(toId(ConfigSource.QNAME)).withChild( + Builders.leafBuilder().withNodeIdentifier(toId(datastore)).withValue(Empty.getInstance()).build()) + .build()).build(); } public static ContainerNode getLockContent(final QName datastore) { @@ -335,10 +334,9 @@ public final class NetconfBaseOps { public static DataContainerChild getTargetNode(final QName datastore) { return Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_TARGET_QNAME)) - .withChild( - Builders.choiceBuilder().withNodeIdentifier(toId(ConfigTarget.QNAME)).withChild( - Builders.leafBuilder().withNodeIdentifier(toId(datastore)).build()).build() - ).build(); + .withChild(Builders.choiceBuilder().withNodeIdentifier(toId(ConfigTarget.QNAME)).withChild( + Builders.leafBuilder().withNodeIdentifier(toId(datastore)).withValue(Empty.getInstance()).build()) + .build()).build(); } public static NormalizedNode getCopyConfigContent(final QName source, final QName target) { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfMessageTransformUtil.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfMessageTransformUtil.java index 4726b7aaa7..100073ce83 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfMessageTransformUtil.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfMessageTransformUtil.java @@ -67,7 +67,7 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; -public class NetconfMessageTransformUtil { +public final class NetconfMessageTransformUtil { private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class); @@ -312,8 +312,8 @@ public class NetconfMessageTransformUtil { } else { final Entry modifyOperation = operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null; - configContent = ImmutableNodes - .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation)); + configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride.toJavaUtil(), + java.util.Optional.ofNullable(modifyOperation)); } final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), @@ -363,7 +363,8 @@ public class NetconfMessageTransformUtil { NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()), notificationElement); } catch (final DocumentedException e) { - throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message); + throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message, + e); } catch (final DateTimeParseException e) { LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcStructureTransformer.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcStructureTransformer.java index 5ccab6ba66..47e6d9eba2 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcStructureTransformer.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcStructureTransformer.java @@ -31,13 +31,13 @@ class NetconfRpcStructureTransformer implements RpcStructureTransformer { public Optional> selectFromDataStructure( final DataContainerChild data, final YangInstanceIdentifier path) { - return NormalizedNodes.findNode(data, path.getPathArguments()); + return Optional.fromJavaUtil(NormalizedNodes.findNode(data, path.getPathArguments())); } @Override public AnyXmlNode createEditConfigStructure(final Optional> data, final YangInstanceIdentifier dataPath, - Optional operation) { + final Optional operation) { return NetconfMessageTransformUtil.createEditConfigAnyxml(schemaContext, dataPath, operation, data); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxy.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxy.java index 07163bbaad..2a0830658d 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxy.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxy.java @@ -15,13 +15,17 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; -import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; +import org.opendaylight.yangtools.yang.model.api.ActionDefinition; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; +import org.opendaylight.yangtools.yang.model.api.MustDefinition; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; +import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; @@ -35,21 +39,21 @@ public final class NodeContainerProxy implements ContainerSchemaNode { private final Map childNodes; private final QName qualifiedName; - private final Set availableAugmentations; + private final Set availableAugmentations; public NodeContainerProxy(final QName qualifiedName, final Map childNodes, - final Set availableAugmentations) { + final Set availableAugmentations) { this.availableAugmentations = availableAugmentations; this.childNodes = Preconditions.checkNotNull(childNodes, "childNodes"); this.qualifiedName = qualifiedName; } public NodeContainerProxy(final QName qualifiedName, final Collection childNodes) { - this(qualifiedName, asMap(childNodes), Collections.emptySet()); + this(qualifiedName, asMap(childNodes), Collections.emptySet()); } public NodeContainerProxy(final QName qualifiedName, final Collection childNodes, - final Set availableAugmentations) { + final Set availableAugmentations) { this(qualifiedName, asMap(childNodes), availableAugmentations); } @@ -73,8 +77,8 @@ public final class NodeContainerProxy implements ContainerSchemaNode { } @Override - public DataSchemaNode getDataChildByName(final QName qualifiedName) { - return childNodes.get(qualifiedName); + public Optional findDataChildByName(final QName name) { + return Optional.ofNullable(childNodes.get(name)); } @Override @@ -88,7 +92,7 @@ public final class NodeContainerProxy implements ContainerSchemaNode { } @Override - public Set getAvailableAugmentations() { + public Set getAvailableAugmentations() { return availableAugmentations; } @@ -107,11 +111,6 @@ public final class NodeContainerProxy implements ContainerSchemaNode { throw new UnsupportedOperationException(); } - @Override - public ConstraintDefinition getConstraints() { - throw new UnsupportedOperationException(); - } - @Override public QName getQName() { return qualifiedName; @@ -123,12 +122,12 @@ public final class NodeContainerProxy implements ContainerSchemaNode { } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException(); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException(); } @@ -141,4 +140,24 @@ public final class NodeContainerProxy implements ContainerSchemaNode { public List getUnknownSchemaNodes() { return Collections.emptyList(); } -} \ No newline at end of file + + @Override + public Set getNotifications() { + return Collections.emptySet(); + } + + @Override + public Set getActions() { + return Collections.emptySet(); + } + + @Override + public Optional getWhenCondition() { + return Optional.empty(); + } + + @Override + public Collection getMustConstraints() { + return Collections.emptySet(); + } +} diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java index 099d2f2dde..28c69e72ab 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java @@ -170,7 +170,7 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer { try { textContent = key.get(0).getTextContent(); } catch (DocumentedException e) { - throw new IllegalStateException("Key value not present in key element"); + throw new IllegalStateException("Key value not present in key element", e); } if (!keyValues.get(qualifiedName).equals(textContent)) { throw new IllegalStateException("Key value in path not equal to key value in xml"); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/util/NetconfTopologyRPCProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/util/NetconfTopologyRPCProvider.java index c963022e06..0c5810aa1e 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/util/NetconfTopologyRPCProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/util/NetconfTopologyRPCProvider.java @@ -61,7 +61,7 @@ public class NetconfTopologyRPCProvider implements NetconfNodeTopologyService { final NetconfNode node = this.encryptPassword(input); final SettableFuture> futureResult = SettableFuture.create(); final NodeId nodeId = new NodeId(input.getNodeId()); - writeToConfigDS(node, nodeId, topologyId, futureResult); + writeToConfigDS(node, nodeId, futureResult); return futureResult; } @@ -91,7 +91,7 @@ public class NetconfTopologyRPCProvider implements NetconfNodeTopologyService { return credentials; } - private void writeToConfigDS(final NetconfNode node, final NodeId nodeId, final String topologyId, + private void writeToConfigDS(final NetconfNode node, final NodeId nodeId, final SettableFuture> futureResult) { final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction(); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemasTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemasTest.java index 12345671b4..7a8846db83 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemasTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemasTest.java @@ -15,6 +15,7 @@ import java.util.Collections; import java.util.Map; import org.junit.Assert; import org.junit.Test; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; @@ -41,15 +42,15 @@ public class LibraryModulesSchemasTest { Assert.assertThat(resolvedModulesSchema.size(), is(3)); Assert.assertTrue(resolvedModulesSchema.containsKey(RevisionSourceIdentifier.create("module-with-revision", - "2014-04-08"))); + Revision.of("2014-04-08")))); Assert.assertThat(resolvedModulesSchema.get( - RevisionSourceIdentifier.create("module-with-revision", "2014-04-08")), + RevisionSourceIdentifier.create("module-with-revision", Revision.of("2014-04-08"))), is(new URL("http://localhost:8181/yanglib/schemas/module-with-revision/2014-04-08"))); Assert.assertTrue(resolvedModulesSchema.containsKey( - RevisionSourceIdentifier.create("another-module-with-revision", "2013-10-21"))); + RevisionSourceIdentifier.create("another-module-with-revision", Revision.of("2013-10-21")))); Assert.assertThat(resolvedModulesSchema.get( - RevisionSourceIdentifier.create("another-module-with-revision", "2013-10-21")), + RevisionSourceIdentifier.create("another-module-with-revision", Revision.of("2013-10-21"))), is(new URL("http://localhost:8181/yanglib/schemas/another-module-with-revision/2013-10-21"))); Assert.assertTrue(resolvedModulesSchema.containsKey( diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDeviceTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDeviceTest.java index efa9d6f15c..c568b1b013 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDeviceTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDeviceTest.java @@ -21,7 +21,6 @@ import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import com.google.common.base.Optional; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -29,13 +28,11 @@ import com.google.common.collect.Sets; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.SettableFuture; import java.io.IOException; -import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -60,6 +57,7 @@ import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransform import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.Module; @@ -76,7 +74,7 @@ import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; -import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; import org.xml.sax.SAXException; @@ -107,12 +105,12 @@ public class NetconfDeviceTest { public static final String TEST_MODULE = "test-module"; public static final String TEST_REVISION = "2013-07-22"; public static final SourceIdentifier TEST_SID = - RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION)); + RevisionSourceIdentifier.create(TEST_MODULE, Revision.of(TEST_REVISION)); public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION; public static final SourceIdentifier TEST_SID2 = - RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION)); + RevisionSourceIdentifier.create(TEST_MODULE + "2", Revision.of(TEST_REVISION)); public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION; @@ -132,9 +130,9 @@ public class NetconfDeviceTest { new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail")); doAnswer(invocation -> { if (((Collection) invocation.getArguments()[0]).size() == 2) { - return Futures.immediateFailedCheckedFuture(schemaResolutionException); + return Futures.immediateFailedFuture(schemaResolutionException); } else { - return Futures.immediateCheckedFuture(schema); + return Futures.immediateFuture(schema); } }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class)); @@ -181,8 +179,7 @@ public class NetconfDeviceTest { final SchemaResolutionException schemaResolutionException = new SchemaResolutionException("fail first", Collections.emptyList(), HashMultimap.create()); - doReturn(Futures.immediateFailedCheckedFuture( - schemaResolutionException)) + doReturn(Futures.immediateFailedFuture(schemaResolutionException)) .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class)); final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice @@ -216,13 +213,13 @@ public class NetconfDeviceTest { // Make fallback attempt to fail due to empty resolved sources final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID); - doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)) + doReturn(Futures.immediateFailedFuture(schemaResolutionException)) .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class)); doAnswer(invocation -> { if (((Collection) invocation.getArguments()[0]).size() == 2) { - return Futures.immediateFailedCheckedFuture(schemaResolutionException); + return Futures.immediateFailedFuture(schemaResolutionException); } else { - return Futures.immediateCheckedFuture(schema); + return Futures.immediateFuture(schema); } }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class)); @@ -268,7 +265,7 @@ public class NetconfDeviceTest { private static SchemaRepository getSchemaRepository() { final SchemaRepository mock = mock(SchemaRepository.class); final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class); - doReturn(Futures.immediateCheckedFuture(mockRep)) + doReturn(Futures.immediateFuture(mockRep)) .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class)); return mock; } @@ -279,8 +276,7 @@ public class NetconfDeviceTest { final NetconfDeviceCommunicator listener = getListener(); final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class); final SettableFuture schemaFuture = SettableFuture.create(); - doReturn(Futures.makeChecked(schemaFuture, e -> new SchemaResolutionException("fail"))) - .when(schemaContextProviderFactory).createSchemaContext(any(Collection.class)); + doReturn(schemaFuture).when(schemaContextProviderFactory).createSchemaContext(any(Collection.class)); final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER); @@ -348,8 +344,7 @@ public class NetconfDeviceTest { final NetconfDeviceCommunicator listener = getListener(); final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class); final SettableFuture schemaFuture = SettableFuture.create(); - doReturn(Futures.makeChecked(schemaFuture, e -> new SchemaResolutionException("fail"))) - .when(schemaContextProviderFactory).createSchemaContext(any(Collection.class)); + doReturn(schemaFuture).when(schemaContextProviderFactory).createSchemaContext(any(Collection.class)); final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER); @@ -414,16 +409,13 @@ public class NetconfDeviceTest { private static SchemaContextFactory getSchemaFactory() throws Exception { final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class); - doReturn(Futures.immediateCheckedFuture(getSchema())) + doReturn(Futures.immediateFuture(getSchema())) .when(schemaFactory).createSchemaContext(any(Collection.class)); return schemaFactory; } - public static SchemaContext getSchema() throws Exception { - final List modelsToParse = Lists.newArrayList( - NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang") - ); - return YangParserTestUtils.parseYangStreams(modelsToParse); + public static SchemaContext getSchema() { + return YangParserTestUtils.parseYangResource("/schemas/test-module.yang"); } private static RemoteDeviceHandler getFacade() throws Exception { diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasTest.java index 3c8cac3181..2398bc71c9 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasTest.java @@ -159,7 +159,7 @@ public class NetconfStateSchemasTest { Assert.assertTrue(availableYangSchemasQNames.isEmpty()); } - @SuppressWarnings("checkstyle:IllegalThrows") + @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" }) @Test(expected = RuntimeException.class) public void testCreateInterrupted() throws Throwable { //NetconfStateSchemas.create calls Thread.currentThread().interrupt(), so it must run in its own thread diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToNotificationTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToNotificationTest.java index 0b37a87e93..a117aea103 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToNotificationTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToNotificationTest.java @@ -14,8 +14,6 @@ import static org.junit.Assert.assertTrue; import com.google.common.collect.Iterables; import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -47,19 +45,16 @@ public class NetconfToNotificationTest { userNotification = new NetconfMessage(doc); } - static SchemaContext getNotificationSchemaContext(final Class loadClass, - final boolean getExceptionTest) throws Exception { - final List modelsToParse = new ArrayList<>(); - + static SchemaContext getNotificationSchemaContext(final Class loadClass, final boolean getExceptionTest) { + final SchemaContext context; if (getExceptionTest) { - modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification4.yang")); - modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification3.yang")); + context = YangParserTestUtils.parseYangResources(loadClass, "/schemas/user-notification4.yang", + "/schemas/user-notification3.yang"); } else { - modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification.yang")); - modelsToParse.add(loadClass.getResourceAsStream("/schemas/user-notification2.yang")); + context = YangParserTestUtils.parseYangResources(loadClass, "/schemas/user-notification.yang", + "/schemas/user-notification2.yang"); } - final SchemaContext context = YangParserTestUtils.parseYangStreams(modelsToParse); final Set modules = context.getModules(); assertTrue(!modules.isEmpty()); assertNotNull(context); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToRpcRequestTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToRpcRequestTest.java index 10cb4e3236..3f153d20a5 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToRpcRequestTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToRpcRequestTest.java @@ -14,10 +14,6 @@ import static org.junit.Assert.assertTrue; import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId; import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath; -import com.google.common.collect.Lists; -import java.io.InputStream; -import java.util.Collections; -import java.util.List; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; @@ -56,16 +52,13 @@ public class NetconfToRpcRequestTest { static NetconfMessageTransformer messageTransformer; @BeforeClass - public static void setup() throws Exception { - List modelsToParse = Collections.singletonList( - NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang")); - final Set notifModules = YangParserTestUtils.parseYangStreams(modelsToParse).getModules(); + public static void setup() { + final Set notifModules = YangParserTestUtils.parseYangResource( + "/schemas/rpc-notification-subscription.yang").getModules(); assertTrue(!notifModules.isEmpty()); - modelsToParse = Lists.newArrayList( - NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/config-test-rpc.yang"), - NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang")); - cfgCtx = YangParserTestUtils.parseYangStreams(modelsToParse); + cfgCtx = YangParserTestUtils.parseYangResources(NetconfToRpcRequestTest.class, + "/schemas/config-test-rpc.yang", "/schemas/rpc-notification-subscription.yang"); messageTransformer = new NetconfMessageTransformer(cfgCtx, true); } diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicatorTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicatorTest.java index f9724cf74e..3cc75f230a 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicatorTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicatorTest.java @@ -11,6 +11,7 @@ package org.opendaylight.netconf.sal.connect.netconf.listener; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.same; @@ -115,11 +116,11 @@ public class NetconfDeviceCommunicatorTest { ChannelFuture mockChannelFuture = mock(ChannelFuture.class); doReturn(mockChannelFuture).when(mockChannelFuture) - .addListener(any((GenericFutureListener.class))); + .addListener(any(GenericFutureListener.class)); doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message)); ListenableFuture> resultFuture = - communicator.sendRequest(message, QName.create("mock rpc")); + communicator.sendRequest(message, QName.create("", "mockRpc")); if (doLastTest) { assertNotNull("ListenableFuture is null", resultFuture); } @@ -210,7 +211,7 @@ public class NetconfDeviceCommunicatorTest { setupSession(); NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument()); - QName rpc = QName.create("mock rpc"); + QName rpc = QName.create("", "mockRpc"); ArgumentCaptor futureListener = ArgumentCaptor.forClass(GenericFutureListener.class); @@ -241,7 +242,7 @@ public class NetconfDeviceCommunicatorTest { @Test public void testSendRequestWithNoSession() throws Exception { NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument()); - QName rpc = QName.create("mock rpc"); + QName rpc = QName.create("", "mockRpc"); ListenableFuture> resultFuture = communicator.sendRequest(message, rpc); @@ -273,7 +274,7 @@ public class NetconfDeviceCommunicatorTest { setupSession(); NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument()); - QName rpc = QName.create("mock rpc"); + QName rpc = QName.create("", "mockRpc"); ArgumentCaptor futureListener = ArgumentCaptor.forClass(GenericFutureListener.class); @@ -355,10 +356,8 @@ public class NetconfDeviceCommunicatorTest { String errorInfo = rpcError.getInfo(); assertNotNull("RpcError info is null", errorInfo); - assertEquals("Error info contains \"foo\"", true, - errorInfo.contains("foo")); - assertEquals("Error info contains \"bar\"", true, - errorInfo.contains("bar")); + assertTrue("Error info contains \"foo\"", errorInfo.contains("foo")); + assertTrue("Error info contains \"bar\"", errorInfo.contains("bar")); } /** @@ -424,15 +423,12 @@ public class NetconfDeviceCommunicatorTest { RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.PROTOCOL, "bad-attribute"); - assertEquals("RpcError message non-empty", true, - !Strings.isNullOrEmpty(rpcError.getMessage())); + assertFalse("RpcError message non-empty", Strings.isNullOrEmpty(rpcError.getMessage())); String errorInfo = rpcError.getInfo(); assertNotNull("RpcError info is null", errorInfo); - assertEquals("Error info contains \"actual-message-id\"", true, - errorInfo.contains("actual-message-id")); - assertEquals("Error info contains \"expected-message-id\"", true, - errorInfo.contains("expected-message-id")); + assertTrue("Error info contains \"actual-message-id\"", errorInfo.contains("actual-message-id")); + assertTrue("Error info contains \"expected-message-id\"", errorInfo.contains("expected-message-id")); } @Test @@ -478,7 +474,7 @@ public class NetconfDeviceCommunicatorTest { private static void verifyResponseMessage(final RpcResult rpcResult, final String dataText) { assertNotNull("RpcResult is null", rpcResult); - assertEquals("isSuccessful", true, rpcResult.isSuccessful()); + assertTrue("isSuccessful", rpcResult.isSuccessful()); NetconfMessage messageResult = rpcResult.getResult(); assertNotNull("getResult", messageResult); // List> nodes = messageResult.getSimpleNodesByName( @@ -491,7 +487,7 @@ public class NetconfDeviceCommunicatorTest { private static RpcError verifyErrorRpcResult(final RpcResult rpcResult, final RpcError.ErrorType expErrorType, final String expErrorTag) { assertNotNull("RpcResult is null", rpcResult); - assertEquals("isSuccessful", false, rpcResult.isSuccessful()); + assertFalse("isSuccessful", rpcResult.isSuccessful()); assertNotNull("RpcResult errors is null", rpcResult.getErrors()); assertEquals("Errors size", 1, rpcResult.getErrors().size()); RpcError rpcError = rpcResult.getErrors().iterator().next(); @@ -502,7 +498,7 @@ public class NetconfDeviceCommunicatorTest { final String msg = rpcError.getMessage(); assertNotNull("getMessage is null", msg); assertFalse("getMessage is empty", msg.isEmpty()); - assertFalse("getMessage is blank", CharMatcher.WHITESPACE.matchesAllOf(msg)); + assertFalse("getMessage is blank", CharMatcher.whitespace().matchesAllOf(msg)); return rpcError; } } diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacadeTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacadeTest.java index 3f0b9d8628..04f4f9dcbb 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacadeTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacadeTest.java @@ -105,10 +105,6 @@ public class KeepaliveSalFacadeTest { doReturn(Futures.immediateCheckedFuture(result)) .when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class)); - final KeepaliveSalFacade keepaliveSalFacade = - new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 1L, 1L); - keepaliveSalFacade.setListener(listener); - keepaliveSalFacade.onDeviceConnected(null, null, deviceRpc); verify(underlyingSalFacade).onDeviceConnected( @@ -123,10 +119,6 @@ public class KeepaliveSalFacadeTest { doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state"))) .when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class)); - final KeepaliveSalFacade keepaliveSalFacade = - new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 1L, 1L); - keepaliveSalFacade.setListener(listener); - keepaliveSalFacade.onDeviceConnected(null, null, deviceRpc); verify(underlyingSalFacade).onDeviceConnected( @@ -167,7 +159,7 @@ public class KeepaliveSalFacadeTest { doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state"))) .when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class)); - final KeepaliveSalFacade keepaliveSalFacade = + keepaliveSalFacade = new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 100L, 1L); keepaliveSalFacade.setListener(listener); @@ -177,4 +169,4 @@ public class KeepaliveSalFacadeTest { verify(listener, times(1)).disconnect(); } -} \ No newline at end of file +} diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationServiceTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationServiceTest.java index 5a2539635d..2324bceb87 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationServiceTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationServiceTest.java @@ -43,8 +43,8 @@ public class NetconfDeviceNotificationServiceTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - final SchemaPath path1 = SchemaPath.create(true, new QName(new URI("namespace1"), "path1")); - final SchemaPath path2 = SchemaPath.create(true, new QName(new URI("namespace2"), "path2")); + final SchemaPath path1 = SchemaPath.create(true, QName.create(new URI("namespace1"), "path1")); + final SchemaPath path2 = SchemaPath.create(true, QName.create(new URI("namespace2"), "path2")); service = new NetconfDeviceNotificationService(); service.registerNotificationListener(listener1, path1); registration = service.registerNotificationListener(listener2, path2); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapterTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapterTest.java index 9397635d9e..bd416339a9 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapterTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapterTest.java @@ -17,12 +17,8 @@ import static org.mockito.Mockito.verify; import com.google.common.base.Optional; import com.google.common.util.concurrent.Futures; -import java.io.InputStream; import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Arrays; import java.util.EnumMap; -import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javassist.ClassPool; @@ -72,7 +68,7 @@ import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; public class NetconfDeviceTopologyAdapterTest { - private RemoteDeviceId id = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22)); + private final RemoteDeviceId id = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22)); @Mock private DataBroker broker; @@ -83,10 +79,10 @@ public class NetconfDeviceTopologyAdapterTest { @Mock private NetconfNode data; - private String txIdent = "test transaction"; + private final String txIdent = "test transaction"; private SchemaContext schemaContext = null; - private String sessionIdForReporting = "netconf-test-session1"; + private final String sessionIdForReporting = "netconf-test-session1"; private BindingTransactionChain transactionChain; @@ -106,7 +102,10 @@ public class NetconfDeviceTopologyAdapterTest { doReturn(txIdent).when(writeTx).getIdentifier(); - this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas()); + this.schemaContext = YangParserTestUtils.parseYangResources(NetconfDeviceTopologyAdapterTest.class, + "/schemas/network-topology@2013-10-21.yang", "/schemas/ietf-inet-types@2013-07-15.yang", + "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang", + "/schemas/network-topology-augment-test@2016-08-08.yang"); schemaContext.getModules(); final SchemaService schemaService = createSchemaService(); @@ -118,7 +117,7 @@ public class NetconfDeviceTopologyAdapterTest { datastores.put(LogicalDatastoreType.OPERATIONAL, operStore); ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool( - 16, 16, "CommitFutures"); + 16, 16, "CommitFutures", NetconfDeviceTopologyAdapterTest.class); concurrentDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor); @@ -137,13 +136,13 @@ public class NetconfDeviceTopologyAdapterTest { transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() { @Override - public void onTransactionChainFailed(TransactionChain chain, AsyncTransaction transaction, - Throwable cause) { + public void onTransactionChainFailed(final TransactionChain chain, + final AsyncTransaction transaction, final Throwable cause) { } @Override - public void onTransactionChainSuccessful(TransactionChain chain) { + public void onTransactionChainSuccessful(final TransactionChain chain) { } }); @@ -209,9 +208,9 @@ public class NetconfDeviceTopologyAdapterTest { NormalizedNode augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId) .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(netconfTestLeafQname)).build(); - DOMDataWriteTransaction writeTx = concurrentDOMDataBroker.newWriteOnlyTransaction(); - writeTx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode); - writeTx.submit(); + DOMDataWriteTransaction wtx = concurrentDOMDataBroker.newWriteOnlyTransaction(); + wtx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode); + wtx.submit(); adapter.updateDeviceData(true, new NetconfDeviceCapabilities()); Optional> testNode = concurrentDOMDataBroker.newReadOnlyTransaction() @@ -229,29 +228,15 @@ public class NetconfDeviceTopologyAdapterTest { dataTestId, testNode.get().getValue()); } - private List getYangSchemas() { - final List schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang", - "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang", - "/schemas/netconf-node-topology.yang", "/schemas/network-topology-augment-test@2016-08-08.yang"); - final List schemas = new ArrayList<>(); - - for (String schemaPath : schemaPaths) { - InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath); - schemas.add(resourceAsStream); - } - - return schemas; - } - private SchemaService createSchemaService() { return new SchemaService() { @Override - public void addModule(Module module) { + public void addModule(final Module module) { } @Override - public void removeModule(Module module) { + public void removeModule(final Module module) { } diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChainTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChainTest.java index 56384cdf32..384d83d5f1 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChainTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChainTest.java @@ -111,7 +111,6 @@ public class TxChainTest { @Test public void testChainFail() throws Exception { final AbstractWriteTx writeTx = chain.newWriteOnlyTransaction(); - final ArgumentCaptor captor = ArgumentCaptor.forClass(TxListener.class); verify(writeOnlyTx1).addListener(captor.capture()); writeTx.submit(); final TransactionCommitFailedException cause = new TransactionCommitFailedException("fail"); @@ -220,4 +219,4 @@ public class TxChainTest { // 1 transaction failed, onTransactionChainSuccessful must not be called verify(listener, never()).onTransactionChainSuccessful(chain); } -} \ No newline at end of file +} diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxTestUtils.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxTestUtils.java index 3d820b6837..5e53287cde 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxTestUtils.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxTestUtils.java @@ -14,11 +14,15 @@ import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; -class TxTestUtils { +final class TxTestUtils { private static final QName Q_NAME_1 = QName.create("test:namespace", "2013-07-22", "c"); private static final QName Q_NAME_2 = QName.create(Q_NAME_1, "a"); + private TxTestUtils() { + + } + static YangInstanceIdentifier getContainerId() { return YangInstanceIdentifier.builder() .node(Q_NAME_1) diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTxTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTxTest.java index fd99a54d76..a7a427e7ef 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTxTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTxTest.java @@ -31,6 +31,7 @@ import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps; import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget; +import org.opendaylight.yangtools.yang.common.Empty; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @@ -50,7 +51,7 @@ public class WriteCandidateRunningTxTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); final SchemaContext schemaContext = - YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang")); + YangParserTestUtils.parseYangResource("/schemas/test-module.yang"); doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any()); netconfOps = new NetconfBaseOps(rpc, schemaContext); id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830)); @@ -84,7 +85,8 @@ public class WriteCandidateRunningTxTest { } private static ContainerNode getLockContent(final QName op, final QName datastore) { - final LeafNode datastoreLeaf = Builders.leafBuilder().withNodeIdentifier(toId(datastore)).build(); + final LeafNode datastoreLeaf = Builders.leafBuilder().withNodeIdentifier(toId(datastore)) + .withValue(Empty.getInstance()).build(); final ChoiceNode choice = Builders.choiceBuilder() .withNodeIdentifier(toId(ConfigTarget.QNAME)) .withChild(datastoreLeaf) diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTxTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTxTest.java index 7370b0da5d..917fb486b6 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTxTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTxTest.java @@ -41,7 +41,7 @@ public class WriteCandidateTxTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); final SchemaContext schemaContext = - YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang")); + YangParserTestUtils.parseYangResource("/schemas/test-module.yang"); doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any()); netconfOps = new NetconfBaseOps(rpc, schemaContext); id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830)); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTxTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTxTest.java index ab53dc4f4d..30f75b11ac 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTxTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTxTest.java @@ -42,7 +42,7 @@ public class WriteRunningTxTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); final SchemaContext schemaContext = - YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang")); + YangParserTestUtils.parseYangResource("/schemas/test-module.yang"); doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any()); netconfOps = new NetconfBaseOps(rpc, schemaContext); id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830)); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProviderTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProviderTest.java index c44413ded9..edf7b96f30 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProviderTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProviderTest.java @@ -31,6 +31,7 @@ import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransform import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.common.RpcError; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; @@ -38,7 +39,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableAnyXmlNodeBuilder; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; +import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.w3c.dom.Document; @@ -65,14 +66,13 @@ public class NetconfRemoteSchemaYangSourceProviderTest { @Test public void testGetSource() throws Exception { - final SourceIdentifier identifier = SourceIdentifier.create("test", Optional.of("2016-02-08")); - final CheckedFuture module = provider.getSource(identifier); - final YangTextSchemaSource source = module.checkedGet(); + final SourceIdentifier identifier = RevisionSourceIdentifier.create("test", Revision.of("2016-02-08")); + final YangTextSchemaSource source = provider.getSource(identifier).get(); Assert.assertEquals(identifier, source.getIdentifier()); verify(service).invokeRpc( SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), - NetconfRemoteSchemaYangSourceProvider - .createGetSchemaRequest(identifier.getName(), Optional.of(identifier.getRevision())) + NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest(identifier.getName(), + Optional.fromJavaUtil(identifier.getRevision().map(Revision::toString))) ); } diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProviderTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProviderTest.java index 623e61a337..bc94ff2f9e 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProviderTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProviderTest.java @@ -7,13 +7,18 @@ */ package org.opendaylight.netconf.sal.connect.netconf.schema; -import com.google.common.base.Optional; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.common.io.ByteStreams; -import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.ListenableFuture; import java.net.InetSocketAddress; +import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ExecutionException; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; @@ -32,7 +37,7 @@ public class YangLibrarySchemaYangSourceProviderTest { @Before public void setUp() throws Exception { final URL url = getClass().getResource("/schemas/config-test-rpc.yang"); - workingSid = RevisionSourceIdentifier.create("abc", Optional.absent()); + workingSid = RevisionSourceIdentifier.create("abc", Optional.empty()); final Map sourceIdentifierURLMap = Collections.singletonMap(workingSid, url); final RemoteDeviceId id = new RemoteDeviceId("id", new InetSocketAddress("localhost", 22)); yangLibrarySchemaYangSourceProvider = new YangLibrarySchemaYangSourceProvider(id, sourceIdentifierURLMap); @@ -40,23 +45,27 @@ public class YangLibrarySchemaYangSourceProviderTest { @Test public void testGetSource() throws Exception { - CheckedFuture source = - yangLibrarySchemaYangSourceProvider.getSource(workingSid); - final String x = new String(ByteStreams.toByteArray(source.checkedGet().openStream())); + ListenableFuture source = yangLibrarySchemaYangSourceProvider + .getSource(workingSid); + final String x = new String(ByteStreams.toByteArray(source.get().openStream())); Assert.assertThat(x, CoreMatchers.containsString("module config-test-rpc")); } - @Test(expected = SchemaSourceException.class) - public void testGetSourceFailure() throws Exception { + @Test + public void testGetSourceFailure() throws InterruptedException, MalformedURLException { final URL url = new URL("http://non-existing-entity.yang"); final Map sourceIdentifierURLMap = Collections.singletonMap(workingSid, url); final RemoteDeviceId id = new RemoteDeviceId("id", new InetSocketAddress("localhost", 22)); final YangLibrarySchemaYangSourceProvider failingYangLibrarySchemaYangSourceProvider = new YangLibrarySchemaYangSourceProvider(id, sourceIdentifierURLMap); - CheckedFuture source = - failingYangLibrarySchemaYangSourceProvider.getSource(workingSid); - source.checkedGet(); + try { + failingYangLibrarySchemaYangSourceProvider.getSource(workingSid).get(); + fail(); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + assertTrue(cause instanceof SchemaSourceException); + } } @Test(expected = IllegalArgumentException.class) diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseRpcSchemalessTransformerTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseRpcSchemalessTransformerTest.java index 8f4c320f97..0b3f3677c1 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseRpcSchemalessTransformerTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseRpcSchemalessTransformerTest.java @@ -8,8 +8,8 @@ package org.opendaylight.netconf.sal.connect.netconf.schema.mapping; -import com.google.common.base.Optional; import java.io.InputStream; +import java.util.Optional; import javax.xml.transform.dom.DOMSource; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; @@ -24,6 +24,7 @@ import org.opendaylight.netconf.sal.connect.util.MessageCounter; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.copy.config.input.target.ConfigTarget; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.target.config.target.Candidate; +import org.opendaylight.yangtools.yang.common.Empty; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode; import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode; @@ -87,7 +88,8 @@ public class BaseRpcSchemalessTransformerTest { final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME)) .withChild(Builders.leafBuilder().withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build()) + new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)) + .withValue(Empty.getInstance()).build()) .build(); final DataContainerChild target = Builders.containerBuilder() .withNodeIdentifier( @@ -120,7 +122,7 @@ public class BaseRpcSchemalessTransformerTest { Assert.assertNotNull(result.getResult()); final ContainerNode rpcReply = (ContainerNode) result.getResult(); Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME, rpcReply.getNodeType()); - final Optional dataOpt = rpcReply.getChild( + final Optional dataOpt = rpcReply.getChild( new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)); Assert.assertTrue(dataOpt.isPresent()); final AnyXmlNode data = (AnyXmlNode) dataOpt.get(); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java index a0c90c7293..a2050628ae 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java @@ -148,7 +148,7 @@ public class NetconfMessageTransformerTest { @Test public void tesGetSchemaResponse() throws Exception { - final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true)); + final NetconfMessageTransformer transformer = getTransformer(getSchema(true)); final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument( "\n" @@ -160,8 +160,7 @@ public class NetconfMessageTransformerTest { + "\n" + "" )); - final DOMRpcResult compositeNodeRpcResult = - netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME)); + final DOMRpcResult compositeNodeRpcResult = transformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME)); assertTrue(compositeNodeRpcResult.getErrors().isEmpty()); assertNotNull(compositeNodeRpcResult.getResult()); final DOMSource schemaContent = @@ -187,9 +186,9 @@ public class NetconfMessageTransformerTest { + "\n" + "")); - final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true)); + final NetconfMessageTransformer transformer = getTransformer(getSchema(true)); final DOMRpcResult compositeNodeRpcResult = - netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME)); + transformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME)); assertTrue(compositeNodeRpcResult.getErrors().isEmpty()); assertNotNull(compositeNodeRpcResult.getResult()); diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOpsTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOpsTest.java index 84dd65b6b9..177aede376 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOpsTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOpsTest.java @@ -92,7 +92,7 @@ public class NetconfBaseOpsTest { when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME))) .thenReturn(RpcResultBuilder.success(ok).buildFuture()); final SchemaContext schemaContext = - YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang")); + YangParserTestUtils.parseYangResource("/schemas/test-module.yang"); final MessageTransformer transformer = new NetconfMessageTransformer(schemaContext, true); final DOMRpcService rpc = new NetconfDeviceRpc(schemaContext, listener, transformer); final RemoteDeviceId id = @@ -272,7 +272,7 @@ public class NetconfBaseOpsTest { private final Document expected; - private NetconfMessageMatcher(final Document expected) { + NetconfMessageMatcher(final Document expected) { this.expected = removeAttrs(expected); } @@ -312,4 +312,4 @@ public class NetconfBaseOpsTest { } } -} \ No newline at end of file +} diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfTopologyRPCProviderTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfTopologyRPCProviderTest.java index 72ef9007d1..7dd88b7453 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfTopologyRPCProviderTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfTopologyRPCProviderTest.java @@ -78,7 +78,7 @@ public class NetconfTopologyRPCProviderTest { assertEquals(TEST_PWD, loginPw.getLoginPasswordUnencrypted().getPassword()); } - private CreateDeviceInput getInput(boolean encrypt) { + private static CreateDeviceInput getInput(final boolean encrypt) { CreateDeviceInputBuilder builder = new CreateDeviceInputBuilder(); final Credentials credentials; if (encrypt) { @@ -92,7 +92,7 @@ public class NetconfTopologyRPCProviderTest { builder.setCredentials(credentials); builder.setHost(new Host(new IpAddress(new Ipv4Address("10.18.16.188")))); builder.setPort(new PortNumber(830)); - builder.setTcpOnly(false); + builder.setTcpOnly(Boolean.FALSE); builder.setNodeId(NODE_ID.toString()); return builder.build(); } diff --git a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxyTest.java b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxyTest.java index 534a9520fc..ede1b39313 100644 --- a/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxyTest.java +++ b/netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxyTest.java @@ -18,7 +18,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; public class NodeContainerProxyTest { @@ -27,9 +27,9 @@ public class NodeContainerProxyTest { private static final QName NODE_1_QNAME = QName.create(QNAME, "node-1"); private static final QName NODE_2_QNAME = QName.create(QNAME, "node-2"); @Mock - private AugmentationSchema augSchema1; + private AugmentationSchemaNode augSchema1; @Mock - private AugmentationSchema augSchema2; + private AugmentationSchemaNode augSchema2; @Mock private DataSchemaNode schemaNode1; @Mock @@ -42,7 +42,7 @@ public class NodeContainerProxyTest { final Map childNodes = new HashMap<>(); childNodes.put(NODE_1_QNAME, schemaNode1); childNodes.put(NODE_2_QNAME, schemaNode2); - final Set augmentations = new HashSet<>(); + final Set augmentations = new HashSet<>(); augmentations.add(augSchema1); augmentations.add(augSchema2); proxy = new NodeContainerProxy(QNAME, childNodes, augmentations); @@ -60,7 +60,7 @@ public class NodeContainerProxyTest { @Test public void testGetAvailableAugmentations() throws Exception { - final Set augmentations = proxy.getAvailableAugmentations(); + final Set augmentations = proxy.getAvailableAugmentations(); Assert.assertEquals(2, augmentations.size()); Assert.assertTrue(augmentations.contains(augSchema1)); Assert.assertTrue(augmentations.contains(augSchema2)); @@ -112,11 +112,6 @@ public class NodeContainerProxyTest { proxy.isConfiguration(); } - @Test(expected = UnsupportedOperationException.class) - public void testGetConstraints() throws Exception { - proxy.getConstraints(); - } - @Test(expected = UnsupportedOperationException.class) public void testGetPath() throws Exception { proxy.getPath(); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java index 4e6c2a327a..6ec885d44c 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java @@ -42,10 +42,13 @@ import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public final class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); + private Main() { + + } + @SuppressWarnings("checkstyle:IllegalCatch") public static void main(final String[] args) { final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser()); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/MdsalOperationProvider.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/MdsalOperationProvider.java index 071085ddf8..fd5c689469 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/MdsalOperationProvider.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/MdsalOperationProvider.java @@ -69,7 +69,7 @@ class MdsalOperationProvider implements NetconfOperationServiceFactory { private final Set caps; private final SchemaContext schemaContext; - private SchemaSourceProvider sourceProvider; + private final SchemaSourceProvider sourceProvider; MdsalOperationProvider(final SessionIdProvider idProvider, final Set caps, @@ -87,17 +87,14 @@ class MdsalOperationProvider implements NetconfOperationServiceFactory { @Override public AutoCloseable registerCapabilityListener( - CapabilityListener listener) { + final CapabilityListener listener) { listener.onCapabilitiesChanged(caps, Collections.emptySet()); - return new AutoCloseable() { - @Override - public void close() throws Exception { - } + return () -> { }; } @Override - public NetconfOperationService createService(String netconfSessionIdForReporting) { + public NetconfOperationService createService(final String netconfSessionIdForReporting) { return new MdsalOperationService(Long.parseLong(netconfSessionIdForReporting), schemaContext, caps, sourceProvider); } @@ -108,7 +105,7 @@ class MdsalOperationProvider implements NetconfOperationServiceFactory { private final Set caps; private final SchemaService schemaService; private final DOMDataBroker dataBroker; - private SchemaSourceProvider sourceProvider; + private final SchemaSourceProvider sourceProvider; MdsalOperationService(final long currentSessionId, final SchemaContext schemaContext, @@ -207,11 +204,11 @@ class MdsalOperationProvider implements NetconfOperationServiceFactory { ContainerNode schemasContainer = Builders.containerBuilder().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(Schemas.QNAME)).withChild(schemaList).build(); - return (ContainerNode) Builders.containerBuilder().withNodeIdentifier( + return Builders.containerBuilder().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(NetconfState.QNAME)).withChild(schemasContainer).build(); } - private DOMDataBroker createDataStore(SchemaService schemaService, long sessionId) { + private static DOMDataBroker createDataStore(final SchemaService schemaService, final long sessionId) { LOG.debug("Session {}: Creating data stores for simulated device", sessionId); final DOMStore operStore = InMemoryDOMDataStoreFactory .create("DOM-OPER", schemaService); @@ -219,7 +216,7 @@ class MdsalOperationProvider implements NetconfOperationServiceFactory { .create("DOM-CFG", schemaService); ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool( - 16, 16, "CommitFutures"); + 16, 16, "CommitFutures", MdsalOperationProvider.class); final EnumMap datastores = new EnumMap<>(LogicalDatastoreType.class); datastores.put(LogicalDatastoreType.CONFIGURATION, configStore); @@ -232,11 +229,11 @@ class MdsalOperationProvider implements NetconfOperationServiceFactory { return new SchemaService() { @Override - public void addModule(Module module) { + public void addModule(final Module module) { } @Override - public void removeModule(Module module) { + public void removeModule(final Module module) { } diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java index e9ab199009..42b162b2de 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java @@ -8,12 +8,11 @@ package org.opendaylight.netconf.test.tool; -import com.google.common.base.MoreObjects; +import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.base.Optional; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.channel.Channel; @@ -36,8 +35,9 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import org.apache.sshd.common.util.ThreadUtils; -import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.common.keyprovider.KeyPairProvider; +import org.apache.sshd.common.util.security.SecurityUtils; +import org.apache.sshd.common.util.threads.ThreadUtils; import org.opendaylight.controller.config.util.capability.BasicCapability; import org.opendaylight.controller.config.util.capability.Capability; import org.opendaylight.controller.config.util.capability.YangModuleCapability; @@ -58,12 +58,10 @@ import org.opendaylight.netconf.test.tool.operations.DefaultOperationsCreator; import org.opendaylight.netconf.test.tool.operations.OperationsProvider; import org.opendaylight.netconf.test.tool.rpchandler.SettableOperationRpcProvider; import org.opendaylight.netconf.test.tool.schemacache.SchemaSourceCache; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; @@ -73,7 +71,7 @@ import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache; import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository; -import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -92,7 +90,7 @@ public class NetconfDeviceSimulator implements Closeable { private boolean sendFakeSchema = false; - public NetconfDeviceSimulator(Configuration configuration) { + public NetconfDeviceSimulator(final Configuration configuration) { this.configuration = configuration; this.nettyThreadgroup = new NioEventLoopGroup(); this.hashedWheelTimer = new HashedWheelTimer(); @@ -189,7 +187,7 @@ public class NetconfDeviceSimulator implements Closeable { final List openDevices = Lists.newArrayList(); // Generate key to temp folder - final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider(); + final KeyPairProvider keyPairProvider = getPemGeneratorHostKeyProvider(); for (int i = 0; i < configuration.getDeviceCount(); i++) { if (currentPort > 65535) { @@ -268,7 +266,7 @@ public class NetconfDeviceSimulator implements Closeable { } private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, - final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException { + final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) throws IOException { return new SshProxyServerConfigurationBuilder() .setBindingAddress(bindingAddress) .setLocalAddress(tcpLocalAddress) @@ -279,10 +277,10 @@ public class NetconfDeviceSimulator implements Closeable { .createSshProxyServerConfiguration(); } - private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() { + private static KeyPairProvider getPemGeneratorHostKeyProvider() { try { final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix"); - return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString(), "RSA", 4096); + return SecurityUtils.createGeneratorHostKeyProvider(tempFile.toAbsolutePath()); } catch (final IOException e) { LOG.error("Unable to generate PEM key", e); throw new RuntimeException(e); @@ -322,16 +320,16 @@ public class NetconfDeviceSimulator implements Closeable { } configuration.getDefaultYangResources().forEach(r -> { - SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create(r.getModuleName(), r.getRevision()); + SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create(r.getModuleName(), + Revision.ofNullable(r.getRevision())); registerSource(consumer, r.getResourcePath(), sourceIdentifier); }); try { //necessary for creating mdsal data stores and operations - this.schemaContext = consumer.createSchemaContextFactory( - SchemaSourceFilter.ALWAYS_ACCEPT) - .createSchemaContext(loadedSources).checkedGet(); - } catch (final SchemaResolutionException e) { + this.schemaContext = consumer.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT) + .createSchemaContext(loadedSources).get(); + } catch (final InterruptedException | ExecutionException e) { throw new RuntimeException("Cannot parse schema context", e); } @@ -346,43 +344,35 @@ public class NetconfDeviceSimulator implements Closeable { return capabilities; } - private void addModuleCapability(final SharedSchemaRepository consumer, final Set capabilities, + private static void addModuleCapability(final SharedSchemaRepository consumer, final Set capabilities, final Module module) { - final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(), - (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() : - Optional.of(module.getQNameModule().getFormattedRevision()))); + final SourceIdentifier moduleSourceIdentifier = RevisionSourceIdentifier.create(module.getName(), + module.getRevision()); try { final String moduleContent = new String( - consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).checkedGet().read()); + consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).get().read()); capabilities.add(new YangModuleCapability(module, moduleContent)); //IOException would be thrown in creating SchemaContext already - } catch (SchemaSourceException | IOException e) { + } catch (ExecutionException | InterruptedException | IOException e) { throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e); } } - private void registerSource(final SharedSchemaRepository consumer, final String resource, + private static void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) { - consumer.registerSchemaSource(new SchemaSourceProvider() { + consumer.registerSchemaSource(sourceIdentifier -> Futures.immediateFuture(new YangTextSchemaSource(sourceId) { @Override - public CheckedFuture getSource( - final SourceIdentifier sourceIdentifier) { - return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) { - @Override - protected MoreObjects.ToStringHelper addToStringAttributes( - final MoreObjects.ToStringHelper toStringHelper) { - return toStringHelper; - } + protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) { + return toStringHelper; + } - @Override - public InputStream openStream() throws IOException { - return getClass().getResourceAsStream(resource); - } - }); + @Override + public InputStream openStream() throws IOException { + return getClass().getResourceAsStream(resource); } - }, PotentialSchemaSource.create( - sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue())); + }), PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, + PotentialSchemaSource.Costs.IMMEDIATE.getValue())); } private static InetSocketAddress getAddress(final String ip, final int port) { @@ -396,7 +386,11 @@ public class NetconfDeviceSimulator implements Closeable { @Override public void close() { for (final SshProxyServer sshWrapper : sshWrappers) { - sshWrapper.close(); + try { + sshWrapper.close(); + } catch (IOException e) { + LOG.debug("Wrapper {} failed to close", sshWrapper, e); + } } for (final Channel deviceCh : devicesChannels) { deviceCh.close(); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TestToolUtils.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TestToolUtils.java index 15fd535de8..6e474c5e9f 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TestToolUtils.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TestToolUtils.java @@ -11,6 +11,9 @@ package org.opendaylight.netconf.test.tool; import java.io.InputStream; public final class TestToolUtils { + private TestToolUtils() { + + } public static String getMac(long mac) { final StringBuilder builder = new StringBuilder(Long.toString(mac, 16)); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java index 775aa7670b..dde89e478c 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java @@ -349,7 +349,7 @@ public class TesttoolParameters { editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); } } catch (final IOException e) { - throw new IllegalArgumentException("Cannot read content of " + editContent); + throw new IllegalArgumentException("Cannot read content of " + editContent, e); } int from; diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java index 97b19f909e..334556704b 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java @@ -25,7 +25,7 @@ import org.opendaylight.netconf.test.tool.TestToolUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RestPerfClient { +public final class RestPerfClient { private static final Logger LOG = LoggerFactory.getLogger(RestPerfClient.class); @@ -63,6 +63,10 @@ public class RestPerfClient { } } + private RestPerfClient() { + + } + public static void main(String[] args) throws IOException { Parameters parameters = parseArgs(args, Parameters.getParser()); @@ -77,7 +81,7 @@ public class RestPerfClient { try { editContentString = Files.toString(parameters.editContent, StandardCharsets.UTF_8); } catch (final IOException e) { - throw new IllegalArgumentException("Cannot read content of " + parameters.editContent); + throw new IllegalArgumentException("Cannot read content of " + parameters.editContent, e); } final int threadAmount = parameters.threadAmount; diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/ConfigurableClientDispatcher.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/ConfigurableClientDispatcher.java index ab10fca2d0..2b1279b543 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/ConfigurableClientDispatcher.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/ConfigurableClientDispatcher.java @@ -15,7 +15,7 @@ import org.opendaylight.netconf.client.NetconfClientDispatcherImpl; import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory; import org.opendaylight.netconf.client.conf.NetconfClientConfiguration; -public class ConfigurableClientDispatcher extends NetconfClientDispatcherImpl { +public final class ConfigurableClientDispatcher extends NetconfClientDispatcherImpl { private final Set capabilities; diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java index 7d1fbcb761..90728207b0 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java @@ -101,6 +101,10 @@ public final class StressClient { private static Parameters params; + private StressClient() { + + } + public static void main(final String[] args) { params = parseArgs(args, Parameters.getParser()); @@ -134,7 +138,7 @@ public final class StressClient { try { editContentString = Files.toString(params.editContent, StandardCharsets.UTF_8); } catch (final IOException e) { - throw new IllegalArgumentException("Cannot read content of " + params.editContent); + throw new IllegalArgumentException("Cannot read content of " + params.editContent, e); } for (int i = 0; i < threadAmount; i++) { @@ -152,7 +156,7 @@ public final class StressClient { final NioEventLoopGroup nioGroup = new NioEventLoopGroup(); final Timer timer = new HashedWheelTimer(); - final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer); + final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(nioGroup, timer); final List callables = new ArrayList<>(threadAmount); for (final List messages : allPreparedMessages) { @@ -224,8 +228,8 @@ public final class StressClient { return netconfMessage; } - private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params, - final NioEventLoopGroup nioGroup, final Timer timer) { + private static NetconfClientDispatcherImpl configureClientDispatcher(final NioEventLoopGroup nioGroup, + final Timer timer) { final NetconfClientDispatcherImpl netconfClientDispatcher; if (params.exi) { if (params.legacyFraming) { diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/Configuration.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/Configuration.java index 342d9b2ca2..418329a4b1 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/Configuration.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/Configuration.java @@ -12,8 +12,7 @@ import java.io.File; import java.security.PublicKey; import java.util.Set; import java.util.concurrent.TimeUnit; - -import org.apache.sshd.server.PublickeyAuthenticator; +import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.opendaylight.netconf.api.xml.XmlNetconfConstants; import org.opendaylight.netconf.auth.AuthProvider; @@ -49,17 +48,14 @@ public class Configuration { "/META-INF/yang/ietf-inet-types@2013-07-15.yang") ); - public static final AuthProvider DEFAULT_AUTH_PROVIDER = new AuthProvider() { - @Override - public boolean authenticated(String username, String password) { - LOG.info("Auth with username and password: {}", username); - return true; - } + public static final AuthProvider DEFAULT_AUTH_PROVIDER = (username, password) -> { + LOG.info("Auth with username and password: {}", username); + return true; }; public static final PublickeyAuthenticator DEFAULT_PUBLIC_KEY_AUTHENTICATOR = new PublickeyAuthenticator() { @Override - public boolean authenticate(String username, PublicKey key, ServerSession session) { + public boolean authenticate(final String username, final PublicKey key, final ServerSession session) { LOG.info("Auth with public key: {}", key); return true; } @@ -102,7 +98,7 @@ public class Configuration { return publickeyAuthenticator; } - public void setPublickeyAuthenticator(PublickeyAuthenticator publickeyAuthenticator) { + public void setPublickeyAuthenticator(final PublickeyAuthenticator publickeyAuthenticator) { this.publickeyAuthenticator = publickeyAuthenticator; } @@ -110,7 +106,7 @@ public class Configuration { return authProvider; } - public void setAuthProvider(AuthProvider authProvider) { + public void setAuthProvider(final AuthProvider authProvider) { this.authProvider = authProvider; } @@ -118,7 +114,7 @@ public class Configuration { return defaultYangResources; } - public void setDefaultYangResources(Set defaultYangResources) { + public void setDefaultYangResources(final Set defaultYangResources) { this.defaultYangResources = defaultYangResources; } @@ -126,7 +122,7 @@ public class Configuration { return threadPoolSize; } - public void setThreadPoolSize(int threadPoolSize) { + public void setThreadPoolSize(final int threadPoolSize) { this.threadPoolSize = threadPoolSize; } @@ -134,7 +130,7 @@ public class Configuration { return startingPort; } - public void setStartingPort(int startingPort) { + public void setStartingPort(final int startingPort) { this.startingPort = startingPort; } @@ -142,7 +138,7 @@ public class Configuration { return deviceCount; } - public void setDeviceCount(int deviceCount) { + public void setDeviceCount(final int deviceCount) { this.deviceCount = deviceCount; } @@ -150,7 +146,7 @@ public class Configuration { return generateConfigsTimeout; } - public void setGenerateConfigsTimeout(int generateConfigsTimeout) { + public void setGenerateConfigsTimeout(final int generateConfigsTimeout) { this.generateConfigsTimeout = generateConfigsTimeout; } @@ -158,7 +154,7 @@ public class Configuration { return ssh; } - public void setSsh(boolean ssh) { + public void setSsh(final boolean ssh) { this.ssh = ssh; } @@ -166,7 +162,7 @@ public class Configuration { return ip; } - public void setIp(String ip) { + public void setIp(final String ip) { this.ip = ip; } @@ -174,7 +170,7 @@ public class Configuration { return models; } - public void setModels(Set models) { + public void setModels(final Set models) { this.models = models; } @@ -182,7 +178,7 @@ public class Configuration { return capabilities; } - public void setCapabilities(Set capabilities) { + public void setCapabilities(final Set capabilities) { this.capabilities = capabilities; } @@ -190,7 +186,7 @@ public class Configuration { return rpcHandler; } - public void setRpcHandler(RpcHandler rpcHandler) { + public void setRpcHandler(final RpcHandler rpcHandler) { this.rpcHandler = rpcHandler; } @@ -198,7 +194,7 @@ public class Configuration { return operationsCreator; } - public void setOperationsCreator(OperationsCreator operationsCreator) { + public void setOperationsCreator(final OperationsCreator operationsCreator) { this.operationsCreator = operationsCreator; } @@ -208,7 +204,7 @@ public class Configuration { } @Deprecated - public void setMdSal(boolean mdSal) { + public void setMdSal(final boolean mdSal) { this.mdSal = mdSal; } @@ -218,7 +214,7 @@ public class Configuration { } @Deprecated - public void setRpcConfigFile(File rpcConfigFile) { + public void setRpcConfigFile(final File rpcConfigFile) { this.rpcConfigFile = rpcConfigFile; } @@ -228,7 +224,7 @@ public class Configuration { } @Deprecated - public void setNotificationFile(File notificationFile) { + public void setNotificationFile(final File notificationFile) { this.notificationFile = notificationFile; } @@ -238,7 +234,7 @@ public class Configuration { } @Deprecated - public void setInitialConfigXMLFile(File initialConfigXMLFile) { + public void setInitialConfigXMLFile(final File initialConfigXMLFile) { this.initialConfigXMLFile = initialConfigXMLFile; } @@ -253,7 +249,7 @@ public class Configuration { } @Deprecated - public void setSchemasDir(File schemasDir) { + public void setSchemasDir(final File schemasDir) { this.schemasDir = schemasDir; } } diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/ConfigurationBuilder.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/ConfigurationBuilder.java index 8c1be77c94..d9be6adb2f 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/ConfigurationBuilder.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/ConfigurationBuilder.java @@ -9,8 +9,7 @@ package org.opendaylight.netconf.test.tool.config; import java.io.File; import java.util.Set; - -import org.apache.sshd.server.PublickeyAuthenticator; +import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.opendaylight.netconf.auth.AuthProvider; import org.opendaylight.netconf.test.tool.TesttoolParameters; import org.opendaylight.netconf.test.tool.operations.OperationsCreator; @@ -18,124 +17,124 @@ import org.opendaylight.netconf.test.tool.rpchandler.RpcHandler; public class ConfigurationBuilder { - private Configuration configuration; + private final Configuration configuration; public ConfigurationBuilder() { this.configuration = new Configuration(); } - public ConfigurationBuilder setPublickeyAuthenticator(PublickeyAuthenticator publickeyAuthenticator) { + public ConfigurationBuilder setPublickeyAuthenticator(final PublickeyAuthenticator publickeyAuthenticator) { this.configuration.setPublickeyAuthenticator(publickeyAuthenticator); return this; } - public ConfigurationBuilder setAuthProvider(AuthProvider authProvider) { + public ConfigurationBuilder setAuthProvider(final AuthProvider authProvider) { this.configuration.setAuthProvider(authProvider); return this; } - public ConfigurationBuilder setGetDefaultYangResources(Set defaultYangResources) { + public ConfigurationBuilder setGetDefaultYangResources(final Set defaultYangResources) { this.configuration.setDefaultYangResources(defaultYangResources); return this; } - public ConfigurationBuilder setThreadPoolSize(int threadPoolSize) { + public ConfigurationBuilder setThreadPoolSize(final int threadPoolSize) { this.configuration.setThreadPoolSize(threadPoolSize); return this; } - public ConfigurationBuilder setGenerateConfigsTimeout(int generateConfigsTimeout) { + public ConfigurationBuilder setGenerateConfigsTimeout(final int generateConfigsTimeout) { this.configuration.setGenerateConfigsTimeout(generateConfigsTimeout); return this; } - public ConfigurationBuilder setModels(Set models) { + public ConfigurationBuilder setModels(final Set models) { this.configuration.setModels(models); return this; } - public ConfigurationBuilder setCapabilities(Set capabilities) { + public ConfigurationBuilder setCapabilities(final Set capabilities) { this.configuration.setCapabilities(capabilities); return this; } - public ConfigurationBuilder setStartingPort(int startingPort) { + public ConfigurationBuilder setStartingPort(final int startingPort) { this.configuration.setStartingPort(startingPort); return this; } - public ConfigurationBuilder setDeviceCount(int deviceCount) { + public ConfigurationBuilder setDeviceCount(final int deviceCount) { this.configuration.setDeviceCount(deviceCount); return this; } - public ConfigurationBuilder setSsh(boolean ssh) { + public ConfigurationBuilder setSsh(final boolean ssh) { this.configuration.setSsh(ssh); return this; } - public ConfigurationBuilder setIp(String ip) { + public ConfigurationBuilder setIp(final String ip) { this.configuration.setIp(ip); return this; } - public ConfigurationBuilder setRpcMapping(RpcHandler rpcHandler) { + public ConfigurationBuilder setRpcMapping(final RpcHandler rpcHandler) { this.configuration.setRpcHandler(rpcHandler); return this; } @Deprecated - public ConfigurationBuilder setMdSal(boolean mdSal) { + public ConfigurationBuilder setMdSal(final boolean mdSal) { this.configuration.setMdSal(mdSal); return this; } @Deprecated - public ConfigurationBuilder setRpcConfigFile(File rpcConfigFile) { + public ConfigurationBuilder setRpcConfigFile(final File rpcConfigFile) { this.configuration.setRpcConfigFile(rpcConfigFile); return this; } @Deprecated - public ConfigurationBuilder setInitialConfigXMLFile(File initialConfigXMLFile) { + public ConfigurationBuilder setInitialConfigXMLFile(final File initialConfigXMLFile) { this.configuration.setInitialConfigXMLFile(initialConfigXMLFile); return this; } @Deprecated - public ConfigurationBuilder setNotificationFile(File notificationFile) { + public ConfigurationBuilder setNotificationFile(final File notificationFile) { this.configuration.setNotificationFile(notificationFile); return this; } - public ConfigurationBuilder setOperationsCreator(OperationsCreator operationsCreator) { + public ConfigurationBuilder setOperationsCreator(final OperationsCreator operationsCreator) { this.configuration.setOperationsCreator(operationsCreator); return this; } - public ConfigurationBuilder from(Configuration configuration) { - this.configuration.setThreadPoolSize(configuration.getThreadPoolSize()); - this.configuration.setGenerateConfigsTimeout(configuration.getGenerateConfigsTimeout()); - this.configuration.setModels(configuration.getModels()); - this.configuration.setCapabilities(configuration.getCapabilities()); - this.configuration.setStartingPort(configuration.getStartingPort()); - this.configuration.setDeviceCount(configuration.getDeviceCount()); - this.configuration.setSsh(configuration.isSsh()); - this.configuration.setIp(configuration.getIp()); - this.configuration.setRpcHandler(configuration.getRpcHandler()); - this.configuration.setOperationsCreator(configuration.getOperationsCreator()); - this.configuration.setMdSal(configuration.isMdSal()); - this.configuration.setRpcConfigFile(configuration.getRpcConfigFile()); - this.configuration.setInitialConfigXMLFile(configuration.getInitialConfigXMLFile()); - this.configuration.setNotificationFile(configuration.getNotificationFile()); - this.configuration.setSchemasDir(configuration.getSchemasDir()); - this.configuration.setDefaultYangResources(configuration.getDefaultYangResources()); - this.configuration.setAuthProvider(configuration.getAuthProvider()); - this.configuration.setPublickeyAuthenticator(configuration.getPublickeyAuthenticator()); + public ConfigurationBuilder from(final Configuration template) { + this.configuration.setThreadPoolSize(template.getThreadPoolSize()); + this.configuration.setGenerateConfigsTimeout(template.getGenerateConfigsTimeout()); + this.configuration.setModels(template.getModels()); + this.configuration.setCapabilities(template.getCapabilities()); + this.configuration.setStartingPort(template.getStartingPort()); + this.configuration.setDeviceCount(template.getDeviceCount()); + this.configuration.setSsh(template.isSsh()); + this.configuration.setIp(template.getIp()); + this.configuration.setRpcHandler(template.getRpcHandler()); + this.configuration.setOperationsCreator(template.getOperationsCreator()); + this.configuration.setMdSal(template.isMdSal()); + this.configuration.setRpcConfigFile(template.getRpcConfigFile()); + this.configuration.setInitialConfigXMLFile(template.getInitialConfigXMLFile()); + this.configuration.setNotificationFile(template.getNotificationFile()); + this.configuration.setSchemasDir(template.getSchemasDir()); + this.configuration.setDefaultYangResources(template.getDefaultYangResources()); + this.configuration.setAuthProvider(template.getAuthProvider()); + this.configuration.setPublickeyAuthenticator(template.getPublickeyAuthenticator()); return this; } - public ConfigurationBuilder from(TesttoolParameters testtoolParameters) { + public ConfigurationBuilder from(final TesttoolParameters testtoolParameters) { this.configuration.setGenerateConfigsTimeout(testtoolParameters.generateConfigsTimeout); this.configuration.setStartingPort(testtoolParameters.startingPort); this.configuration.setDeviceCount(testtoolParameters.deviceCount); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java index 2edab7e0a7..a1faa44950 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java @@ -76,7 +76,7 @@ class RpcMapping { private final XmlElement xmlElement; private final int hashCode; - private Request(final XmlElement element) { + Request(final XmlElement element) { this.xmlElement = element; hashCode = XmlUtil.toString(element) .replaceAll("message-id=.*(>| )", "") //message id is variable, remove it diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableOperationProvider.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableOperationProvider.java index d811fe70f4..d0e19cef97 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableOperationProvider.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableOperationProvider.java @@ -46,7 +46,7 @@ public class SettableOperationProvider implements NetconfOperationServiceFactory private final SettableRpc rpc; - private SettableOperationService(final File rpcConfig) { + SettableOperationService(final File rpcConfig) { this.rpc = new SettableRpc(rpcConfig); } diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableRpc.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableRpc.java index fddc0be003..49a60da37f 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableRpc.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/SettableRpc.java @@ -58,7 +58,7 @@ class SettableRpc implements NetconfOperation { } } - private void checkForError(final Document document) throws DocumentedException { + private static void checkForError(final Document document) throws DocumentedException { final XmlElement rpcReply = XmlElement.fromDomDocument(document); if (rpcReply.getOnlyChildElementOptionally("rpc-error").isPresent()) { throw DocumentedException.fromXMLDocument(document); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/operations/DefaultOperationsCreator.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/operations/DefaultOperationsCreator.java index 21e2b59169..d528df5b51 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/operations/DefaultOperationsCreator.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/operations/DefaultOperationsCreator.java @@ -25,7 +25,7 @@ import org.opendaylight.netconf.test.tool.rpc.SimulatedGetConfig; import org.opendaylight.netconf.test.tool.rpc.SimulatedLock; import org.opendaylight.netconf.test.tool.rpc.SimulatedUnLock; -public class DefaultOperationsCreator implements OperationsCreator { +public final class DefaultOperationsCreator implements OperationsCreator { private final SimulatedOperationService simulatedOperationService; diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedCreateSubscription.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedCreateSubscription.java index 9ec5795de2..682723af17 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedCreateSubscription.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedCreateSubscription.java @@ -46,19 +46,19 @@ public class SimulatedCreateSubscription extends AbstractLastNetconfOperation im public SimulatedCreateSubscription(final String id, final Optional notificationsFile) { super(id); - Optional notifications; + Optional notifs; if (notificationsFile.isPresent()) { - notifications = Optional.of(loadNotifications(notificationsFile.get())); + notifs = Optional.of(loadNotifications(notificationsFile.get())); scheduledExecutorService = Executors.newScheduledThreadPool(1); } else { - notifications = Optional.absent(); + notifs = Optional.absent(); } - if (notifications.isPresent()) { + if (notifs.isPresent()) { Map preparedMessages = Maps.newHashMapWithExpectedSize( - notifications.get().getNotificationList().size()); - for (final Notification notification : notifications.get().getNotificationList()) { + notifs.get().getNotificationList().size()); + for (final Notification notification : notifs.get().getNotificationList()) { final NetconfMessage parsedNotification = parseNetconfNotification(notification.getContent()); preparedMessages.put(notification, parsedNotification); } @@ -69,7 +69,7 @@ public class SimulatedCreateSubscription extends AbstractLastNetconfOperation im } - private Notifications loadNotifications(final File file) { + private static Notifications loadNotifications(final File file) { try { final JAXBContext jaxbContext = JAXBContext.newInstance(Notifications.class); final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); @@ -99,12 +99,9 @@ public class SimulatedCreateSubscription extends AbstractLastNetconfOperation im delayAggregator += notification.getKey().getDelayInSeconds(); - scheduledExecutorService.schedule(new Runnable() { - @Override - public void run() { - Preconditions.checkState(session != null, "Session is not set, cannot process notifications"); - session.sendMessage(notification.getValue()); - } + scheduledExecutorService.schedule(() -> { + Preconditions.checkState(session != null, "Session is not set, cannot process notifications"); + session.sendMessage(notification.getValue()); }, delayAggregator, TimeUnit.SECONDS); } } @@ -127,8 +124,8 @@ public class SimulatedCreateSubscription extends AbstractLastNetconfOperation im } @Override - public void setNetconfSession(final NetconfServerSession session) { - this.session = session; + public void setNetconfSession(final NetconfServerSession newSession) { + this.session = newSession; } @XmlRootElement(name = "notifications") diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java index e6db368b92..f139a9000d 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java @@ -43,7 +43,7 @@ public class SimulatedGetConfig extends AbstractConfigNetconfOperation { } } - private DataList loadInitialConfigXMLFile(final File file) { + private static DataList loadInitialConfigXMLFile(final File file) { LOG.info("Loading initial config xml file: {}", file.getName()); DataList configData = new DataList(); List xmlElementList = Collections.emptyList(); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableOperationRpcProvider.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableOperationRpcProvider.java index 66199d984c..ed36c44398 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableOperationRpcProvider.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableOperationRpcProvider.java @@ -45,7 +45,7 @@ public class SettableOperationRpcProvider implements NetconfOperationServiceFact private final SettableRpc rpc; - private SettableOperationService(RpcHandler rpcHandler) { + SettableOperationService(RpcHandler rpcHandler) { this.rpc = new SettableRpc(rpcHandler); } diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableRpc.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableRpc.java index 1f2b97df62..a85136564a 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableRpc.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpchandler/SettableRpc.java @@ -27,7 +27,7 @@ class SettableRpc implements NetconfOperation { private final RpcHandler rpcHandler; - SettableRpc(RpcHandler rpcHandler) { + SettableRpc(final RpcHandler rpcHandler) { this.rpcHandler = rpcHandler; } @@ -57,7 +57,7 @@ class SettableRpc implements NetconfOperation { } } - private void checkForError(final Document document) throws DocumentedException { + private static void checkForError(final Document document) throws DocumentedException { final XmlElement rpcReply = XmlElement.fromDomDocument(document); if (rpcReply.getOnlyChildElementOptionally("rpc-error").isPresent()) { throw DocumentedException.fromXMLDocument(document); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/schemacache/SchemaSourceCache.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/schemacache/SchemaSourceCache.java index 9ece5a910b..51f80848bd 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/schemacache/SchemaSourceCache.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/schemacache/SchemaSourceCache.java @@ -8,21 +8,21 @@ package org.opendaylight.netconf.test.tool.schemacache; import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.opendaylight.netconf.test.tool.TestToolUtils; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; @@ -40,9 +40,8 @@ public final class SchemaSourceCache private static final Logger LOG = LoggerFactory.getLogger(SchemaSourceCache.class); - public static final Pattern CACHED_FILE_PATTERN = - Pattern.compile( - ".*/(?[^@]+)" + "(@(?" + SourceIdentifier.REVISION_PATTERN + "))?.yang"); + public static final Pattern CACHED_FILE_PATTERN = Pattern.compile( + ".*/(?[^@]+)" + "(@(?" + Revision.STRING_FORMAT_PATTERN + "))?.yang"); private final Class representation; private final Set modelList; @@ -77,17 +76,15 @@ public final class SchemaSourceCache } @Override - public synchronized CheckedFuture getSource( - final SourceIdentifier sourceIdentifier) { + public synchronized ListenableFuture getSource(final SourceIdentifier sourceIdentifier) { ModelData modelData = cachedSchemas.get(sourceIdentifier.toYangFilename()); if (modelData != null) { final SchemaSourceRepresentation restored = restoreAsType(modelData.getId(), modelData.getPath()); - return Futures.immediateCheckedFuture(representation.cast(restored)); - } else { - LOG.debug("Source {} not found in cache as {}", sourceIdentifier); - return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("Source not found", - sourceIdentifier)); + return Futures.immediateFuture(representation.cast(restored)); } + + LOG.debug("Source {} not found in cache as {}", sourceIdentifier); + return Futures.immediateFailedFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier)); } @Override @@ -95,7 +92,8 @@ public final class SchemaSourceCache LOG.trace("Source {} offered to cache", source.getIdentifier()); } - private YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final String cachedSource) { + private static YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, + final String cachedSource) { return new YangTextSchemaSource(sourceIdentifier) { @Override @@ -114,10 +112,9 @@ public final class SchemaSourceCache final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName); if (matcher.matches()) { final String moduleName = matcher.group("moduleName"); - final String revision = matcher.group("revision"); - return Optional.of(RevisionSourceIdentifier.create(moduleName, Optional.fromNullable(revision))); + final Optional revision = Revision.ofNullable(matcher.group("revision")); + return Optional.of(RevisionSourceIdentifier.create(moduleName, revision)); } - return Optional.absent(); + return Optional.empty(); } - } diff --git a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java index df88860c1f..ba7e22a025 100644 --- a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java +++ b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java @@ -5,7 +5,6 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ - package org.opendaylight.yanglib.impl; import com.google.common.base.Preconditions; @@ -33,6 +32,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.librar import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; @@ -47,7 +47,6 @@ import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * Listens on new schema sources registered event. For each new source * registered generates URL representing its schema source and write this URL @@ -186,14 +185,12 @@ public class YangLibProvider implements AutoCloseable, SchemaSourceListener { } private static String revString(final SourceIdentifier id) { - final String rev = id.getRevision(); - return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? "" : rev; + return id.getRevision().map(Revision::toString).orElse(""); } private static OptionalRevision getRevisionForModule(final SourceIdentifier sourceIdentifier) { - final String rev = sourceIdentifier.getRevision(); - return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? NO_REVISION - : new OptionalRevision(new RevisionIdentifier(rev)); + return sourceIdentifier.getRevision().map(rev -> new OptionalRevision(new RevisionIdentifier(rev.toString()))) + .orElse(NO_REVISION); } private T getObjectFromBundleContext(final Class type, final String serviceRefName) { diff --git a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java index 5f66daea82..e75776f84b 100644 --- a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java +++ b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java @@ -8,15 +8,15 @@ package org.opendaylight.yanglib.impl; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; -import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; +import java.util.concurrent.ExecutionException; import org.opendaylight.yanglib.api.YangLibService; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.slf4j.Logger; @@ -43,17 +43,17 @@ public class YangLibServiceImpl implements YangLibService { public String getSchema(final String name, final String revision) { Preconditions.checkNotNull(schemaRepository, "Schema repository is not initialized"); LOG.debug("Attempting load for schema source {}:{}", name, revision); - final SourceIdentifier sourceId = - RevisionSourceIdentifier.create(name, Optional.fromNullable(revision.equals("") ? null : revision)); + final SourceIdentifier sourceId = RevisionSourceIdentifier.create(name, + revision.isEmpty() ? null : Revision.of(revision)); - final CheckedFuture sourceFuture = - schemaRepository.getSchemaSource(sourceId, YangTextSchemaSource.class); + final ListenableFuture sourceFuture = schemaRepository.getSchemaSource(sourceId, + YangTextSchemaSource.class); try { - final YangTextSchemaSource source = sourceFuture.checkedGet(); + final YangTextSchemaSource source = sourceFuture.get(); return new String(ByteStreams.toByteArray(source.openStream())); - } catch (SchemaSourceException | IOException e) { - throw new IllegalStateException("Unable to get schema" + sourceId, e); + } catch (InterruptedException | ExecutionException | IOException e) { + throw new IllegalStateException("Unable to get schema " + sourceId, e); } } } diff --git a/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibProviderTest.java b/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibProviderTest.java index ab0cb2359c..5372a07260 100644 --- a/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibProviderTest.java +++ b/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibProviderTest.java @@ -45,11 +45,12 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types. import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfigBuilder; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.api.YinSchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource; -import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource; public class YangLibProviderTest { private static final File CACHE_DIR = new File("target/yanglib"); @@ -106,7 +107,7 @@ public class YangLibProviderTest { list.add( PotentialSchemaSource.create( - RevisionSourceIdentifier.create("with-revision", "2016-04-28"), + RevisionSourceIdentifier.create("with-revision", Revision.of("2016-04-28")), YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue())); when(writeTransaction.submit()).thenReturn(Futures.immediateCheckedFuture(null)); @@ -224,7 +225,7 @@ public class YangLibProviderTest { yangUnregistererSource = PotentialSchemaSource.create( - RevisionSourceIdentifier.create("unregistered-yang-with-revision", "2016-04-28"), + RevisionSourceIdentifier.create("unregistered-yang-with-revision", Revision.of("2016-04-28")), YangTextSchemaSource.class, PotentialSchemaSource.Costs.LOCAL_IO.getValue()); yangLibProvider.schemaSourceUnregistered(yangUnregistererSource); diff --git a/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibServiceImplTest.java b/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibServiceImplTest.java index ab1b55210e..4c9338e1e7 100644 --- a/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibServiceImplTest.java +++ b/netconf/yanglib/src/test/java/org/opendaylight/yanglib/impl/YangLibServiceImplTest.java @@ -14,13 +14,14 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import com.google.common.base.MoreObjects; -import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Test; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; @@ -38,11 +39,11 @@ public class YangLibServiceImplTest { final YangLibServiceImpl yangLibService = new YangLibServiceImpl(); yangLibService.setSchemaRepository(schemaRepository); - final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("name", "2016-01-01"); + final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("name", Revision.of("2016-01-01")); final YangTextSchemaSource yangTextSchemaSource = new YangTextSchemaSource(sourceIdentifier) { @Override - protected MoreObjects.ToStringHelper addToStringAttributes(MoreObjects.ToStringHelper toStringHelper) { + protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) { return null; } @@ -52,8 +53,7 @@ public class YangLibServiceImplTest { } }; - final CheckedFuture sourceFuture = - Futures.immediateCheckedFuture(yangTextSchemaSource); + final ListenableFuture sourceFuture = Futures.immediateFuture(yangTextSchemaSource); doReturn(sourceFuture).when(schemaRepository).getSchemaSource(any(SourceIdentifier.class), eq(YangTextSchemaSource.class)); diff --git a/restconf/restconf-common/src/main/java/org/opendaylight/restconf/common/errors/RestconfDocumentedException.java b/restconf/restconf-common/src/main/java/org/opendaylight/restconf/common/errors/RestconfDocumentedException.java index 38a6211749..18519d6e98 100644 --- a/restconf/restconf-common/src/main/java/org/opendaylight/restconf/common/errors/RestconfDocumentedException.java +++ b/restconf/restconf-common/src/main/java/org/opendaylight/restconf/common/errors/RestconfDocumentedException.java @@ -156,7 +156,7 @@ public class RestconfDocumentedException extends WebApplicationException { this.status = status; } - private RestconfDocumentedException(final Throwable cause, final RestconfError error) { + public RestconfDocumentedException(final Throwable cause, final RestconfError error) { super(cause); Preconditions.checkNotNull(error, "RestconfError can't be null"); errors = ImmutableList.of(error); diff --git a/restconf/restconf-common/src/test/java/org/opendaylight/restconf/common/util/RestconfSchemaUtilTest.java b/restconf/restconf-common/src/test/java/org/opendaylight/restconf/common/util/RestconfSchemaUtilTest.java index ddc816d59e..31be076851 100644 --- a/restconf/restconf-common/src/test/java/org/opendaylight/restconf/common/util/RestconfSchemaUtilTest.java +++ b/restconf/restconf-common/src/test/java/org/opendaylight/restconf/common/util/RestconfSchemaUtilTest.java @@ -9,13 +9,11 @@ package org.opendaylight.restconf.common.util; import java.util.ArrayList; -import java.util.Date; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; import org.opendaylight.yangtools.yang.model.api.SchemaNode; /** @@ -47,7 +45,7 @@ public class RestconfSchemaUtilTest { private static SchemaNode mockSchemaNode(final String origKey) { final SchemaNode mockSchNode = Mockito.mock(SchemaNode.class); Mockito.when(mockSchNode.getQName()) - .thenReturn(QName.create("ns", SimpleDateFormatUtil.getRevisionFormat().format(new Date()), origKey)); + .thenReturn(QName.create("ns", "2016-10-10", origKey)); return mockSchNode; } } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaExportContentYangBodyWriter.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaExportContentYangBodyWriter.java index 4826405496..941f3a9d2f 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaExportContentYangBodyWriter.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaExportContentYangBodyWriter.java @@ -11,6 +11,7 @@ import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; +import java.util.concurrent.ExecutionException; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; @@ -19,7 +20,6 @@ import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.opendaylight.restconf.common.schema.SchemaExportContext; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; @Provider @@ -44,11 +44,11 @@ public class SchemaExportContentYangBodyWriter implements MessageBodyWriter httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { final RevisionSourceIdentifier sourceId = RevisionSourceIdentifier.create(context.getModule().getName(), - context.getModule().getQNameModule().getFormattedRevision()); + context.getModule().getQNameModule().getRevision()); final YangTextSchemaSource yangTextSchemaSource; try { - yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).checkedGet(); - } catch (SchemaSourceException e) { + yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).get(); + } catch (InterruptedException | ExecutionException e) { throw new WebApplicationException("Unable to retrieve source from SourceProvider.", e); } yangTextSchemaSource.copyTo(entityStream); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaRetrievalServiceImpl.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaRetrievalServiceImpl.java index 7282d03b1a..45a677df1c 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaRetrievalServiceImpl.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/md/sal/rest/schema/SchemaRetrievalServiceImpl.java @@ -9,8 +9,7 @@ package org.opendaylight.netconf.md.sal.rest.schema; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; -import java.text.ParseException; -import java.util.Date; +import java.time.format.DateTimeParseException; import java.util.Iterator; import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider; import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; @@ -20,7 +19,7 @@ import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag; import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; import org.opendaylight.restconf.common.schema.SchemaExportContext; import org.opendaylight.restconf.common.validation.RestconfValidationUtils; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -76,13 +75,11 @@ public class SchemaRetrievalServiceImpl implements SchemaRetrievalService { final String moduleName, final String revisionStr, final DOMYangTextSourceProvider yangTextSourceProvider) { try { - final Date revision = SimpleDateFormatUtil.getRevisionFormat().parse(revisionStr); - final Module module = schemaContext.findModuleByName(moduleName, revision); - + final Module module = schemaContext.findModule(moduleName, Revision.of(revisionStr)).orElse(null); return new SchemaExportContext( schemaContext, RestconfValidationUtils.checkNotNullDocumented(module, moduleName), yangTextSourceProvider); - } catch (final ParseException e) { + } catch (final DateTimeParseException e) { throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e); } } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriter.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriter.java index 7b088f69e7..9374f13e49 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriter.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriter.java @@ -9,12 +9,12 @@ package org.opendaylight.netconf.sal.rest.impl; import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.io.IOException; import java.util.Collection; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter; import org.opendaylight.yangtools.yang.common.QName; diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/RestconfDelegatingNormalizedNodeWriter.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/RestconfDelegatingNormalizedNodeWriter.java index cfab0111a8..38e3c13000 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/RestconfDelegatingNormalizedNodeWriter.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/RestconfDelegatingNormalizedNodeWriter.java @@ -16,7 +16,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWrit /** * This class just delegates all of the functionality to Yangtools normalized node writer. */ -public class RestconfDelegatingNormalizedNodeWriter implements RestconfNormalizedNodeWriter { +public final class RestconfDelegatingNormalizedNodeWriter implements RestconfNormalizedNodeWriter { private NormalizedNodeWriter delegNNWriter; private RestconfDelegatingNormalizedNodeWriter(NormalizedNodeStreamWriter streamWriter, final boolean diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/StringModuleInstanceIdentifierCodec.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/StringModuleInstanceIdentifierCodec.java index f4833c07c6..ef0c8a3eb5 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/StringModuleInstanceIdentifierCodec.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/StringModuleInstanceIdentifierCodec.java @@ -44,9 +44,9 @@ public final class StringModuleInstanceIdentifierCodec extends AbstractModuleStr @Override protected Module moduleForPrefix(@Nonnull final String prefix) { if (prefix.isEmpty() && !this.defaultPrefix.isEmpty()) { - return this.context.findModuleByName(this.defaultPrefix, null); + return this.context.findModules(this.defaultPrefix).stream().findFirst().orElse(null); } else { - return this.context.findModuleByName(prefix, null); + return this.context.findModules(prefix).stream().findFirst().orElse(null); } } @@ -59,7 +59,6 @@ public final class StringModuleInstanceIdentifierCodec extends AbstractModuleStr @Nullable @Override protected String prefixForNamespace(@Nonnull final URI namespace) { - final Module module = this.context.findModuleByNamespaceAndRevision(namespace, null); - return module == null ? null : module.getName(); + return this.context.findModules(namespace).stream().findFirst().map(Module::getName).orElse(null); } } \ No newline at end of file diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlNormalizedNodeBodyReader.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlNormalizedNodeBodyReader.java index 4c2eae4992..12d933f4b1 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlNormalizedNodeBodyReader.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlNormalizedNodeBodyReader.java @@ -47,9 +47,9 @@ import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter; import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult; import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.AugmentationTarget; -import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; +import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; @@ -134,8 +134,8 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro } while (!foundSchemaNodes.isEmpty()) { final Object child = foundSchemaNodes.pop(); - if (child instanceof AugmentationSchema) { - final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child; + if (child instanceof AugmentationSchemaNode) { + final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child; iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode)); } else if (child instanceof DataSchemaNode) { schemaNode = (DataSchemaNode) child; @@ -205,7 +205,7 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro // find augmentation if (child.isAugmenting()) { - final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child); + final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child); if (augment != null) { result.push(augment); } @@ -217,12 +217,12 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro } for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) { - for (final ChoiceCaseNode caseNode : choiceNode.getCases()) { + for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) { final Deque resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace); if (!resultFromRecursion.isEmpty()) { resultFromRecursion.push(choiceNode); if (choiceNode.isAugmenting()) { - final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode); + final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode); if (augment != null) { resultFromRecursion.push(augment); } @@ -234,10 +234,11 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro return result; } - private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, + private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) { - if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) { - for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) { + if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) { + for (final AugmentationSchemaNode augmentation : + ((AugmentationTarget) parent).getAvailableAugmentations()) { final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName()); if (childInAugmentation != null) { return augmentation; diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlToPatchBodyReader.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlToPatchBodyReader.java index c81c770e8c..fdc2896fb0 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlToPatchBodyReader.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlToPatchBodyReader.java @@ -42,6 +42,7 @@ import org.opendaylight.restconf.common.patch.PatchEntity; import org.opendaylight.restconf.common.util.RestUtil; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; @@ -106,7 +107,7 @@ public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider i LOG.debug("Error parsing xml input", e); throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE); + ErrorTag.MALFORMED_MESSAGE, e); } } @@ -132,8 +133,7 @@ public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider i ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI(); // find module according to namespace - final Module module = pathContext.getSchemaContext().findModuleByNamespace( - URI.create(namespace)).iterator().next(); + final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next(); // initialize codec + set default prefix derived from module name final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec( @@ -149,7 +149,8 @@ public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider i } else { targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier()) .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement, - namespace, module.getQNameModule().getFormattedRevision()))); + namespace, + module.getQNameModule().getRevision().map(Revision::toString).orElse(null)))); targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(), codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent()); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java index 3b460fdfa1..1e3379cabc 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java @@ -97,14 +97,16 @@ public class BrokerFacade { private DOMDataBroker domDataBroker; private DOMNotificationService domNotification; - private BrokerFacade() {} + BrokerFacade() { + + } public void setRpcService(final DOMRpcService router) { this.rpcService = router; } - public void setDomNotificationService(final DOMNotificationService domNotification) { - this.domNotification = domNotification; + public void setDomNotificationService(final DOMNotificationService service) { + this.domNotification = service; } public static BrokerFacade getInstance() { @@ -563,7 +565,7 @@ public class BrokerFacade { throw new RestconfDocumentedException( error.getMessage(), ErrorType.TRANSPORT, - ErrorTag.RESOURCE_DENIED_TRANSPORT); + ErrorTag.RESOURCE_DENIED_TRANSPORT, e); } } throw new RestconfDocumentedException("Error reading data.", e, e.getErrorList()); @@ -620,8 +622,8 @@ public class BrokerFacade { ((ListSchemaNode) childSchema).getKeyDefinition()); builder.withChild(childBuilder.build()); } else if (child instanceof LeafNode) { - final String defaultVal = ((LeafSchemaNode) childSchema).getDefault(); - final String nodeVal = ((LeafNode) child).getValue(); + final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null); + final Object nodeVal = ((LeafNode) child).getValue(); final NormalizedNodeAttrBuilder> leafBuilder = Builders.leafBuilder((LeafSchemaNode) childSchema); if (keys.contains(child.getNodeType())) { @@ -675,8 +677,8 @@ public class BrokerFacade { ((ListSchemaNode) childSchema).getKeyDefinition()); builder.withChild(childBuilder.build()); } else if (child instanceof LeafNode) { - final String defaultVal = ((LeafSchemaNode) childSchema).getDefault(); - final String nodeVal = ((LeafNode) child).getValue(); + final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null); + final Object nodeVal = ((LeafNode) child).getValue(); final NormalizedNodeAttrBuilder> leafBuilder = Builders.leafBuilder((LeafSchemaNode) childSchema); if (trim) { diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/ControllerContext.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/ControllerContext.java index a99495cc05..0707231f7b 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/ControllerContext.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/ControllerContext.java @@ -23,8 +23,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -36,6 +36,7 @@ import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider; +import org.opendaylight.netconf.sal.rest.api.Draft02; import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule; import org.opendaylight.restconf.common.context.InstanceIdentifierContext; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; @@ -44,6 +45,7 @@ import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; import org.opendaylight.restconf.common.util.RestUtil; import org.opendaylight.yangtools.concepts.Codec; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder; @@ -51,7 +53,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; +import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; @@ -116,7 +118,8 @@ public class ControllerContext implements SchemaContextListener { this.yangTextSourceProvider = yangTextSourceProvider; } - private ControllerContext() { + ControllerContext() { + } public static ControllerContext getInstance() { @@ -168,15 +171,15 @@ public class ControllerContext implements SchemaContextListener { } final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder(); - final Module latestModule = this.globalSchema.findModuleByName(startModule, null); + final Set latestModule = this.globalSchema.findModules(startModule); - if (latestModule == null) { + if (latestModule.isEmpty()) { throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } final InstanceIdentifierContext iiWithSchemaNode = - collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier); + collectPathArguments(builder, pathArgs, latestModule.iterator().next(), null, toMountPointIdentifier); if (iiWithSchemaNode == null) { throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); @@ -209,55 +212,52 @@ public class ControllerContext implements SchemaContextListener { public Module findModuleByName(final String moduleName) { checkPreconditions(); - Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty()); - return this.globalSchema.findModuleByName(moduleName, null); + Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty()); + return this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null); } public Module findModuleByName(final DOMMountPoint mountPoint, final String moduleName) { - Preconditions.checkArgument((moduleName != null) && (mountPoint != null)); + Preconditions.checkArgument(moduleName != null && mountPoint != null); final SchemaContext mountPointSchema = mountPoint.getSchemaContext(); if (mountPointSchema == null) { return null; } - return mountPointSchema.findModuleByName(moduleName, null); + return mountPointSchema.findModules(moduleName).stream().findFirst().orElse(null); } public Module findModuleByNamespace(final URI namespace) { checkPreconditions(); Preconditions.checkArgument(namespace != null); - return this.globalSchema.findModuleByNamespaceAndRevision(namespace, null); + return this.globalSchema.findModules(namespace).stream().findFirst().orElse(null); } public Module findModuleByNamespace(final DOMMountPoint mountPoint, final URI namespace) { - Preconditions.checkArgument((namespace != null) && (mountPoint != null)); + Preconditions.checkArgument(namespace != null && mountPoint != null); final SchemaContext mountPointSchema = mountPoint.getSchemaContext(); if (mountPointSchema == null) { return null; } - return mountPointSchema.findModuleByNamespaceAndRevision(namespace, null); + return mountPointSchema.findModules(namespace).stream().findFirst().orElse(null); } - public Module findModuleByNameAndRevision(final QName module) { + public Module findModuleByNameAndRevision(final String name, final Revision revision) { checkPreconditions(); - Preconditions - .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)); + Preconditions.checkArgument(name != null && revision != null); - return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision()); + return this.globalSchema.findModule(name, revision).orElse(null); } - public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) { + public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final String name, + final Revision revision) { checkPreconditions(); - Preconditions - .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null) - && (mountPoint != null)); + Preconditions.checkArgument(name != null && revision != null && mountPoint != null); final SchemaContext schemaContext = mountPoint.getSchemaContext(); - return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(), - module.getRevision()); + return schemaContext == null ? null : schemaContext.findModule(name, revision).orElse(null); } public DataNodeContainer getDataNodeContainerFor(final YangInstanceIdentifier path) { @@ -266,13 +266,12 @@ public class ControllerContext implements SchemaContextListener { final Iterable elements = path.getPathArguments(); final PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); - final Module initialModule = this.globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(), - startQName.getRevision()); + final Module initialModule = this.globalSchema.findModule(startQName.getModule()).orElse(null); DataNodeContainer node = initialModule; for (final PathArgument element : elements) { final QName _nodeType = element.getNodeType(); final DataSchemaNode potentialNode = childByQName(node, _nodeType); - if ((potentialNode == null) || !isListOrContainer(potentialNode)) { + if (potentialNode == null || !isListOrContainer(potentialNode)) { return null; } node = (DataNodeContainer) potentialNode; @@ -294,14 +293,13 @@ public class ControllerContext implements SchemaContextListener { } else { schemaContext = this.globalSchema; } - final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(startQName.getNamespace(), - startQName.getRevision()); + final Module initialModule = schemaContext.findModule(startQName.getModule()).orElse(null); DataNodeContainer node = initialModule; for (final PathArgument element : elements) { if (!(element instanceof AugmentationIdentifier)) { final QName _nodeType = element.getNodeType(); final DataSchemaNode potentialNode = childByQName(node, _nodeType); - if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode)) + if (!(element instanceof NodeIdentifier && potentialNode instanceof ListSchemaNode) && !(potentialNode instanceof ChoiceSchemaNode)) { builder.append(convertToRestconfIdentifier(element, potentialNode, mount)); if (potentialNode instanceof DataNodeContainer) { @@ -349,7 +347,7 @@ public class ControllerContext implements SchemaContextListener { } private static CharSequence toRestconfIdentifier(final SchemaContext context, final QName qname) { - final Module schema = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision()); + final Module schema = context.findModule(qname.getModule()).orElse(null); return schema == null ? null : schema.getName() + ':' + qname.getLocalName(); } @@ -380,7 +378,7 @@ public class ControllerContext implements SchemaContextListener { } public Module getRestconfModule() { - return findModuleByNameAndRevision(RestConfModule.IETF_RESTCONF_QNAME); + return findModuleByNameAndRevision(Draft02.RestConfModule.NAME, Revision.of(Draft02.RestConfModule.REVISION)); } public DataSchemaNode getRestconfModuleErrorsSchemaNode() { @@ -423,33 +421,33 @@ public class ControllerContext implements SchemaContextListener { if (RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) { final List instances = findInstanceDataChildrenByName( - ((DataNodeContainer) restconfContainer), RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); + (DataNodeContainer) restconfContainer, RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) { final List instances = findInstanceDataChildrenByName( - ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); } else if (RestConfModule.STREAM_LIST_SCHEMA_NODE.equals(schemaNodeName)) { List instances = findInstanceDataChildrenByName( - ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); final DataSchemaNode modules = Iterables.getFirst(instances, null); - instances = findInstanceDataChildrenByName(((DataNodeContainer) modules), + instances = findInstanceDataChildrenByName((DataNodeContainer) modules, RestConfModule.STREAM_LIST_SCHEMA_NODE); return Iterables.getFirst(instances, null); } else if (RestConfModule.MODULES_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) { final List instances = findInstanceDataChildrenByName( - ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); } else if (RestConfModule.MODULE_LIST_SCHEMA_NODE.equals(schemaNodeName)) { List instances = findInstanceDataChildrenByName( - ((DataNodeContainer) restconfContainer), RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + (DataNodeContainer) restconfContainer, RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); final DataSchemaNode modules = Iterables.getFirst(instances, null); - instances = findInstanceDataChildrenByName(((DataNodeContainer) modules), + instances = findInstanceDataChildrenByName((DataNodeContainer) modules, RestConfModule.MODULE_LIST_SCHEMA_NODE); return Iterables.getFirst(instances, null); } else if (RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE.equals(schemaNodeName)) { final List instances = findInstanceDataChildrenByName( - ((DataNodeContainer) restconfContainer), RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + (DataNodeContainer) restconfContainer, RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); } @@ -457,7 +455,7 @@ public class ControllerContext implements SchemaContextListener { } private static DataSchemaNode childByQName(final ChoiceSchemaNode container, final QName name) { - for (final ChoiceCaseNode caze : container.getCases()) { + for (final CaseSchemaNode caze : container.getCases().values()) { final DataSchemaNode ret = childByQName(caze, name); if (ret != null) { return ret; @@ -467,7 +465,7 @@ public class ControllerContext implements SchemaContextListener { return null; } - private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) { + private static DataSchemaNode childByQName(final CaseSchemaNode container, final QName name) { return container.getDataChildByName(name); } @@ -489,8 +487,8 @@ public class ControllerContext implements SchemaContextListener { private static DataSchemaNode childByQName(final Object container, final QName name) { - if (container instanceof ChoiceCaseNode) { - return childByQName((ChoiceCaseNode) container, name); + if (container instanceof CaseSchemaNode) { + return childByQName((CaseSchemaNode) container, name); } else if (container instanceof ChoiceSchemaNode) { return childByQName((ChoiceSchemaNode) container, name); } else if (container instanceof ContainerSchemaNode) { @@ -511,8 +509,8 @@ public class ControllerContext implements SchemaContextListener { final DataSchemaNode ret = container.getDataChildByName(name); if (ret == null) { for (final DataSchemaNode node : container.getChildNodes()) { - if ((node instanceof ChoiceSchemaNode)) { - final ChoiceSchemaNode choiceNode = ((ChoiceSchemaNode) node); + if (node instanceof ChoiceSchemaNode) { + final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) node; final DataSchemaNode childByQName = childByQName(choiceNode, name); if (childByQName != null) { return childByQName; @@ -540,7 +538,7 @@ public class ControllerContext implements SchemaContextListener { } if (strings.isEmpty()) { - return createContext(builder.build(), ((DataSchemaNode) parentNode), + return createContext(builder.build(), (DataSchemaNode) parentNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : this.globalSchema); } @@ -577,7 +575,7 @@ public class ControllerContext implements SchemaContextListener { ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT); } - if (returnJustMountPoint || (strings.size() == 1)) { + if (returnJustMountPoint || strings.size() == 1) { final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().build(); return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema); } @@ -589,22 +587,21 @@ public class ControllerContext implements SchemaContextListener { ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - final Module moduleBehindMountPoint = - mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null); - if (moduleBehindMountPoint == null) { + final Iterator it = mountPointSchema.findModules(moduleNameBehindMountPoint).iterator(); + if (!it.hasNext()) { throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } final List subList = strings.subList(1, strings.size()); - return collectPathArguments(YangInstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount, + return collectPathArguments(YangInstanceIdentifier.builder(), subList, it.next(), mount, returnJustMountPoint); } Module module = null; if (mountPoint == null) { checkPreconditions(); - module = this.globalSchema.findModuleByName(moduleName, null); + module = this.globalSchema.findModules(moduleName).stream().findFirst().orElse(null); if (module == null) { throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); @@ -612,7 +609,7 @@ public class ControllerContext implements SchemaContextListener { } else { final SchemaContext schemaContext = mountPoint.getSchemaContext(); if (schemaContext != null) { - module = schemaContext.findModuleByName(moduleName, null); + module = schemaContext.findModules(moduleName).stream().findFirst().orElse(null); } else { module = null; } @@ -624,7 +621,7 @@ public class ControllerContext implements SchemaContextListener { targetNode = findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace()); - if ((targetNode == null) && (parentNode instanceof Module)) { + if (targetNode == null && parentNode instanceof Module) { final RpcDefinition rpc; if (mountPoint == null) { rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision()); @@ -676,10 +673,10 @@ public class ControllerContext implements SchemaContextListener { } int consumed = 1; - if ((targetNode instanceof ListSchemaNode)) { - final ListSchemaNode listNode = ((ListSchemaNode) targetNode); + if (targetNode instanceof ListSchemaNode) { + final ListSchemaNode listNode = (ListSchemaNode) targetNode; final int keysSize = listNode.getKeyDefinition().size(); - if ((strings.size() - consumed) < keysSize) { + if (strings.size() - consumed < keysSize) { throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName() + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING); } @@ -707,9 +704,9 @@ public class ControllerContext implements SchemaContextListener { builder.node(targetNode.getQName()); } - if ((targetNode instanceof DataNodeContainer)) { + if (targetNode instanceof DataNodeContainer) { final List remaining = strings.subList(consumed, strings.size()); - return collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint, + return collectPathArguments(builder, remaining, (DataNodeContainer) targetNode, mountPoint, returnJustMountPoint); } @@ -758,22 +755,23 @@ public class ControllerContext implements SchemaContextListener { final Iterable choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class); - final Iterable> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases); - for (final ChoiceCaseNode caze : Iterables.concat(map)) { + final Iterable> map = Iterables.transform(choiceNodes, + choice -> choice.getCases().values()); + for (final CaseSchemaNode caze : Iterables.concat(map)) { collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name); } } public static boolean isInstantiatedDataSchema(final DataSchemaNode node) { - return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode) - || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode) - || (node instanceof AnyXmlSchemaNode); + return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode + || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode + || node instanceof AnyXmlSchemaNode; } private void addKeyValue(final HashMap map, final DataSchemaNode node, final String uriValue, final DOMMountPoint mountPoint) { Preconditions.checkNotNull(uriValue); - Preconditions.checkArgument((node instanceof LeafSchemaNode)); + Preconditions.checkArgument(node instanceof LeafSchemaNode); final String urlDecoded = urlPathArgDecode(uriValue); TypeDefinition typedef = ((LeafSchemaNode) node).getType(); @@ -786,10 +784,10 @@ public class ControllerContext implements SchemaContextListener { Object decoded = codec.deserialize(urlDecoded); String additionalInfo = ""; if (decoded == null) { - if ((typedef instanceof IdentityrefTypeDefinition)) { + if (typedef instanceof IdentityrefTypeDefinition) { final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext(); - decoded = toQName(schemaContext, urlDecoded, null); + decoded = toQName(schemaContext, urlDecoded); additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name."; } @@ -831,23 +829,37 @@ public class ControllerContext implements SchemaContextListener { return str.substring(idx + 1); } - private QName toQName(final SchemaContext schemaContext, final String name, final Date revisionDate) { + private QName toQName(final SchemaContext schemaContext, final String name, + final java.util.Optional revisionDate) { checkPreconditions(); final String module = toModuleName(name); final String node = toNodeName(name); - final Module m = schemaContext.findModuleByName(module, revisionDate); + final Module m = schemaContext.findModule(module, revisionDate).orElse(null); return m == null ? null : QName.create(m.getQNameModule(), node); } + private QName toQName(final SchemaContext schemaContext, final String name) { + checkPreconditions(); + final String module = toModuleName(name); + final String node = toNodeName(name); + final Set modules = schemaContext.findModules(module); + return modules.isEmpty() ? null : QName.create(modules.iterator().next().getQNameModule(), node); + } + private static boolean isListOrContainer(final DataSchemaNode node) { - return (node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode); + return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode; } - public RpcDefinition getRpcDefinition(final String name, final Date revisionDate) { + public RpcDefinition getRpcDefinition(final String name, final java.util.Optional revisionDate) { final QName validName = toQName(this.globalSchema, name, revisionDate); return validName == null ? null : this.qnameToRpc.get().get(validName); } + public RpcDefinition getRpcDefinition(final String name) { + final QName validName = toQName(this.globalSchema, name); + return validName == null ? null : this.qnameToRpc.get().get(validName); + } + private static RpcDefinition getRpcDefinition(final Module module, final String rpcName) { final QName rpcQName = QName.create(module.getQNameModule(), rpcName); for (final RpcDefinition rpcDefinition : module.getRpcs()) { @@ -884,7 +896,7 @@ public class ControllerContext implements SchemaContextListener { return decodedPathArgs; } catch (final UnsupportedEncodingException e) { throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(), - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e); } } @@ -894,7 +906,7 @@ public class ControllerContext implements SchemaContextListener { return URLDecoder.decode(pathArg, URI_ENCODING_CHARSET.name()); } catch (final UnsupportedEncodingException e) { throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(), - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e); } } @@ -905,10 +917,10 @@ public class ControllerContext implements SchemaContextListener { final DOMMountPoint mount) { if (argument instanceof NodeIdentifier) { return convertToRestconfIdentifier((NodeIdentifier) argument, mount); - } else if ((argument instanceof NodeIdentifierWithPredicates) && (node instanceof ListSchemaNode)) { + } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) { return convertToRestconfIdentifierWithPredicates((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node, mount); - } else if ((argument != null) && (node != null)) { + } else if (argument != null && node != null) { throw new IllegalArgumentException("Conversion of generic path argument is not supported"); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.asList(argument, node)); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeContainerSchemaNode.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeContainerSchemaNode.java index b1bbeb7902..7a7b136050 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeContainerSchemaNode.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeContainerSchemaNode.java @@ -11,15 +11,19 @@ import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; -import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; +import org.opendaylight.yangtools.yang.model.api.ActionDefinition; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.MustDefinition; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; +import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; @@ -57,10 +61,10 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { } @Override - public DataSchemaNode getDataChildByName(final QName name) { + public Optional findDataChildByName(final QName name) { for (final DataSchemaNode node : this.children) { if (node.getQName().equals(name)) { - return node; + return Optional.of(node); } } throw new RestconfDocumentedException(name + " is not in child of " + PATH.getLastComponent()); @@ -72,7 +76,7 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { } @Override - public Set getAvailableAugmentations() { + public Set getAvailableAugmentations() { return new HashSet<>(); } @@ -91,11 +95,6 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { return false; } - @Override - public ConstraintDefinition getConstraints() { - throw new UnsupportedOperationException("Not supported."); - } - @Override public QName getQName() { return PATH.getLastComponent(); @@ -112,12 +111,12 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException("Not supported."); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException("Not supported."); } @@ -130,4 +129,24 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { public boolean isPresenceContainer() { throw new UnsupportedOperationException("Not supported."); } + + @Override + public Optional getWhenCondition() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Set getNotifications() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Set getActions() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Collection getMustConstraints() { + throw new UnsupportedOperationException("Not supported."); + } } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeImportedModule.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeImportedModule.java index 1000220660..d5d43e7af0 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeImportedModule.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeImportedModule.java @@ -13,12 +13,15 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.net.URI; import java.util.Collection; -import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.Set; +import org.opendaylight.yangtools.concepts.SemVer; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.common.Revision; +import org.opendaylight.yangtools.yang.common.YangVersion; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Deviation; import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition; @@ -27,6 +30,7 @@ import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.ModuleImport; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; @@ -60,21 +64,11 @@ final class FakeImportedModule extends ForwardingObject implements Module { return ImmutableSet.of(); } - @Override - public DataSchemaNode getDataChildByName(final QName name) { - return null; - } - @Override public Set getUses() { return ImmutableSet.of(); } - @Override - public String getModuleSourcePath() { - return null; - } - @Override public QNameModule getQNameModule() { return delegate.getQNameModule(); @@ -91,7 +85,7 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public Date getRevision() { + public Optional getRevision() { return delegate.getRevision(); } @@ -101,27 +95,27 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public String getYangVersion() { + public YangVersion getYangVersion() { return delegate.getYangVersion(); } @Override - public String getDescription() { + public Optional getDescription() { return delegate.getDescription(); } @Override - public String getReference() { + public Optional getReference() { return delegate.getReference(); } @Override - public String getOrganization() { + public Optional getOrganization() { return delegate.getOrganization(); } @Override - public String getContact() { + public Optional getContact() { return delegate.getContact(); } @@ -141,7 +135,7 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public Set getAugmentations() { + public Set getAugmentations() { return ImmutableSet.of(); } @@ -171,7 +165,17 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public String getSource() { - return null; + public Optional findDataChildByName(final QName name) { + return Optional.empty(); + } + + @Override + public Set getNotifications() { + return delegate.getNotifications(); + } + + @Override + public Optional getSemanticVersion() { + return delegate.getSemanticVersion(); } } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeLeafSchemaNode.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeLeafSchemaNode.java index dbcbf38113..65aebbea33 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeLeafSchemaNode.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeLeafSchemaNode.java @@ -7,10 +7,13 @@ */ package org.opendaylight.netconf.sal.restconf.impl; +import java.util.Collection; import java.util.List; +import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.MustDefinition; +import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; @@ -51,11 +54,6 @@ final class FakeLeafSchemaNode implements LeafSchemaNode { return false; } - @Override - public ConstraintDefinition getConstraints() { - throw new UnsupportedOperationException("Not supported."); - } - @Override public QName getQName() { return path.getLastComponent(); @@ -72,12 +70,12 @@ final class FakeLeafSchemaNode implements LeafSchemaNode { } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException("Not supported operations."); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException("Not supported."); } @@ -92,13 +90,17 @@ final class FakeLeafSchemaNode implements LeafSchemaNode { } @Override - public String getDefault() { + public Optional getWhenCondition() { throw new UnsupportedOperationException("Not supported."); } @Override - public String getUnits() { + public boolean isMandatory() { throw new UnsupportedOperationException("Not supported."); } + @Override + public Collection getMustConstraints() { + throw new UnsupportedOperationException("Not supported."); + } } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeModuleImport.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeModuleImport.java index 8d781e88c5..aae1e039c1 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeModuleImport.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeModuleImport.java @@ -8,12 +8,14 @@ package org.opendaylight.netconf.sal.restconf.impl; import com.google.common.base.Preconditions; -import java.util.Date; +import java.util.Optional; +import org.opendaylight.yangtools.concepts.SemVer; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.ModuleImport; /** - * Fake {@link ModuleImport} implementation used to attach corrent prefix mapping to fake RPCs. + * Fake {@link ModuleImport} implementation used to attach current prefix mapping to fake RPCs. * * @author Robert Varga */ @@ -30,7 +32,7 @@ final class FakeModuleImport implements ModuleImport { } @Override - public Date getRevision() { + public Optional getRevision() { return module.getRevision(); } @@ -38,4 +40,19 @@ final class FakeModuleImport implements ModuleImport { public String getPrefix() { return module.getName(); } + + @Override + public Optional getDescription() { + return module.getDescription(); + } + + @Override + public Optional getReference() { + return module.getReference(); + } + + @Override + public Optional getSemanticVersion() { + return module.getSemanticVersion(); + } } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeRestconfModule.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeRestconfModule.java index f1e6b8ab4f..fcd4d65336 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeRestconfModule.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/FakeRestconfModule.java @@ -11,16 +11,17 @@ import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.net.URI; -import java.text.ParseException; import java.util.Collection; -import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.Set; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; +import org.opendaylight.yangtools.concepts.SemVer; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.common.Revision; +import org.opendaylight.yangtools.yang.common.YangVersion; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Deviation; @@ -43,17 +44,8 @@ import org.opendaylight.yangtools.yang.model.api.UsesNode; */ final class FakeRestconfModule implements Module { - static final QNameModule QNAME; - - static { - Date date; - try { - date = SimpleDateFormatUtil.getRevisionFormat().parse("2016-06-28"); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"), date).intern(); - } + static final QNameModule QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"), + Revision.of("2016-06-28")).intern(); private final Collection children; private final ImmutableSet imports; @@ -85,10 +77,10 @@ final class FakeRestconfModule implements Module { } @Override - public DataSchemaNode getDataChildByName(final QName name) { + public Optional findDataChildByName(final QName name) { for (final DataSchemaNode node : this.children) { if (node.getQName().equals(name)) { - return node; + return Optional.of(node); } } throw new RestconfDocumentedException(name + " is not in child of " + FakeRestconfModule.QNAME); @@ -99,11 +91,6 @@ final class FakeRestconfModule implements Module { throw new UnsupportedOperationException("Not supported operations."); } - @Override - public String getModuleSourcePath() { - throw new UnsupportedOperationException("Not supported operations."); - } - @Override public QNameModule getQNameModule() { return QNAME; @@ -120,7 +107,7 @@ final class FakeRestconfModule implements Module { } @Override - public Date getRevision() { + public Optional getRevision() { return QNAME.getRevision(); } @@ -130,27 +117,27 @@ final class FakeRestconfModule implements Module { } @Override - public String getYangVersion() { + public YangVersion getYangVersion() { throw new UnsupportedOperationException("Not supported operations."); } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException("Not supported operations."); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException("Not supported operations."); } @Override - public String getOrganization() { + public Optional getOrganization() { throw new UnsupportedOperationException("Not supported operations."); } @Override - public String getContact() { + public Optional getContact() { throw new UnsupportedOperationException("Not supported operations."); } @@ -175,7 +162,7 @@ final class FakeRestconfModule implements Module { } @Override - public Set getAugmentations() { + public Set getAugmentations() { throw new UnsupportedOperationException("Not supported operations."); } @@ -205,8 +192,7 @@ final class FakeRestconfModule implements Module { } @Override - public String getSource() { + public Optional getSemanticVersion() { throw new UnsupportedOperationException("Not supported operations."); } - } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/QueryParametersParser.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/QueryParametersParser.java index 783700bcba..7e878591a1 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/QueryParametersParser.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/QueryParametersParser.java @@ -13,7 +13,7 @@ import org.opendaylight.restconf.common.context.WriterParameters; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.restconf.common.errors.RestconfError; -public class QueryParametersParser { +public final class QueryParametersParser { private enum UriParameters { PRETTY_PRINT("prettyPrint"), @@ -31,6 +31,10 @@ public class QueryParametersParser { } } + private QueryParametersParser() { + + } + public static WriterParameters parseWriterParameters(final UriInfo info) { return parseParams(info, false); } @@ -58,7 +62,7 @@ public class QueryParametersParser { } wpBuilder.setDepth(depth); } catch (final NumberFormatException e) { - throw new RestconfDocumentedException(new RestconfError( + throw new RestconfDocumentedException(e, new RestconfError( RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE, "Invalid depth parameter: " + e.getMessage(), null, "The depth parameter must be an integer > 1 or \"unbounded\"")); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestCodec.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestCodec.java index c35a9b07d4..eba0042414 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestCodec.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestCodec.java @@ -41,14 +41,14 @@ import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RestCodec { +public final class RestCodec { private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class); private RestCodec() { } - public static final Codec from(final TypeDefinition typeDefinition, + public static Codec from(final TypeDefinition typeDefinition, final DOMMountPoint mountPoint) { return new ObjectCodec(typeDefinition, mountPoint); } diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestconfImpl.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestconfImpl.java index 090e861eef..715d66c955 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestconfImpl.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestconfImpl.java @@ -18,18 +18,17 @@ import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import java.net.URI; -import java.text.ParseException; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; +import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -76,7 +75,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types. import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; @@ -117,7 +116,7 @@ import org.opendaylight.yangtools.yang.model.util.SimpleSchemaContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RestconfImpl implements RestconfService { +public final class RestconfImpl implements RestconfService { private static final RestconfImpl INSTANCE = new RestconfImpl(); @@ -148,19 +147,11 @@ public class RestconfImpl implements RestconfService { private static final String NETCONF_BASE_PAYLOAD_NAME = "data"; - private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE), null), + private static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(NETCONF_BASE)), NETCONF_BASE_PAYLOAD_NAME).intern(); - private static final QNameModule SAL_REMOTE_AUGMENT; - - static { - try { - SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, - SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08")); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - } + private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, + Revision.of("2014-07-08")); private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER = new AugmentationIdentifier(ImmutableSet.of( @@ -259,7 +250,7 @@ public class RestconfImpl implements RestconfService { @Override public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) { Preconditions.checkNotNull(identifier); - final QName moduleNameAndRevision = getModuleNameAndRevision(identifier); + final Entry nameRev = getModuleNameAndRevision(identifier); Module module = null; DOMMountPoint mountPoint = null; final SchemaContext schemaContext; @@ -267,16 +258,17 @@ public class RestconfImpl implements RestconfService { final InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); - module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision); + module = this.controllerContext.findModuleByNameAndRevision(mountPoint, nameRev.getKey(), + nameRev.getValue()); schemaContext = mountPoint.getSchemaContext(); } else { - module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision); + module = this.controllerContext.findModuleByNameAndRevision(nameRev.getKey(), nameRev.getValue()); schemaContext = this.controllerContext.getGlobalSchema(); } if (module == null) { - final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" - + moduleNameAndRevision.getRevision() + "' was not found."; + final String errMsg = "Module with name '" + nameRev.getKey() + "' and revision '" + + nameRev.getValue() + "' was not found."; LOG.debug(errMsg); throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } @@ -407,7 +399,7 @@ public class RestconfImpl implements RestconfService { return restconfModule; } - private static QName getModuleNameAndRevision(final String identifier) { + private static Entry getModuleNameAndRevision(final String identifier) { final int mountIndex = identifier.indexOf(ControllerContext.MOUNT); String moduleNameAndRevision = ""; if (mountIndex >= 0) { @@ -416,9 +408,8 @@ public class RestconfImpl implements RestconfService { moduleNameAndRevision = identifier; } - final Splitter splitter = Splitter.on("/").omitEmptyStrings(); - final Iterable split = splitter.split(moduleNameAndRevision); - final List pathArgs = Lists.newArrayList(split); + final Splitter splitter = Splitter.on('/').omitEmptyStrings(); + final List pathArgs = splitter.splitToList(moduleNameAndRevision); if (pathArgs.size() < 2) { LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier); throw new RestconfDocumentedException( @@ -427,13 +418,11 @@ public class RestconfImpl implements RestconfService { } try { - final String moduleName = pathArgs.get(0); - final String revision = pathArgs.get(1); - return QName.create(null, SimpleDateFormatUtil.getRevisionFormat().parse(revision), moduleName); - } catch (final ParseException e) { + return new SimpleImmutableEntry<>(pathArgs.get(0), Revision.of(pathArgs.get(1))); + } catch (final DateTimeParseException e) { LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier); throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e); } } @@ -524,7 +513,7 @@ public class RestconfImpl implements RestconfService { RpcDefinition rpc = null; if (mountPoint == null) { - rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null); + rpc = this.controllerContext.getRpcDefinition(identifierDecoded); } else { rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded); } @@ -557,6 +546,7 @@ public class RestconfImpl implements RestconfService { result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo)); } + @SuppressWarnings("checkstyle:avoidHidingCauseException") private static DOMRpcResult checkRpcResponse(final CheckedFuture response) { if (response == null) { return null; @@ -571,7 +561,7 @@ public class RestconfImpl implements RestconfService { } catch (final InterruptedException e) { final String errMsg = "The operation was interrupted while executing and did not complete."; LOG.debug("Rpc Interrupt - " + errMsg, e); - throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION); + throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e); } catch (final ExecutionException e) { LOG.debug("Execution RpcError: ", e); Throwable cause = e.getCause(); @@ -614,8 +604,9 @@ public class RestconfImpl implements RestconfService { invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) { final ContainerNode value = (ContainerNode) payload.getData(); final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName(); - final Optional> path = value.getChild(new NodeIdentifier( - QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path"))); + final java.util.Optional> path = value.getChild( + new NodeIdentifier(QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), + "path"))); final Object pathValue = path.isPresent() ? path.get().getValue() : null; if (!(pathValue instanceof YangInstanceIdentifier)) { @@ -1071,8 +1062,8 @@ public class RestconfImpl implements RestconfService { final Optional searchedException = Iterables.tryFind(Throwables.getCausalChain(e), Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)); if (searchedException.isPresent()) { - throw new RestconfDocumentedException("Data specified for delete doesn't exist.", ErrorType.APPLICATION, - ErrorTag.DATA_MISSING); + throw new RestconfDocumentedException("Data specified for delete doesn't exist.", + ErrorType.APPLICATION, ErrorTag.DATA_MISSING, e); } final String errMsg = "Error while deleting data"; @@ -1197,7 +1188,7 @@ public class RestconfImpl implements RestconfService { final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi"); final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema(); final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx - .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision()) + .findModule(qnameBase.getModule()).orElse(null) .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location")); final List path = new ArrayList<>(); path.add(NodeIdentifier.create(qnameBase)); @@ -1318,7 +1309,7 @@ public class RestconfImpl implements RestconfService { return this.broker.patchConfigurationDataWithinTransaction(context); } catch (final Exception e) { LOG.debug("Patch transaction failed", e); - throw new RestconfDocumentedException(e.getMessage()); + throw new RestconfDocumentedException(e.getMessage(), e); } } @@ -1333,7 +1324,7 @@ public class RestconfImpl implements RestconfService { return this.broker.patchConfigurationDataWithinTransaction(context); } catch (final Exception e) { LOG.debug("Patch transaction failed", e); - throw new RestconfDocumentedException(e.getMessage()); + throw new RestconfDocumentedException(e.getMessage(), e); } } @@ -1347,7 +1338,7 @@ public class RestconfImpl implements RestconfService { */ private static T parseEnumTypeParameter(final ContainerNode value, final Class classDescriptor, final String paramName) { - final Optional> optAugNode = value.getChild( + final java.util.Optional> optAugNode = value.getChild( SAL_REMOTE_AUG_IDENTIFIER); if (!optAugNode.isPresent()) { return null; @@ -1356,8 +1347,8 @@ public class RestconfImpl implements RestconfService { if (!(augNode instanceof AugmentationNode)) { return null; } - final Optional> enumNode = ((AugmentationNode) augNode).getChild( - new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName))); + final java.util.Optional> enumNode = ((AugmentationNode) augNode) + .getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName))); if (!enumNode.isPresent()) { return null; } @@ -1441,9 +1432,11 @@ public class RestconfImpl implements RestconfService { ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "revision"); final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode); - final String revision = module.getQNameModule().getFormattedRevision(); - moduleNodeValues - .withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision).build()); + final java.util.Optional revision = module.getQNameModule().getRevision(); + if (revision.isPresent()) { + moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode) + .withValue(revision.get().toString()).build()); + } instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(listModuleSchemaNode, "namespace"); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/StatisticsRestconfServiceWrapper.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/StatisticsRestconfServiceWrapper.java index dffcf87507..a6c2a8d7c4 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/StatisticsRestconfServiceWrapper.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/restconf/impl/StatisticsRestconfServiceWrapper.java @@ -17,7 +17,7 @@ import org.opendaylight.restconf.common.context.NormalizedNodeContext; import org.opendaylight.restconf.common.patch.PatchContext; import org.opendaylight.restconf.common.patch.PatchStatusContext; -public class StatisticsRestconfServiceWrapper implements RestconfService { +public final class StatisticsRestconfServiceWrapper implements RestconfService { AtomicLong operationalGet = new AtomicLong(); AtomicLong configGet = new AtomicLong(); @@ -292,4 +292,4 @@ public class StatisticsRestconfServiceWrapper implements RestconfService { public BigInteger getFailureDelete() { return BigInteger.valueOf(this.failureDelete.get()); } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/AbstractQueryParams.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/AbstractQueryParams.java index 411183b648..618bf4de91 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/AbstractQueryParams.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/AbstractQueryParams.java @@ -71,6 +71,7 @@ abstract class AbstractQueryParams extends AbstractNotificationsData { * @param leafNodesOnly * if true, notifications will contain changes to leaf nodes only */ + @SuppressWarnings("checkstyle:hiddenField") public void setQueryParams(final Instant start, final Optional stop, final Optional filter, final boolean leafNodesOnly) { this.start = Preconditions.checkNotNull(start); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapter.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapter.java index 6355769336..2775cce134 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapter.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapter.java @@ -7,7 +7,6 @@ */ package org.opendaylight.netconf.sal.streams.listeners; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.Collection; @@ -52,7 +51,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster private final String streamName; private final NotificationOutputType outputType; - private Collection dataTreeCandidates; + private Collection candidates; /** * Creates new {@link ListenerAdapter} listener specified by path and stream @@ -70,13 +69,13 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster register(this); this.outputType = Preconditions.checkNotNull(outputType); this.path = Preconditions.checkNotNull(path); - Preconditions.checkArgument((streamName != null) && !streamName.isEmpty()); + Preconditions.checkArgument(streamName != null && !streamName.isEmpty()); this.streamName = streamName; } @Override - public void onDataTreeChanged(@Nonnull Collection dataTreeCandidates) { - this.dataTreeCandidates = dataTreeCandidates; + public void onDataTreeChanged(@Nonnull final Collection dataTreeCandidates) { + this.candidates = dataTreeCandidates; final String xml = prepareXml(); if (checkQueryParams(xml, this)) { prepareAndPostData(xml); @@ -141,7 +140,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification"); addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, - this.dataTreeCandidates, schemaContext, dataContextTree); + this.candidates, schemaContext, dataContextTree); notificationElement.appendChild(dataChangedNotificationEventElement); return transformDoc(doc); } @@ -173,11 +172,11 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster } private void addNodeToDataChangeNotificationEventElement(final Document doc, - final Element dataChangedNotificationEventElement, DataTreeCandidateNode candidateNode, - YangInstanceIdentifier parentYiid, SchemaContext schemaContext, - DataSchemaContextTree dataSchemaContextTree) { + final Element dataChangedNotificationEventElement, final DataTreeCandidateNode candidateNode, + final YangInstanceIdentifier parentYiid, final SchemaContext schemaContext, + final DataSchemaContextTree dataSchemaContextTree) { - Optional> optionalNormalizedNode = Optional.absent(); + java.util.Optional> optionalNormalizedNode = java.util.Optional.empty(); switch (candidateNode.getModificationType()) { case APPEARED: case SUBTREE_MODIFIED: @@ -244,7 +243,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster * {@link Operation} * @return {@link Node} node represented by changed event element. */ - private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path, + private static Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path, final Operation operation) { final Element dataChangeEventElement = doc.createElement("data-change-event"); final Element pathElement = doc.createElement("path"); @@ -259,11 +258,11 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster } private Node createCreatedChangedDataChangeEventElement(final Document doc, - YangInstanceIdentifier path, NormalizedNode normalized, final Operation operation, + final YangInstanceIdentifier eventPath, final NormalizedNode normalized, final Operation operation, final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) { final Element dataChangeEventElement = doc.createElement("data-change-event"); final Element pathElement = doc.createElement("path"); - addPathAsValueToElement(path, pathElement); + addPathAsValueToElement(eventPath, pathElement); dataChangeEventElement.appendChild(pathElement); final Element operationElement = doc.createElement("operation"); @@ -272,10 +271,10 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster try { SchemaPath nodePath; - if ((normalized instanceof MapEntryNode) || (normalized instanceof UnkeyedListEntryNode)) { - nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath(); + if (normalized instanceof MapEntryNode || normalized instanceof UnkeyedListEntryNode) { + nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath(); } else { - nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath().getParent(); + nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath().getParent(); } final DOMResult domResult = writeNormalizedNode(normalized, schemaContext, nodePath); final Node result = doc.importNode(domResult.getNode().getFirstChild(), true); @@ -300,7 +299,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster * {@link Element} */ @SuppressWarnings("rawtypes") - private void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) { + private static void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) { final YangInstanceIdentifier normalizedPath = ControllerContext.getInstance().toXpathRepresentation(path); final StringBuilder textContent = new StringBuilder(); @@ -343,8 +342,8 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements Cluster */ private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent, final QName qualifiedName) { - final Module module = ControllerContext.getInstance().getGlobalSchema() - .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision()); + final Module module = ControllerContext.getInstance().getGlobalSchema().findModule(qualifiedName.getModule()) + .get(); textContent.append(module.getName()); textContent.append(":"); diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerAdapter.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerAdapter.java index 54e25a7c18..9775e344f6 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerAdapter.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerAdapter.java @@ -84,6 +84,7 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem } @Override + @SuppressWarnings("checkstyle:hiddenField") public void onNotification(final DOMNotification notification) { this.schemaContext = ControllerContext.getInstance().getGlobalSchema(); this.notification = notification; @@ -173,18 +174,13 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem final Element notificationEventElement = doc.createElementNS( "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream"); - addValuesToNotificationEventElement(doc, notificationEventElement, this.notification, this.schemaContext); + addValuesToNotificationEventElement(doc, notificationEventElement); notificationElement.appendChild(notificationEventElement); return transformDoc(doc); } - private void addValuesToNotificationEventElement(final Document doc, final Element element, - final DOMNotification notification, final SchemaContext schemaContext) { - if (notification == null) { - return; - } - + private void addValuesToNotificationEventElement(final Document doc, final Element element) { final NormalizedNode>> body = notification.getBody(); try { diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/Notificator.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/Notificator.java index 8d7af400df..c08a2463c3 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/Notificator.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/listeners/Notificator.java @@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory; * {@link Notificator} is responsible to create, remove and find * {@link ListenerAdapter} listener. */ -public class Notificator { +public final class Notificator { private static Map dataChangeListener = new ConcurrentHashMap<>(); private static Map> notificationListenersByStreamName = diff --git a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/websockets/WebSocketServer.java b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/websockets/WebSocketServer.java index 1fdfd4d63d..b8093dcb7a 100644 --- a/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/websockets/WebSocketServer.java +++ b/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/websockets/WebSocketServer.java @@ -22,7 +22,7 @@ import org.slf4j.LoggerFactory; * {@link WebSocketServer} is the singleton responsible for starting and stopping the * web socket server. */ -public class WebSocketServer implements Runnable { +public final class WebSocketServer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/md/sal/rest/common/TestRestconfUtils.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/md/sal/rest/common/TestRestconfUtils.java index 1b76e4b98c..39b881ac65 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/md/sal/rest/common/TestRestconfUtils.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/md/sal/rest/common/TestRestconfUtils.java @@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; -public class TestRestconfUtils { +public final class TestRestconfUtils { private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class); @@ -55,14 +55,14 @@ public class TestRestconfUtils { public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) { try { Preconditions.checkArgument(yangPath != null, "Path can not be null."); - Preconditions.checkArgument((!yangPath.isEmpty()), "Path can not be empty."); + Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty."); if (schemaContext == null) { - return YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(yangPath)); + return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath)); } else { throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context."); } } catch (final Exception e) { - LOG.error("Yang files at path: " + yangPath + " weren't loaded."); + LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e); } return schemaContext; } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java index 8d8c2aa96e..4e0801c2c8 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java @@ -24,7 +24,7 @@ public class InstanceIdentifierTypeLeafTest { @Test public void stringToInstanceIdentifierTest() throws Exception { final SchemaContext schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/instanceidentifier")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/instanceidentifier")); ControllerContext.getInstance().setGlobalSchema(schemaContext); final InstanceIdentifierContext instanceIdentifier = ControllerContext.getInstance().toInstanceIdentifier( diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReader.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReader.java index e9c772018e..7d5b015c16 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReader.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReader.java @@ -12,13 +12,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import com.google.common.base.Optional; import com.google.common.collect.Sets; import java.io.File; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; +import java.util.Optional; import javax.ws.rs.core.MediaType; import org.junit.BeforeClass; import org.junit.Test; @@ -27,7 +26,7 @@ import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader; import org.opendaylight.restconf.common.context.NormalizedNodeContext; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @@ -39,23 +38,13 @@ import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - public class TestJsonBodyReader extends AbstractBodyReaderTest { private final JsonNormalizedNodeBodyReader jsonBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } - + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public TestJsonBodyReader() throws NoSuchFieldException, SecurityException { this.jsonBodyReader = new JsonNormalizedNodeBodyReader(); @@ -71,7 +60,7 @@ public class TestJsonBodyReader extends AbstractBodyReaderTest { throws Exception { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); CONTROLLER_CONTEXT.setSchemas(schemaContext); } @@ -127,7 +116,7 @@ public class TestJsonBodyReader extends AbstractBodyReaderTest { public void moduleSubContainerAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment"); final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier( Sets.newHashSet(contAugmentQName)); @@ -148,7 +137,7 @@ public class TestJsonBodyReader extends AbstractBodyReaderTest { public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1"); final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2"); final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1"); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReaderMountPoint.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReaderMountPoint.java index 9190a49cad..328e6182c1 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReaderMountPoint.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyReaderMountPoint.java @@ -18,7 +18,6 @@ import com.google.common.base.Optional; import java.io.File; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.junit.BeforeClass; @@ -31,7 +30,7 @@ import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; import org.opendaylight.restconf.common.context.NormalizedNodeContext; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @@ -47,16 +46,8 @@ public class TestJsonBodyReaderMountPoint extends AbstractBodyReaderTest { private final JsonNormalizedNodeBodyReader jsonBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public TestJsonBodyReaderMountPoint() throws NoSuchFieldException, SecurityException { @@ -72,7 +63,7 @@ public class TestJsonBodyReaderMountPoint extends AbstractBodyReaderTest { public static void initialization() throws Exception { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); final DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContext); @@ -139,14 +130,14 @@ public class TestJsonBodyReaderMountPoint extends AbstractBodyReaderTest { final ContainerNode inputNode = (ContainerNode) returnValue.getData(); final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName .create(inputNode.getNodeType(), "cont")); - final Optional> contDataNode = inputNode + final java.util.Optional> contDataNode = inputNode .getChild(yangCont.getLastPathArgument()); assertTrue(contDataNode.isPresent()); assertTrue(contDataNode.get() instanceof ContainerNode); final YangInstanceIdentifier yangleaf = YangInstanceIdentifier.of(QName .create(inputNode.getNodeType(), "lf")); - final Optional> leafDataNode = ((ContainerNode) contDataNode - .get()).getChild(yangleaf.getLastPathArgument()); + final java.util.Optional> leafDataNode = + ((ContainerNode) contDataNode.get()).getChild(yangleaf.getLastPathArgument()); assertTrue(leafDataNode.isPresent()); assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue() .toString())); @@ -169,7 +160,7 @@ public class TestJsonBodyReaderMountPoint extends AbstractBodyReaderTest { .getSchemaContext().getDataChildByName( dataSchemaNode.getQName()); assertNotNull(mountDataSchemaNode); - if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) { + if (qualifiedName != null && dataSchemaNode instanceof DataNodeContainer) { final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode) .getDataChildByName(qualifiedName); dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent) diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyWriter.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyWriter.java index c145c5b895..8f7b008ec6 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyWriter.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestJsonBodyWriter.java @@ -45,7 +45,7 @@ public class TestJsonBodyWriter extends AbstractBodyReaderTest { public static void initialization() throws Exception { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); CONTROLLER_CONTEXT.setSchemas(schemaContext); } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReader.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReader.java index 7b6bda9352..a34308160e 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReader.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReader.java @@ -13,12 +13,10 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import com.google.common.base.Optional; import com.google.common.collect.Sets; import java.io.File; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.junit.Assert; @@ -31,7 +29,7 @@ import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.restconf.common.errors.RestconfError; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @@ -48,16 +46,8 @@ public class TestXmlBodyReader extends AbstractBodyReaderTest { private final XmlNormalizedNodeBodyReader xmlBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public TestXmlBodyReader() throws Exception { this.xmlBodyReader = new XmlNormalizedNodeBodyReader(); @@ -73,7 +63,7 @@ public class TestXmlBodyReader extends AbstractBodyReaderTest { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); testFiles.addAll(TestRestconfUtils.loadFiles("/foo-xml-test/yang")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); CONTROLLER_CONTEXT.setSchemas(schemaContext); } @@ -163,7 +153,7 @@ public class TestXmlBodyReader extends AbstractBodyReaderTest { public void moduleSubContainerAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment"); final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier( Sets.newHashSet(contAugmentQName)); @@ -183,7 +173,7 @@ public class TestXmlBodyReader extends AbstractBodyReaderTest { public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext.getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1"); final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2"); final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1"); @@ -215,14 +205,14 @@ public class TestXmlBodyReader extends AbstractBodyReaderTest { checkNormalizedNodeContext(returnValue); final ContainerNode contNode = (ContainerNode) returnValue.getData(); final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont")); - final Optional> contDataNodePotential = contNode.getChild(yangCont - .getLastPathArgument()); + final java.util.Optional> contDataNodePotential = contNode + .getChild(yangCont.getLastPathArgument()); assertTrue(contDataNodePotential.isPresent()); final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get(); final YangInstanceIdentifier yangLeaf = YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf")); - final Optional> leafDataNode = contDataNode.getChild(yangLeaf - .getLastPathArgument()); + final java.util.Optional> leafDataNode = contDataNode.getChild( + yangLeaf.getLastPathArgument()); assertTrue(leafDataNode.isPresent()); assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString())); } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReaderMountPoint.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReaderMountPoint.java index 9ab3a2ce5f..214ee79cc0 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReaderMountPoint.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReaderMountPoint.java @@ -19,7 +19,6 @@ import com.google.common.base.Optional; import java.io.File; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.junit.Assert; @@ -35,7 +34,7 @@ import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.restconf.common.errors.RestconfError; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @@ -50,16 +49,8 @@ public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest { private final XmlNormalizedNodeBodyReader xmlBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public TestXmlBodyReaderMountPoint() throws Exception { this.xmlBodyReader = new XmlNormalizedNodeBodyReader(); @@ -74,7 +65,7 @@ public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest { public static void initialization() throws Exception { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); final DOMMountPoint mountInstance = mock(DOMMountPoint.class); when(mountInstance.getSchemaContext()).thenReturn(schemaContext); @@ -140,14 +131,14 @@ public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest { checkNormalizedNodeContext(returnValue); final ContainerNode contNode = (ContainerNode) returnValue.getData(); final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont")); - final Optional> contDataNodePotential = contNode.getChild(yangCont - .getLastPathArgument()); + final java.util.Optional> contDataNodePotential = contNode + .getChild(yangCont.getLastPathArgument()); assertTrue(contDataNodePotential.isPresent()); final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get(); final YangInstanceIdentifier yangLeaf = YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf")); - final Optional> leafDataNode = contDataNode.getChild(yangLeaf - .getLastPathArgument()); + final java.util.Optional> leafDataNode = contDataNode.getChild( + yangLeaf.getLastPathArgument()); assertTrue(leafDataNode.isPresent()); assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString())); } @@ -169,7 +160,7 @@ public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest { .getSchemaContext().getDataChildByName( dataSchemaNode.getQName()); assertNotNull(mountDataSchemaNode); - if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) { + if (qualifiedName != null && dataSchemaNode instanceof DataNodeContainer) { final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode) .getDataChildByName(qualifiedName); dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent) diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyWriter.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyWriter.java index a1b8777b0c..ca594a3690 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyWriter.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyWriter.java @@ -41,7 +41,7 @@ public class TestXmlBodyWriter extends AbstractBodyReaderTest { public static void initialization() throws Exception { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); CONTROLLER_CONTEXT.setSchemas(schemaContext); } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java index 22aacbda1f..f82fc170fa 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java @@ -22,7 +22,6 @@ import java.io.StringReader; import java.util.Map; import org.junit.BeforeClass; import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader { @@ -178,7 +177,7 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader } @BeforeClass - public static void initialize() throws FileNotFoundException, ReactorException { + public static void initialize() throws FileNotFoundException { dataLoad("/cnsn-to-json/simple-data-types"); } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java index 20eba2be0d..c18c13a232 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java @@ -51,7 +51,6 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; public class RestPutListDataTest { @@ -68,7 +67,7 @@ public class RestPutListDataTest { } @Before - public void initialize() throws FileNotFoundException, ReactorException { + public void initialize() throws FileNotFoundException { final ControllerContext controllerContext = ControllerContext.getInstance(); schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module"); controllerContext.setSchemas(schemaContextTestModule); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/nn/test/JsonToNnTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/nn/test/JsonToNnTest.java index ff7cd5703d..7f1de7f3f1 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/nn/test/JsonToNnTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/nn/test/JsonToNnTest.java @@ -101,7 +101,7 @@ public class JsonToNnTest extends AbstractBodyReaderTest { final String dataTree = NormalizedNodes.toStringTree(normalizedNodeContext .getData()); assertTrue(dataTree.contains("lf")); - assertTrue(dataTree.contains("null")); + assertTrue(dataTree.contains("empty")); } @Test @@ -126,7 +126,7 @@ public class JsonToNnTest extends AbstractBodyReaderTest { } assertNotNull(exception); assertEquals( - "Error parsing input: Schema node with name cont wasn't found under " + "Error parsing input: Schema node with name cont was not found under " + "(urn:ietf:params:xml:ns:netconf:base:1.0)data.", exception.getErrors().get(0).getErrorMessage()); @@ -142,7 +142,7 @@ public class JsonToNnTest extends AbstractBodyReaderTest { } assertNotNull(exception); assertEquals( - "Error parsing input: Schema node with name lst1 wasn't found under " + "Error parsing input: Schema node with name lst1 was not found under " + "(urn:ietf:params:xml:ns:netconf:base:1.0)data.", exception.getErrors().get(0).getErrorMessage()); @@ -158,7 +158,7 @@ public class JsonToNnTest extends AbstractBodyReaderTest { } assertNotNull(exception); assertEquals( - "Error parsing input: Schema node with name lf wasn't found under " + "Error parsing input: Schema node with name lf was not found under " + "(urn:ietf:params:xml:ns:netconf:base:1.0)data.", exception.getErrors().get(0).getErrorMessage()); assertEquals(3, countExceptions); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnInstanceIdentifierToXmlTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnInstanceIdentifierToXmlTest.java index 501c6eff5a..f1e5786b47 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnInstanceIdentifierToXmlTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnInstanceIdentifierToXmlTest.java @@ -153,7 +153,6 @@ public class NnInstanceIdentifierToXmlTest extends AbstractBodyReaderTest { public void nnAsYangInstanceIdentifierAugment() throws Exception { final NormalizedNodeContext normalizedNodeContext = preparNNC(); - final NormalizedNodeXmlBodyWriter xmlBodyWriter = new NormalizedNodeXmlBodyWriter(); final OutputStream output = new ByteArrayOutputStream(); xmlBodyWriter.writeTo(normalizedNodeContext, null, null, null, diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlTest.java index 03a6279965..da5f91e25c 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlTest.java @@ -225,7 +225,7 @@ public class NnToXmlTest extends AbstractBodyReaderTest { public void nnAsYangEmptyToXmlTest() throws Exception { final String elName = "lfEmpty"; final NormalizedNodeContext normalizedNodeContext = prepareNNC( - TypeDefinitionAwareCodec.from(BaseTypes.emptyType()).deserialize(null), elName); + TypeDefinitionAwareCodec.from(BaseTypes.emptyType()).deserialize(""), elName); nnToXml(normalizedNodeContext, "<" + elName + ">"); } @@ -288,8 +288,8 @@ public class NnToXmlTest extends AbstractBodyReaderTest { } private static NormalizedNodeContext prepareNNC(final Object object, final String name) { - final QName cont = QName.create("basic:module", "2013-12-2", "cont"); - final QName lf = QName.create("basic:module", "2013-12-2", name); + final QName cont = QName.create("basic:module", "2013-12-02", "cont"); + final QName lf = QName.create("basic:module", "2013-12-02", name); final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont); @@ -319,9 +319,9 @@ public class NnToXmlTest extends AbstractBodyReaderTest { } private static NormalizedNodeContext prepareLeafrefData() { - final QName cont = QName.create("basic:module", "2013-12-2", "cont"); - final QName lfBoolean = QName.create("basic:module", "2013-12-2", "lfBoolean"); - final QName lfLfref = QName.create("basic:module", "2013-12-2", "lfLfref"); + final QName cont = QName.create("basic:module", "2013-12-02", "cont"); + final QName lfBoolean = QName.create("basic:module", "2013-12-02", "lfBoolean"); + final QName lfLfref = QName.create("basic:module", "2013-12-02", "lfLfref"); final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont); @@ -347,8 +347,8 @@ public class NnToXmlTest extends AbstractBodyReaderTest { } private static NormalizedNodeContext prepareLeafrefNegativeData() { - final QName cont = QName.create("basic:module", "2013-12-2", "cont"); - final QName lfLfref = QName.create("basic:module", "2013-12-2", "lfLfrefNegative"); + final QName cont = QName.create("basic:module", "2013-12-02", "cont"); + final QName lfLfref = QName.create("basic:module", "2013-12-02", "lfLfrefNegative"); final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont); final DataContainerNodeAttrBuilder contData = Builders @@ -365,9 +365,9 @@ public class NnToXmlTest extends AbstractBodyReaderTest { } private static NormalizedNodeContext prepareIdrefData(final String prefix, final boolean valueAsQName) { - final QName cont = QName.create("basic:module", "2013-12-2", "cont"); - final QName cont1 = QName.create("basic:module", "2013-12-2", "cont1"); - final QName lf11 = QName.create("basic:module", "2013-12-2", "lf11"); + final QName cont = QName.create("basic:module", "2013-12-02", "cont"); + final QName cont1 = QName.create("basic:module", "2013-12-02", "cont1"); + final QName lf11 = QName.create("basic:module", "2013-12-02", "lf11"); final DataSchemaNode contSchema = schemaContext.getDataChildByName(cont); @@ -381,7 +381,7 @@ public class NnToXmlTest extends AbstractBodyReaderTest { Object value = null; if (valueAsQName) { - value = QName.create("referenced:module", "2013-12-2", "iden"); + value = QName.create("referenced:module", "2013-12-02", "iden"); } else { value = "no qname value"; } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlWithDataFromSeveralModulesTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlWithDataFromSeveralModulesTest.java index 0791b8ab12..08539d0a5b 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlWithDataFromSeveralModulesTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/nn/to/xml/test/NnToXmlWithDataFromSeveralModulesTest.java @@ -73,13 +73,13 @@ public class NnToXmlWithDataFromSeveralModulesTest extends assertTrue(outputString.contains( "')); assertTrue(outputString.contains("lf1 m2 value")); - assertTrue(outputString.contains("")); + assertTrue(outputString.contains("")); assertTrue(outputString.contains("")); // cont m1 assertTrue(outputString.contains( "')); - assertTrue(outputString.contains("")); + assertTrue(outputString.contains("")); assertTrue(outputString.contains("lf1 m1 value")); assertTrue(outputString.contains("")); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug3595Test.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug3595Test.java index deb443ad0c..db96f0cb2b 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug3595Test.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug3595Test.java @@ -18,9 +18,9 @@ import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; import org.opendaylight.restconf.common.context.InstanceIdentifierContext; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; public class Bug3595Test { @@ -32,7 +32,7 @@ public class Bug3595Test { private static ControllerContext controllerContext = ControllerContext.getInstance(); @BeforeClass - public static void initialize() throws FileNotFoundException, ReactorException { + public static void initialize() throws FileNotFoundException { final SchemaContext schemaContext = TestUtils.loadSchemaContext("/leafref/yang"); Module module = TestUtils.findModule(schemaContext.getModules(), "leafref-module"); assertNotNull(module); @@ -45,7 +45,7 @@ public class Bug3595Test { @Test public void testLeafrefListKeyDeserializtion() { final YangInstanceIdentifier node1IIexpected = YangInstanceIdentifier.of(CONT_QNAME) - .node(LST_WITH_LFREF_KEY_QNAME).node(new YangInstanceIdentifier.NodeIdentifierWithPredicates( + .node(LST_WITH_LFREF_KEY_QNAME).node(new NodeIdentifierWithPredicates( LST_WITH_LFREF_KEY_QNAME, LFREF_KEY_QNAME, "node1")); final InstanceIdentifierContext iiContext = controllerContext.toInstanceIdentifier("leafref-module:cont/lst-with-lfref-key/node1"); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug8072Test.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug8072Test.java index 8edda9dab9..ad2ce0dc7b 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug8072Test.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/Bug8072Test.java @@ -9,7 +9,6 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,7 +45,7 @@ public class Bug8072Test { @BeforeClass public static void init() throws FileNotFoundException, ReactorException { final SchemaContext globalContext = TestUtils.loadSchemaContext("/full-versions/yangs"); - assertNull(globalContext.findModuleByName(EXTERNAL_MODULE_NAME, null)); + assertEquals(0, globalContext.findModules(EXTERNAL_MODULE_NAME).size()); final Set allModules = globalContext.getModules(); assertNotNull(allModules); CONTROLLER_CONTEXT.setSchemas(globalContext); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java index dd0ea449a1..dc049410da 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java @@ -124,27 +124,28 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch private static YangInstanceIdentifier createInstanceIdentifier() throws URISyntaxException { final List pathArguments = new ArrayList<>(); - pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont"))); - pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1"))); + pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont"))); + pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont1"))); - final QName qName = new QName(new URI("augment:module"), "lst11"); + final QName qName = QName.create(new URI("augment:module"), "lst11"); final Map keyValues = new HashMap<>(); - keyValues.put(new QName(new URI("augment:module"), "keyvalue111"), "value1"); - keyValues.put(new QName(new URI("augment:module"), "keyvalue112"), "value2"); + keyValues.put(QName.create(new URI("augment:module"), "keyvalue111"), "value1"); + keyValues.put(QName.create(new URI("augment:module"), "keyvalue112"), "value2"); final NodeIdentifierWithPredicates nodeIdentifierWithPredicates = new NodeIdentifierWithPredicates(qName, keyValues); pathArguments.add(nodeIdentifierWithPredicates); - pathArguments.add(new NodeIdentifier(new QName(new URI("augment:augment:module"), "lf112"))); + pathArguments.add(new NodeIdentifier(QName.create(new URI("augment:augment:module"), "lf112"))); return YangInstanceIdentifier.create(pathArguments); } private static YangInstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException { final List pathArguments = new ArrayList<>(); - pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont"))); - pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1"))); - pathArguments.add(new NodeWithValue<>(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1")); + pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont"))); + pathArguments.add(new NodeIdentifier(QName.create(new URI("instance:identifier:module"), "cont1"))); + pathArguments.add(new NodeWithValue<>(QName.create(new URI("augment:module:leaf:list"), "lflst11"), + "lflst11_1")); return YangInstanceIdentifier.create(pathArguments); } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CutDataToCorrectDepthTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CutDataToCorrectDepthTest.java index 93c23c2b05..649ec8fc87 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CutDataToCorrectDepthTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CutDataToCorrectDepthTest.java @@ -303,16 +303,16 @@ public class CutDataToCorrectDepthTest extends JerseyTest { } private static NodeIdentifier toIdentifier(final String localName) { - return new NodeIdentifier(QName.create("urn:nested:module", "2014-06-3", localName)); + return new NodeIdentifier(QName.create("urn:nested:module", "2014-06-03", localName)); } private static NodeIdentifierWithPredicates toIdentifier(final String localName, final Map keys) { - return new NodeIdentifierWithPredicates(QName.create("urn:nested:module", "2014-06-3", localName), + return new NodeIdentifierWithPredicates(QName.create("urn:nested:module", "2014-06-03", localName), keys); } private static NodeWithValue toIdentifier(final String localName, final Object value) { - return new NodeWithValue<>(QName.create("urn:nested:module", "2014-06-3", localName), value); + return new NodeWithValue<>(QName.create("urn:nested:module", "2014-06-03", localName), value); } private static UnkeyedListEntryNode nodeDataDepth3Operational() { diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java index 8ae8d0bdac..9a1d2074ae 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java @@ -67,23 +67,23 @@ public class DummyFuture implements Future> { private boolean isDone; private RpcResult result; - public Builder cancel(final boolean cancel) { - this.cancel = cancel; + public Builder cancel(final boolean newCancel) { + this.cancel = newCancel; return this; } - public Builder isCancelled(final boolean isCancelled) { - this.isCancelled = isCancelled; + public Builder isCancelled(final boolean cancelled) { + this.isCancelled = cancelled; return this; } - public Builder isDone(final boolean isDone) { - this.isDone = isDone; + public Builder isDone(final boolean done) { + this.isDone = done; return this; } - public Builder rpcResult(final RpcResult result) { - this.result = result; + public Builder rpcResult(final RpcResult newResult) { + this.result = newResult; return this; } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java index 3c545c06e9..f03330e3c3 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java @@ -49,18 +49,18 @@ public class DummyRpcResult implements RpcResult { private T result; private Collection errors; - public Builder isSuccessful(final boolean isSuccessful) { - this.isSuccessful = isSuccessful; + public Builder isSuccessful(final boolean successful) { + this.isSuccessful = successful; return this; } - public Builder result(final T result) { - this.result = result; + public Builder result(final T newResult) { + this.result = newResult; return this; } - public Builder errors(final Collection errors) { - this.errors = errors; + public Builder errors(final Collection newErrors) { + this.errors = newErrors; return this; } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java index 008fda4e09..1a7de78c5b 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.sal.restconf.impl.test; import java.util.List; +import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; @@ -29,15 +30,13 @@ public class DummyType implements TypeDefinition { } @Override - public String getDescription() { - // TODO Auto-generated method stub - return null; + public Optional getDescription() { + return Optional.empty(); } @Override - public String getReference() { - // TODO Auto-generated method stub - return null; + public Optional getReference() { + return Optional.empty(); } @Override @@ -59,15 +58,12 @@ public class DummyType implements TypeDefinition { } @Override - public String getUnits() { - // TODO Auto-generated method stub - return null; + public Optional getUnits() { + return Optional.empty(); } @Override - public Object getDefaultValue() { - // TODO Auto-generated method stub - return null; + public Optional getDefaultValue() { + return Optional.empty(); } - } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/ExpressionParserTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/ExpressionParserTest.java index 63666c78a9..434304da21 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/ExpressionParserTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/ExpressionParserTest.java @@ -132,7 +132,7 @@ public class ExpressionParserTest { } } final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class); - final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-14-12", "localName")); + final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName")); Mockito.when(path.getLastPathArgument()).thenReturn(pathValue); final ListenerAdapter listener = Notificator.createListener(path, "streamName", NotificationOutputType.JSON); listener.setQueryParams(Instant.now(), Optional.empty(), Optional.ofNullable(filter), false); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java index a1c497636b..bebb7f4e5f 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java @@ -128,7 +128,7 @@ public class InvokeRpcMethodTest { private static NormalizedNodeContext prepareDomPayload() { final SchemaContext schema = controllerContext.getGlobalSchema(); - final Module rpcModule = schema.findModuleByName("invoke-rpc-module", null); + final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next(); assertNotNull(rpcModule); final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test"); final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input"); @@ -290,7 +290,7 @@ public class InvokeRpcMethodTest { QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")); final SchemaContext schemaContext = controllerContext.getGlobalSchema(); - final Module rpcModule = schemaContext.findModuleByName("toaster", null); + final Module rpcModule = schemaContext.findModules("toaster").iterator().next(); assertNotNull(rpcModule); final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast"); final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input"); @@ -341,7 +341,7 @@ public class InvokeRpcMethodTest { @Test public void testInvokeRpcWithNoPayloadWithOutput_Success() { final SchemaContext schema = controllerContext.getGlobalSchema(); - final Module rpcModule = schema.findModuleByName("toaster", null); + final Module rpcModule = schema.findModules("toaster").iterator().next(); assertNotNull(rpcModule); final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput"); final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output"); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/JSONRestconfServiceImplTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/JSONRestconfServiceImplTest.java index 31807c84e8..5037c4bbf0 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/JSONRestconfServiceImplTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/JSONRestconfServiceImplTest.java @@ -233,14 +233,15 @@ public class JSONRestconfServiceImplTest { final ContainerNode actualNode = (ContainerNode) capturedNode.getValue(); assertEquals("ContainerNode node type", INTERFACES_QNAME, actualNode.getNodeType()); - final Optional> mapChild = actualNode.getChild(new NodeIdentifier(INTERFACE_QNAME)); + final java.util.Optional> mapChild = actualNode.getChild( + new NodeIdentifier(INTERFACE_QNAME)); assertEquals(INTERFACE_QNAME.toString() + " present", true, mapChild.isPresent()); assertTrue("Expected MapNode. Actual " + mapChild.get().getClass(), mapChild.get() instanceof MapNode); final MapNode mapNode = (MapNode)mapChild.get(); final NodeIdentifierWithPredicates entryNodeID = new NodeIdentifierWithPredicates( INTERFACE_QNAME, NAME_QNAME, "eth0"); - final Optional entryChild = mapNode.getChild(entryNodeID); + final java.util.Optional entryChild = mapNode.getChild(entryNodeID); assertEquals(entryNodeID.toString() + " present", true, entryChild.isPresent()); final MapEntryNode entryNode = entryChild.get(); verifyLeafNode(entryNode, NAME_QNAME, "eth0"); @@ -278,7 +279,7 @@ public class JSONRestconfServiceImplTest { } @Test(expected = TransactionCommitFailedException.class) - @SuppressWarnings("checkstyle:IllegalThrows") + @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" }) public void testPostFailure() throws Throwable { doReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock"))).when(brokerFacade) .commitConfigurationDataPost(any(SchemaContext.class), any(YangInstanceIdentifier.class), @@ -540,7 +541,7 @@ public class JSONRestconfServiceImplTest { } void verifyLeafNode(final DataContainerNode parent, final QName leafType, final Object leafValue) { - final Optional> leafChild = parent.getChild(new NodeIdentifier(leafType)); + final java.util.Optional> leafChild = parent.getChild(new NodeIdentifier(leafType)); assertEquals(leafType.toString() + " present", true, leafChild.isPresent()); assertEquals(leafType.toString() + " value", leafValue, leafChild.get().getValue()); } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java index 7050f72211..051ca9e7da 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java @@ -24,7 +24,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.net.URI; import java.util.ArrayList; -import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -56,7 +55,7 @@ import org.opendaylight.netconf.sal.restconf.impl.ControllerContext; import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; @@ -224,9 +223,7 @@ public class RestGetOperationTest extends JerseyTest { } private static QName newTestModuleQName(final String localPart) throws Exception { - final Date revision = SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-09"); - final URI uri = URI.create("test:module"); - return QName.create(uri, revision, localPart); + return QName.create(URI.create("test:module"), Revision.of("2014-01-09"), localPart); } @Test @@ -325,7 +322,7 @@ public class RestGetOperationTest extends JerseyTest { assertEquals("module2", qname.getLocalName()); assertEquals("module:2", qname.getNamespace().toString()); - assertEquals("2014-01-02", qname.getFormattedRevision()); + assertEquals("2014-01-02", qname.getRevision().get().toString()); response = target(uri).request("application/yang.api+json").get(); assertEquals(200, response.getStatus()); @@ -513,7 +510,7 @@ public class RestGetOperationTest extends JerseyTest { final QName module = assertedModuleXmlToModuleQName(responseXml.getDocumentElement()); assertEquals("module1-behind-mount-point", module.getLocalName()); - assertEquals("2014-02-03", module.getFormattedRevision()); + assertEquals("2014-02-03", module.getRevision().get().toString()); assertEquals("module:1:behind:mount:point", module.getNamespace().toString()); @@ -743,7 +740,7 @@ public class RestGetOperationTest extends JerseyTest { final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont"); final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build(); final NormalizedNode value = - (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build()); + Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build(); when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value); restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo); fail("Expected RestconfDocumentedException"); @@ -790,7 +787,7 @@ public class RestGetOperationTest extends JerseyTest { "Unexpected child element for parent \"" + element.getLocalName() + "\": " + actualElement.getLocalName(), expChild); - if ((expChild.data == null) || (expChild.data instanceof List)) { + if (expChild.data == null || expChild.data instanceof List) { verifyContainerElement(actualElement, expChild); } else { assertEquals("Text content for element: " + actualElement.getLocalName(), expChild.data, diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestOperationUtils.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestOperationUtils.java index 7bf4782790..bdc9679744 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestOperationUtils.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestOperationUtils.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.sal.restconf.impl.test; -public class RestOperationUtils { +public final class RestOperationUtils { public static final String JSON = "+json"; public static final String XML = "+xml"; diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplNotificationSubscribingTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplNotificationSubscribingTest.java index bbac0c5cf6..945eb6b211 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplNotificationSubscribingTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplNotificationSubscribingTest.java @@ -59,10 +59,10 @@ public class RestconfImplNotificationSubscribingTest { this.broker.setDomDataBroker(this.domDataBroker); RestconfImpl.getInstance().setBroker(this.broker); ControllerContext.getInstance() - .setGlobalSchema(YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/notifications"))); + .setGlobalSchema(YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/notifications"))); final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class); - final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-14-12", "localName")); + final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName")); Mockito.when(path.getLastPathArgument()).thenReturn(pathValue); Notificator.createListener(path, this.identifier, NotificationOutputType.XML); } @@ -196,7 +196,7 @@ public class RestconfImplNotificationSubscribingTest { @Test public void onNotifiTest() throws Exception { final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class); - final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-14-12", "localName")); + final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName")); Mockito.when(path.getLastPathArgument()).thenReturn(pathValue); final ListenerAdapter listener = Notificator.createListener(path, this.identifier, NotificationOutputType.XML); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java index f55a97ad7b..433684041f 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java @@ -102,7 +102,7 @@ public class RestconfImplTest { private void binaryKeyTest(final List al, final List al2) { - final QName keyDef = QName.create("test:key:binary", "2017-14-08", "b1"); + final QName keyDef = QName.create("test:key:binary", "2017-08-14", "b1"); final Map uriKeyValues = new HashMap<>(); uriKeyValues.put(keyDef, al.toArray()); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java index ffd4ae3632..481898d4b1 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java @@ -21,7 +21,6 @@ import java.io.OutputStreamWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; -import java.sql.Date; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; @@ -38,6 +37,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; @@ -48,7 +48,6 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMa import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,8 +58,11 @@ public final class TestUtils { private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class); - public static SchemaContext loadSchemaContext(final String... yangPath) - throws FileNotFoundException, ReactorException { + private TestUtils() { + + } + + public static SchemaContext loadSchemaContext(final String... yangPath) throws FileNotFoundException { final List files = new ArrayList<>(); for (final String path : yangPath) { final String pathToFile = TestUtils.class.getResource(path).getPath(); @@ -78,7 +80,7 @@ public final class TestUtils { } } - return YangParserTestUtils.parseYangSources(files); + return YangParserTestUtils.parseYangFiles(files); } public static Module findModule(final Set modules, final String moduleName) { @@ -159,12 +161,7 @@ public final class TestUtils { public static QName buildQName(final String name, final String uri, final String date, final String prefix) { try { - final URI u = new URI(uri); - Date dt = null; - if (date != null) { - dt = Date.valueOf(date); - } - return QName.create(u, dt, name); + return QName.create(new URI(uri), Revision.ofNullable(date), name); } catch (final URISyntaxException e) { return null; } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java index e0596f6988..10d7f75d17 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URIParametersParsing.java @@ -12,12 +12,9 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat; import com.google.common.base.Preconditions; import java.io.FileNotFoundException; -import java.text.ParseException; -import java.util.Date; import java.util.Set; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; @@ -36,6 +33,7 @@ import org.opendaylight.restconf.common.context.InstanceIdentifierContext; import org.opendaylight.restconf.common.context.NormalizedNodeContext; import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder; @@ -46,7 +44,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder; import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; @@ -87,7 +85,7 @@ public class URIParametersParsing { final LogicalDatastoreType datastoreExpected, final DataChangeScope scopeExpected) { final InstanceIdentifierBuilder iiBuilder = YangInstanceIdentifier.builder(); - iiBuilder.node(QName.create("dummyStreamName")); + iiBuilder.node(QName.create("", "dummyStreamName")); final String datastoreValue = datastore == null ? "CONFIGURATION" : datastore; final String scopeValue = scope == null ? "BASE" : scope + ""; @@ -105,8 +103,8 @@ public class URIParametersParsing { final UriBuilder uriBuilder = UriBuilder.fromUri("www.whatever.com"); when(mockedUriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder); - this.restconf.invokeRpc("sal-remote:create-data-change-event-subscription", prepareDomRpcNode(datastore, scope), - mockedUriInfo); + this.restconf.invokeRpc("sal-remote:create-data-change-event-subscription", + prepareDomRpcNode(datastoreValue, scopeValue), mockedUriInfo); final ListenerAdapter listener = Notificator.getListenerFor("data-change-event-subscription/opendaylight-inventory:nodes/datastore=" @@ -116,13 +114,7 @@ public class URIParametersParsing { private NormalizedNodeContext prepareDomRpcNode(final String datastore, final String scope) { final SchemaContext schema = this.controllerContext.getGlobalSchema(); - final Date revDate; - try { - revDate = getRevisionFormat().parse("2014-01-14"); - } catch (final ParseException e) { - throw new IllegalStateException(e); - } - final Module rpcSalRemoteModule = schema.findModuleByName("sal-remote", revDate); + final Module rpcSalRemoteModule = schema.findModule("sal-remote", Revision.of("2014-01-14")).get(); final Set setRpcs = rpcSalRemoteModule.getRpcs(); final QName rpcQName = QName.create(rpcSalRemoteModule.getQNameModule(), "create-data-change-event-subscription"); @@ -145,36 +137,37 @@ public class URIParametersParsing { QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "2014-01-14", "path"); final DataSchemaNode pathSchemaNode = rpcInputSchemaNode.getDataChildByName(pathQName); assertTrue(pathSchemaNode instanceof LeafSchemaNode); - final LeafNode pathNode = (Builders.leafBuilder((LeafSchemaNode) pathSchemaNode) + final LeafNode pathNode = Builders.leafBuilder((LeafSchemaNode) pathSchemaNode) .withValue(YangInstanceIdentifier.builder() - .node(QName.create("urn:opendaylight:inventory", "2013-08-19", "nodes")).build())).build(); + .node(QName.create("urn:opendaylight:inventory", "2013-08-19", "nodes")).build()).build(); container.withChild(pathNode); - final AugmentationSchema augmentationSchema = rpcInputSchemaNode.getAvailableAugmentations().iterator().next(); + final AugmentationSchemaNode augmentationSchema = rpcInputSchemaNode.getAvailableAugmentations().iterator() + .next(); Preconditions.checkNotNull(augmentationSchema); final DataContainerNodeBuilder augmentationBuilder = Builders.augmentationBuilder(augmentationSchema); - final QName dataStoreQName = QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "datastore"); + final QName dataStoreQName = QName.create("urn:sal:restconf:event:subscription", "2014-07-08", "datastore"); final DataSchemaNode dsSchemaNode = augmentationSchema.getDataChildByName(dataStoreQName); assertTrue(dsSchemaNode instanceof LeafSchemaNode); - final LeafNode dsNode = (Builders.leafBuilder((LeafSchemaNode) dsSchemaNode) - .withValue(datastore)).build(); + final LeafNode dsNode = Builders.leafBuilder((LeafSchemaNode) dsSchemaNode) + .withValue(datastore).build(); augmentationBuilder.withChild(dsNode); - final QName scopeQName = QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "scope"); + final QName scopeQName = QName.create("urn:sal:restconf:event:subscription", "2014-07-08", "scope"); final DataSchemaNode scopeSchemaNode = augmentationSchema.getDataChildByName(scopeQName); assertTrue(scopeSchemaNode instanceof LeafSchemaNode); - final LeafNode scopeNode = (Builders.leafBuilder((LeafSchemaNode) scopeSchemaNode) - .withValue(scope)).build(); + final LeafNode scopeNode = Builders.leafBuilder((LeafSchemaNode) scopeSchemaNode) + .withValue(scope).build(); augmentationBuilder.withChild(scopeNode); final QName outputQName = - QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "notification-output-type"); + QName.create("urn:sal:restconf:event:subscription", "2014-07-08", "notification-output-type"); final DataSchemaNode outputSchemaNode = augmentationSchema.getDataChildByName(outputQName); assertTrue(outputSchemaNode instanceof LeafSchemaNode); final LeafNode outputNode = - (Builders.leafBuilder((LeafSchemaNode) outputSchemaNode).withValue("XML")).build(); + Builders.leafBuilder((LeafSchemaNode) outputSchemaNode).withValue("XML").build(); augmentationBuilder.withChild(outputNode); container.withChild(augmentationBuilder.build()); @@ -183,7 +176,7 @@ public class URIParametersParsing { when(rpcDef.getPath()).thenReturn(SchemaPath.create(true, rpcQName)); when(rpcDef.getQName()).thenReturn(rpcQName); - return new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcDef, null, schema), + return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcDef, null, schema), container.build()); } } diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java index 6688ade142..b1562b1433 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java @@ -14,7 +14,6 @@ import java.io.FileNotFoundException; import java.util.Set; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; public abstract class YangAndXmlAndDataSchemaLoader { @@ -24,12 +23,12 @@ public abstract class YangAndXmlAndDataSchemaLoader { protected static String searchedDataSchemaName; protected static String schemaNodePath; - protected static void dataLoad(final String yangPath) throws FileNotFoundException, ReactorException { + protected static void dataLoad(final String yangPath) throws FileNotFoundException { dataLoad(yangPath, 1, null, null); } protected static void dataLoad(final String yangPath, final int modulesNumber, final String moduleName, - final String dataSchemaName) throws FileNotFoundException, ReactorException { + final String dataSchemaName) throws FileNotFoundException { modules = TestUtils.loadSchemaContext(yangPath).getModules(); assertEquals(modulesNumber, modules.size()); final Module module = TestUtils.resolveModule(moduleName, modules); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriterTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriterTest.java index d8893fe047..d8ed4902cb 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriterTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/rest/impl/DepthAwareNormalizedNodeWriterTest.java @@ -8,10 +8,10 @@ package org.opendaylight.netconf.sal.rest.impl; -import com.google.common.base.Optional; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Collections; +import java.util.Optional; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/restconf/impl/InstanceIdentifierCodecImplTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/restconf/impl/InstanceIdentifierCodecImplTest.java index 0c7ab15b53..fca1543b05 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/restconf/impl/InstanceIdentifierCodecImplTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/restconf/impl/InstanceIdentifierCodecImplTest.java @@ -33,7 +33,7 @@ public class InstanceIdentifierCodecImplTest { @Before public void setUp() throws Exception { this.schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser/deserializer")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/deserializer")); this.instanceIdentifierDTO = new InstanceIdentifierCodecImpl(null); ControllerContext.getInstance().setGlobalSchema(this.schemaContext); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapterTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapterTest.java index 41bc13146f..df9cf7fca0 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapterTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/ListenerAdapterTest.java @@ -17,7 +17,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; - import org.json.JSONObject; import org.junit.Before; import org.junit.Test; @@ -62,7 +61,7 @@ public class ListenerAdapterTest extends AbstractConcurrentDataBrokerTest { public void setUp() throws Exception { dataBroker = getDataBroker(); domDataBroker = getDomBroker(); - SchemaContext sc = YangParserTestUtils.parseYangSource( + SchemaContext sc = YangParserTestUtils.parseYangResource( "/instanceidentifier/yang/instance-identifier-patch-module.yang"); ControllerContext.getInstance().setGlobalSchema(sc); } @@ -71,8 +70,9 @@ public class ListenerAdapterTest extends AbstractConcurrentDataBrokerTest { private String lastNotification = null; - ListenerAdapterTester(YangInstanceIdentifier path, String streamName, - NotificationOutputTypeGrouping.NotificationOutputType outputType, boolean leafNodesOnly) { + ListenerAdapterTester(final YangInstanceIdentifier path, final String streamName, + final NotificationOutputTypeGrouping.NotificationOutputType outputType, + final boolean leafNodesOnly) { super(path, streamName, outputType); setQueryParams(EPOCH, Optional.empty(), Optional.empty(), leafNodesOnly); } @@ -82,7 +82,7 @@ public class ListenerAdapterTest extends AbstractConcurrentDataBrokerTest { this.lastNotification = event.getData(); } - public void assertGot(String json) throws Exception { + public void assertGot(final String json) throws Exception { long start = System.currentTimeMillis(); while (true) { if (lastNotification != null) { @@ -91,7 +91,8 @@ public class ListenerAdapterTest extends AbstractConcurrentDataBrokerTest { if (System.currentTimeMillis() - start > 1000) { throw new Exception("TIMED OUT waiting for notification with " + json); } - Thread.currentThread().sleep(200); + Thread.currentThread(); + Thread.sleep(200); } LOG.debug("Comparing {} {}", json, lastNotification); JSONAssert.assertEquals(json, withFakeDate(lastNotification), false); @@ -99,7 +100,7 @@ public class ListenerAdapterTest extends AbstractConcurrentDataBrokerTest { } } - static String withFakeDate(String in) { + static String withFakeDate(final String in) { JSONObject doc = new JSONObject(in); JSONObject notification = doc.getJSONObject("notification"); if (notification == null) { @@ -109,7 +110,7 @@ public class ListenerAdapterTest extends AbstractConcurrentDataBrokerTest { return doc.toString(); } - private String getNotifJson(String path) throws IOException, URISyntaxException { + private String getNotifJson(final String path) throws IOException, URISyntaxException { URL url = getClass().getResource(path); byte[] bytes = Files.readAllBytes(Paths.get(url.toURI())); return withFakeDate(new String(bytes, StandardCharsets.UTF_8)); diff --git a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerTest.java b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerTest.java index 920d7e0249..1edfecb327 100644 --- a/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerTest.java +++ b/restconf/restconf-nb-bierman02/src/test/java/org/opendaylight/netconf/sal/streams/listeners/NotificationListenerTest.java @@ -12,16 +12,15 @@ import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.net.URI; -import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; @@ -32,7 +31,7 @@ import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev14070 import org.opendaylight.yangtools.util.SingletonSet; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; @@ -47,16 +46,7 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; public class NotificationListenerTest { - private static final QNameModule MODULE; - - static { - try { - MODULE = QNameModule.create(URI.create("notifi:mod"), - SimpleDateFormatUtil.getRevisionFormat().parse("2016-11-23")); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - } + private static final QNameModule MODULE = QNameModule.create(URI.create("notifi:mod"), Revision.of("2016-11-23")); private SchemaContext schmeaCtx; diff --git a/restconf/restconf-nb-bierman02/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang b/restconf/restconf-nb-bierman02/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang index f88f17b587..cdc8c69c4b 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/datastore-and-scope-specification/sal-remote-augment.yang @@ -9,7 +9,7 @@ module sal-remote-augment { description "Added input parameters to rpc create-data-change-event-subscription"; - revision "2014-7-8" { + revision "2014-07-08" { } augment "/salrmt:create-data-change-event-subscription/salrmt:input" { @@ -36,4 +36,4 @@ module sal-remote-augment { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/invoke-rpc/invoke-rpc-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/invoke-rpc/invoke-rpc-module.yang index ad4883c064..e74481868f 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/invoke-rpc/invoke-rpc-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/invoke-rpc/invoke-rpc-module.yang @@ -3,7 +3,7 @@ module invoke-rpc-module { prefix "inrpcmod"; - revision 2013-12-3 { + revision 2013-12-03 { } @@ -27,4 +27,4 @@ module invoke-rpc-module { rpc rpc-noop { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identity-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identity-module.yang index 30890bf9c3..09a34c5f06 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identity-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identity-module.yang @@ -2,9 +2,9 @@ module identity-module { namespace "identity:module"; prefix "idemod"; - revision 2013-12-2 { + revision 2013-12-02 { } identity iden { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identityref-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identityref-module.yang index b90b533ce5..80ec3965fb 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identityref-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/json-to-nn/identityref/identityref-module.yang @@ -2,15 +2,15 @@ module identityref-module { namespace "identityref:module"; prefix "iderefmod"; - - import identity-module {prefix idemo; revision-date 2013-12-2;} - - revision 2013-12-2 { + + import identity-module {prefix idemo; revision-date 2013-12-02; } + + revision 2013-12-02 { } - + identity iden_local { } - + container cont { container cont1 { leaf lf11 { @@ -36,4 +36,4 @@ module identityref-module { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/modules/nested-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/modules/nested-module.yang index aa2795afeb..794859b0c2 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/modules/nested-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/modules/nested-module.yang @@ -1,7 +1,7 @@ module nested-module { namespace "urn:nested:module"; prefix "nested"; - revision "2014-06-3"; + revision "2014-06-03"; container depth1-cont { list depth2-cont1 { diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identity-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identity-module.yang index 30890bf9c3..09a34c5f06 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identity-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identity-module.yang @@ -2,9 +2,9 @@ module identity-module { namespace "identity:module"; prefix "idemod"; - revision 2013-12-2 { + revision 2013-12-02 { } identity iden { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identityref-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identityref-module.yang index 20f91b2bdd..c5c8f622a9 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identityref-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/identityref/identityref-module.yang @@ -3,9 +3,9 @@ module identityref-module { prefix "iderefmod"; - import identity-module {prefix idemo; revision-date 2013-12-2;} + import identity-module {prefix idemo; revision-date 2013-12-02; } - revision 2013-12-2 { + revision 2013-12-02 { } container cont { @@ -18,4 +18,4 @@ module identityref-module { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/cont-augment-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/cont-augment-module.yang index 528eb5e420..b54027e0bc 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/cont-augment-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/cont-augment-module.yang @@ -3,9 +3,9 @@ module cont-augment-module { prefix "cntaugmod"; - import main-module {prefix mamo; revision-date 2013-12-2;} + import main-module {prefix mamo; revision-date 2013-12-02;} - revision 2013-12-2 { + revision 2013-12-02 { } @@ -36,4 +36,4 @@ module cont-augment-module { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/main-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/main-module.yang index 1641aaae6e..0d90d2b4eb 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/main-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-json/leafref/main-module.yang @@ -2,7 +2,7 @@ module main-module { namespace "main:module"; prefix "mainmod"; - revision 2013-12-2 { + revision 2013-12-02 { } container cont { diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/aug-referenced-elements-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/aug-referenced-elements-module.yang index 1b861f5765..5829e0481c 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/aug-referenced-elements-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/aug-referenced-elements-module.yang @@ -3,9 +3,9 @@ module aug-referenced-elements-module { prefix "augrefelmo"; - import referenced-elements-module {prefix refelmo; revision-date 2013-12-3;} + import referenced-elements-module {prefix refelmo; revision-date 2013-12-03;} - revision 2013-12-3 { + revision 2013-12-03 { } augment "/refelmo:cont" { @@ -15,4 +15,4 @@ module aug-referenced-elements-module { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/eferenced-elements-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/eferenced-elements-module.yang index fd6e0fb27a..a844ac683c 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/eferenced-elements-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/eferenced-elements-module.yang @@ -3,7 +3,7 @@ module referenced-elements-module { prefix "refelmo"; - revision 2013-12-3 { + revision 2013-12-03 { } container cont { @@ -17,4 +17,4 @@ module referenced-elements-module { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/rinstance-identifier-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/rinstance-identifier-module.yang index 61ce8228b7..41a9001113 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/rinstance-identifier-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/instance_identifier/rinstance-identifier-module.yang @@ -3,7 +3,7 @@ module instance-identifier-module { prefix "inidmod"; - revision 2013-12-3 { + revision 2013-12-03 { } container cont { @@ -13,4 +13,4 @@ module instance-identifier-module { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/basic-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/basic-module.yang index 992c9af00c..efbac4dae4 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/basic-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/basic-module.yang @@ -3,9 +3,9 @@ module basic-module { prefix "basmod"; - import referenced-module {prefix refmo; revision-date 2013-12-2;} + import referenced-module {prefix refmo; revision-date 2013-12-02;} - revision 2013-12-2 { + revision 2013-12-02 { } container cont { diff --git a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/referenced-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/referenced-module.yang index 9821b1e169..e78266fbb2 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/referenced-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/nn-to-xml/yang/referenced-module.yang @@ -2,9 +2,9 @@ module referenced-module { namespace "referenced:module"; prefix "refmod"; - revision 2013-12-2 { + revision 2013-12-02 { } identity iden { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identity-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identity-module.yang index 30890bf9c3..09a34c5f06 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identity-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identity-module.yang @@ -2,9 +2,9 @@ module identity-module { namespace "identity:module"; prefix "idemod"; - revision 2013-12-2 { + revision 2013-12-02 { } identity iden { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identityref-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identityref-module.yang index a43d43990d..e0ef1bbe34 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identityref-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/identityref-module.yang @@ -3,9 +3,9 @@ module identityref-module { prefix "iderefmod"; - import identity-module {prefix idemo; revision-date 2013-12-2;} + import identity-module {prefix idemo; revision-date 2013-12-02;} - revision 2013-12-2 { + revision 2013-12-02 { } container cont { @@ -18,4 +18,4 @@ module identityref-module { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identity-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identity-module.yang index 30890bf9c3..09a34c5f06 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identity-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identity-module.yang @@ -2,9 +2,9 @@ module identity-module { namespace "identity:module"; prefix "idemod"; - revision 2013-12-2 { + revision 2013-12-02 { } identity iden { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identityref-module.yang b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identityref-module.yang index 719ac12226..8fd900277c 100644 --- a/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identityref-module.yang +++ b/restconf/restconf-nb-bierman02/src/test/resources/xml-to-cnsn/identityref/yang-augments/identityref-module.yang @@ -3,10 +3,10 @@ module identityref-module { prefix "iderefmod"; - import identity-module {prefix idemo; revision-date 2013-12-2;} + import identity-module {prefix idemo; revision-date 2013-12-02;} import general-module {prefix gmo; revision-date 2013-12-12;} - revision 2013-12-2 { + revision 2013-12-02 { } augment "/gmo:cont/gmo:cont1" { @@ -17,4 +17,4 @@ module identityref-module { } } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/Rfc8040.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/Rfc8040.java index 8c6d2ca944..8de2d24da9 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/Rfc8040.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/Rfc8040.java @@ -8,11 +8,9 @@ package org.opendaylight.restconf.nb.rfc8040; import java.net.URI; -import java.text.ParseException; -import java.util.Date; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; /** * Base Draft for Restconf project. @@ -57,25 +55,14 @@ public final class Rfc8040 { throw new UnsupportedOperationException("Util class"); } - public static final String REVISION = "2017-01-26"; + public static final Revision REVISION = Revision.of("2017-01-26"); public static final String NAME = "ietf-restconf"; public static final String NAMESPACE = "urn:ietf:params:xml:ns:yang:ietf-restconf"; + public static final URI URI_MODULE = URI.create(NAMESPACE); - public static final QName IETF_RESTCONF_QNAME = QName.create(Rfc8040.RestconfModule.NAMESPACE, + public static final QName IETF_RESTCONF_QNAME = QName.create(URI_MODULE, Rfc8040.RestconfModule.REVISION, Rfc8040.RestconfModule.NAME).intern(); - public static final Date DATE; - - static { - try { - DATE = SimpleDateFormatUtil.getRevisionFormat().parse(REVISION); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - } - - public static final URI URI_MODULE = URI.create(NAMESPACE); - // RESTCONF public static final String RESTCONF_GROUPING_SCHEMA_NODE = "restconf"; public static final String RESTCONF_CONTAINER_SCHEMA_NODE = "restconf"; @@ -117,21 +104,10 @@ public final class Rfc8040 { public static final String NAME = "ietf-yang-library"; public static final String NAMESPACE = "urn:ietf:params:xml:ns:yang:ietf-yang-library"; - public static final String REVISION = "2016-06-21"; - - public static final Date DATE; - - static { - try { - DATE = SimpleDateFormatUtil.getRevisionFormat().parse(REVISION); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - } - public static final URI URI_MODULE = URI.create(NAMESPACE); + public static final Revision REVISION = Revision.of("2016-06-21"); - public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, DATE).intern(); + public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, REVISION).intern(); public static final String MODULE_SET_ID_LEAF = "module-set-id"; public static final QName MODULE_SET_ID_LEAF_QNAME = QName.create(MODULE_QNAME, MODULE_SET_ID_LEAF).intern(); @@ -192,24 +168,14 @@ public final class Rfc8040 { public static final String NAME = "ietf-restconf-monitoring"; public static final String NAMESPACE = "urn:ietf:params:xml:ns:yang:ietf-restconf-monitoring"; - public static final String REVISION = "2017-01-26"; + public static final Revision REVISION = Revision.of("2017-01-26"); public static final String PATH_TO_STREAM_WITHOUT_KEY = "ietf-restconf-monitoring:restconf-state/streams/stream="; public static final String PATH_TO_STREAMS = "ietf-restconf-monitoring:restconf-state/streams"; - public static final Date DATE; - - static { - try { - DATE = SimpleDateFormatUtil.getRevisionFormat().parse(REVISION); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - } - public static final URI URI_MODULE = URI.create(NAMESPACE); - public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, DATE).intern(); + public static final QNameModule MODULE_QNAME = QNameModule.create(URI_MODULE, REVISION).intern(); public static final String CONT_RESTCONF_STATE_NAME = "restconf-state"; public static final QName CONT_RESTCONF_STATE_QNAME = QName.create(MODULE_QNAME, CONT_RESTCONF_STATE_NAME) diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/RestCodec.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/RestCodec.java index a4239e8bb9..947002c9f0 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/RestCodec.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/RestCodec.java @@ -11,10 +11,10 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.net.URI; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.restconf.common.util.IdentityValuesDTO; import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue; @@ -32,7 +32,7 @@ import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec; import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec; import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec; import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; +import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; @@ -49,14 +49,14 @@ import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RestCodec { +public final class RestCodec { private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class); private RestCodec() { } - public static final Codec from(final TypeDefinition typeDefinition, + public static Codec from(final TypeDefinition typeDefinition, final DOMMountPoint mountPoint, final SchemaContext schemaContext) { return new ObjectCodec(typeDefinition, mountPoint, schemaContext); } @@ -345,9 +345,9 @@ public class RestCodec { final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext); Module module = null; if (mountPoint != null) { - module = mountPoint.getSchemaContext().findModuleByNamespace(validNamespace).iterator().next(); + module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next(); } else { - module = schemaContext.findModuleByNamespace(validNamespace).iterator().next(); + module = schemaContext.findModules(validNamespace).iterator().next(); } if (module == null) { LOG.info("Module for namespace " + validNamespace + " wasn't found."); @@ -415,15 +415,16 @@ public class RestCodec { final Iterable choiceNodes = Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class); - final Iterable> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases); - for (final ChoiceCaseNode caze : Iterables.concat(map)) { + final Iterable> map = Iterables.transform(choiceNodes, + choice -> choice.getCases().values()); + for (final CaseSchemaNode caze : Iterables.concat(map)) { collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name); } } private static boolean isInstantiatedDataSchema(final DataSchemaNode node) { - return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode) - || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode) - || (node instanceof AnyXmlSchemaNode); + return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode + || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode + || node instanceof AnyXmlSchemaNode; } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/StringModuleInstanceIdentifierCodec.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/StringModuleInstanceIdentifierCodec.java index 69d26a5a67..3dc7778782 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/StringModuleInstanceIdentifierCodec.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/codecs/StringModuleInstanceIdentifierCodec.java @@ -37,11 +37,8 @@ public final class StringModuleInstanceIdentifierCodec extends AbstractModuleStr @Override protected Module moduleForPrefix(@Nonnull final String prefix) { - if (prefix.isEmpty() && !this.defaultPrefix.isEmpty()) { - return this.context.findModuleByName(this.defaultPrefix, null); - } else { - return this.context.findModuleByName(prefix, null); - } + final String moduleName = prefix.isEmpty() && !defaultPrefix.isEmpty() ? defaultPrefix : prefix; + return context.findModules(moduleName).stream().findFirst().orElse(null); } @Nonnull @@ -53,7 +50,6 @@ public final class StringModuleInstanceIdentifierCodec extends AbstractModuleStr @Nullable @Override protected String prefixForNamespace(@Nonnull final URI namespace) { - final Module module = this.context.findModuleByNamespaceAndRevision(namespace, null); - return module == null ? null : module.getName(); + return this.context.findModules(namespace).stream().findFirst().map(Module::getName).orElse(null); } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandler.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandler.java index 6ba7018cb5..e50b0152a5 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandler.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandler.java @@ -54,6 +54,7 @@ public class SchemaContextHandler implements SchemaContextListenerHandler { } @Override + @SuppressWarnings("checkstyle:hiddenField") public void onGlobalContextUpdated(final SchemaContext context) { Preconditions.checkNotNull(context); this.context = null; @@ -63,14 +64,14 @@ public class SchemaContextHandler implements SchemaContextListenerHandler { this.moduleSetId++; final Module ietfYangLibraryModule = - context.findModuleByNamespaceAndRevision(IetfYangLibrary.URI_MODULE, IetfYangLibrary.DATE); + context.findModule(IetfYangLibrary.MODULE_QNAME).orElse(null); NormalizedNode>> normNode = RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), ietfYangLibraryModule, context, String.valueOf(this.moduleSetId)); putData(normNode); final Module monitoringModule = - this.context.findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE); + this.context.findModule(MonitoringModule.MODULE_QNAME).orElse(null); normNode = RestconfMappingNodeUtil.mapCapabilites(monitoringModule); putData(normNode); } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/TransactionChainHandler.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/TransactionChainHandler.java index c949b15bcf..573dc36e01 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/TransactionChainHandler.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/handlers/TransactionChainHandler.java @@ -31,6 +31,7 @@ public class TransactionChainHandler implements Handler { } @Override + @SuppressWarnings("checkstyle:hiddenField") public void update(final DOMTransactionChain transactionChain) { Preconditions.checkNotNull(transactionChain); this.transactionChain = transactionChain; diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriter.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriter.java index 55c404a1f7..9da9bc85e6 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriter.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriter.java @@ -11,13 +11,13 @@ package org.opendaylight.restconf.nb.rfc8040.jersey.providers; import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE; import com.google.common.annotations.Beta; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter; import org.opendaylight.yangtools.yang.common.QName; diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlNormalizedNodeBodyReader.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlNormalizedNodeBodyReader.java index dc5a1f2438..54ea4fe368 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlNormalizedNodeBodyReader.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlNormalizedNodeBodyReader.java @@ -42,9 +42,9 @@ import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter; import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult; import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.AugmentationTarget; -import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; +import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; @@ -106,8 +106,8 @@ public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReade } while (!foundSchemaNodes.isEmpty()) { final Object child = foundSchemaNodes.pop(); - if (child instanceof AugmentationSchema) { - final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child; + if (child instanceof AugmentationSchemaNode) { + final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child; iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode)); } else if (child instanceof DataSchemaNode) { schemaNode = (DataSchemaNode) child; @@ -177,7 +177,7 @@ public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReade // find augmentation if (child.isAugmenting()) { - final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child); + final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child); if (augment != null) { result.push(augment); } @@ -189,12 +189,12 @@ public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReade } for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) { - for (final ChoiceCaseNode caseNode : choiceNode.getCases()) { + for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) { final Deque resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace); if (!resultFromRecursion.isEmpty()) { resultFromRecursion.push(choiceNode); if (choiceNode.isAugmenting()) { - final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode); + final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode); if (augment != null) { resultFromRecursion.push(augment); } @@ -206,10 +206,11 @@ public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReade return result; } - private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, + private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) { if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) { - for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) { + for (final AugmentationSchemaNode augmentation + : ((AugmentationTarget) parent).getAvailableAugmentations()) { final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName()); if (childInAugmentation != null) { return augmentation; diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/patch/XmlToPatchBodyReader.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/patch/XmlToPatchBodyReader.java index 62cef20f5f..2db6167dc0 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/patch/XmlToPatchBodyReader.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/patch/XmlToPatchBodyReader.java @@ -36,6 +36,7 @@ import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifie import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; @@ -77,7 +78,7 @@ public class XmlToPatchBodyReader extends AbstractToPatchBodyReader { LOG.debug("Error parsing xml input", e); throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE); + ErrorTag.MALFORMED_MESSAGE, e); } } @@ -102,8 +103,7 @@ public class XmlToPatchBodyReader extends AbstractToPatchBodyReader { ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI(); // find module according to namespace - final Module module = pathContext.getSchemaContext().findModuleByNamespace( - URI.create(namespace)).iterator().next(); + final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next(); // initialize codec + set default prefix derived from module name final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec( @@ -119,7 +119,8 @@ public class XmlToPatchBodyReader extends AbstractToPatchBodyReader { } else { targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier()) .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement, - namespace, module.getQNameModule().getFormattedRevision()))); + namespace, + module.getQNameModule().getRevision().map(Revision::toString).orElse(null)))); targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(), codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent()); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/schema/SchemaExportContentYangBodyWriter.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/schema/SchemaExportContentYangBodyWriter.java index 395f2362f4..1266a580bb 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/schema/SchemaExportContentYangBodyWriter.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/schema/SchemaExportContentYangBodyWriter.java @@ -11,6 +11,7 @@ import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; +import java.util.concurrent.ExecutionException; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; @@ -20,7 +21,6 @@ import javax.ws.rs.ext.Provider; import org.opendaylight.restconf.common.schema.SchemaExportContext; import org.opendaylight.restconf.nb.rfc8040.Rfc8040; import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; @Provider @@ -45,11 +45,11 @@ public class SchemaExportContentYangBodyWriter implements MessageBodyWriter httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { final RevisionSourceIdentifier sourceId = RevisionSourceIdentifier.create(context.getModule().getName(), - context.getModule().getQNameModule().getFormattedRevision()); + context.getModule().getQNameModule().getRevision()); final YangTextSchemaSource yangTextSchemaSource; try { - yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).checkedGet(); - } catch (SchemaSourceException e) { + yangTextSchemaSource = context.getSourceProvider().getSource(sourceId).get(); + } catch (InterruptedException | ExecutionException e) { throw new WebApplicationException("Unable to retrieve source from SourceProvider.", e); } yangTextSchemaSource.copyTo(entityStream); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/references/SchemaContextRef.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/references/SchemaContextRef.java index 64623c6e7b..40fdd71e9c 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/references/SchemaContextRef.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/references/SchemaContextRef.java @@ -10,10 +10,12 @@ package org.opendaylight.restconf.nb.rfc8040.references; import java.lang.ref.SoftReference; import java.net.URI; import java.util.Date; +import java.util.Optional; import java.util.Set; import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.restconf.nb.rfc8040.Rfc8040; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -35,7 +37,7 @@ public final class SchemaContextRef { * actual {@link SchemaContext} */ public SchemaContextRef(final SchemaContext schemaContext) { - this.schemaContextRef = new SoftReference(schemaContext); + this.schemaContextRef = new SoftReference<>(schemaContext); } /** @@ -92,11 +94,10 @@ public final class SchemaContextRef { * revision of module * @return {@link Module} */ - public Module findModuleByNamespaceAndRevision(final URI namespace, final Date revision) { - return this.get().findModuleByNamespaceAndRevision(namespace, revision); + public Module findModuleByNamespaceAndRevision(final URI namespace, final Optional revision) { + return this.get().findModule(namespace, revision).orElse(null); } - /** * Find {@link Module} in {@link SchemaContext} of {@link DOMMountPoint} by * {@link QName} of {@link Module}. @@ -110,7 +111,7 @@ public final class SchemaContextRef { public Module findModuleInMountPointByQName(final DOMMountPoint mountPoint, final QName moduleQname) { final SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext(); return schemaContext == null ? null - : schemaContext.findModuleByName(moduleQname.getLocalName(), moduleQname.getRevision()); + : schemaContext.findModule(moduleQname.getLocalName(), moduleQname.getRevision()).orElse(null); } /** @@ -134,7 +135,7 @@ public final class SchemaContextRef { * revision of module * @return {@link Module} */ - public Module findModuleByNameAndRevision(final String localName, final Date revision) { - return this.get().findModuleByName(localName, revision); + public Module findModuleByNameAndRevision(final String localName, final Optional revision) { + return this.get().findModule(localName, revision).orElse(null); } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImpl.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImpl.java index 0e8971ff4c..a8f6b91bb9 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImpl.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImpl.java @@ -48,6 +48,8 @@ import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil; import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaNode; import org.slf4j.Logger; @@ -161,12 +163,13 @@ public class RestconfDataServiceImpl implements RestconfDataService { RestconfError.ErrorTag.DATA_MISSING); } - if ((parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)) + if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL) || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) { + final QName type = node.getNodeType(); return Response.status(200) .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)) - .header("ETag", '"' + node.getNodeType().getModule().getFormattedRevision() - + node.getNodeType().getLocalName() + '"') + .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null) + + type.getLocalName() + '"') .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC()))) .build(); } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/transactions/TransactionVarsWrapper.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/transactions/TransactionVarsWrapper.java index fb7ef5c48b..b678623fdd 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/transactions/TransactionVarsWrapper.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/transactions/TransactionVarsWrapper.java @@ -64,11 +64,11 @@ public final class TransactionVarsWrapper { /** * Set {@link LogicalDatastoreType} of data for transaction. * - * @param configuration + * @param datastoreType * {@link LogicalDatastoreType} */ - public void setLogicalDatastoreType(final LogicalDatastoreType configuration) { - this.configuration = configuration; + public void setLogicalDatastoreType(final LogicalDatastoreType datastoreType) { + this.configuration = datastoreType; } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtil.java index 3986598cff..dff93ea258 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtil.java @@ -7,11 +7,11 @@ */ package org.opendaylight.restconf.nb.rfc8040.rests.utils; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.CheckedFuture; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ParametersUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ParametersUtil.java index 919446f74b..853face35e 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ParametersUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ParametersUtil.java @@ -17,7 +17,7 @@ import org.opendaylight.restconf.common.errors.RestconfError; import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag; import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; -class ParametersUtil { +final class ParametersUtil { private ParametersUtil() { throw new UnsupportedOperationException("Util class."); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtil.java index fe772b2d8f..1d6d96083b 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtil.java @@ -53,6 +53,10 @@ import org.opendaylight.yangtools.yang.model.api.SchemaNode; */ public final class PutDataTransactionUtil { + private PutDataTransactionUtil() { + + } + /** * Valid input data with {@link SchemaNode}. * diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ReadDataTransactionUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ReadDataTransactionUtil.java index 2aa4f0603b..fc55fa7649 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ReadDataTransactionUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/ReadDataTransactionUtil.java @@ -171,9 +171,9 @@ public final class ReadDataTransactionUtil { if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) { final Integer value = Ints.tryParse(depth.get(0)); - if ((value == null) - || (!((value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH) - && (value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)))) { + if (value == null + || !(value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH + && value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)) { throw new RestconfDocumentedException( new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE, "Invalid depth parameter: " + depth, null, @@ -347,8 +347,8 @@ public final class ReadDataTransactionUtil { ((ListSchemaNode) childSchema).getKeyDefinition()); builder.withChild(childBuilder.build()); } else if (child instanceof LeafNode) { - final String defaultVal = ((LeafSchemaNode) childSchema).getDefault(); - final String nodeVal = ((LeafNode) child).getValue(); + final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null); + final Object nodeVal = ((LeafNode) child).getValue(); final NormalizedNodeAttrBuilder> leafBuilder = Builders.leafBuilder((LeafSchemaNode) childSchema); if (keys.contains(child.getNodeType())) { @@ -356,12 +356,12 @@ public final class ReadDataTransactionUtil { builder.withChild(leafBuilder.build()); } else { if (trim) { - if ((defaultVal == null) || !defaultVal.equals(nodeVal)) { + if (defaultVal == null || !defaultVal.equals(nodeVal)) { leafBuilder.withValue(((LeafNode) child).getValue()); builder.withChild(leafBuilder.build()); } } else { - if ((defaultVal != null) && defaultVal.equals(nodeVal)) { + if (defaultVal != null && defaultVal.equals(nodeVal)) { leafBuilder.withValue(((LeafNode) child).getValue()); builder.withChild(leafBuilder.build()); } @@ -402,17 +402,17 @@ public final class ReadDataTransactionUtil { ((ListSchemaNode) childSchema).getKeyDefinition()); builder.withChild(childBuilder.build()); } else if (child instanceof LeafNode) { - final String defaultVal = ((LeafSchemaNode) childSchema).getDefault(); - final String nodeVal = ((LeafNode) child).getValue(); + final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null); + final Object nodeVal = ((LeafNode) child).getValue(); final NormalizedNodeAttrBuilder> leafBuilder = Builders.leafBuilder((LeafSchemaNode) childSchema); if (trim) { - if ((defaultVal == null) || !defaultVal.equals(nodeVal)) { + if (defaultVal == null || !defaultVal.equals(nodeVal)) { leafBuilder.withValue(((LeafNode) child).getValue()); builder.withChild(leafBuilder.build()); } } else { - if ((defaultVal != null) && defaultVal.equals(nodeVal)) { + if (defaultVal != null && defaultVal.equals(nodeVal)) { leafBuilder.withValue(((LeafNode) child).getValue()); builder.withChild(leafBuilder.build()); } @@ -473,7 +473,7 @@ public final class ReadDataTransactionUtil { } // if no data exists - if ((stateDataNode == null) && (configDataNode == null)) { + if (stateDataNode == null && configDataNode == null) { return null; } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfDataServiceConstant.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfDataServiceConstant.java index c0acdcb0ca..8077b5cc00 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfDataServiceConstant.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfDataServiceConstant.java @@ -8,10 +8,6 @@ package org.opendaylight.restconf.nb.rfc8040.rests.utils; import java.net.URI; -import java.net.URISyntaxException; -import org.opendaylight.restconf.common.errors.RestconfDocumentedException; -import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag; -import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; @@ -21,18 +17,8 @@ import org.opendaylight.yangtools.yang.common.QNameModule; */ public final class RestconfDataServiceConstant { - public static final QName NETCONF_BASE_QNAME; - - static { - try { - NETCONF_BASE_QNAME = QName.create( - QNameModule.create(new URI(PutData.NETCONF_BASE), null), PutData.NETCONF_BASE_PAYLOAD_NAME); - } catch (final URISyntaxException e) { - final String errMsg = "It wasn't possible to create instance of URI class with " + PutData.NETCONF_BASE - + " URI"; - throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED); - } - } + public static final QName NETCONF_BASE_QNAME = QName.create(QNameModule.create(URI.create(PutData.NETCONF_BASE)), + PutData.NETCONF_BASE_PAYLOAD_NAME); private RestconfDataServiceConstant() { throw new UnsupportedOperationException("Util class."); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfInvokeOperationsUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfInvokeOperationsUtil.java index c76c79d33f..b5d44cd5ac 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfInvokeOperationsUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfInvokeOperationsUtil.java @@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory; * Util class for rpc. * */ -public class RestconfInvokeOperationsUtil { +public final class RestconfInvokeOperationsUtil { private static final Logger LOG = LoggerFactory.getLogger(RestconfInvokeOperationsUtil.class); @@ -102,7 +102,7 @@ public class RestconfInvokeOperationsUtil { } catch (final CancellationException e) { final String errMsg = "The operation was cancelled while executing."; LOG.debug("Cancel RpcExecution: " + errMsg, e); - throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION); + throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e); } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfStreamsConstants.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfStreamsConstants.java index c68cb49c8b..7f17200664 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfStreamsConstants.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/RestconfStreamsConstants.java @@ -9,50 +9,28 @@ package org.opendaylight.restconf.nb.rfc8040.rests.utils; import com.google.common.collect.ImmutableSet; import java.net.URI; -import java.text.ParseException; -import java.util.Date; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.restconf.common.errors.RestconfDocumentedException; -import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag; -import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Constants for streams. * */ public final class RestconfStreamsConstants { - - private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsConstants.class); - public static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote"; public static final String DATASTORE_PARAM_NAME = "datastore"; private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription"); - public static final QNameModule SAL_REMOTE_AUGMENT; - - static { - final Date eventSubscriptionAugRevision; - try { - eventSubscriptionAugRevision = SimpleDateFormatUtil.getRevisionFormat().parse("2014-07-08"); - } catch (final ParseException e) { - final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date"; - LOG.debug(errMsg); - throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED); - } - SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, eventSubscriptionAugRevision) - .intern(); - } + public static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT, + Revision.of("2014-07-08")).intern(); public static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER = new AugmentationIdentifier( ImmutableSet.of(QName.create(SAL_REMOTE_AUGMENT, "scope"), QName.create(SAL_REMOTE_AUGMENT, "datastore"), diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/SubscribeToStreamUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/SubscribeToStreamUtil.java index b7430c674a..f6b685ac06 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/SubscribeToStreamUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/SubscribeToStreamUtil.java @@ -113,7 +113,7 @@ public final class SubscribeToStreamUtil { } else { listeners = pickSpecificListenerByOutput(listeners, NotificationOutputType.XML.getName()); } - if ((listeners == null) || listeners.isEmpty()) { + if (listeners == null || listeners.isEmpty()) { throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } @@ -163,7 +163,7 @@ public final class SubscribeToStreamUtil { public static InstanceIdentifierContext prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) { final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi"); final DataSchemaNode location = ((ContainerSchemaNode) schemaHandler.get() - .findModuleByNamespaceAndRevision(qnameBase.getNamespace(), qnameBase.getRevision()) + .findModule(qnameBase.getModule()).get() .getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location")); final List path = new ArrayList<>(); path.add(NodeIdentifier.create(qnameBase)); @@ -238,9 +238,7 @@ public final class SubscribeToStreamUtil { } public static Module getMonitoringModule(final SchemaContext schemaContext) { - final Module monitoringModule = - schemaContext.findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE); - return monitoringModule; + return schemaContext.findModule(MonitoringModule.MODULE_QNAME).orElse(null); } /** @@ -389,7 +387,7 @@ public final class SubscribeToStreamUtil { * @return enum */ private static T parseURIEnum(final Class clazz, final String value) { - if ((value == null) || value.equals("")) { + if (value == null || value.equals("")) { return null; } return ResolveEnumUtil.resolveEnum(clazz, value); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeContainerSchemaNode.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeContainerSchemaNode.java index 8604f57568..db1641618a 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeContainerSchemaNode.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeContainerSchemaNode.java @@ -11,15 +11,19 @@ import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; -import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; +import org.opendaylight.yangtools.yang.model.api.ActionDefinition; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.MustDefinition; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; +import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; @@ -57,10 +61,10 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { } @Override - public DataSchemaNode getDataChildByName(final QName name) { + public Optional findDataChildByName(final QName name) { for (final DataSchemaNode node : this.children) { if (node.getQName().equals(name)) { - return node; + return Optional.of(node); } } throw new RestconfDocumentedException(name + " is not in child of " + PATH.getLastComponent()); @@ -72,7 +76,7 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { } @Override - public Set getAvailableAugmentations() { + public Set getAvailableAugmentations() { return new HashSet<>(); } @@ -91,11 +95,6 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { return false; } - @Override - public ConstraintDefinition getConstraints() { - throw new UnsupportedOperationException("Not supported."); - } - @Override public QName getQName() { return PATH.getLastComponent(); @@ -112,12 +111,12 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException("Not supported."); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException("Not supported."); } @@ -130,4 +129,24 @@ class FakeContainerSchemaNode implements ContainerSchemaNode { public boolean isPresenceContainer() { throw new UnsupportedOperationException("Not supported."); } + + @Override + public Optional getWhenCondition() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Set getNotifications() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Set getActions() { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Collection getMustConstraints() { + throw new UnsupportedOperationException("Not supported."); + } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeImportedModule.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeImportedModule.java index 5bcab1ac52..3d7feae3fd 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeImportedModule.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeImportedModule.java @@ -13,12 +13,15 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.net.URI; import java.util.Collection; -import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.Set; +import org.opendaylight.yangtools.concepts.SemVer; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.common.Revision; +import org.opendaylight.yangtools.yang.common.YangVersion; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Deviation; import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition; @@ -27,6 +30,7 @@ import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.ModuleImport; +import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; @@ -61,8 +65,8 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public DataSchemaNode getDataChildByName(final QName name) { - return null; + public Optional findDataChildByName(final QName name) { + return Optional.empty(); } @Override @@ -70,11 +74,6 @@ final class FakeImportedModule extends ForwardingObject implements Module { return ImmutableSet.of(); } - @Override - public String getModuleSourcePath() { - return null; - } - @Override public QNameModule getQNameModule() { return delegate.getQNameModule(); @@ -91,7 +90,7 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public Date getRevision() { + public Optional getRevision() { return delegate.getRevision(); } @@ -101,27 +100,27 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public String getYangVersion() { + public YangVersion getYangVersion() { return delegate.getYangVersion(); } @Override - public String getDescription() { + public Optional getDescription() { return delegate.getDescription(); } @Override - public String getReference() { + public Optional getReference() { return delegate.getReference(); } @Override - public String getOrganization() { + public Optional getOrganization() { return delegate.getOrganization(); } @Override - public String getContact() { + public Optional getContact() { return delegate.getContact(); } @@ -141,7 +140,7 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public Set getAugmentations() { + public Set getAugmentations() { return ImmutableSet.of(); } @@ -171,7 +170,12 @@ final class FakeImportedModule extends ForwardingObject implements Module { } @Override - public String getSource() { - return null; + public Set getNotifications() { + return ImmutableSet.of(); + } + + @Override + public Optional getSemanticVersion() { + return Optional.empty(); } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeLeafSchemaNode.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeLeafSchemaNode.java index 053fd334cd..e758342ac4 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeLeafSchemaNode.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeLeafSchemaNode.java @@ -7,10 +7,14 @@ */ package org.opendaylight.restconf.nb.rfc8040.services.simple.impl; +import com.google.common.collect.ImmutableList; +import java.util.Collection; import java.util.List; +import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; +import org.opendaylight.yangtools.yang.model.api.MustDefinition; +import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; @@ -51,11 +55,6 @@ final class FakeLeafSchemaNode implements LeafSchemaNode { return false; } - @Override - public ConstraintDefinition getConstraints() { - throw new UnsupportedOperationException("Not supported."); - } - @Override public QName getQName() { return path.getLastComponent(); @@ -72,12 +71,12 @@ final class FakeLeafSchemaNode implements LeafSchemaNode { } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException("Not supported operations."); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException("Not supported."); } @@ -92,13 +91,17 @@ final class FakeLeafSchemaNode implements LeafSchemaNode { } @Override - public String getDefault() { - throw new UnsupportedOperationException("Not supported."); + public Optional getWhenCondition() { + return Optional.empty(); } @Override - public String getUnits() { + public boolean isMandatory() { throw new UnsupportedOperationException("Not supported."); } + @Override + public Collection getMustConstraints() { + return ImmutableList.of(); + } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeModuleImport.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeModuleImport.java index 8ce1b391c8..eff7662440 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeModuleImport.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeModuleImport.java @@ -8,7 +8,9 @@ package org.opendaylight.restconf.nb.rfc8040.services.simple.impl; import com.google.common.base.Preconditions; -import java.util.Date; +import java.util.Optional; +import org.opendaylight.yangtools.concepts.SemVer; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.ModuleImport; @@ -30,7 +32,7 @@ final class FakeModuleImport implements ModuleImport { } @Override - public Date getRevision() { + public Optional getRevision() { return module.getRevision(); } @@ -38,4 +40,19 @@ final class FakeModuleImport implements ModuleImport { public String getPrefix() { return module.getName(); } + + @Override + public Optional getDescription() { + return module.getDescription(); + } + + @Override + public Optional getReference() { + return module.getReference(); + } + + @Override + public Optional getSemanticVersion() { + return module.getSemanticVersion(); + } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeRestconfModule.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeRestconfModule.java index 73ed275767..8dcc91c214 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeRestconfModule.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/FakeRestconfModule.java @@ -11,17 +11,17 @@ import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.net.URI; -import java.text.ParseException; import java.util.Collection; -import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.Set; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; +import org.opendaylight.yangtools.concepts.SemVer; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.common.YangVersion; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; +import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Deviation; @@ -44,17 +44,8 @@ import org.opendaylight.yangtools.yang.model.api.UsesNode; */ final class FakeRestconfModule implements Module { - static final QNameModule QNAME; - - static { - Date date; - try { - date = SimpleDateFormatUtil.getRevisionFormat().parse("2016-06-28"); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"), date).intern(); - } + static final QNameModule QNAME = QNameModule.create(URI.create("urn:ietf:params:xml:ns:yang:ietf-restconf"), + Revision.of("2016-06-28")).intern(); private final Collection children; private final ImmutableSet imports; @@ -86,10 +77,10 @@ final class FakeRestconfModule implements Module { } @Override - public DataSchemaNode getDataChildByName(final QName name) { + public Optional findDataChildByName(final QName name) { for (final DataSchemaNode node : this.children) { if (node.getQName().equals(name)) { - return node; + return Optional.of(node); } } throw new RestconfDocumentedException(name + " is not in child of " + FakeRestconfModule.QNAME); @@ -100,11 +91,6 @@ final class FakeRestconfModule implements Module { throw new UnsupportedOperationException("Not supported operations."); } - @Override - public String getModuleSourcePath() { - throw new UnsupportedOperationException("Not supported operations."); - } - @Override public QNameModule getQNameModule() { return QNAME; @@ -121,7 +107,7 @@ final class FakeRestconfModule implements Module { } @Override - public Date getRevision() { + public Optional getRevision() { return QNAME.getRevision(); } @@ -131,27 +117,27 @@ final class FakeRestconfModule implements Module { } @Override - public String getYangVersion() { - return YangVersion.VERSION_1.toString(); + public YangVersion getYangVersion() { + return YangVersion.VERSION_1; } @Override - public String getDescription() { + public Optional getDescription() { throw new UnsupportedOperationException("Operation not implemented."); } @Override - public String getReference() { + public Optional getReference() { throw new UnsupportedOperationException("Operation not implemented."); } @Override - public String getOrganization() { + public Optional getOrganization() { throw new UnsupportedOperationException("Operation not implemented."); } @Override - public String getContact() { + public Optional getContact() { throw new UnsupportedOperationException("Operation not implemented."); } @@ -176,7 +162,7 @@ final class FakeRestconfModule implements Module { } @Override - public Set getAugmentations() { + public Set getAugmentations() { throw new UnsupportedOperationException("Operation not implemented."); } @@ -206,7 +192,7 @@ final class FakeRestconfModule implements Module { } @Override - public String getSource() { + public Optional getSemanticVersion() { throw new UnsupportedOperationException("Operation not implemented."); } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImpl.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImpl.java index 386c991ad3..bd09420727 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImpl.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImpl.java @@ -36,7 +36,7 @@ public class RestconfImpl implements RestconfService { final SchemaContext context = this.schemaContextHandler.get(); SchemaNode schemaNode = null; for (final GroupingDefinition groupingDefinition : context - .findModuleByNamespaceAndRevision(RestconfModule.URI_MODULE, RestconfModule.DATE).getGroupings()) { + .findModule(RestconfModule.IETF_RESTCONF_QNAME.getModule()).get().getGroupings()) { if (groupingDefinition.getQName().equals(RestconfModule.RESTCONF_GROUPING_QNAME)) { schemaNode = ((ContainerSchemaNode) groupingDefinition .getDataChildByName(RestconfModule.RESTCONF_CONTAINER_QNAME)) @@ -44,9 +44,9 @@ public class RestconfImpl implements RestconfService { } } final YangInstanceIdentifier yangIId = YangInstanceIdentifier.of( - QName.create(RestconfModule.NAME, RestconfModule.REVISION, RestconfModule.LIB_VER_LEAF_SCHEMA_NODE)); + QName.create(RestconfModule.IETF_RESTCONF_QNAME, RestconfModule.LIB_VER_LEAF_SCHEMA_NODE)); final InstanceIdentifierContext iid = - new InstanceIdentifierContext(yangIId, schemaNode, null, context); + new InstanceIdentifierContext<>(yangIId, schemaNode, null, context); final NormalizedNode data = Builders.leafBuilder((LeafSchemaNode) schemaNode).withValue(IetfYangLibrary.REVISION).build(); return new NormalizedNodeContext(iid, data); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceImpl.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceImpl.java index 93c99146c4..d51a634757 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceImpl.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceImpl.java @@ -25,6 +25,7 @@ import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef; import org.opendaylight.restconf.nb.rfc8040.services.simple.api.RestconfOperationsService; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier; +import org.opendaylight.yangtools.yang.common.Empty; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; @@ -132,7 +133,7 @@ public class RestconfOperationsServiceImpl implements RestconfOperationsService Builders.containerBuilder(fakeCont); for (final LeafSchemaNode leaf : fakeRpcSchema) { - containerBuilder.withChild(Builders.leafBuilder(leaf).build()); + containerBuilder.withChild(Builders.leafBuilder(leaf).withValue(Empty.getInstance()).build()); } final Collection fakeModules = new ArrayList<>(neededModules.size() + 1); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/wrapper/ServicesWrapperImpl.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/wrapper/ServicesWrapperImpl.java index 269900231d..2f1358bfb0 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/wrapper/ServicesWrapperImpl.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/services/wrapper/ServicesWrapperImpl.java @@ -46,7 +46,7 @@ import org.opendaylight.restconf.nb.rfc8040.services.simple.impl.RestconfSchemaS * */ @Path("/") -public class ServicesWrapperImpl implements BaseServicesWrapper, TransactionServicesWrapper, ServiceWrapper { +public final class ServicesWrapperImpl implements BaseServicesWrapper, TransactionServicesWrapper, ServiceWrapper { private RestconfDataService delegRestconfDataService; private RestconfInvokeOperationsService delegRestconfInvokeOpsService; diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractNotificationsData.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractNotificationsData.java index 768309fb17..598d4b15cf 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractNotificationsData.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractNotificationsData.java @@ -66,6 +66,7 @@ abstract class AbstractNotificationsData { * {@link MonitoringModule#PATH_TO_STREAM_WITHOUT_KEY} to * {@link YangInstanceIdentifier} */ + @SuppressWarnings("checkstyle:hiddenField") public void setCloseVars(final TransactionChainHandler transactionChainHandler, final SchemaContextHandler schemaHandler) { this.transactionChainHandler = transactionChainHandler; @@ -88,6 +89,7 @@ abstract class AbstractNotificationsData { * @param localName * local name */ + @SuppressWarnings("checkstyle:hiddenField") protected void setLocalNameOfPath(final String localName) { this.localName = localName; } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractQueryParams.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractQueryParams.java index e9a412d1f3..93dfc80309 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractQueryParams.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractQueryParams.java @@ -71,6 +71,7 @@ abstract class AbstractQueryParams extends AbstractNotificationsData { * @param leafNodesOnly * if true, notifications will contain changes to leaf nodes only */ + @SuppressWarnings("checkstyle:hiddenField") public void setQueryParams(final Instant start, final Optional stop, final Optional filter, final boolean leafNodesOnly) { this.start = Preconditions.checkNotNull(start); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/ListenerAdapter.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/ListenerAdapter.java index 7e2d89b6ff..815f4b413e 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/ListenerAdapter.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/ListenerAdapter.java @@ -71,11 +71,12 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData this.outputType = Preconditions.checkNotNull(outputType); this.path = Preconditions.checkNotNull(path); - Preconditions.checkArgument((streamName != null) && !streamName.isEmpty()); + Preconditions.checkArgument(streamName != null && !streamName.isEmpty()); this.streamName = streamName; } @Override + @SuppressWarnings("checkstyle:hiddenField") public void onDataChanged(final AsyncDataChangeEvent> change) { this.change = change; final String xml = prepareXml(); @@ -163,6 +164,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData * @param change * {@link AsyncDataChangeEvent} */ + @SuppressWarnings("checkstyle:hiddenField") private void addValuesToDataChangedNotificationEventElement(final Document doc, final Element dataChangedNotificationEventElement, final AsyncDataChangeEvent> change, @@ -197,12 +199,12 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData private void addValuesFromDataToElement(final Document doc, final Set data, final Element element, final Operation operation, final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) { - if ((data == null) || data.isEmpty()) { + if (data == null || data.isEmpty()) { return; } - for (final YangInstanceIdentifier path : data) { - if (!dataSchemaContextTree.getChild(path).isMixin()) { - final Node node = createDataChangeEventElement(doc, path, operation, schemaContext); + for (final YangInstanceIdentifier yiid : data) { + if (!dataSchemaContextTree.getChild(yiid).isMixin()) { + final Node node = createDataChangeEventElement(doc, yiid, operation, schemaContext); element.appendChild(node); } } @@ -212,7 +214,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData final Set>> data, final Element element, final Operation operation, final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) { - if ((data == null) || data.isEmpty()) { + if (data == null || data.isEmpty()) { return; } for (final Entry> entry : data) { @@ -238,11 +240,11 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData * schema context * @return {@link Node} node represented by changed event element. */ - private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path, + private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier eventPath, final Operation operation, final SchemaContext schemaContext) { final Element dataChangeEventElement = doc.createElement("data-change-event"); final Element pathElement = doc.createElement("path"); - addPathAsValueToElement(path, pathElement, schemaContext); + addPathAsValueToElement(eventPath, pathElement, schemaContext); dataChangeEventElement.appendChild(pathElement); final Element operationElement = doc.createElement("operation"); @@ -257,8 +259,8 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData final SchemaContext schemaContext, final DataSchemaContextTree dataSchemaContextTree) { final Element dataChangeEventElement = doc.createElement("data-change-event"); final Element pathElement = doc.createElement("path"); - final YangInstanceIdentifier path = entry.getKey(); - addPathAsValueToElement(path, pathElement, schemaContext); + final YangInstanceIdentifier eventPath = entry.getKey(); + addPathAsValueToElement(eventPath, pathElement, schemaContext); dataChangeEventElement.appendChild(pathElement); final Element operationElement = doc.createElement("operation"); @@ -268,10 +270,10 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData try { SchemaPath nodePath; final NormalizedNode normalized = entry.getValue(); - if ((normalized instanceof MapEntryNode) || (normalized instanceof UnkeyedListEntryNode)) { - nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath(); + if (normalized instanceof MapEntryNode || normalized instanceof UnkeyedListEntryNode) { + nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath(); } else { - nodePath = dataSchemaContextTree.getChild(path).getDataSchemaNode().getPath().getParent(); + nodePath = dataSchemaContextTree.getChild(eventPath).getDataSchemaNode().getPath().getParent(); } final DOMResult domResult = writeNormalizedNode(normalized, schemaContext, nodePath); final Node result = doc.importNode(domResult.getNode().getFirstChild(), true); @@ -290,7 +292,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData /** * Adds path as value to element. * - * @param path + * @param eventPath * Path to data in data store. * @param element * {@link Element} @@ -298,11 +300,11 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData * schema context */ @SuppressWarnings("rawtypes") - private void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element, + private void addPathAsValueToElement(final YangInstanceIdentifier eventPath, final Element element, final SchemaContext schemaContext) { final StringBuilder textContent = new StringBuilder(); - for (final PathArgument pathArgument : path.getPathArguments()) { + for (final PathArgument pathArgument : eventPath.getPathArguments()) { if (pathArgument instanceof YangInstanceIdentifier.AugmentationIdentifier) { continue; } @@ -343,8 +345,7 @@ public class ListenerAdapter extends AbstractCommonSubscriber implements DOMData */ private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent, final QName qualifiedName, final SchemaContext schemaContext) { - final Module module = schemaContext.findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), - qualifiedName.getRevision()); + final Module module = schemaContext.findModule(qualifiedName.getModule()).get(); textContent.append(module.getName()); textContent.append(":"); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerAdapter.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerAdapter.java index 33e08d2e2f..a7b573038b 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerAdapter.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerAdapter.java @@ -85,6 +85,7 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem } @Override + @SuppressWarnings("checkstyle:hiddenField") public void onNotification(final DOMNotification notification) { this.schemaContext = schemaHandler.get(); this.notification = notification; @@ -174,14 +175,13 @@ public class NotificationListenerAdapter extends AbstractCommonSubscriber implem final Element notificationEventElement = doc.createElementNS( "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "create-notification-stream"); - addValuesToNotificationEventElement(doc, notificationEventElement, this.notification, this.schemaContext); + addValuesToNotificationEventElement(doc, notificationEventElement); notificationElement.appendChild(notificationEventElement); return transformDoc(doc); } - private void addValuesToNotificationEventElement(final Document doc, final Element element, - final DOMNotification notification, final SchemaContext schemaContext) { + private void addValuesToNotificationEventElement(final Document doc, final Element element) { if (notification == null) { return; } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/Notificator.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/Notificator.java index cd4c74ad18..d26fca4ed2 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/Notificator.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/Notificator.java @@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory; * {@link Notificator} is responsible to create, remove and find * {@link ListenerAdapter} listener. */ -public class Notificator { +public final class Notificator { private static Map dataChangeListener = new ConcurrentHashMap<>(); private static Map> notificationListenersByStreamName = diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/websockets/WebSocketServer.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/websockets/WebSocketServer.java index b497f74a76..029cb27f78 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/websockets/WebSocketServer.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/websockets/WebSocketServer.java @@ -22,7 +22,7 @@ import org.slf4j.LoggerFactory; * {@link WebSocketServer} is the singleton responsible for starting and stopping the * web socket server. */ -public class WebSocketServer implements Runnable { +public final class WebSocketServer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtil.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtil.java index 4f645edf9a..b0eb474b0a 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtil.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtil.java @@ -22,6 +22,7 @@ import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule.QueryParams import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.Module.ConformanceType; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; @@ -119,19 +120,20 @@ public final class RestconfMappingNodeUtil { addCommonLeafs(module, mapEntryBuilder, ietfYangLibraryModule); addChildOfModuleBySpecificModuleInternal( IetfYangLibrary.SPECIFIC_MODULE_SCHEMA_LEAF_QNAME, mapEntryBuilder, IetfYangLibrary.BASE_URI_OF_SCHEMA - + module.getName() + "/" + module.getQNameModule().getFormattedRevision(), + + module.getName() + "/" + + module.getQNameModule().getRevision().map(Revision::toString).orElse(null), ietfYangLibraryModule); if (!isSubmodule) { addChildOfModuleBySpecificModuleOfListChild(IetfYangLibrary.SPECIFIC_MODULE_NAMESPACE_LEAF_QNAME, mapEntryBuilder, module.getNamespace().toString(), ietfYangLibraryModule); // features - not mandatory - if ((module.getFeatures() != null) && !module.getFeatures().isEmpty()) { + if (module.getFeatures() != null && !module.getFeatures().isEmpty()) { addFeatureLeafList(IetfYangLibrary.SPECIFIC_MODULE_FEATURE_LEAF_LIST_QNAME, mapEntryBuilder, module.getFeatures(), ietfYangLibraryModule); } // deviations - not mandatory - if ((module.getDeviations() != null) && !module.getDeviations().isEmpty()) { + if (module.getDeviations() != null && !module.getDeviations().isEmpty()) { addDeviationList(module, mapEntryBuilder, ietfYangLibraryModule, context); addChildOfModuleBySpecificModuleOfListChild(IetfYangLibrary.SPECIFIC_MODULE_CONFORMANCE_LEAF_QNAME, mapEntryBuilder, ConformanceType.Implement.getName(), ietfYangLibraryModule); @@ -140,7 +142,7 @@ public final class RestconfMappingNodeUtil { mapEntryBuilder, ConformanceType.Import.getName(), ietfYangLibraryModule); } // submodules - not mandatory - if ((module.getSubmodules() != null) && !module.getSubmodules().isEmpty()) { + if (module.getSubmodules() != null && !module.getSubmodules().isEmpty()) { addSubmodules(module, mapEntryBuilder, ietfYangLibraryModule, context); } } @@ -196,8 +198,7 @@ public final class RestconfMappingNodeUtil { Builders.mapEntryBuilder((ListSchemaNode) deviationsSchema); final QName lastComponent = deviation.getTargetPath().getLastComponent(); addChildOfModuleBySpecificModule(IetfYangLibrary.SPECIFIC_MODULE_NAME_LEAF_QNAME, deviationEntryNode, - context.findModuleByNamespaceAndRevision(lastComponent.getNamespace(), lastComponent.getRevision()) - .getName(), + context.findModule(lastComponent.getModule()).get().getName(), ietfYangLibraryModule); addChildOfModuleBySpecificModule(IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF_QNAME, deviationEntryNode, lastComponent.getRevision(), ietfYangLibraryModule); @@ -249,7 +250,7 @@ public final class RestconfMappingNodeUtil { addChildOfModuleBySpecificModuleInternal(IetfYangLibrary.SPECIFIC_MODULE_NAME_LEAF_QNAME, mapEntryBuilder, module.getName(), ietfYangLibraryModule); addChildOfModuleBySpecificModuleInternal(IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF_QNAME, mapEntryBuilder, - module.getQNameModule().getFormattedRevision(), ietfYangLibraryModule); + module.getQNameModule().getRevision().map(Revision::toString).orElse(""), ietfYangLibraryModule); } /** @@ -486,15 +487,15 @@ public final class RestconfMappingNodeUtil { final DataContainerNodeAttrBuilder streamEntry = Builders.mapEntryBuilder((ListSchemaNode) streamListSchema); - final ListSchemaNode listSchema = ((ListSchemaNode) streamListSchema); + final ListSchemaNode listSchema = (ListSchemaNode) streamListSchema; prepareLeafAndFillEntryBuilder(streamEntry, listSchema.getDataChildByName(MonitoringModule.LEAF_NAME_STREAM_QNAME), notificationDefinition.getQName().getLocalName()); - if ((notificationDefinition.getDescription() != null) - && !notificationDefinition.getDescription().equals("")) { + + final java.util.Optional optDesc = notificationDefinition.getDescription(); + if (optDesc.isPresent()) { prepareLeafAndFillEntryBuilder(streamEntry, - listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME), - notificationDefinition.getDescription()); + listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME), optDesc.get()); } prepareLeafAndFillEntryBuilder(streamEntry, listSchema.getDataChildByName(MonitoringModule.LEAF_REPLAY_SUPP_STREAM_QNAME), true); @@ -589,14 +590,15 @@ public final class RestconfMappingNodeUtil { final DataContainerNodeAttrBuilder streamEntry = Builders.mapEntryBuilder((ListSchemaNode) streamListSchema); - final ListSchemaNode listSchema = ((ListSchemaNode) streamListSchema); + final ListSchemaNode listSchema = (ListSchemaNode) streamListSchema; prepareLeafAndFillEntryBuilder(streamEntry, listSchema.getDataChildByName(MonitoringModule.LEAF_NAME_STREAM_QNAME), schemaNode.getQName().getLocalName()); - if ((schemaNode.getDescription() != null) && !schemaNode.getDescription().equals("")) { + + final java.util.Optional optDesc = schemaNode.getDescription(); + if (optDesc.isPresent()) { prepareLeafAndFillEntryBuilder(streamEntry, - listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME), - schemaNode.getDescription()); + listSchema.getDataChildByName(MonitoringModule.LEAF_DESCR_STREAM_QNAME), optDesc.get()); } prepareLeafAndFillEntryBuilder(streamEntry, listSchema.getDataChildByName(MonitoringModule.LEAF_REPLAY_SUPP_STREAM_QNAME), true); diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameter.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameter.java index 0ed8a485b0..ffe010cb19 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameter.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameter.java @@ -25,13 +25,17 @@ import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -public class ParserFieldsParameter { +public final class ParserFieldsParameter { private static final char COLON = ':'; private static final char SEMICOLON = ';'; private static final char SLASH = '/'; private static final char STARTING_PARENTHESIS = '('; private static final char CLOSING_PARENTHESIS = ')'; + private ParserFieldsParameter() { + + } + /** * Parse fields parameter and return complete list of child nodes organized into levels. * @param identifier identifier context created from request URI @@ -102,8 +106,8 @@ public class ParserFieldsParameter { switch (currentChar) { case COLON : // new namespace and revision found - currentQNameModule = context.findModuleByName( - input.substring(startPosition, currentPosition), null).getQNameModule(); + currentQNameModule = context.findModules( + input.substring(startPosition, currentPosition)).iterator().next().getQNameModule(); currentPosition++; break; case STARTING_PARENTHESIS: @@ -180,10 +184,7 @@ public class ParserFieldsParameter { @Nonnull final String identifier, @Nonnull final QNameModule currentQNameModule, @Nonnull final Set level) { - final QName childQName = QName.create( - currentQNameModule.getNamespace().toString(), - identifier, - currentQNameModule.getRevision()); + final QName childQName = QName.create(currentQNameModule, identifier); // resolve parent node final DataSchemaContextNode parentNode = resolveMixinNode( diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifier.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifier.java index 0df51eacd3..b5438ff866 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifier.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifier.java @@ -10,10 +10,12 @@ package org.opendaylight.restconf.nb.rfc8040.utils.parser; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; -import java.text.ParseException; +import java.time.format.DateTimeParseException; +import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Date; import java.util.Iterator; import java.util.List; +import java.util.Map.Entry; import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider; @@ -25,7 +27,7 @@ import org.opendaylight.restconf.common.schema.SchemaExportContext; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode; import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree; @@ -104,7 +106,7 @@ public final class ParserIdentifier { final QName rpcQName = pathYangInstanceIdentifier.getLastPathArgument().getNodeType(); RpcDefinition def = null; for (final RpcDefinition rpcDefinition : mountSchemaContext - .findModuleByNamespaceAndRevision(rpcQName.getNamespace(), rpcQName.getRevision()).getRpcs()) { + .findModule(rpcQName.getModule()).get().getRpcs()) { if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) { def = rpcDefinition; break; @@ -121,9 +123,7 @@ public final class ParserIdentifier { } final QName rpcQName = deserialize.getLastPathArgument().getNodeType(); RpcDefinition def = null; - for (final RpcDefinition rpcDefinition - : schemaContext.findModuleByNamespaceAndRevision(rpcQName.getNamespace(), - rpcQName.getRevision()).getRpcs()) { + for (final RpcDefinition rpcDefinition : schemaContext.findModule(rpcQName.getModule()).get().getRpcs()) { if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) { def = rpcDefinition; break; @@ -146,13 +146,13 @@ public final class ParserIdentifier { } /** - * Make a {@link QName} from identifier. + * Make a moduleName/Revision pair from identifier. * * @param identifier * path parameter * @return {@link QName} */ - public static QName makeQNameFromIdentifier(final String identifier) { + public static Entry makeQNameFromIdentifier(final String identifier) { // check if more than one slash is not used as path separator if (identifier.contains( String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) { @@ -179,16 +179,16 @@ public final class ParserIdentifier { ErrorTag.INVALID_VALUE); } - final Date moduleRevision; + final Revision moduleRevision; try { - moduleRevision = SimpleDateFormatUtil.getRevisionFormat().parse(pathArgs.get(1)); - } catch (final ParseException e) { + moduleRevision = Revision.of(pathArgs.get(1)); + } catch (final DateTimeParseException e) { LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier); throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e); } - return QName.create(null, moduleRevision, pathArgs.get(0)); + return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision); } /** @@ -211,9 +211,8 @@ public final class ParserIdentifier { final Iterator componentIter = pathComponents.iterator(); if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) { final String moduleName = RestconfValidation.validateAndGetModulName(componentIter); - final Date revision = RestconfValidation.validateAndGetRevision(componentIter); - final Module module = schemaContext.findModuleByName(moduleName, revision); - + final Revision revision = RestconfValidation.validateAndGetRevision(componentIter); + final Module module = schemaContext.findModule(moduleName, revision).orElse(null); return new SchemaExportContext(schemaContext, module, sourceProvider); } else { final StringBuilder pathBuilder = new StringBuilder(); @@ -235,8 +234,9 @@ public final class ParserIdentifier { final InstanceIdentifierContext point = ParserIdentifier .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService)); final String moduleName = RestconfValidation.validateAndGetModulName(componentIter); - final Date revision = RestconfValidation.validateAndGetRevision(componentIter); - final Module module = point.getMountPoint().getSchemaContext().findModuleByName(moduleName, revision); + final Revision revision = RestconfValidation.validateAndGetRevision(componentIter); + final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision) + .orElse(null); return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider); } } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializer.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializer.java index 5c1bbf37b0..7136efbe17 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializer.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializer.java @@ -75,7 +75,7 @@ public final class YangInstanceIdentifierDeserializer { // this is the last identifier (input is consumed) or end of identifier (slash) if (allCharsConsumed(variables) - || (currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH)) { + || currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH) { prepareIdentifier(qname, path, variables); if (variables.getCurrent() == null) { path.add(NodeIdentifier.create(qname)); @@ -103,7 +103,7 @@ public final class YangInstanceIdentifierDeserializer { final MainVarsWrapper variables) { final DataSchemaNode dataSchemaNode = variables.getCurrent().getDataSchemaNode(); - checkValid((dataSchemaNode != null), "Data schema node is null", variables.getData(), variables.getOffset()); + checkValid(dataSchemaNode != null, "Data schema node is null", variables.getData(), variables.getOffset()); final Iterator keys = ((ListSchemaNode) dataSchemaNode).getKeyDefinition().iterator(); final ImmutableMap.Builder values = ImmutableMap.builder(); @@ -112,8 +112,8 @@ public final class YangInstanceIdentifierDeserializer { skipCurrentChar(variables); // read key value separated by comma - while (keys.hasNext() && !allCharsConsumed(variables) && (currentChar(variables.getOffset(), - variables.getData()) != RestconfConstants.SLASH)) { + while (keys.hasNext() && !allCharsConsumed(variables) && currentChar(variables.getOffset(), + variables.getData()) != RestconfConstants.SLASH) { // empty key value if (currentChar(variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA) { @@ -146,8 +146,8 @@ public final class YangInstanceIdentifierDeserializer { // skip comma - if (keys.hasNext() && !allCharsConsumed(variables) && (currentChar( - variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA)) { + if (keys.hasNext() && !allCharsConsumed(variables) && currentChar( + variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA) { skipCurrentChar(variables); } } @@ -155,7 +155,7 @@ public final class YangInstanceIdentifierDeserializer { // the last key is considered to be empty if (keys.hasNext()) { if (allCharsConsumed(variables) - || (currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH)) { + || currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH) { values.put(keys.next(), ParserBuilderConstants.Deserializer.EMPTY_STRING); } @@ -189,7 +189,7 @@ public final class YangInstanceIdentifierDeserializer { final Codec codec = RestCodec.from(typedef, null, vars.getSchemaContext()); decoded = codec.deserialize(value); if (decoded == null) { - if ((baseType instanceof IdentityrefTypeDefinition)) { + if (baseType instanceof IdentityrefTypeDefinition) { decoded = toQName(value, schemaNode, vars.getSchemaContext()); } } @@ -200,7 +200,7 @@ public final class YangInstanceIdentifierDeserializer { final SchemaContext schemaContext) { final String moduleName = toModuleName(value); final String nodeName = toNodeName(value); - final Module module = schemaContext.findModuleByName(moduleName, null); + final Module module = schemaContext.findModules(moduleName).iterator().next(); for (final IdentitySchemaNode identitySchemaNode : module.getIdentities()) { final QName qName = identitySchemaNode.getQName(); if (qName.getLocalName().equals(nodeName)) { @@ -264,8 +264,8 @@ public final class YangInstanceIdentifierDeserializer { variables.getOffset()); localName = nextIdentifierFromNextSequence(ParserBuilderConstants.Deserializer.IDENTIFIER, variables); - if (!allCharsConsumed(variables) && (currentChar( - variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL)) { + if (!allCharsConsumed(variables) && currentChar( + variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL) { return getQNameOfDataSchemaNode(localName, variables); } else { final Module module = moduleForPrefix(prefix, variables.getSchemaContext()); @@ -327,7 +327,7 @@ public final class YangInstanceIdentifierDeserializer { DataSchemaContextNode current = variables.getCurrent(); if (current == null) { for (final RpcDefinition rpcDefinition : variables.getSchemaContext() - .findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision()).getRpcs()) { + .findModule(qname.getModule()).orElse(null).getRpcs()) { if (rpcDefinition.getQName().getLocalName().equals(qname.getLocalName())) { return null; } @@ -382,7 +382,7 @@ public final class YangInstanceIdentifierDeserializer { } private static Module moduleForPrefix(final String prefix, final SchemaContext schemaContext) { - return schemaContext.findModuleByName(prefix, null); + return schemaContext.findModules(prefix).stream().findFirst().orElse(null); } private static void validArg(final MainVarsWrapper variables) { diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializer.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializer.java index a8c28d7984..b20c5c15bd 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializer.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializer.java @@ -8,7 +8,6 @@ package org.opendaylight.restconf.nb.rfc8040.utils.parser; import com.google.common.base.Preconditions; -import java.net.URI; import java.util.Iterator; import java.util.Map.Entry; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; @@ -170,9 +169,7 @@ public final class YangInstanceIdentifierSerializer { * @return {@link String} */ private static String prefixForNamespace(final QName qname, final SchemaContext schemaContext) { - final URI namespace = qname.getNamespace(); - Preconditions.checkArgument(namespace != null, "Failed to map QName {}", qname); - final Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, qname.getRevision()); + final Module module = schemaContext.findModule(qname.getModule()).orElse(null); return module.getName(); } diff --git a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidation.java b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidation.java index 74c5012e3f..84db15e8f1 100644 --- a/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidation.java +++ b/restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidation.java @@ -7,7 +7,7 @@ */ package org.opendaylight.restconf.nb.rfc8040.utils.validations; -import java.text.ParseException; +import java.time.format.DateTimeParseException; import java.util.Date; import java.util.Iterator; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; @@ -15,7 +15,7 @@ import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag; import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; import org.opendaylight.restconf.common.validation.RestconfValidationUtils; import org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; /** * Util class for validations. @@ -34,12 +34,12 @@ public final class RestconfValidation { * iterator * @return {@link Date} */ - public static Date validateAndGetRevision(final Iterator revisionDate) { + public static Revision validateAndGetRevision(final Iterator revisionDate) { RestconfValidationUtils.checkDocumentedError(revisionDate.hasNext(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Revision date must be supplied."); try { - return SimpleDateFormatUtil.getRevisionFormat().parse(revisionDate.next()); - } catch (final ParseException e) { + return Revision.of(revisionDate.next()); + } catch (final DateTimeParseException e) { throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e); } } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestRestconfUtils.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestRestconfUtils.java index 12d93952b8..86a36649bb 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestRestconfUtils.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestRestconfUtils.java @@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; -public class TestRestconfUtils { +public final class TestRestconfUtils { private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class); @@ -55,14 +55,14 @@ public class TestRestconfUtils { public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) { try { Preconditions.checkArgument(yangPath != null, "Path can not be null."); - Preconditions.checkArgument((!yangPath.isEmpty()), "Path can not be empty."); + Preconditions.checkArgument(!yangPath.isEmpty(), "Path can not be empty."); if (schemaContext == null) { - return YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(yangPath)); + return YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(yangPath)); } else { throw new UnsupportedOperationException("Unable to add new yang sources to existing schema context."); } } catch (final Exception e) { - LOG.error("Yang files at path: " + yangPath + " weren't loaded."); + LOG.error("Yang files at path: " + yangPath + " weren't loaded.", e); } return schemaContext; } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestUtils.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestUtils.java index 4b6992e3f7..ab7ad9bf87 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestUtils.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/TestUtils.java @@ -21,7 +21,6 @@ import java.io.OutputStreamWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; -import java.sql.Date; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; @@ -38,6 +37,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; @@ -48,7 +48,6 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMa import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,8 +58,12 @@ public final class TestUtils { private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class); + private TestUtils() { + + } + public static SchemaContext loadSchemaContext(final String... yangPath) - throws FileNotFoundException, ReactorException { + throws FileNotFoundException { final List files = new ArrayList<>(); for (final String path : yangPath) { final String pathToFile = TestUtils.class.getResource(path).getPath(); @@ -78,7 +81,7 @@ public final class TestUtils { } } - return YangParserTestUtils.parseYangSources(files); + return YangParserTestUtils.parseYangFiles(files); } public static Module findModule(final Set modules, final String moduleName) { @@ -160,11 +163,7 @@ public final class TestUtils { public static QName buildQName(final String name, final String uri, final String date, final String prefix) { try { final URI u = new URI(uri); - Date dt = null; - if (date != null) { - dt = Date.valueOf(date); - } - return QName.create(u, dt, name); + return QName.create(u, Revision.ofNullable(date), name); } catch (final URISyntaxException e) { return null; } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandlerTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandlerTest.java index 43cf40a9e2..ef4c63b985 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandlerTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/handlers/SchemaContextHandlerTest.java @@ -47,7 +47,7 @@ public class SchemaContextHandlerTest { this.schemaContextHandler = new SchemaContextHandler(txHandler); this.schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_ACTUAL_SCHEMA_CONTEXT)); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_ACTUAL_SCHEMA_CONTEXT)); this.schemaContextHandler.onGlobalContextUpdated(this.schemaContext); } @@ -83,7 +83,7 @@ public class SchemaContextHandlerTest { public void onGlobalContextUpdateTest() throws Exception { // create new SchemaContext and update SchemaContextHandler final SchemaContext newSchemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)); this.schemaContextHandler.onGlobalContextUpdated(newSchemaContext); assertNotEquals("SchemaContextHandler should not has reference to old SchemaContext", diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterDepthTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterDepthTest.java index 9ff864c8c5..51dbdef7af 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterDepthTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterDepthTest.java @@ -8,10 +8,10 @@ package org.opendaylight.restconf.nb.rfc8040.jersey.providers; -import com.google.common.base.Optional; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Collections; +import java.util.Optional; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterFieldsTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterFieldsTest.java index 031fc6370f..37a5b897de 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterFieldsTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/ParameterAwareNormalizedNodeWriterFieldsTest.java @@ -8,12 +8,12 @@ package org.opendaylight.restconf.nb.rfc8040.jersey.providers; -import com.google.common.base.Optional; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlBodyReaderMountPointTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlBodyReaderMountPointTest.java index 4378a882a5..b5365e0c1c 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlBodyReaderMountPointTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/XmlBodyReaderMountPointTest.java @@ -19,7 +19,6 @@ import com.google.common.base.Optional; import java.io.File; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.junit.Assert; @@ -36,7 +35,7 @@ import org.opendaylight.restconf.nb.rfc8040.jersey.providers.test.AbstractBodyRe import org.opendaylight.restconf.nb.rfc8040.jersey.providers.test.XmlBodyReaderTest; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @@ -51,16 +50,8 @@ public class XmlBodyReaderMountPointTest extends AbstractBodyReaderTest { private final XmlNormalizedNodeBodyReader xmlBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public XmlBodyReaderMountPointTest() throws Exception { this.xmlBodyReader = new XmlNormalizedNodeBodyReader(); @@ -75,7 +66,7 @@ public class XmlBodyReaderMountPointTest extends AbstractBodyReaderTest { public static void initialization() throws Exception { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); final DOMMountPointService mountPointService = mock(DOMMountPointService.class); final DOMMountPoint mountPoint = mock(DOMMountPoint.class); @@ -140,13 +131,13 @@ public class XmlBodyReaderMountPointTest extends AbstractBodyReaderTest { checkNormalizedNodeContext(returnValue); final ContainerNode contNode = (ContainerNode) returnValue.getData(); final YangInstanceIdentifier yangCont = YangInstanceIdentifier.of(QName.create(contNode.getNodeType(), "cont")); - final Optional> contDataNodePotential = contNode.getChild( - yangCont.getLastPathArgument()); + final java.util.Optional> contDataNodePotential = contNode + .getChild(yangCont.getLastPathArgument()); assertTrue(contDataNodePotential.isPresent()); final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get(); final YangInstanceIdentifier yangLeaf = YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf")); - final Optional> leafDataNode = contDataNode.getChild( + final java.util.Optional> leafDataNode = contDataNode.getChild( yangLeaf.getLastPathArgument()); assertTrue(leafDataNode.isPresent()); assertTrue("lf-test".equalsIgnoreCase(leafDataNode.get().getValue().toString())); @@ -168,7 +159,7 @@ public class XmlBodyReaderMountPointTest extends AbstractBodyReaderTest { .getSchemaContext().getDataChildByName( dataSchemaNode.getQName()); assertNotNull(mountDataSchemaNode); - if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) { + if (qualifiedName != null && dataSchemaNode instanceof DataNodeContainer) { final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode) .getDataChildByName(qualifiedName); dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent) diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/JsonBodyReaderTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/JsonBodyReaderTest.java index da0e964a95..635c568902 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/JsonBodyReaderTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/JsonBodyReaderTest.java @@ -18,7 +18,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.junit.BeforeClass; @@ -26,10 +25,11 @@ import org.junit.Test; import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.restconf.common.context.NormalizedNodeContext; import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils; +import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler; import org.opendaylight.restconf.nb.rfc8040.jersey.providers.JsonNormalizedNodeBodyReader; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; @@ -45,16 +45,8 @@ public class JsonBodyReaderTest extends AbstractBodyReaderTest { private final JsonNormalizedNodeBodyReader jsonBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public JsonBodyReaderTest() throws Exception { this.jsonBodyReader = new JsonNormalizedNodeBodyReader(); @@ -70,8 +62,9 @@ public class JsonBodyReaderTest extends AbstractBodyReaderTest { throws NoSuchFieldException, SecurityException, FileNotFoundException, SourceException, ReactorException { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/modules")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class)); + SchemaContextHandler.setActualSchemaContext(schemaContext); } @Test @@ -126,7 +119,7 @@ public class JsonBodyReaderTest extends AbstractBodyReaderTest { public void moduleSubContainerAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment"); final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier( Sets.newHashSet(contAugmentQName)); @@ -147,7 +140,7 @@ public class JsonBodyReaderTest extends AbstractBodyReaderTest { public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1"); final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2"); final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1"); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/XmlBodyReaderTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/XmlBodyReaderTest.java index 7a6fb00367..291a383554 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/XmlBodyReaderTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/jersey/providers/test/XmlBodyReaderTest.java @@ -19,7 +19,6 @@ import com.google.common.collect.Sets; import java.io.File; import java.io.InputStream; import java.net.URI; -import java.text.ParseException; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.junit.Assert; @@ -34,7 +33,7 @@ import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler; import org.opendaylight.restconf.nb.rfc8040.jersey.providers.XmlNormalizedNodeBodyReader; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; @@ -50,16 +49,8 @@ public class XmlBodyReaderTest extends AbstractBodyReaderTest { private final XmlNormalizedNodeBodyReader xmlBodyReader; private static SchemaContext schemaContext; - private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = initializeInstanceIdentifierModule(); - - private static QNameModule initializeInstanceIdentifierModule() { - try { - return QNameModule.create(URI.create("instance:identifier:module"), - SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-17")); - } catch (final ParseException e) { - throw new Error(e); - } - } + private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create( + URI.create("instance:identifier:module"), Revision.of("2014-01-17")); public XmlBodyReaderTest() throws Exception { this.xmlBodyReader = new XmlNormalizedNodeBodyReader(); @@ -75,7 +66,7 @@ public class XmlBodyReaderTest extends AbstractBodyReaderTest { final Collection testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang"); testFiles.addAll(TestRestconfUtils.loadFiles("/modules")); testFiles.addAll(TestRestconfUtils.loadFiles("/foo-xml-test/yang")); - schemaContext = YangParserTestUtils.parseYangSources(testFiles); + schemaContext = YangParserTestUtils.parseYangFiles(testFiles); when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class)); SchemaContextHandler.setActualSchemaContext(schemaContext); } @@ -166,7 +157,7 @@ public class XmlBodyReaderTest extends AbstractBodyReaderTest { public void moduleSubContainerAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName contAugmentQName = QName.create(augmentModule.getQNameModule(), "cont-augment"); final YangInstanceIdentifier.AugmentationIdentifier augII = new YangInstanceIdentifier.AugmentationIdentifier( Sets.newHashSet(contAugmentQName)); @@ -186,7 +177,7 @@ public class XmlBodyReaderTest extends AbstractBodyReaderTest { public void moduleSubContainerChoiceAugmentDataPostTest() throws Exception { final DataSchemaNode dataSchemaNode = schemaContext .getDataChildByName(QName.create(INSTANCE_IDENTIFIER_MODULE_QNAME, "cont")); - final Module augmentModule = schemaContext.findModuleByNamespace(new URI("augment:module")).iterator().next(); + final Module augmentModule = schemaContext.findModules(new URI("augment:module")).iterator().next(); final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1"); final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2"); final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1"); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/JSONRestconfServiceRfc8040ImplTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/JSONRestconfServiceRfc8040ImplTest.java index cf6066b655..348569bd73 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/JSONRestconfServiceRfc8040ImplTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/JSONRestconfServiceRfc8040ImplTest.java @@ -282,14 +282,15 @@ public class JSONRestconfServiceRfc8040ImplTest { final ContainerNode actualNode = (ContainerNode) capturedNode.getValue(); assertEquals("ContainerNode node type", INTERFACES_QNAME, actualNode.getNodeType()); - final Optional> mapChild = actualNode.getChild(new NodeIdentifier(INTERFACE_QNAME)); + final java.util.Optional> mapChild = actualNode.getChild( + new NodeIdentifier(INTERFACE_QNAME)); assertEquals(INTERFACE_QNAME.toString() + " present", true, mapChild.isPresent()); assertTrue("Expected MapNode. Actual " + mapChild.get().getClass(), mapChild.get() instanceof MapNode); final MapNode mapNode = (MapNode)mapChild.get(); final NodeIdentifierWithPredicates entryNodeID = new NodeIdentifierWithPredicates( INTERFACE_QNAME, NAME_QNAME, "eth0"); - final Optional entryChild = mapNode.getChild(entryNodeID); + final java.util.Optional entryChild = mapNode.getChild(entryNodeID); assertEquals(entryNodeID.toString() + " present", true, entryChild.isPresent()); final MapEntryNode entryNode = entryChild.get(); verifyLeafNode(entryNode, NAME_QNAME, "eth0"); @@ -325,7 +326,7 @@ public class JSONRestconfServiceRfc8040ImplTest { } @Test(expected = TransactionCommitFailedException.class) - @SuppressWarnings("checkstyle:IllegalThrows") + @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" }) public void testPostFailure() throws Throwable { doReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock"))) .when(mockReadWriteTx).submit(); @@ -581,7 +582,7 @@ public class JSONRestconfServiceRfc8040ImplTest { } void verifyLeafNode(final DataContainerNode parent, final QName leafType, final Object leafValue) { - final Optional> leafChild = parent.getChild(new NodeIdentifier(leafType)); + final java.util.Optional> leafChild = parent.getChild(new NodeIdentifier(leafType)); assertEquals(leafType.toString() + " present", true, leafChild.isPresent()); assertEquals(leafType.toString() + " value", leafValue, leafChild.get().getValue()); } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImplTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImplTest.java index d767b3dacb..ad05a23320 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImplTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataServiceImplTest.java @@ -175,7 +175,7 @@ public class RestconfDataServiceImplTest { .build(); this.contextRef = new SchemaContextRef( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); this.schemaNode = DataSchemaContextTree.from(this.contextRef.get()).getChild(this.iidBase).getDataSchemaNode(); final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class); @@ -334,7 +334,6 @@ public class RestconfDataServiceImplTest { @Test public void testPutDataWithMountPoint() { final DOMDataBroker dataBroker = Mockito.mock(DOMDataBroker.class); - final DOMMountPoint mountPoint = Mockito.mock(DOMMountPoint.class); doReturn(Optional.of(dataBroker)).when(mountPoint).getService(DOMDataBroker.class); doReturn(this.transactionChainHandler.get()).when(dataBroker) .createTransactionChain(RestConnectorProvider.TRANSACTION_CHAIN_LISTENER); @@ -533,4 +532,4 @@ public class RestconfDataServiceImplTest { final String errorMessage = status.getEditCollection().get(2).getEditErrors().get(0).getErrorMessage(); assertEquals("Data does not exist", errorMessage); } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfInvokeOperationsServiceImplTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfInvokeOperationsServiceImplTest.java index c70960c063..87998c82aa 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfInvokeOperationsServiceImplTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfInvokeOperationsServiceImplTest.java @@ -52,7 +52,7 @@ public class RestconfInvokeOperationsServiceImplTest { public void setup() throws Exception { MockitoAnnotations.initMocks(this); final SchemaContextRef contextRef = new SchemaContextRef( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class); final DOMTransactionChain domTx = Mockito.mock(DOMTransactionChain.class); Mockito.when(txHandler.get()).thenReturn(domTx); @@ -82,7 +82,7 @@ public class RestconfInvokeOperationsServiceImplTest { private NormalizedNodeContext prepNNC(final NormalizedNode result) { final InstanceIdentifierContext context = Mockito.mock(InstanceIdentifierContext.class); final RpcDefinition schemaNode = Mockito.mock(RpcDefinition.class); - final QName qname = QName.create("invoke:rpc:module", "2013-12-3", "rpcTest"); + final QName qname = QName.create("invoke:rpc:module", "2013-12-03", "rpcTest"); final SchemaPath schemaPath = SchemaPath.create(true, qname); Mockito.when(schemaNode.getPath()).thenReturn(schemaPath); Mockito.when(schemaNode.getQName()).thenReturn(qname); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfStreamsSubscriptionServiceImplTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfStreamsSubscriptionServiceImplTest.java index 9f40febe48..24d9d8b9ee 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfStreamsSubscriptionServiceImplTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfStreamsSubscriptionServiceImplTest.java @@ -109,7 +109,7 @@ public class RestconfStreamsSubscriptionServiceImplTest { Mockito.when(uriInfo.getBaseUri()).thenReturn(baseUriBuilder.build()); Mockito.when(uriInfo.getBaseUriBuilder()).thenReturn(baseUriBuilder); this.schemaHandler.onGlobalContextUpdated( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/notifications"))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/notifications"))); } private static class LocalUriInfo extends SimpleUriInfo { diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtilTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtilTest.java index a268b1b4c8..97dde3fdd5 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtilTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/CreateStreamUtilTest.java @@ -50,7 +50,7 @@ public class CreateStreamUtilTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.refSchemaCtx = new SchemaContextRef( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); } @Test @@ -82,8 +82,7 @@ public class CreateStreamUtilTest { private NormalizedNodeContext prepareDomPayload(final String rpcName, final String inputOutput, final String toasterValue, final String inputOutputName) { final SchemaContext schema = this.refSchemaCtx.get(); - final Module rpcModule = schema.findModuleByName("sal-remote", null); - assertNotNull(rpcModule); + final Module rpcModule = schema.findModules("sal-remote").iterator().next(); final QName rpcQName = QName.create(rpcModule.getQNameModule(), rpcName); final QName rpcInputQName = QName.create(rpcModule.getQNameModule(), inputOutput); final Set setRpcs = rpcModule.getRpcs(); @@ -111,8 +110,8 @@ public class CreateStreamUtilTest { } else { o = toasterValue; } - final LeafNode lfNode = (Builders.leafBuilder((LeafSchemaNode) lfSchemaNode) - .withValue(o)).build(); + final LeafNode lfNode = Builders.leafBuilder((LeafSchemaNode) lfSchemaNode) + .withValue(o).build(); container.withChild(lfNode); return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PatchDataTransactionUtilTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PatchDataTransactionUtilTest.java index 1113510a01..efb9b05f16 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PatchDataTransactionUtilTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PatchDataTransactionUtilTest.java @@ -63,6 +63,7 @@ public class PatchDataTransactionUtilTest { private DOMDataReadWriteTransaction rwTransaction; private SchemaContextRef refSchemaCtx; + private YangInstanceIdentifier instanceIdContainer; private YangInstanceIdentifier instanceIdCreateAndDelete; private YangInstanceIdentifier instanceIdMerge; private ContainerNode buildBaseContainerForTests; @@ -88,7 +89,7 @@ public class PatchDataTransactionUtilTest { PatchDataTransactionUtilTest.broker.set(RestConnectorProvider.class, mock(DOMDataBroker.class)); this.refSchemaCtx = new SchemaContextRef( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox"); final QName containerPlayerQName = QName.create(baseQName, "player"); final QName leafGapQName = QName.create(baseQName, "gap"); @@ -98,13 +99,15 @@ public class PatchDataTransactionUtilTest { final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeWithKey = new YangInstanceIdentifier.NodeIdentifierWithPredicates(listArtistQName, leafNameQName, "name of artist"); - /* instance identifier for accessing leaf node "gap" */ - this.instanceIdCreateAndDelete = YangInstanceIdentifier.builder() + /* instance identifier for accessing container node "player" */ + this.instanceIdContainer = YangInstanceIdentifier.builder() .node(baseQName) .node(containerPlayerQName) - .node(leafGapQName) .build(); + /* instance identifier for accessing leaf node "gap" */ + this.instanceIdCreateAndDelete = instanceIdContainer.node(leafGapQName); + /* values that are used for creating leaf for testPatchDataCreateAndDelete test */ final LeafNode buildGapLeaf = Builders.leafBuilder() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(leafGapQName)) @@ -199,11 +202,13 @@ public class PatchDataTransactionUtilTest { @Test public void testPatchDataCreateAndDelete() throws Exception { - doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true)) - .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete); + doReturn(Futures.immediateCheckedFuture(false)) + .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceIdContainer); + doReturn(Futures.immediateCheckedFuture(true)) + .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete); final PatchEntity entityCreate = - new PatchEntity("edit1", CREATE, this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests); + new PatchEntity("edit1", CREATE, this.instanceIdContainer, this.buildBaseContainerForTests); final PatchEntity entityDelete = new PatchEntity("edit2", DELETE, this.targetNodeForCreateAndDelete); final List entities = new ArrayList<>(); @@ -219,7 +224,7 @@ public class PatchDataTransactionUtilTest { PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx); for (final PatchStatusEntity entity : patchStatusContext.getEditCollection()) { - assertTrue(entity.isOk()); + assertTrue("Edit " + entity.getEditId() + " failed", entity.isOk()); } assertTrue(patchStatusContext.isOk()); } @@ -255,7 +260,7 @@ public class PatchDataTransactionUtilTest { .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete); final PatchEntity entityMerge = - new PatchEntity("edit1", MERGE, this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests); + new PatchEntity("edit1", MERGE, this.instanceIdContainer, this.buildBaseContainerForTests); final List entities = new ArrayList<>(); entities.add(entityMerge); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PostDataTransactionUtilTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PostDataTransactionUtilTest.java index aa205a8165..a22edb1933 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PostDataTransactionUtilTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PostDataTransactionUtilTest.java @@ -74,7 +74,7 @@ public class PostDataTransactionUtilTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.refSchemaCtx = new SchemaContextRef( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); this.schema = this.refSchemaCtx.get(); final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox"); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtilTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtilTest.java index 11c9770a23..9c9bdbe860 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtilTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/rests/utils/PutDataTransactionUtilTest.java @@ -72,7 +72,7 @@ public class PutDataTransactionUtilTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.refSchemaCtx = new SchemaContextRef( - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT))); this.schema = this.refSchemaCtx.get(); final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox"); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImplTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImplTest.java index 8a269048c3..dcfa41a805 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImplTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfImplTest.java @@ -28,7 +28,7 @@ public class RestconfImplTest { @Test public void restImplTest() throws Exception { final SchemaContext schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/impl")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/impl")); final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class); final DOMTransactionChain domTx = Mockito.mock(DOMTransactionChain.class); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceTest.java index 88bae0c00a..562a1f2bbe 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfOperationsServiceTest.java @@ -8,7 +8,6 @@ package org.opendaylight.restconf.nb.rfc8040.services.simple.impl; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableSet; @@ -29,6 +28,7 @@ import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils; import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler; import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler; import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler; +import org.opendaylight.yangtools.yang.common.Empty; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; @@ -54,7 +54,7 @@ public class RestconfOperationsServiceTest { @Before public void init() throws Exception { MockitoAnnotations.initMocks(this); - this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules")); + this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules")); final TransactionChainHandler txHandler = Mockito.mock(TransactionChainHandler.class); final DOMTransactionChain domTx = Mockito.mock(DOMTransactionChain.class); @@ -67,8 +67,8 @@ public class RestconfOperationsServiceTest { this.domMountPointServiceHandler = new DOMMountPointServiceHandler(this.domMountPointService); - final QNameModule module1 = QNameModule.create(new URI("module:1"), null); - final QNameModule module2 = QNameModule.create(new URI("module:2"), null); + final QNameModule module1 = QNameModule.create(URI.create("module:1")); + final QNameModule module2 = QNameModule.create(URI.create("module:2")); this.listOfRpcsNames = ImmutableSet.of(QName.create(module1, "dummy-rpc1-module1"), QName.create(module1, "dummy-rpc2-module1"), QName.create(module2, "dummy-rpc1-module2"), @@ -87,7 +87,7 @@ public class RestconfOperationsServiceTest { assertEquals(4, data.getValue().size()); for (final DataContainerChild child : data.getValue()) { - assertNull(child.getValue()); + assertEquals(Empty.getInstance(), child.getValue()); final QName qname = child.getNodeType().withoutRevision(); assertTrue(this.listOfRpcsNames.contains(qname)); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfSchemaServiceTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfSchemaServiceTest.java index d3c0a19cd9..80b9231159 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfSchemaServiceTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/services/simple/impl/RestconfSchemaServiceTest.java @@ -36,7 +36,7 @@ import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler; import org.opendaylight.restconf.nb.rfc8040.services.simple.api.RestconfSchemaService; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -85,11 +85,11 @@ public class RestconfSchemaServiceTest { public void setup() throws Exception { MockitoAnnotations.initMocks(this); - this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules")); + this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules")); this.schemaContextBehindMountPoint = YangParserTestUtils - .parseYangSources(TestRestconfUtils.loadFiles("/modules/modules-behind-mount-point")); + .parseYangFiles(TestRestconfUtils.loadFiles("/modules/modules-behind-mount-point")); this.schemaContextWithMountPoints = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules/mount-points")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules/mount-points")); // create and register mount points this.mountPoint = SimpleDOMMountPoint.create( @@ -139,8 +139,7 @@ public class RestconfSchemaServiceTest { assertNotNull("Existing module should be found", module); assertEquals("Not expected module name", "module1", module.getName()); - assertEquals("Not expected module revision", "2014-01-01", - SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision())); + assertEquals("Not expected module revision", Revision.ofNullable("2014-01-01"), module.getRevision()); assertEquals("Not expected module namespace", "module:1", module.getNamespace().toString()); } @@ -180,8 +179,7 @@ public class RestconfSchemaServiceTest { assertNotNull("Existing module should be found", module); assertEquals("Not expected module name", "module1-behind-mount-point", module.getName()); - assertEquals("Not expected module revision", "2014-02-03", - SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision())); + assertEquals("Not expected module revision", Revision.ofNullable("2014-02-03"), module.getRevision()); assertEquals("Not expected module namespace", "module:1:behind:mount:point", module.getNamespace().toString()); } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerTest.java index 7a07674265..5542501bc1 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/NotificationListenerTest.java @@ -12,16 +12,15 @@ import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.net.URI; -import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; @@ -31,7 +30,7 @@ import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev14070 import org.opendaylight.yangtools.util.SingletonSet; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; @@ -46,16 +45,7 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; public class NotificationListenerTest { - private static final QNameModule MODULE; - - static { - try { - MODULE = QNameModule.create(URI.create("notifi:mod"), - SimpleDateFormatUtil.getRevisionFormat().parse("2016-11-23")); - } catch (final ParseException e) { - throw new ExceptionInInitializerError(e); - } - } + private static final QNameModule MODULE = QNameModule.create(URI.create("notifi:mod"), Revision.of("2016-11-23")); private SchemaContext schmeaCtx; diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtilTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtilTest.java index d3839245e7..c16ebd5396 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtilTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/mapping/RestconfMappingNodeUtilTest.java @@ -37,7 +37,7 @@ import org.opendaylight.restconf.nb.rfc8040.Rfc8040.RestconfModule; import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils; import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; @@ -83,11 +83,11 @@ public class RestconfMappingNodeUtilTest { @BeforeClass public static void loadTestSchemaContextAndModules() throws Exception { schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")); - schemaContextMonitoring = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/modules")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")); + schemaContextMonitoring = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/modules")); modules = schemaContextMonitoring.getModules(); modulesRest = YangParserTestUtils - .parseYangSources(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")).getModules(); + .parseYangFiles(TestRestconfUtils.loadFiles("/modules/restconf-module-testing")).getModules(); } @Before @@ -98,7 +98,7 @@ public class RestconfMappingNodeUtilTest { when(this.leafDescription.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.DESCRIPTION)); when(this.leafReplaySupport.getQName()).thenReturn( QName.create("", RestconfMappingNodeConstants.REPLAY_SUPPORT)); - when(this.leafReplayLog.getQName()).thenReturn(QName.create(RestconfMappingNodeConstants.REPLAY_LOG)); + when(this.leafReplayLog.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.REPLAY_LOG)); when(this.leafEvents.getQName()).thenReturn(QName.create("", RestconfMappingNodeConstants.EVENTS)); } @@ -109,20 +109,18 @@ public class RestconfMappingNodeUtilTest { @Test public void restconfMappingNodeTest() { // write modules into list module in Restconf - final Module ietfYangLibMod = - schemaContext.findModuleByNamespaceAndRevision(IetfYangLibrary.URI_MODULE, IetfYangLibrary.DATE); - final NormalizedNode>> modules = + final Module ietfYangLibMod = schemaContext.findModule(IetfYangLibrary.MODULE_QNAME).get(); + final NormalizedNode>> mods = RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(RestconfMappingNodeUtilTest.modules, ietfYangLibMod, schemaContext, "1"); // verify loaded modules - verifyLoadedModules((ContainerNode) modules); + verifyLoadedModules((ContainerNode) mods); } @Test public void restconfStateCapabilitesTest() { - final Module monitoringModule = schemaContextMonitoring - .findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE); + final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).get(); final NormalizedNode>> normNode = RestconfMappingNodeUtil.mapCapabilites(monitoringModule); assertNotNull(normNode); @@ -152,8 +150,7 @@ public class RestconfMappingNodeUtilTest { final Instant start = Instant.now(); final String outputType = "XML"; final URI uri = new URI("uri"); - final Module monitoringModule = schemaContextMonitoring - .findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE); + final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).orElse(null); final boolean exist = true; final Map map = @@ -171,14 +168,13 @@ public class RestconfMappingNodeUtilTest { final Instant start = Instant.now(); final String outputType = "JSON"; final URI uri = new URI("uri"); - final Module monitoringModule = schemaContextMonitoring - .findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE); + final Module monitoringModule = schemaContextMonitoring.findModule(MonitoringModule.MODULE_QNAME).orElse(null); final boolean exist = true; final Map map = prepareMap("notifi", uri, start, outputType); map.put(MonitoringModule.LEAF_DESCR_STREAM_QNAME, "Notifi"); - final QName notifiQName = QName.create("urn:nested:module", "2014-06-3", "notifi"); + final QName notifiQName = QName.create("urn:nested:module", "2014-06-03", "notifi"); final NormalizedNode mappedData = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(notifiQName, schemaContextMonitoring.getNotifications(), start, outputType, uri, monitoringModule, exist); @@ -264,8 +260,7 @@ public class RestconfMappingNodeUtilTest { final String revision = loadedModules.get(name); assertNotNull("Expected module not found", revision); - assertEquals("Not correct revision of loaded module", - SimpleDateFormatUtil.getRevisionFormat().format(m.getRevision()), revision); + assertEquals("Incorrect revision of loaded module", Revision.ofNullable(revision), m.getRevision()); loadedModules.remove(name); } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/IdentifierCodecTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/IdentifierCodecTest.java index 5c58ae8d24..fed9756f65 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/IdentifierCodecTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/IdentifierCodecTest.java @@ -11,6 +11,7 @@ package org.opendaylight.restconf.nb.rfc8040.utils.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.io.FileNotFoundException; import org.junit.Before; import org.junit.Test; import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils; @@ -30,8 +31,8 @@ public class IdentifierCodecTest { private SchemaContext schemaContext; @Before - public void init() throws Exception { - this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser")); + public void init() throws FileNotFoundException { + this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser")); } /** diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameterTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameterTest.java index 58d1153960..8883ac8f88 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameterTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserFieldsParameterTest.java @@ -28,7 +28,7 @@ import org.opendaylight.restconf.common.errors.RestconfError.ErrorType; import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; @@ -77,10 +77,10 @@ public class ParserFieldsParameterTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); final SchemaContext schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/jukebox")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/jukebox")); final QNameModule qNameModule = QNameModule.create(URI.create("http://example.com/ns/example-jukebox"), - SimpleDateFormatUtil.getRevisionFormat().parse("2015-04-04")); + Revision.of("2015-04-04")); this.jukeboxQName = QName.create(qNameModule, "jukebox"); this.playerQName = QName.create(qNameModule, "player"); @@ -88,7 +88,7 @@ public class ParserFieldsParameterTest { this.augmentedLibraryQName = QName.create( QNameModule.create( URI.create("http://example.com/ns/augmented-jukebox"), - SimpleDateFormatUtil.getRevisionFormat().parse("2016-05-05")), + Revision.of("2016-05-05")), "augmented-library"); this.albumQName = QName.create(qNameModule, "album"); this.nameQName = QName.create(qNameModule, "name"); diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifierTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifierTest.java index ba33cd6ef0..bf0b513375 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifierTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/ParserIdentifierTest.java @@ -17,6 +17,7 @@ import static org.mockito.Mockito.when; import com.google.common.base.Optional; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.common.collect.Maps; +import java.util.Map.Entry; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -38,7 +39,7 @@ import org.opendaylight.restconf.common.schema.SchemaExportContext; import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils; import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; @@ -110,9 +111,9 @@ public class ParserIdentifierTest { @Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); - this.schemaContext = YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/parser-identifier")); + this.schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/parser-identifier")); this.schemaContextOnMountPoint = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/parser-identifier")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/parser-identifier")); // create and register mount point this.mountPoint = SimpleDOMMountPoint.create( @@ -286,13 +287,12 @@ public class ParserIdentifierTest { */ @Test public void makeQNameFromIdentifierTest() { - final QName qName = ParserIdentifier.makeQNameFromIdentifier(TEST_MODULE_NAME + "/" + TEST_MODULE_REVISION); + final Entry qName = ParserIdentifier.makeQNameFromIdentifier( + TEST_MODULE_NAME + "/" + TEST_MODULE_REVISION); assertNotNull("QName should be created", qName); - assertEquals("Returned not expected module name", - TEST_MODULE_NAME, qName.getLocalName()); - assertEquals("Returned not expected module revision", - TEST_MODULE_REVISION, qName.getFormattedRevision()); + assertEquals("Returned not expected module name", TEST_MODULE_NAME, qName.getKey()); + assertEquals("Returned not expected module revision", Revision.of(TEST_MODULE_REVISION), qName.getValue()); } /** @@ -341,7 +341,7 @@ public class ParserIdentifierTest { */ @Test public void makeQNameFromIdentifierMountTest() { - final QName qName = ParserIdentifier.makeQNameFromIdentifier( + final Entry qName = ParserIdentifier.makeQNameFromIdentifier( MOUNT_POINT_IDENT + "/" + TEST_MODULE_NAME @@ -349,10 +349,8 @@ public class ParserIdentifierTest { + TEST_MODULE_REVISION); assertNotNull("QName should be created", qName); - assertEquals("Returned not expected module name", - TEST_MODULE_NAME, qName.getLocalName()); - assertEquals("Returned not expected module revision", - TEST_MODULE_REVISION, qName.getFormattedRevision()); + assertEquals("Returned not expected module name", TEST_MODULE_NAME, qName.getKey()); + assertEquals("Returned not expected module revision", Revision.of(TEST_MODULE_REVISION), qName.getValue()); } /** @@ -477,7 +475,7 @@ public class ParserIdentifierTest { assertEquals("Returned not expected module name", TEST_MODULE_NAME, module.getName()); assertEquals("Returned not expected module revision", - TEST_MODULE_REVISION, SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision())); + Revision.ofNullable(TEST_MODULE_REVISION), module.getRevision()); assertEquals("Returned not expected module namespace", TEST_MODULE_NAMESPACE, module.getNamespace().toString()); } @@ -535,7 +533,7 @@ public class ParserIdentifierTest { assertEquals("Returned not expected module name", TEST_MODULE_NAME, module.getName()); assertEquals("Returned not expected module revision", - TEST_MODULE_REVISION, SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision())); + Revision.ofNullable(TEST_MODULE_REVISION), module.getRevision()); assertEquals("Returned not expected module namespace", TEST_MODULE_NAMESPACE, module.getNamespace().toString()); } diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializerTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializerTest.java index 66157f6816..86aa0307b6 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializerTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierDeserializerTest.java @@ -14,6 +14,7 @@ import static org.junit.Assert.fail; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; +import java.io.FileNotFoundException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; @@ -42,9 +43,9 @@ public class YangInstanceIdentifierDeserializerTest { private SchemaContext schemaContext; @Before - public void init() throws Exception { + public void init() throws FileNotFoundException { this.schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser/deserializer")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/deserializer")); } /** diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializerTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializerTest.java index 824343172b..35bb3dc162 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializerTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/parser/YangInstanceIdentifierSerializerTest.java @@ -41,7 +41,7 @@ public class YangInstanceIdentifierSerializerTest { @Before public void init() throws Exception { this.schemaContext = - YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/parser/serializer")); + YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/serializer")); } /** diff --git a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidationTest.java b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidationTest.java index 5ccf9634d6..b1929dc795 100644 --- a/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidationTest.java +++ b/restconf/restconf-nb-rfc8040/src/test/java/org/opendaylight/restconf/nb/rfc8040/utils/validations/RestconfValidationTest.java @@ -15,12 +15,11 @@ import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; import java.util.List; import org.junit.Test; import org.opendaylight.restconf.common.errors.RestconfDocumentedException; import org.opendaylight.restconf.common.errors.RestconfError; +import org.opendaylight.yangtools.yang.common.Revision; /** * Unit test for {@link RestconfValidation}. @@ -34,15 +33,9 @@ public class RestconfValidationTest { */ @Test public void validateAndGetRevisionTest() { - final Date revision = RestconfValidation.validateAndGetRevision(REVISIONS.iterator()); + final Revision revision = RestconfValidation.validateAndGetRevision(REVISIONS.iterator()); assertNotNull("Correct module revision should be validated", revision); - - final Calendar calendar = Calendar.getInstance(); - calendar.setTime(revision); - - assertEquals(2014, calendar.get(Calendar.YEAR)); - assertEquals(0, calendar.get(Calendar.MONTH)); - assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(Revision.of("2014-01-01"), revision); } /** diff --git a/restconf/restconf-nb-rfc8040/src/test/resources/invoke-rpc/invoke-rpc-module.yang b/restconf/restconf-nb-rfc8040/src/test/resources/invoke-rpc/invoke-rpc-module.yang index c23c50ab48..92cf1a9d6c 100644 --- a/restconf/restconf-nb-rfc8040/src/test/resources/invoke-rpc/invoke-rpc-module.yang +++ b/restconf/restconf-nb-rfc8040/src/test/resources/invoke-rpc/invoke-rpc-module.yang @@ -3,7 +3,7 @@ module invoke-rpc-module { prefix "inrpcmod"; - revision 2013-12-3 { + revision 2013-12-03 { } @@ -26,4 +26,4 @@ module invoke-rpc-module { rpc rpc-noop { } -} \ No newline at end of file +} diff --git a/restconf/restconf-nb-rfc8040/src/test/resources/modules/nested-module.yang b/restconf/restconf-nb-rfc8040/src/test/resources/modules/nested-module.yang index aa2795afeb..794859b0c2 100644 --- a/restconf/restconf-nb-rfc8040/src/test/resources/modules/nested-module.yang +++ b/restconf/restconf-nb-rfc8040/src/test/resources/modules/nested-module.yang @@ -1,7 +1,7 @@ module nested-module { namespace "urn:nested:module"; prefix "nested"; - revision "2014-06-3"; + revision "2014-06-03"; container depth1-cont { list depth2-cont1 { diff --git a/restconf/sal-rest-docgen-maven/src/main/java/org/opendaylight/netconf/sal/rest/doc/maven/StaticDocGenerator.java b/restconf/sal-rest-docgen-maven/src/main/java/org/opendaylight/netconf/sal/rest/doc/maven/StaticDocGenerator.java index 7a06710f5c..dbb1c1e1ee 100644 --- a/restconf/sal-rest-docgen-maven/src/main/java/org/opendaylight/netconf/sal/rest/doc/maven/StaticDocGenerator.java +++ b/restconf/sal-rest-docgen-maven/src/main/java/org/opendaylight/netconf/sal/rest/doc/maven/StaticDocGenerator.java @@ -17,7 +17,9 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; +import java.util.function.Function; import javax.ws.rs.core.UriInfo; import org.apache.maven.project.MavenProject; import org.opendaylight.netconf.sal.rest.doc.impl.ApiDocGenerator; @@ -41,35 +43,27 @@ public class StaticDocGenerator extends ApiDocGenerator implements BasicCodeGene private Map additionalConfig; private File resourceBaseDir; - /** - * Generate sources. - * - * @param context schema context - * @param outputDir output directory - * @param yangModules modules - * @return {@link Collection} of resource files - * @throws IOException when file operation fails - */ @Override - public Collection generateSources(final SchemaContext context, final File outputDir, - final Set yangModules) throws IOException { + public Collection generateSources(final SchemaContext context, final File outputBaseDir, + final Set currentModules, final Function> moduleResourcePathResolver) + throws IOException { List result = new ArrayList<>(); // Create Base Directory - final File outputBaseDir; - if (outputDir == null) { - outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH); + final File outputDir; + if (outputBaseDir == null) { + outputDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH); } else { - outputBaseDir = outputDir; + outputDir = outputBaseDir; } - outputBaseDir.mkdirs(); + outputDir.mkdirs(); // Create Resources directory - File resourcesDir = new File(outputBaseDir, "resources"); + File resourcesDir = new File(outputDir, "resources"); resourcesDir.mkdirs(); // Create JS file - File resourcesJsFile = new File(outputBaseDir, "resources.js"); + File resourcesJsFile = new File(outputDir, "resources.js"); resourcesJsFile.createNewFile(); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resourcesJsFile)); ObjectMapper mapper = new ObjectMapper(); diff --git a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/BaseYangSwaggerGenerator.java b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/BaseYangSwaggerGenerator.java index 91612c1eac..9c333f793c 100644 --- a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/BaseYangSwaggerGenerator.java +++ b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/BaseYangSwaggerGenerator.java @@ -15,15 +15,13 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Preconditions; import java.io.IOException; import java.net.URI; -import java.text.ParseException; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Calendar; import java.util.Collection; import java.util.Collections; -import java.util.Date; -import java.util.GregorianCalendar; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; @@ -40,7 +38,7 @@ import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter; import org.opendaylight.netconf.sal.rest.doc.swagger.Resource; import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList; import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; @@ -49,7 +47,6 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -88,7 +85,7 @@ public class BaseYangSwaggerGenerator { LOG.info("Modules found [{}]", modules.size()); for (final Module module : modules) { - final String revisionString = module.getQNameModule().getFormattedRevision(); + final String revisionString = module.getQNameModule().getRevision().map(Revision::toString).orElse(null); final Resource resource = new Resource(); LOG.debug("Working on [{},{}]...", module.getName(), revisionString); final ApiDeclaration doc = @@ -121,34 +118,22 @@ public class BaseYangSwaggerGenerator { public ApiDeclaration getApiDeclaration(final String moduleName, final String revision, final UriInfo uriInfo, final SchemaContext schemaContext, final String context) { - Date rev = null; + final Optional rev; try { - if (revision != null && !SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(revision)) { - rev = SimpleDateFormatUtil.getRevisionFormat().parse(revision); - } - } catch (final ParseException e) { + rev = Revision.ofNullable(revision); + } catch (final DateTimeParseException e) { throw new IllegalArgumentException(e); } - if (rev != null) { - final Calendar cal = new GregorianCalendar(); - - cal.setTime(rev); - - if (cal.get(Calendar.YEAR) < 1970) { - rev = null; - } - } - - final Module module = schemaContext.findModuleByName(moduleName, rev); + final Module module = schemaContext.findModule(moduleName, rev).orElse(null); Preconditions.checkArgument(module != null, "Could not find module by name,revision: " + moduleName + "," + revision); - return getApiDeclaration(module, rev, uriInfo, context, schemaContext); + return getApiDeclaration(module, uriInfo, context, schemaContext); } - public ApiDeclaration getApiDeclaration(final Module module, final Date revision, final UriInfo uriInfo, + public ApiDeclaration getApiDeclaration(final Module module, final UriInfo uriInfo, final String context, final SchemaContext schemaContext) { final String basePath = createBasePathFromUriInfo(uriInfo); @@ -181,7 +166,7 @@ public class BaseYangSwaggerGenerator { final Collection dataSchemaNodes = module.getChildNodes(); LOG.debug("child nodes size [{}]", dataSchemaNodes.size()); for (final DataSchemaNode node : dataSchemaNodes) { - if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { + if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) { LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName()); List pathParams = new ArrayList<>(); @@ -251,7 +236,7 @@ public class BaseYangSwaggerGenerator { final Api apiForRootPostUri = new Api(); apiForRootPostUri.setPath(resourcePath.concat(getContent(dataStore))); apiForRootPostUri.setOperations(operationPost(module.getName() + MODULE_NAME_SUFFIX, - module.getDescription(), module, pathParams, true, "")); + module.getDescription().orElse(null), module, pathParams, true, "")); apis.add(apiForRootPostUri); } } @@ -291,7 +276,7 @@ public class BaseYangSwaggerGenerator { api.setPath(resourcePath.concat(getContent(dataStore))); Iterable childSchemaNodes = Collections.emptySet(); - if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { + if (node instanceof ListSchemaNode || node instanceof ContainerSchemaNode) { final DataNodeContainer dataNodeContainer = (DataNodeContainer) node; childSchemaNodes = dataNodeContainer.getChildNodes(); } @@ -299,7 +284,7 @@ public class BaseYangSwaggerGenerator { apis.add(api); for (final DataSchemaNode childNode : childSchemaNodes) { - if ((childNode instanceof ListSchemaNode) || (childNode instanceof ContainerSchemaNode)) { + if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) { // keep config and operation attributes separate. if (childNode.isConfiguration() == addConfigApi) { final String newParent = parentName + "/" + node.getQName().getLocalName(); @@ -341,14 +326,15 @@ public class BaseYangSwaggerGenerator { operations.add(getBuilder.pathParams(pathParams).build()); if (isConfig) { - final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription(), parentName); + final Put putBuilder = new Put(node.getQName().getLocalName(), node.getDescription().orElse(null), + parentName); operations.add(putBuilder.pathParams(pathParams).build()); final Delete deleteBuilder = new Delete(node); operations.add(deleteBuilder.pathParams(pathParams).build()); if (containsListOrContainer(childSchemaNodes)) { - operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), + operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription().orElse(null), (DataNodeContainer) node, pathParams, isConfig, parentName + "/")); } } @@ -373,7 +359,7 @@ public class BaseYangSwaggerGenerator { final String localName = resolvePathArgumentsName(schemaNode, schemaContext); path.append(localName); - if ((schemaNode instanceof ListSchemaNode)) { + if (schemaNode instanceof ListSchemaNode) { final List listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition(); StringBuilder keyBuilder = null; if (newDraft) { @@ -382,7 +368,7 @@ public class BaseYangSwaggerGenerator { for (final QName listKey : listKeys) { final DataSchemaNode dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey); - pathListParams.add(((LeafSchemaNode) dataChildByName)); + pathListParams.add((LeafSchemaNode) dataChildByName); final String pathParamIdentifier; if (newDraft) { pathParamIdentifier = keyBuilder.append("{").append(listKey.getLocalName()).append("}").toString(); @@ -393,7 +379,7 @@ public class BaseYangSwaggerGenerator { final Parameter pathParam = new Parameter(); pathParam.setName(listKey.getLocalName()); - pathParam.setDescription(dataChildByName.getDescription()); + pathParam.setDescription(dataChildByName.getDescription().orElse(null)); pathParam.setType("string"); pathParam.setParamType("path"); @@ -414,7 +400,7 @@ public class BaseYangSwaggerGenerator { final Operation operationSpec = new Operation(); operationSpec.setMethod("POST"); - operationSpec.setNotes(rpcDefn.getDescription()); + operationSpec.setNotes(rpcDefn.getDescription().orElse(null)); operationSpec.setNickname(rpcDefn.getQName().getLocalName()); if (!rpcDefn.getOutput().getChildNodes().isEmpty()) { operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output" + OperationBuilder.TOP); @@ -442,9 +428,7 @@ public class BaseYangSwaggerGenerator { final SortedSet sortedModules = new TreeSet<>((module1, module2) -> { int result = module1.getName().compareTo(module2.getName()); if (result == 0) { - final Date module1Revision = module1.getRevision() != null ? module1.getRevision() : new Date(0); - final Date module2Revision = module2.getRevision() != null ? module2.getRevision() : new Date(0); - result = module1Revision.compareTo(module2Revision); + result = Revision.compare(module1.getRevision(), module2.getRevision()); } if (result == 0) { result = module1.getNamespace().compareTo(module2.getNamespace()); diff --git a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/ModelGenerator.java b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/ModelGenerator.java index ca6cb577a2..f9b02d6c63 100644 --- a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/ModelGenerator.java +++ b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/ModelGenerator.java @@ -14,9 +14,12 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; +import com.google.common.collect.Range; +import com.google.common.collect.RangeSet; import com.mifmif.common.regex.Generex; import java.io.IOException; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import javax.annotation.concurrent.NotThreadSafe; @@ -25,37 +28,37 @@ import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; +import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint; import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; +import org.opendaylight.yangtools.yang.model.api.MandatoryAware; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaNode; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode; +import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode; import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit; import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair; import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint; import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint; +import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; +import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition; import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl; import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; import org.slf4j.Logger; @@ -190,7 +193,7 @@ public class ModelGenerator { dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE); dataNodeProperties.put(ITEMS_KEY, items); - putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription()); + putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription().orElse(null)); final ObjectNode properties = JsonNodeFactory.instance.objectNode(); properties.put(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties); final ObjectNode finalChildSchema = getSchemaTemplate(); @@ -220,12 +223,11 @@ public class ModelGenerator { LOG.debug("Processing Identity: {}", identityName); identityObj.put(ID_KEY, identityName); - putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription()); + putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription().orElse(null)); final ObjectNode props = JsonNodeFactory.instance.objectNode(); - final IdentitySchemaNode baseId = idNode.getBaseIdentity(); - if (baseId == null) { + if (idNode.getBaseIdentities().isEmpty()) { /* * This is a base identity. So lets see if it has sub types. If it does, then add them to the model * definition. @@ -244,7 +246,7 @@ public class ModelGenerator { /* * This is a derived entity. Add it's base type & move on. */ - props.put(TYPE_KEY, baseId.getQName().getLocalName()); + props.put(TYPE_KEY, idNode.getBaseIdentities().iterator().next().getQName().getLocalName()); } // Add the properties. For a base type, this will be an empty object as required by the Swagger spec. @@ -332,9 +334,9 @@ public class ModelGenerator { property = processLeafListNode((LeafListSchemaNode) node, schemaContext); } else if (node instanceof ChoiceSchemaNode) { - if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) { - processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(), - parentName, models, schemaContext, isConfig, properties); + if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) { + processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next() + .getChildNodes(), parentName, models, schemaContext, isConfig, properties); } continue; @@ -348,7 +350,7 @@ public class ModelGenerator { } else { throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass()); } - putIfNonNull(property, DESCRIPTION_KEY, node.getDescription()); + putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null)); properties.put(topLevelModule.getName() + ":" + name, property); } } @@ -361,8 +363,16 @@ public class ModelGenerator { props.put(TYPE_KEY, ARRAY_TYPE); final ObjectNode itemsVal = JsonNodeFactory.instance.objectNode(); - final ConstraintDefinition constraints = listNode.getConstraints(); - int max = constraints.getMaxElements() == null ? 2 : constraints.getMaxElements(); + final Optional optConstraint = listNode.getElementCountConstraint(); + final int max; + if (optConstraint.isPresent()) { + final Integer constraintMax = optConstraint.get().getMaxElements(); + max = constraintMax == null ? 2 : constraintMax; + processElementCount(optConstraint.get(), props); + } else { + max = 2; + } + if (max >= 2) { processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext); processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext); @@ -371,9 +381,6 @@ public class ModelGenerator { } props.put(ITEMS_KEY, itemsVal); - - processConstraints(constraints, props); - return props; } @@ -396,8 +403,8 @@ public class ModelGenerator { property = processLeafListNode((LeafListSchemaNode) node, schemaContext); } else if (node instanceof ChoiceSchemaNode) { - if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) { - processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(), + if (((ChoiceSchemaNode) node).getCases().values().iterator().hasNext()) { + processChoiceNode(((ChoiceSchemaNode) node).getCases().values().iterator().next().getChildNodes(), moduleName, models, schemaContext, isConfig, properties); } continue; @@ -413,33 +420,33 @@ public class ModelGenerator { throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass()); } - putIfNonNull(property, DESCRIPTION_KEY, node.getDescription()); + putIfNonNull(property, DESCRIPTION_KEY, node.getDescription().orElse(null)); properties.put(name, property); } } - private static void processConstraints(final ConstraintDefinition constraints, - final ObjectNode props) { - final boolean isMandatory = constraints.isMandatory(); - props.put(REQUIRED_KEY, isMandatory); - - final Integer minElements = constraints.getMinElements(); - final Integer maxElements = constraints.getMaxElements(); + private static void processElementCount(final ElementCountConstraint constraint, final ObjectNode props) { + final Integer minElements = constraint.getMinElements(); if (minElements != null) { props.put(MIN_ITEMS, minElements); } + final Integer maxElements = constraint.getMaxElements(); if (maxElements != null) { props.put(MAX_ITEMS, maxElements); } } + private static void processMandatory(final MandatoryAware node, final ObjectNode props) { + props.put(REQUIRED_KEY, node.isMandatory()); + } + private ObjectNode processLeafNode(final LeafSchemaNode leafNode, final SchemaContext schemaContext) { final ObjectNode property = JsonNodeFactory.instance.objectNode(); - final String leafDescription = leafNode.getDescription(); + final String leafDescription = leafNode.getDescription().orElse(null); putIfNonNull(property, DESCRIPTION_KEY, leafDescription); - processConstraints(leafNode.getConstraints(), property); + processMandatory(leafNode, property); processTypeDef(leafNode.getType(), leafNode, property, schemaContext); return property; @@ -448,10 +455,10 @@ public class ModelGenerator { private static ObjectNode processAnyXMLNode(final AnyXmlSchemaNode leafNode) { final ObjectNode property = JsonNodeFactory.instance.objectNode(); - final String leafDescription = leafNode.getDescription(); + final String leafDescription = leafNode.getDescription().orElse(null); putIfNonNull(property, DESCRIPTION_KEY, leafDescription); - processConstraints(leafNode.getConstraints(), property); + processMandatory(leafNode, property); final String localName = leafNode.getQName().getLocalName(); property.put(TYPE_KEY, "example of anyxml " + localName); @@ -473,8 +480,8 @@ public class ModelGenerator { } else if (leafTypeDef instanceof IdentityrefTypeDefinition) { final String name = topLevelModule.getName(); - jsonType = - name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName(); + jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentities().iterator().next() + .getQName().getLocalName(); } else if (leafTypeDef instanceof StringTypeDefinition) { jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName()); @@ -491,17 +498,11 @@ public class ModelGenerator { } else if (leafTypeDef instanceof BooleanTypeDefinition) { jsonType = "true"; - } else if (leafTypeDef instanceof DecimalTypeDefinition) { - jsonType = String.valueOf(((DecimalTypeDefinition) leafTypeDef).getRangeConstraints() - .iterator().next().getMin()); - - } else if (leafTypeDef instanceof IntegerTypeDefinition) { - jsonType = String.valueOf(((IntegerTypeDefinition) leafTypeDef).getRangeConstraints() - .iterator().next().getMin()); - - } else if (leafTypeDef instanceof UnsignedIntegerTypeDefinition) { - jsonType = String.valueOf(((UnsignedIntegerTypeDefinition) leafTypeDef).getRangeConstraints() - .iterator().next().getMin()); + } else if (leafTypeDef instanceof RangeRestrictedTypeDefinition) { + final Number maybeLower = ((RangeRestrictedTypeDefinition) leafTypeDef).getRangeConstraint() + .map(RangeConstraint::getAllowedRanges).map(RangeSet::span).map(Range::lowerEndpoint) + .orElse(null); + jsonType = String.valueOf(maybeLower); } else { jsonType = OBJECT_TYPE; @@ -531,13 +532,12 @@ public class ModelGenerator { schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath); } - return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode, + return processTypeDef(((TypedDataSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode, property, schemaContext); } private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) { - return schemaContext - .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision()); + return schemaContext.findModule(qualifiedName.getNamespace(), qualifiedName.getRevision()).orElse(null); } private static String processBinaryType(final ObjectNode property) { @@ -576,23 +576,21 @@ public class ModelGenerator { private static String processStringType(final TypeDefinition stringType, final ObjectNode property, final String nodeName) { StringTypeDefinition type = (StringTypeDefinition) stringType; - List lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraints(); - while (lengthConstraints.isEmpty() && type.getBaseType() != null) { + Optional lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint(); + while (!lengthConstraints.isPresent() && type.getBaseType() != null) { type = type.getBaseType(); - lengthConstraints = type.getLengthConstraints(); + lengthConstraints = type.getLengthConstraint(); } - // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum - // and true maximum implied by the constraints and use that. - for (final LengthConstraint lengthConstraint : lengthConstraints) { - final Number min = lengthConstraint.getMin(); - final Number max = lengthConstraint.getMax(); - putIfNonNull(property, MIN_LENGTH_KEY, min); - putIfNonNull(property, MAX_LENGTH_KEY, max); + if (lengthConstraints.isPresent()) { + final Range range = lengthConstraints.get().getAllowedRanges().span(); + putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint()); + putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint()); } + if (type.getPatternConstraints().iterator().hasNext()) { final PatternConstraint pattern = type.getPatternConstraints().iterator().next(); - String regex = pattern.getRegularExpression(); + String regex = pattern.getJavaPatternString(); regex = regex.substring(1, regex.length() - 1); final Generex generex = new Generex(regex); return generex.random(); @@ -621,7 +619,7 @@ public class ModelGenerator { return schemaJSON; } - private static void putIfNonNull(ObjectNode property, String key, Number number) { + private static void putIfNonNull(final ObjectNode property, final String key, final Number number) { if (key != null && number != null) { if (number instanceof Double) { property.put(key, (Double) number); @@ -637,7 +635,7 @@ public class ModelGenerator { } } - private static void putIfNonNull(ObjectNode property, String key, String value) { + private static void putIfNonNull(final ObjectNode property, final String key, final String value) { if (key != null && value != null) { property.put(key, value); } diff --git a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/model/builder/OperationBuilder.java b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/model/builder/OperationBuilder.java index bb14d5a593..4a4eba98d1 100644 --- a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/model/builder/OperationBuilder.java +++ b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/model/builder/OperationBuilder.java @@ -29,6 +29,10 @@ public final class OperationBuilder { CONSUMES_PUT_POST.add("application/xml"); } + private OperationBuilder() { + + } + public static class Get { protected Operation spec; @@ -41,7 +45,7 @@ public final class OperationBuilder { spec.setMethod(METHOD_NAME); spec.setNickname(METHOD_NAME + "-" + node.getQName().getLocalName()); spec.setType((isConfig ? CONFIG : OPERATIONAL) + node.getQName().getLocalName()); - spec.setNotes(node.getDescription()); + spec.setNotes(node.getDescription().orElse(null)); } public Get pathParams(final List params) { diff --git a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/util/RestDocgenUtil.java b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/util/RestDocgenUtil.java index 6c21c267af..1fa3a01dc3 100644 --- a/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/util/RestDocgenUtil.java +++ b/restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/util/RestDocgenUtil.java @@ -8,21 +8,22 @@ package org.opendaylight.netconf.sal.rest.doc.util; import java.net.URI; -import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.common.Revision; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaNode; -public class RestDocgenUtil { +public final class RestDocgenUtil { private RestDocgenUtil() { } - private static final Map> NAMESPACE_AND_REVISION_TO_MODULE = new HashMap<>(); + private static final Map, Module>> NAMESPACE_AND_REVISION_TO_MODULE = new HashMap<>(); /** * Resolve path argument name for {@code node}. @@ -52,16 +53,16 @@ public class RestDocgenUtil { private static synchronized String resolveFullNameFromNode(final SchemaNode node, final SchemaContext schemaContext) { final URI namespace = node.getQName().getNamespace(); - final Date revision = node.getQName().getRevision(); + final Optional revision = node.getQName().getRevision(); - Map revisionToModule = NAMESPACE_AND_REVISION_TO_MODULE.get(namespace); + Map, Module> revisionToModule = NAMESPACE_AND_REVISION_TO_MODULE.get(namespace); if (revisionToModule == null) { revisionToModule = new HashMap<>(); NAMESPACE_AND_REVISION_TO_MODULE.put(namespace, revisionToModule); } Module module = revisionToModule.get(revision); if (module == null) { - module = schemaContext.findModuleByNamespaceAndRevision(namespace, revision); + module = schemaContext.findModule(namespace, revision).orElse(null); revisionToModule.put(revision, module); } if (module != null) { diff --git a/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/DocGenTestHelper.java b/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/DocGenTestHelper.java index a8196dac47..1c48480a83 100644 --- a/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/DocGenTestHelper.java +++ b/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/DocGenTestHelper.java @@ -19,18 +19,15 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.Set; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; public class DocGenTestHelper { @@ -39,8 +36,7 @@ public class DocGenTestHelper { private ObjectMapper mapper; private SchemaContext schemaContext; - public Set loadModules(final String resourceDirectory) - throws URISyntaxException, FileNotFoundException, ReactorException { + public Set loadModules(final String resourceDirectory) throws URISyntaxException, FileNotFoundException { final URI resourceDirUri = getClass().getResource(resourceDirectory).toURI(); final File testDir = new File(resourceDirUri); @@ -53,7 +49,7 @@ public class DocGenTestHelper { files.add(new File(testDir, fileName)); } - this.schemaContext = YangParserTestUtils.parseYangSources(files); + this.schemaContext = YangParserTestUtils.parseYangFiles(files); return this.schemaContext.getModules(); } @@ -90,36 +86,30 @@ public class DocGenTestHelper { when(mockContext.getModules()).thenReturn(this.modules); final ArgumentCaptor moduleCapture = ArgumentCaptor.forClass(String.class); - final ArgumentCaptor dateCapture = ArgumentCaptor.forClass(Date.class); + final ArgumentCaptor dateCapture = ArgumentCaptor.forClass(Optional.class); final ArgumentCaptor namespaceCapture = ArgumentCaptor.forClass(URI.class); - when(mockContext.findModuleByName(moduleCapture.capture(), dateCapture.capture())).then( - new Answer() { - @Override - public Module answer(final InvocationOnMock invocation) throws Throwable { - final String module = moduleCapture.getValue(); - final Date date = dateCapture.getValue(); - for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) { - if (m.getName().equals(module) && m.getRevision().equals(date)) { - return m; - } - } - return null; + when(mockContext.findModule(moduleCapture.capture(), dateCapture.capture())).then( + invocation -> { + final String module = moduleCapture.getValue(); + final Optional date = dateCapture.getValue(); + for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) { + if (m.getName().equals(module) && m.getRevision().equals(date)) { + return Optional.of(m); } - }); - when(mockContext.findModuleByNamespaceAndRevision(namespaceCapture.capture(), dateCapture.capture())).then( - new Answer() { - @Override - public Module answer(final InvocationOnMock invocation) throws Throwable { - final URI namespace = namespaceCapture.getValue(); - final Date date = dateCapture.getValue(); - for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) { - if (m.getNamespace().equals(namespace) && m.getRevision().equals(date)) { - return m; - } - } - return null; + } + return Optional.empty(); + }); + when(mockContext.findModule(namespaceCapture.capture(), dateCapture.capture())).then( + invocation -> { + final URI namespace = namespaceCapture.getValue(); + final Optional date = dateCapture.getValue(); + for (final Module m : Collections.unmodifiableSet(DocGenTestHelper.this.modules)) { + if (m.getNamespace().equals(namespace) && m.getRevision().equals(date)) { + return Optional.of(m); } - }); + } + return Optional.empty(); + }); return mockContext; } @@ -130,12 +120,7 @@ public class DocGenTestHelper { final ArgumentCaptor subStringCapture = ArgumentCaptor.forClass(String.class); when(mockBuilder.path(subStringCapture.capture())).thenReturn(mockBuilder); - when(mockBuilder.build()).then(new Answer() { - @Override - public URI answer(final InvocationOnMock invocation) throws Throwable { - return URI.create(uri + "/" + subStringCapture.getValue()); - } - }); + when(mockBuilder.build()).then(invocation -> URI.create(uri + "/" + subStringCapture.getValue())); final UriInfo info = mock(UriInfo.class); diff --git a/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/MountPointSwaggerTest.java b/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/MountPointSwaggerTest.java index a8c9bebecc..2ee9a90255 100644 --- a/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/MountPointSwaggerTest.java +++ b/restconf/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/MountPointSwaggerTest.java @@ -38,9 +38,9 @@ public class MountPointSwaggerTest { private static final String HTTP_URL = "http://localhost/path"; private static final YangInstanceIdentifier INSTANCE_ID = YangInstanceIdentifier.builder() - .node(QName.create("nodes")) - .node(QName.create("node")) - .nodeWithKey(QName.create("node"), QName.create("id"), "123").build(); + .node(QName.create("", "nodes")) + .node(QName.create("", "node")) + .nodeWithKey(QName.create("", "node"), QName.create("", "id"), "123").build(); private static final String INSTANCE_URL = "/nodes/node/123/"; private MountPointSwagger swagger; private DocGenTestHelper helper; diff --git a/restconf/sal-rest-docgen/src/test/resources/yang/toaster_augmented.yang b/restconf/sal-rest-docgen/src/test/resources/yang/toaster_augmented.yang index 4db7897a99..05056e905a 100644 --- a/restconf/sal-rest-docgen/src/test/resources/yang/toaster_augmented.yang +++ b/restconf/sal-rest-docgen/src/test/resources/yang/toaster_augmented.yang @@ -8,7 +8,7 @@ module toaster-augmented { prefix toast; import toaster2 {prefix tst; revision-date 2009-11-20;} - revision "2014-7-14" { + revision "2014-07-14" { } augment "/tst:toaster/tst:toasterSlot" { @@ -18,4 +18,4 @@ module toaster-augmented { } } } -} \ No newline at end of file +} -- 2.36.6