<tag>HEAD</tag>
<url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
</scm>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
</project>
import org.slf4j.LoggerFactory;
/**
- * Instead of using loopback (controller-config mount point) to create your netconf-connector, you should use the network-topology capability.
+ * Instead of using loopback (controller-config mount point) to create your netconf-connector,
+ * you should use the network-topology capability.
+ *
* <p>
- * Follow instructions provided in this <a href="https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf#Spawning_netconf_connectors_via_topology_configuration">wiki</a>.
+ * Follow instructions provided in this
+ * <a href="https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf#Spawning_netconf_connectors_via_topology_configuration">wiki</a>.
+ *
* <p>
* Deprecation notice in Carbon, removal planned for Nitrogen.
*/
@Deprecated
-public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule implements BindingAwareConsumer {
+public final class NetconfConnectorModule
+ extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
+ implements BindingAwareConsumer {
private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
private static final InstanceIdentifier<Topology> TOPOLOGY_PATH = InstanceIdentifier.create(NetworkTopology.class)
private InstanceIdentifier<Node> nodePath;
private DataBroker dataBroker;
- public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+ public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
instanceName = identifier.getInstanceName();
}
- public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
+ public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+ final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
instanceName = identifier.getInstanceName();
}
@Override
protected void customValidation() {
checkNotNull(getAddress(), addressJmxAttribute);
- checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
+ checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(),
+ addressJmxAttribute);
checkNotNull(getPort(), portJmxAttribute);
checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
}
private static boolean isHostAddressPresent(final Host address) {
- return address.getDomainName() != null ||
- address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
+ return address.getDomainName() != null || address.getIpAddress() != null
+ && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
}
@Override
}
@Override
- public void onFailure(final Throwable t) {
- LOG.error("Node {} creation failed: {}", instanceName, t);
+ public void onFailure(final Throwable throwable) {
+ LOG.error("Node {} creation failed: {}", instanceName, throwable);
}
});
}
}
@Override
- public void onFailure(final Throwable t) {
- LOG.error("Node {} deletion failed: {}", instanceName, t);
+ public void onFailure(final Throwable throwable) {
+ LOG.error("Node {} deletion failed: {}", instanceName, throwable);
}
});
}
NonModuleCapabilities nonModuleCapabilities = null;
- if(getNonModuleCapabilities() != null) {
+ if (getNonModuleCapabilities() != null) {
nonModuleCapabilities = new NonModuleCapabilitiesBuilder()
.setOverride(getNonModuleCapabilities().getOverride())
.setCapability(getNonModuleCapabilities().getCapability())
@Override
public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
- old, bundleContext);
+ final NetconfConnectorModule module =
+ (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, old, bundleContext);
return module;
}
@Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
- bundleContext);
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
+ final NetconfConnectorModule module =
+ (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, bundleContext);
return module;
}
}
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
/**
- * Factory for netconf device schemas
+ * Factory for netconf device schemas.
*/
public interface NetconfDeviceSchemasResolver {
- NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id);
+ NetconfDeviceSchemas resolve(
+ NetconfDeviceRpc deviceRpc, NetconfSessionPreferences remoteSessionCapabilities, RemoteDeviceId id);
}
package org.opendaylight.netconf.sal.connect.api;
/**
- *
+ * Remote device.
*/
public interface RemoteDevice<PREF, M, LISTENER extends RemoteDeviceCommunicator<M>> {
/**
* Holds URLs with YANG schema resources for all yang modules reported in
- * ietf-netconf-yang-library/modules-state/modules node
+ * ietf-netconf-yang-library/modules-state/modules node.
*/
public class LibraryModulesSchemas implements NetconfDeviceSchemas {
static {
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- moduleInfoBackedContext.registerModuleInfo(
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.
- $YangModuleInfoImpl.getInstance());
+ moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
+ .library.rev160409.$YangModuleInfoImpl.getInstance());
LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
}
final Map<SourceIdentifier, URL> result = Maps.newHashMap();
for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
final SourceIdentifier sId = RevisionSourceIdentifier
- .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
+ .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
result.put(sId, entry.getValue());
}
final URL urlConnection = new URL(url);
final URLConnection connection = urlConnection.openConnection();
- if(connection instanceof HttpURLConnection) {
+ if (connection instanceof HttpURLConnection) {
connection.setRequestProperty("Accept", "application/xml");
final String userpass = username + ":" + password;
final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
throw new RuntimeException(deviceId + ": Interrupted while waiting for response to "
+ MODULES_STATE_MODULE_LIST, e);
} catch (final ExecutionException e) {
- LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId, MODULES_STATE_MODULE_LIST, e);
+ LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
+ MODULES_STATE_MODULE_LIST, e);
return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
}
- if(moduleListNodeResult.getErrors().isEmpty() == false) {
+ if (moduleListNodeResult.getErrors().isEmpty() == false) {
LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
findModulesStateNode(moduleListNodeResult.getResult());
- if(modulesStateNode.isPresent()) {
+ if (modulesStateNode.isPresent()) {
Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
"Expecting container containing schemas, but was %s", modulesStateNode.get());
return create(((ContainerNode) modulesStateNode.get()));
}
}
- private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
- if(result == null) {
- return Optional.absent();
- }
- final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
- if(dataNode.isPresent() == false) {
- return Optional.absent();
- }
-
- return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
- }
-
private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
return new LibraryModulesSchemas(schemasMapping.build());
}
+ /**
+ * Resolves URLs with YANG schema resources from modules-state.
+ * @param url URL pointing to yang library
+ * @return Resolved URLs with YANG schema resources for all yang modules from yang library
+ */
+ public static LibraryModulesSchemas create(final String url) {
+ Preconditions.checkNotNull(url);
+ try {
+ final URL urlConnection = new URL(url);
+ final URLConnection connection = urlConnection.openConnection();
+
+ if (connection instanceof HttpURLConnection) {
+ connection.setRequestProperty("Accept", "application/xml");
+ }
+
+ return createFromURLConnection(connection);
+
+ } catch (final IOException e) {
+ LOG.warn("Unable to download yang library from {}", url, e);
+ return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ }
+ }
+
+ private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
+ if (result == null) {
+ return Optional.absent();
+ }
+ final Optional<DataContainerChild<?, ?>> dataNode =
+ ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+ if (dataNode.isPresent() == false) {
+ return Optional.absent();
+ }
+
+ return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
+ }
+
private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
String contentType = connection.getContentType();
Preconditions.checkNotNull(contentType, "Content type unknown");
Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
"Only XML and JSON types are supported.");
- try (final InputStream in = connection.getInputStream()) {
+ try (InputStream in = connection.getInputStream()) {
final Optional<NormalizedNode<?, ?>> optionalModulesStateNode =
contentType.equals("application/json") ? readJson(in) : readXml(in);
}
}
- /**
- * Resolves URLs with YANG schema resources from modules-state
- * @param url URL pointing to yang library
- * @return Resolved URLs with YANG schema resources for all yang modules from yang library
- */
- public static LibraryModulesSchemas create(final String url) {
- Preconditions.checkNotNull(url);
- try {
- final URL urlConnection = new URL(url);
- final URLConnection connection = urlConnection.openConnection();
-
- if(connection instanceof HttpURLConnection) {
- connection.setRequestProperty("Accept", "application/xml");
- }
-
- return createFromURLConnection(connection);
-
- } catch (final IOException e) {
- LOG.warn("Unable to download yang library from {}", url, e);
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
- }
- }
-
private static boolean guessJsonFromFileName(final String fileName) {
String extension = "";
final int i = fileName.lastIndexOf(46);
- if(i != -1) {
+ if (i != -1) {
extension = fileName.substring(i).toLowerCase();
}
jsonParser.parse(reader);
- return resultHolder.isFinished() ?
- Optional.of(resultHolder.getResult()) :
- Optional.<NormalizedNode<?, ?>>absent();
+ return resultHolder.isFinished()
+ ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
}
private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
parserFactory.getContainerNodeParser().parse(Collections.singleton(XmlUtil.readXmlToElement(in)),
(ContainerSchemaNode) LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME));
return Optional.of(parsed);
- } catch (IOException|SAXException e) {
+ } catch (IOException | SAXException e) {
LOG.warn("Unable to parse yang library xml content", e);
}
childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
- if(revision.isPresent()) {
- if(!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
+ if (revision.isPresent()) {
+ if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
return Optional.<Map.Entry<QName, URL>>absent();
}
import org.slf4j.LoggerFactory;
/**
- * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
+ * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
*/
-public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
+public class NetconfDevice
+ implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION =
- input -> RevisionSourceIdentifier.create(input.getLocalName(),
+ input -> RevisionSourceIdentifier.create(input.getLocalName(),
Optional.fromNullable(input.getFormattedRevision()));
protected final RemoteDeviceId id;
protected final SchemaRepository schemaRepository;
private final NetconfDeviceSchemasResolver stateSchemasResolver;
private final NotificationHandler notificationHandler;
- protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
+ protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
+ Lists.newArrayList();
// Message transformer is constructed once the schemas are available
private MessageTransformer<NetconfMessage> messageTransformer;
/**
- * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
+ * Create rpc implementation capable of handling RPC for monitoring and notifications
+ * even before the schemas of remote device are downloaded.
*/
- static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
- final BaseSchema baseSchema = notificationSupport ?
- BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
- BaseSchema.BASE_NETCONF_CTX;
-
- return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
+ static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
+ final boolean notificationSupport) {
+ final BaseSchema baseSchema = notificationSupport
+ ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS
+ : BaseSchema.BASE_NETCONF_CTX;
+
+ return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
+ new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
}
- public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
+ public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
+ final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
this.id = id;
this.reconnectOnSchemasChange = reconnectOnSchemasChange;
// http://netty.io/wiki/thread-model.html
LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
- final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
- final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
+ final NetconfDeviceRpc initRpc =
+ getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
+ final DeviceSourcesResolver task =
+ new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
- handleSalInitializationFailure(t, listener);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("{}: Unexpected error resolving device sources: {}", id, throwable);
+ handleSalInitializationFailure(throwable, listener);
}
};
Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
}
- private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
+ private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
+ final NetconfDeviceCommunicator listener) {
// TODO check whether the model describing create subscription is present in schema
- // Perhaps add a default schema context to support create-subscription if the model was not provided (same as what we do for base netconf operations in transformer)
+ // Perhaps add a default schema context to support create-subscription if the model was not provided
+ // (same as what we do for base netconf operations in transformer)
final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
if (isCapabilityChanged(notification)) {
LOG.info("{}: Schemas change detected, reconnecting", id);
- // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
+ // Only disconnect is enough,
+ // the reconnecting nature of the connector will take care of reconnecting
listener.disconnect();
return Optional.absent();
}
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
+ throwable);
}
});
}
final NetconfSessionPreferences remoteSessionCapabilities,
final DOMRpcService deviceRpc) {
final BaseSchema baseSchema =
- remoteSessionCapabilities.isNotificationsSupported() ?
- BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
- BaseSchema.BASE_NETCONF_CTX;
+ remoteSessionCapabilities.isNotificationsSupported()
+ ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
updateTransformer(messageTransformer);
LOG.info("{}: Netconf connector initialized successfully", id);
}
- void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
- LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
+ void handleSalInitializationFailure(final Throwable throwable,
+ final RemoteDeviceCommunicator<NetconfMessage> listener) {
+ LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
listener.close();
onRemoteSessionDown();
resetMessageTransformer();
}
/**
- * Set the transformer to null as is in initial state
+ * Set the transformer to null as is in initial state.
*/
private void resetMessageTransformer() {
updateTransformer(null);
final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
- PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
+ PotentialSchemaSource.create(
+ sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
}
}
notificationHandler.onRemoteSchemaDown();
salFacade.onDeviceDisconnected();
- for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
+ for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
+ : sourceRegistrations) {
sourceRegistration.close();
}
resetMessageTransformer();
private final RemoteDeviceId id;
private final NetconfDeviceSchemasResolver stateSchemasResolver;
- DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
- final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
+ DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
+ final NetconfSessionPreferences remoteSessionCapabilities,
+ final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
this.deviceRpc = deviceRpc;
this.remoteSessionCapabilities = remoteSessionCapabilities;
this.id = id;
this.stateSchemasResolver = stateSchemasResolver;
}
- public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
+ DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
+ final NetconfDeviceSchemasResolver stateSchemasResolver,
+ final NetconfDeviceRpc rpcForMonitoring) {
this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
}
@Override
public DeviceSources call() throws Exception {
- final NetconfDeviceSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
- LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
+ final NetconfDeviceSchemas availableSchemas =
+ stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
+ LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
+ availableSchemas.getAvailableYangSchemasQNames());
final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
if (!requiredSourcesNotProvided.isEmpty()) {
- LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
- id, requiredSourcesNotProvided);
+ LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
+ + " required but not provided: {}", id, requiredSourcesNotProvided);
LOG.warn("{}: Attempting to build schema context from required sources", id);
}
// Here all the sources reported in netconf monitoring are merged with those reported in hello.
// It is necessary to perform this since submodules are not mentioned in hello but still required.
- // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
- // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
+ // This clashes with the option of a user to specify supported yang models manually in configuration
+ // for netconf-connector and as a result one is not able to fully override yang models of a device.
+ // It is only possible to add additional models.
final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
if (!providedSourcesNotRequired.isEmpty()) {
- LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
- id, providedSourcesNotRequired);
+ LOG.warn("{}: Netconf device provides additional yang models not reported in "
+ + "hello message capabilities: {}", id, providedSourcesNotRequired);
LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
requiredSources.addAll(providedSourcesNotRequired);
}
final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- if(availableSchemas instanceof LibraryModulesSchemas) {
+ if (availableSchemas instanceof LibraryModulesSchemas) {
sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
((LibraryModulesSchemas) availableSchemas).getAvailableModels());
} else {
private final Set<QName> providedSources;
private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
+ DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
this.requiredSources = requiredSources;
this.providedSources = providedSources;
private final RemoteDeviceCommunicator<NetconfMessage> listener;
private final NetconfDeviceCapabilities capabilities;
- public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
+ SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
+ final RemoteDeviceCommunicator<NetconfMessage> listener) {
this.deviceSources = deviceSources;
this.remoteSessionCapabilities = remoteSessionCapabilities;
this.listener = listener;
private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
return requiredSources.parallelStream().filter(sourceIdentifier -> {
- boolean remove = false;
- try {
- schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
- } catch (SchemaSourceException e) {
- remove = true;
- }
- return remove;
- }).collect(Collectors.toList());
+ boolean remove = false;
+ try {
+ schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
+ } catch (SchemaSourceException e) {
+ remove = true;
+ }
+ return remove;
+ }).collect(Collectors.toList());
}
/**
- * Build schema context, in case of success or final failure notify device
+ * Build schema context, in case of success or final failure notify device.
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
while (!requiredSources.isEmpty()) {
LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
try {
- final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
+ final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture =
+ schemaContextFactory.createSchemaContext(requiredSources);
final SchemaContext result = schemaBuilderFuture.checkedGet();
LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
- final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
+ final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
+ capabilities.getUnresolvedCapabilites().keySet());
capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
- .setCapability(entry.toString()).setCapabilityOrigin(remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
+ .setCapability(entry.toString()).setCapabilityOrigin(
+ remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
.collect(Collectors.toList()));
- capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
- .setCapability(entry).setCapabilityOrigin(remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
+ capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
+ .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
+ .setCapability(entry).setCapabilityOrigin(
+ remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
.collect(Collectors.toList()));
handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
return;
} catch (final Throwable t) {
- if (t instanceof MissingSchemaSourceException){
- requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
+ if (t instanceof MissingSchemaSourceException) {
+ requiredSources =
+ handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
} else if (t instanceof SchemaResolutionException) {
// 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 (t.getCause() instanceof MissingSchemaSourceException) {
- requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
+ requiredSources = handleMissingSchemaSourceException(
+ requiredSources, (MissingSchemaSourceException) t.getCause());
continue;
}
- requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
+ requiredSources =
+ handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
} else {
// unknown error, fail
handleSalInitializationFailure(t, listener);
salFacade.onDeviceFailed(cause);
}
- private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
+ private Collection<SourceIdentifier> handleMissingSchemaSourceException(
+ final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
// In case source missing, try without it
- final SourceIdentifier missingSource = t.getSourceId();
- LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
- LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
- final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
+ final SourceIdentifier missingSource = exception.getSourceId();
+ LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id,
+ missingSource);
+ LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
+ exception);
+ final Collection<QName> qNameOfMissingSource =
+ getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
if (!qNameOfMissingSource.isEmpty()) {
- capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
+ capabilities.addUnresolvedCapabilities(
+ qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
}
return stripUnavailableSource(requiredSources, missingSource);
}
- private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
+ private Collection<SourceIdentifier> handleSchemaResolutionException(
+ final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
// In case resolution error, try only with resolved sources
// There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
// FIXME Do we really have assurance that these two cases cannot happen at once?
if (resolutionException.getFailedSource() != null) {
// flawed model - exclude it
final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
- LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId);
- LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException);
- capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
- UnavailableCapability.FailureReason.UnableToResolve);
+ LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
+ id, failedSourceId);
+ LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
+ id, resolutionException);
+ capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(
+ Collections.singleton(failedSourceId)), UnavailableCapability.FailureReason.UnableToResolve);
return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
}
// unsatisfied imports
final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
- capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
- LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
- LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
+ capabilities.addUnresolvedCapabilities(
+ getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
+ LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
+ id, resolutionException.getUnsatisfiedImports());
+ LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
+ resolutionException);
return resolutionException.getResolvedSources();
}
return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
}
- private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
+ private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
+ final SourceIdentifier sourceIdToRemove) {
final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
- final boolean removed = sourceIdentifiers.remove(sIdToRemove);
- Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
+ final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
+ Preconditions.checkState(
+ removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources);
return sourceIdentifiers;
}
final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
if (qNames.isEmpty()) {
- LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
+ LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
+ identifiers);
}
return Collections2.filter(qNames, Predicates.notNull());
}
return qname;
}
}
- LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
- // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability
+ LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
+ deviceSources.getRequiredSourcesQName());
+ // return null since we cannot find the QName,
+ // this capability will be removed from required sources and not reported as unresolved-capability
return null;
}
import org.slf4j.LoggerFactory;
/**
- * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas
+ * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
*/
public final class NetconfStateSchemas implements NetconfDeviceSchemas {
YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
private static final ContainerNode GET_SCHEMAS_RPC;
+
static {
final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
@Override
public Set<QName> getAvailableYangSchemasQNames() {
- return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), new Function<RemoteYangSchema, QName>() {
- @Override
- public QName apply(final RemoteYangSchema input) {
- return input.getQName();
- }
- }));
+ return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(),
+ new Function<RemoteYangSchema, QName>() {
+ @Override
+ public QName apply(final RemoteYangSchema input) {
+ return input.getQName();
+ }
+ }));
}
/**
- * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas
+ * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
*/
- static NetconfStateSchemas create(final DOMRpcService deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
- if(remoteSessionCapabilities.isMonitoringSupported() == false) {
+ static NetconfStateSchemas create(final DOMRpcService deviceRpc,
+ final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+ if (remoteSessionCapabilities.isMonitoringSupported() == false) {
// TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
// issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
- throw new RuntimeException(id + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
+ throw new RuntimeException(id
+ + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
} catch (final ExecutionException e) {
LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
return EMPTY;
}
- if(schemasNodeResult.getErrors().isEmpty() == false) {
- LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
+ if (schemasNodeResult.getErrors().isEmpty() == false) {
+ LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
+ id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
return EMPTY;
}
final Optional<? extends NormalizedNode<?, ?>> schemasNode = findSchemasNode(schemasNodeResult.getResult());
- if(schemasNode.isPresent()) {
+ if (schemasNode.isPresent()) {
Preconditions.checkState(schemasNode.get() instanceof ContainerNode,
"Expecting container containing schemas, but was %s", schemasNode.get());
return create(id, (ContainerNode) schemasNode.get());
}
}
- private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
- if(result == null) {
- return Optional.absent();
- }
- final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
- if(dataNode.isPresent() == false) {
- return Optional.absent();
- }
-
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
- ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
- if(nStateNode.isPresent() == false) {
- return Optional.absent();
- }
-
- return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
- }
-
/**
- * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas
+ * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
*/
@VisibleForTesting
protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemasNode.getChild(toId(Schema.QNAME));
- Preconditions.checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
- Preconditions.checkState(child.get() instanceof MapNode, "Unexpected structure for container: %s in response: %s. Expecting a list", Schema.QNAME.withoutRevision(), schemasNode);
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ schemasNode.getChild(toId(Schema.QNAME));
+ Preconditions.checkState(child.isPresent(),
+ "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
+ Preconditions.checkState(child.get() instanceof MapNode,
+ "Unexpected structure for container: %s in response: %s. Expecting a list",
+ Schema.QNAME.withoutRevision(), schemasNode);
for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
- final Optional<RemoteYangSchema> fromCompositeNode = RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
- if(fromCompositeNode.isPresent()) {
+ final Optional<RemoteYangSchema> fromCompositeNode =
+ RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
+ if (fromCompositeNode.isPresent()) {
availableYangSchemas.add(fromCompositeNode.get());
}
}
return new NetconfStateSchemas(availableYangSchemas);
}
- public final static class RemoteYangSchema {
+ private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
+ if (result == null) {
+ return Optional.absent();
+ }
+ final Optional<DataContainerChild<?, ?>> dataNode =
+ ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+ if (dataNode.isPresent() == false) {
+ return Optional.absent();
+ }
+
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
+ ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
+ if (nStateNode.isPresent() == false) {
+ return Optional.absent();
+ }
+
+ return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
+ }
+
+ public static final class RemoteYangSchema {
private final QName qname;
RemoteYangSchema(final QName qname) {
return qname;
}
- static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id, final MapEntryNode schemaNode) {
- Preconditions.checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
+ static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
+ final MapEntryNode schemaNode) {
+ Preconditions.checkArgument(
+ schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
- if(formatAsString.equals(Yang.QNAME.toString()) == false) {
+ if (formatAsString.equals(Yang.QNAME.toString()) == false) {
LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
return Optional.absent();
}
childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
- if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
+ if (locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
return Optional.absent();
}
}
/**
- * Extracts all values of a leaf-list node as a set of strings
+ * Extracts all values of a leaf-list node as a set of strings.
*/
- private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode, final QName childNodeQName) {
+ private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
+ final QName childNodeQName) {
final Set<String> extractedValues = Sets.newHashSet();
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemaNode.getChild(toId(childNodeQName));
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ schemaNode.getChild(toId(childNodeQName));
Preconditions.checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
- Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
+ Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>,
+ "Child nodes %s not present", childNodeQName);
for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
extractedValues.add(getValueOfSimpleNode(childNode).get());
}
return extractedValues;
}
- private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode, final QName childNode) {
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node = schemaNode.getChild(toId(childNode));
+ private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
+ final QName childNode) {
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
+ schemaNode.getChild(toId(childNode));
if (node.isPresent()) {
return getValueOfSimpleNode(node.get());
} else {
}
}
- private static Optional<String> getValueOfSimpleNode(final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
+ private static Optional<String> getValueOfSimpleNode(
+ final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.<String>absent() : Optional.of(value.toString().trim());
+ return value == null || Strings.isNullOrEmpty(value.toString())
+ ? Optional.<String>absent() : Optional.of(value.toString().trim());
}
@Override
- public boolean equals(final Object o) {
- if (this == o) {
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (o == null || getClass() != o.getClass()) {
+ if (obj == null || getClass() != obj.getClass()) {
return false;
}
- final RemoteYangSchema that = (RemoteYangSchema) o;
+ final RemoteYangSchema that = (RemoteYangSchema) obj;
if (!qname.equals(that.qname)) {
return false;
import org.opendaylight.yangtools.yang.common.QName;
/**
- * Default implementation resolving schemas QNames from netconf-state or from modules-state
+ * Default implementation resolving schemas QNames from netconf-state or from modules-state.
*/
public final class NetconfStateSchemasResolverImpl implements NetconfDeviceSchemasResolver {
@Override
- public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+ public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc,
+ final NetconfSessionPreferences remoteSessionCapabilities,
+ final RemoteDeviceId id) {
if (remoteSessionCapabilities.isMonitoringSupported()) {
return NetconfStateSchemas.create(deviceRpc, remoteSessionCapabilities, id);
- } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME, "ietf-yang-library"))) {
+ } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME,
+ "ietf-yang-library"))) {
return LibraryModulesSchemas.create(deviceRpc, id);
}
return NetconfStateSchemas.EMPTY;
}
synchronized void handleNotification(final NetconfMessage notification) {
- if(passNotifications) {
+ if (passNotifications) {
passNotification(transformNotification(notification));
} else {
queueNotification(notification);
/**
* Forward all cached notifications and pass all notifications from this point directly to sal facade.
- * @param messageTransformer
+ * @param messageTransformer Message transformer
*/
synchronized void onRemoteSchemaUp(final MessageTransformer<NetconfMessage> messageTransformer) {
this.messageTransformer = Preconditions.checkNotNull(messageTransformer);
private DOMNotification transformNotification(final NetconfMessage cachedNotification) {
final DOMNotification parsedNotification = messageTransformer.toNotification(cachedNotification);
- Preconditions.checkNotNull(parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification);
+ Preconditions.checkNotNull(
+ parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification);
return parsedNotification;
}
Preconditions.checkState(passNotifications == false);
LOG.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
}
private synchronized void passNotification(final DOMNotification parsedNotification) {
LOG.debug("{}: Forwarding notification {}", id, parsedNotification);
- if(filter == null || filter.filterNotification(parsedNotification).isPresent()) {
+ if (filter == null || filter.filterNotification(parsedNotification).isPresent()) {
salFacade.onNotification(parsedNotification);
}
}
messageTransformer = null;
}
- static interface NotificationFilter {
+ interface NotificationFilter {
Optional<DOMNotification> filterNotification(DOMNotification notification);
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
+public class NetconfDeviceCommunicator
+ implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
return isSessionClosing.get();
}
- public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
- final UserPreferences NetconfSessionPreferences, final int rpcMessageLimit) {
- this(id, remoteDevice, Optional.of(NetconfSessionPreferences), rpcMessageLimit);
+ public NetconfDeviceCommunicator(
+ final RemoteDeviceId id,
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+ final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) {
+ this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit);
}
- public NetconfDeviceCommunicator(final RemoteDeviceId id,
- final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
- final int rpcMessageLimit) {
+ public NetconfDeviceCommunicator(
+ final RemoteDeviceId id,
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+ final int rpcMessageLimit) {
this(id, remoteDevice, Optional.<UserPreferences>absent(), rpcMessageLimit);
}
- private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
- final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
+ private NetconfDeviceCommunicator(
+ final RemoteDeviceId id,
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+ final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
this.concurentRpcMsgs = rpcMessageLimit;
this.id = id;
this.remoteDevice = remoteDevice;
if (!firstConnectionFuture.isDone()) {
firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
}
- }
- finally {
+ } finally {
sessionLock.unlock();
}
}
/**
+ * Initialize remote connection.
*
- * @param dispatcher
- * @param config
+ * @param dispatcher {@code NetconfCLientDispatcher}
+ * @param config {@code NetconfClientConfiguration}
* @return future that returns succes on first succesfull connection and failure when the underlying
- * reconnecting strategy runs out of reconnection attempts
+ * reconnecting strategy runs out of reconnection attempts
*/
- public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
- if(config instanceof NetconfReconnectingClientConfiguration) {
+ public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(
+ final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
+ if (config instanceof NetconfReconnectingClientConfiguration) {
initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
} else {
initFuture = dispatcher.createClient(config);
public void disconnect() {
// If session is already in closing, no need to close it again
- if(session != null && isSessionClosing.compareAndSet(false, true)) {
+ if (session != null && isSessionClosing.compareAndSet(false, true)) {
session.close();
}
}
final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
sessionLock.lock();
try {
- if( session != null ) {
+ if (session != null) {
session = null;
-
/*
* Walk all requests, check if they have been executing
* or cancelled and remove them from the queue.
while (it.hasNext()) {
final Request r = it.next();
if (r.future.isUncancellable()) {
- futuresToCancel.add( r.future );
+ futuresToCancel.add(r.future);
it.remove();
} else if (r.future.isCancelled()) {
// This just does some house-cleaning
remoteDevice.onRemoteSessionDown();
}
- }
- finally {
+ } finally {
sessionLock.unlock();
}
// Notify pending request futures outside of the sessionLock to avoid unnecessarily
// blocking the caller.
for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
- if( Strings.isNullOrEmpty( reason ) ) {
- future.set( createSessionDownRpcResult() );
+ if (Strings.isNullOrEmpty(reason)) {
+ future.set(createSessionDownRpcResult());
} else {
- future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
+ future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, reason));
}
}
}
private RpcResult<NetconfMessage> createSessionDownRpcResult() {
- return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
- String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
+ return createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
+ String.format("The netconf session to %1$s is disconnected", id.getName()));
}
private static RpcResult<NetconfMessage> createErrorRpcResult(final RpcError.ErrorType errorType,
final String message) {
return RpcResultBuilder.<NetconfMessage>failed()
- .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
+ .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
}
@Override
- public void onSessionDown(final NetconfClientSession session, final Exception e) {
+ public void onSessionDown(final NetconfClientSession session, final Exception exception) {
// If session is already in closing, no need to call tearDown again.
if (isSessionClosing.compareAndSet(false, true)) {
- LOG.warn("{}: Session went down", id, e);
- tearDown( null );
+ LOG.warn("{}: Session went down", id, exception);
+ tearDown(null);
}
}
public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
// onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
LOG.warn("{}: Session terminated {}", id, reason);
- tearDown( reason.getErrorMessage() );
+ tearDown(reason.getErrorMessage());
}
@Override
public void close() {
// Cancel reconnect if in progress
- if(initFuture != null) {
+ if (initFuture != null) {
initFuture.cancel(false);
}
// Disconnect from device
requests.poll();
// we have just removed one request from the queue
// we can also release one permit
- if(semaphore != null) {
+ if (semaphore != null) {
semaphore.release();
}
} else {
LOG.warn("{}: Ignoring unsolicited message {}", id,
msgToS(message));
}
- }
- finally {
+ } finally {
sessionLock.unlock();
}
- if( request != null ) {
+ if (request != null) {
LOG.debug("{}: Message received {}", id, message);
- if(LOG.isTraceEnabled()) {
- LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
}
try {
- NetconfMessageTransformUtil.checkValidReply( request.request, message );
+ NetconfMessageTransformUtil.checkValidReply(request.request, message);
} catch (final NetconfDocumentedException e) {
LOG.warn(
- "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
+ "{}: Invalid request-reply match,"
+ + "reply message contains different message-id, request: {}, response: {}",
id, msgToS(request.request), msgToS(message), e);
- request.future.set( RpcResultBuilder.<NetconfMessage>failed()
- .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
+ request.future.set(RpcResultBuilder.<NetconfMessage>failed()
+ .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
//recursively processing message to eventually find matching request
processMessage(message);
try {
NetconfMessageTransformUtil.checkSuccessReply(message);
- } catch(final NetconfDocumentedException e) {
+ } catch (final NetconfDocumentedException e) {
LOG.warn(
"{}: Error reply from remote device, request: {}, response: {}",
id, msgToS(request.request), msgToS(message), e);
- request.future.set( RpcResultBuilder.<NetconfMessage>failed()
- .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
+ request.future.set(RpcResultBuilder.<NetconfMessage>failed()
+ .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
return;
}
- request.future.set( RpcResultBuilder.success( message ).build() );
+ request.future.set(RpcResultBuilder.success(message).build());
}
}
sessionLock.lock();
if (semaphore != null && !semaphore.tryAcquire()) {
- LOG.warn("Limit of concurrent rpc messages was reached (limit :" +
- concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
+ LOG.warn("Limit of concurrent rpc messages was reached (limit :"
+ + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id"
+ + id.getName());
sessionLock.unlock();
- return Futures.immediateFailedFuture(new NetconfDocumentedException("Limit of rpc messages was reached (Limit :" +
- concurentRpcMsgs + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
+ return Futures.immediateFailedFuture(new NetconfDocumentedException(
+ "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
+ + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
}
try {
}
}
- private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
- final NetconfMessage message, final QName rpc) {
- if(LOG.isTraceEnabled()) {
+ private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
+ final QName rpc) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("{}: Sending message {}", id, msgToS(message));
}
if (session == null) {
LOG.warn("{}: Session is disconnected, failing RPC request {}",
id, message);
- return Futures.immediateFuture( createSessionDownRpcResult() );
+ return Futures.immediateFuture(createSessionDownRpcResult());
}
final Request req = new Request(new UncancellableFuture<>(true), message);
requests.add(req);
session.sendMessage(req.request).addListener(future -> {
- if( !future.isSuccess() ) {
+ if (!future.isSuccess()) {
// We expect that a session down will occur at this point
LOG.debug("{}: Failed to send request {}", id,
XmlUtil.toString(req.request.getDocument()),
future.cause());
- if( future.cause() != null ) {
- req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
- future.cause().getLocalizedMessage() ) );
+ if (future.cause() != null) {
+ req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
+ future.cause().getLocalizedMessage()));
} else {
- req.future.set( createSessionDownRpcResult() ); // assume session is down
+ req.future.set(createSessionDownRpcResult()); // assume session is down
}
- req.future.setException( future.cause() );
- }
- else {
+ req.future.setException(future.cause());
+ } else {
LOG.trace("Finished sending request {}", req.request);
}
});
}
private void processNotification(final NetconfMessage notification) {
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("{}: Notification received: {}", id, notification);
}
private final Map<QName, CapabilityOrigin> moduleBasedCaps;
private final Map<String, CapabilityOrigin> nonModuleCaps;
- NetconfSessionPreferences(final Map<String, CapabilityOrigin> nonModuleCaps, final Map<QName, CapabilityOrigin> moduleBasedCaps) {
+ NetconfSessionPreferences(final Map<String, CapabilityOrigin> nonModuleCaps,
+ final Map<QName, CapabilityOrigin> moduleBasedCaps) {
this.nonModuleCaps = Preconditions.checkNotNull(nonModuleCaps);
this.moduleBasedCaps = Preconditions.checkNotNull(moduleBasedCaps);
}
// allows partial matches - assuming parameters are in the same order
public boolean containsPartialNonModuleCapability(final String capability) {
final Iterator<String> iterator = getNonModuleCaps().iterator();
- while(iterator.hasNext()) {
+ while (iterator.hasNext()) {
if (iterator.next().startsWith(capability)) {
LOG.trace("capability {} partially matches {}", capability, nonModuleCaps);
return true;
public boolean isMonitoringSupported() {
return containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
- || containsPartialNonModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+ || containsPartialNonModuleCapability(
+ NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
}
/**
- * Merge module-based list of capabilities with current list of module-based capabilities
+ * Merge module-based list of capabilities with current list of module-based capabilities.
*
* @param netconfSessionModuleCapabilities capabilities to merge into this
*
* @return new instance of preferences with merged module-based capabilities
*/
public NetconfSessionPreferences addModuleCaps(final NetconfSessionPreferences netconfSessionModuleCapabilities) {
- final Map<QName, CapabilityOrigin> mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size() + netconfSessionModuleCapabilities.getModuleBasedCaps().size());
+ final Map<QName, CapabilityOrigin> mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size()
+ + netconfSessionModuleCapabilities.getModuleBasedCaps().size());
mergedCaps.putAll(moduleBasedCaps);
mergedCaps.putAll(netconfSessionModuleCapabilities.getModuleBasedCapsOrigin());
return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), mergedCaps);
}
/**
- * Override current list of module-based capabilities
+ * Override current list of module-based capabilities.
*
* @param netconfSessionPreferences capabilities to override in this
*
* @return new instance of preferences with replaced module-based capabilities
*/
public NetconfSessionPreferences replaceModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) {
- return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin());
+ return new NetconfSessionPreferences(
+ getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin());
}
public NetconfSessionPreferences replaceModuleCaps(final Map<QName, CapabilityOrigin> newModuleBasedCaps) {
/**
- * Merge list of non-module based capabilities with current list of non-module based capabilities
+ * Merge list of non-module based capabilities with current list of non-module based capabilities.
*
* @param netconfSessionNonModuleCapabilities capabilities to merge into this
*
}
/**
- * Override current list of non-module based capabilities
+ * Override current list of non-module based capabilities.
*
* @param netconfSessionPreferences capabilities to override in this
*
* @return new instance of preferences with replaced non-module based capabilities
*/
public NetconfSessionPreferences replaceNonModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) {
- return new NetconfSessionPreferences(netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin());
+ return new NetconfSessionPreferences(
+ netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin());
}
public static NetconfSessionPreferences fromNetconfSession(final NetconfClientSession session) {
return fromStrings(capabilities, CapabilityOrigin.DeviceAdvertised);
}
- public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities, final CapabilityOrigin capabilityOrigin) {
+ public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities,
+ final CapabilityOrigin capabilityOrigin) {
final Map<QName, CapabilityOrigin> moduleBasedCaps = new HashMap<>();
final Map<String, CapabilityOrigin> nonModuleCaps = new HashMap<>();
String revision = REVISION_PARAM.from(queryParams);
if (!Strings.isNullOrEmpty(revision)) {
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName),
+ capabilityOrigin);
continue;
}
revision = BROKEN_REVISON_PARAM.from(queryParams);
if (Strings.isNullOrEmpty(revision)) {
LOG.warn("Netconf device returned revision incorrectly escaped for {}, ignoring it", capability);
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+ cachedQName(namespace, moduleName), capabilityOrigin);
} else {
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+ cachedQName(namespace, revision, moduleName), capabilityOrigin);
}
continue;
}
// Fallback, no revision provided for module
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+ cachedQName(namespace, moduleName), capabilityOrigin);
}
return new NetconfSessionPreferences(ImmutableMap.copyOf(nonModuleCaps), ImmutableMap.copyOf(moduleBasedCaps));
}
- private static void addModuleQName(final Map<QName, CapabilityOrigin> moduleBasedCaps, final Map<String, CapabilityOrigin> nonModuleCaps, final String capability, final QName qName, final CapabilityOrigin capabilityOrigin) {
- moduleBasedCaps.put(qName, capabilityOrigin);
+ private static void addModuleQName(final Map<QName, CapabilityOrigin> moduleBasedCaps,
+ final Map<String, CapabilityOrigin> nonModuleCaps, final String capability,
+ final QName qualifiedName, final CapabilityOrigin capabilityOrigin) {
+ moduleBasedCaps.put(qualifiedName, capabilityOrigin);
nonModuleCaps.remove(capability);
}
@GuardedBy("this")
private boolean uncancellable = false;
- public UncancellableFuture(final boolean uncancellable) {
+ UncancellableFuture(final boolean uncancellable) {
this.uncancellable = uncancellable;
}
import javax.annotation.Nonnull;
/**
- * DTO with user capabilities to override or merge with device specific capabilities
+ * DTO with user capabilities to override or merge with device specific capabilities.
*/
public class UserPreferences {
private volatile DOMRpcService currentDeviceRpc;
public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
- final ScheduledExecutorService executor, final long keepaliveDelaySeconds, final long defaultRequestTimeoutMillis) {
+ final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
+ final long defaultRequestTimeoutMillis) {
this.id = id;
this.salFacade = salFacade;
this.executor = executor;
}
/**
- * Set the netconf session listener whenever ready
+ * Set the netconf session listener whenever ready.
*
* @param listener netconf session listener
*/
* Just cancel current keepalive task.
* If its already started, let it finish ... not such a big deal.
*
+ * <p>
* Then schedule next keepalive.
*/
private void resetKeepalive() {
LOG.trace("{}: Resetting netconf keepalive timer", id);
- if(currentKeepalive != null) {
+ if (currentKeepalive != null) {
currentKeepalive.cancel(false);
}
scheduleKeepalive();
}
/**
- * Cancel current keepalive and also reset current deviceRpc
+ * Cancel current keepalive and also reset current deviceRpc.
*/
private void stopKeepalives() {
- if(currentKeepalive != null) {
+ if (currentKeepalive != null) {
currentKeepalive.cancel(false);
}
currentDeviceRpc = null;
}
@Override
- public void onDeviceConnected(final SchemaContext remoteSchemaContext, final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
+ public void onDeviceConnected(final SchemaContext remoteSchemaContext,
+ final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
this.currentDeviceRpc = deviceRpc;
- final DOMRpcService deviceRpc1 = new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
+ final DOMRpcService deviceRpc1 =
+ new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
LOG.debug("{}: Netconf session initiated, starting keepalives", id);
// Keepalive RPC static resources
private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
- private static final ContainerNode KEEPALIVE_PAYLOAD =
- NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
+ private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
+ getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
/**
* Invoke keepalive RPC and check the response. In case of any received response the keepalive
private final ScheduledFuture<?> previousKeepalive;
- public Keepalive(final ScheduledFuture<?> previousKeepalive) {
+ Keepalive(final ScheduledFuture<?> previousKeepalive) {
this.previousKeepalive = previousKeepalive;
}
LOG.trace("{}: Invoking keepalive RPC", id);
try {
- if(previousKeepalive != null && !previousKeepalive.isDone()) {
+ if (previousKeepalive != null && !previousKeepalive.isDone()) {
onFailure(new IllegalStateException("Previous keepalive timed out"));
} else {
Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this);
}
@Override
- public void onFailure(@Nonnull final Throwable t) {
- LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, t);
+ public void onFailure(@Nonnull final Throwable throwable) {
+ LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
reconnect();
}
}
/**
- * Reset keepalive after each RPC response received
+ * Reset keepalive after each RPC response received.
*/
private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
@Override
public void onSuccess(@Nullable final DOMRpcResult result) {
- // No matter what response we got, rpc-reply or rpc-error, we got it from device so the netconf session is OK
+ // No matter what response we got,
+ // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
resetKeepalive();
}
@Override
- public void onFailure(@Nonnull final Throwable t) {
- // User/Application RPC failed (The RPC did not reach the remote device or .. TODO what other reasons could cause this ?)
+ public void onFailure(@Nonnull final Throwable throwable) {
+ // User/Application RPC failed (The RPC did not reach the remote device or ..
+ // TODO what other reasons could cause this ?)
// There is no point in keeping this session. Reconnect.
- LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, t);
+ LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
reconnect();
}
}
private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
- public RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
+ RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
this.rpcResultFuture = rpcResultFuture;
}
private final long defaultRequestTimeoutMillis;
private final ScheduledExecutorService executor;
- public KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
+ KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
this.deviceRpc = deviceRpc;
this.resetKeepaliveTask = resetKeepaliveTask;
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, final NormalizedNode<?, ?> input) {
- final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture = deviceRpc.invokeRpc(type, input);
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+ final NormalizedNode<?, ?> input) {
+ final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
+ deviceRpc.invokeRpc(type, input);
Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask);
final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
}
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
// There is no real communication with the device (yet), no reset here
return deviceRpc.registerRpcListener(listener);
}
private final boolean candidateSupported;
private final boolean runningWritable;
- public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext, final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) {
+ public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext,
+ final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) {
this.id = id;
this.netconfOps = new NetconfBaseOps(rpc, schemaContext);
// get specific attributes from netconf preferences and get rid of it
runningWritable = netconfSessionPreferences.isRunningWritable();
rollbackSupport = netconfSessionPreferences.isRollbackSupported();
Preconditions.checkArgument(candidateSupported || runningWritable,
- "Device %s has advertised neither :writable-running nor :candidate capability. At least one of these should be advertised. Failed to establish a session.", id.getName());
+ "Device %s has advertised neither :writable-running nor :candidate capability."
+ + "At least one of these should be advertised. Failed to establish a session.", id.getName());
}
@Override
@Override
public DOMDataWriteTransaction newWriteOnlyTransaction() {
- if(candidateSupported) {
- if(runningWritable) {
+ if (candidateSupported) {
+ if (runningWritable) {
return new WriteCandidateRunningTx(id, netconfOps, rollbackSupport);
} else {
return new WriteCandidateTx(id, netconfOps, rollbackSupport);
}
@Override
- public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener, final DataChangeScope triggeringScope) {
+ public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(
+ final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener,
+ final DataChangeScope triggeringScope) {
throw new UnsupportedOperationException(id + ": Data change listeners not supported for netconf mount point");
}
// Notification publish is very simple and hijacks the thread of the caller
// TODO shouldnt we reuse the implementation for notification router from sal-broker-impl ?
+ @SuppressWarnings("checkstyle:IllegalCatch")
public synchronized void publishNotification(final DOMNotification notification) {
for (final DOMNotificationListener domNotificationListener : listeners.get(notification.getType())) {
try {
}
@Override
- public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(@Nonnull final T listener, @Nonnull final Collection<SchemaPath> types) {
+ public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+ @Nonnull final T listener, @Nonnull final Collection<SchemaPath> types) {
for (final SchemaPath type : types) {
listeners.put(type, listener);
}
}
@Override
- public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(@Nonnull final T listener, final SchemaPath... types) {
+ public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+ @Nonnull final T listener, final SchemaPath... types) {
return registerNotificationListener(listener, Lists.newArrayList(types));
}
}
*/
public final class NetconfDeviceRpc implements DOMRpcService {
- private static final Function<RpcDefinition, DOMRpcIdentifier> RPC_TO_RPC_IDENTIFIER = new Function<RpcDefinition, DOMRpcIdentifier>() {
- @Override
- public DOMRpcIdentifier apply(final RpcDefinition input) {
- return DOMRpcIdentifier.create(input.getPath());
- }
- };
+ private static final Function<RpcDefinition, DOMRpcIdentifier> RPC_TO_RPC_IDENTIFIER =
+ new Function<RpcDefinition, DOMRpcIdentifier>() {
+ @Override
+ public DOMRpcIdentifier apply(final RpcDefinition input) {
+ return DOMRpcIdentifier.create(input.getPath());
+ }
+ };
private final RemoteDeviceCommunicator<NetconfMessage> listener;
private final MessageTransformer<NetconfMessage> transformer;
private final Collection<DOMRpcIdentifier> availableRpcs;
- public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener, final MessageTransformer<NetconfMessage> transformer) {
+ public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener,
+ final MessageTransformer<NetconfMessage> transformer) {
this.listener = listener;
this.transformer = transformer;
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+ @Nullable final NormalizedNode<?, ?> input) {
final NetconfMessage message = transformer.toRpcRequest(type, input);
- final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener.sendRequest(message, type.getLastComponent());
+ final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult =
+ listener.sendRequest(message, type.getLastComponent());
- final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
- @Override
- public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
- if (input.isSuccessful()) {
- return transformer.toRpcResult(input.getResult(), type);
- } else {
- return new DefaultDOMRpcResult(input.getErrors());
+ final ListenableFuture<DOMRpcResult> transformed =
+ Futures.transform(delegateFutureWithPureResult, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
+ @Override
+ public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
+ if (input.isSuccessful()) {
+ return transformer.toRpcResult(input.getResult(), type);
+ } else {
+ return new DefaultDOMRpcResult(input.getErrors());
+ }
}
- }
- });
+ });
return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
@Nullable
@Override
- public DOMRpcException apply(@Nullable final Exception e) {
- return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type);
+ public DOMRpcException apply(@Nullable final Exception exception) {
+ return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type);
}
});
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
listener.onRpcAvailable(availableRpcs);
@Override
public synchronized void onDeviceConnected(final SchemaContext schemaContext,
- final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
+ final NetconfSessionPreferences netconfSessionPreferences,
+ final DOMRpcService deviceRpc) {
- final DOMDataBroker domBroker = new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences);
+ final DOMDataBroker domBroker =
+ new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences);
final NetconfDeviceNotificationService notificationService = new NetconfDeviceNotificationService();
- salProvider.getMountInstance().onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService);
- salProvider.getTopologyDatastoreAdapter().updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
+ salProvider.getMountInstance()
+ .onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService);
+ salProvider.getTopologyDatastoreAdapter()
+ .updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
}
@Override
closeGracefully(salProvider);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void closeGracefully(final AutoCloseable resource) {
if (resource != null) {
try {
public class NetconfDeviceSalProvider implements AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
private final RemoteDeviceId id;
private final MountInstance mountInstance;
private final TransactionChainListener transactionChainListener = new TransactionChainListener() {
@Override
- public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
- logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
+ public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
+ final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+ LOG.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
chain.close();
resetTransactionChainForAdapaters();
throw new IllegalStateException(id + " TransactionChain(" + chain + ") not committed correctly", cause);
@Override
public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
- logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
+ LOG.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
}
};
topologyDatastoreAdapter.setTxChain(txChain);
- logger.trace("{}: Resetting TransactionChain {}", id, txChain);
+ LOG.trace("{}: Resetting TransactionChain {}", id, txChain);
}
Preconditions.checkNotNull(mountService, "Closed");
Preconditions.checkState(topologyRegistration == null, "Already initialized");
- final DOMMountPointService.DOMMountPointBuilder mountBuilder = mountService.createMountPoint(id.getTopologyPath());
+ final DOMMountPointService.DOMMountPointBuilder mountBuilder =
+ mountService.createMountPoint(id.getTopologyPath());
mountBuilder.addInitialSchemaContext(initialCtx);
mountBuilder.addService(DOMDataBroker.class, broker);
this.notificationService = notificationService;
topologyRegistration = mountBuilder.register();
- logger.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
+ LOG.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public synchronized void onTopologyDeviceDisconnected() {
- if(topologyRegistration == null) {
- logger.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
+ if (topologyRegistration == null) {
+ LOG.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
return;
}
topologyRegistration.close();
} catch (final Exception e) {
// Only log and ignore
- logger.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e);
+ LOG.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e);
} finally {
- logger.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration);
+ LOG.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration);
topologyRegistration = null;
}
}
}
public synchronized void publish(final DOMNotification domNotification) {
- Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}", domNotification);
+ Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}",
+ domNotification);
notificationService.publishNotification(domNotification);
}
}
public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
- public static final Function<Entry<QName, FailureReason>, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = input -> new UnavailableCapabilityBuilder()
- .setCapability(input.getKey().toString())
- .setFailureReason(input.getValue()).build();
+ public static final Function<Entry<QName, FailureReason>, UnavailableCapability>
+ UNAVAILABLE_CAPABILITY_TRANSFORMER =
+ input -> new UnavailableCapabilityBuilder()
+ .setCapability(input.getKey().toString()).setFailureReason(input.getValue()).build();
private final RemoteDeviceId id;
private BindingTransactionChain txChain;
this.txChain = Preconditions.checkNotNull(txChain);
this.networkTopologyPath = InstanceIdentifier.builder(NetworkTopology.class).build();
- this.topologyListPath = networkTopologyPath.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
+ this.topologyListPath = networkTopologyPath
+ .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
initDeviceData();
}
createNetworkTopologyIfNotPresent(writeTx);
final InstanceIdentifier<Node> path = id.getTopologyBindingPath();
- NodeBuilder nodeBuilder = getNodeIdBuilder(id);
+ final NodeBuilder nodeBuilder = getNodeIdBuilder(id);
NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder();
netconfNodeBuilder.setConnectionStatus(ConnectionStatus.Connecting);
netconfNodeBuilder.setHost(id.getHost());
LOG.trace(
"{}: Update device state transaction {} merging operational data started.",
id, writeTx.getIdentifier());
- writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+ writeTx.put(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
LOG.trace(
"{}: Update device state transaction {} merging operational data ended.",
id, writeTx.getIdentifier());
commitTransaction(writeTx, "update");
}
- public void updateClusteredDeviceData(final boolean up, final String masterAddress, final NetconfDeviceCapabilities capabilities) {
+ public void updateClusteredDeviceData(final boolean up, final String masterAddress,
+ final NetconfDeviceCapabilities capabilities) {
final NetconfNode data = buildDataForNetconfClusteredNode(up, masterAddress, capabilities);
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
LOG.trace(
"{}: Update device state transaction {} merging operational data started.",
id, writeTx.getIdentifier());
- writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+ writeTx.put(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
LOG.trace(
"{}: Update device state transaction {} merging operational data ended.",
id, writeTx.getIdentifier());
public void setDeviceAsFailed(final Throwable throwable) {
String reason = (throwable != null && throwable.getMessage() != null) ? throwable.getMessage() : UNKNOWN_REASON;
- final NetconfNode data = new NetconfNodeBuilder().setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
+ final NetconfNode data = new NetconfNodeBuilder()
+ .setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
LOG.trace(
"{}: Setting device state as failed {} putting operational data started.",
id, writeTx.getIdentifier());
- writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+ writeTx.put(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
LOG.trace(
"{}: Setting device state as failed {} putting operational data ended.",
id, writeTx.getIdentifier());
final AvailableCapabilitiesBuilder avCapabalitiesBuilder = new AvailableCapabilitiesBuilder();
avCapabalitiesBuilder.setAvailableCapability(capabilityList);
- final UnavailableCapabilities unavailableCapabilities =
- new UnavailableCapabilitiesBuilder().setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
+ final UnavailableCapabilities unavailableCapabilities = new UnavailableCapabilitiesBuilder()
+ .setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
.transform(UNAVAILABLE_CAPABILITY_TRANSFORMER).toList()).build();
final NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder()
return netconfNodeBuilder.build();
}
- private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress, final NetconfDeviceCapabilities capabilities) {
+ private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress,
+ final NetconfDeviceCapabilities capabilities) {
List<AvailableCapability> capabilityList = new ArrayList<>();
capabilityList.addAll(capabilities.getNonModuleBasedCapabilities());
capabilityList.addAll(capabilities.getResolvedCapabilities());
NetworkTopology.QNAME, writeTx.getIdentifier());
writeTx.merge(LogicalDatastoreType.OPERATIONAL, networkTopologyPath, networkTopology);
- final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
+ final Topology topology =
+ new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
LOG.trace("{}: Merging {} container to ensure its presence", id,
Topology.QNAME, writeTx.getIdentifier());
writeTx.merge(LogicalDatastoreType.OPERATIONAL, topologyListPath, topology);
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
LOG.error("{}: Transaction({}) {} FAILED!", id, txType,
- transaction.getIdentifier(), t);
- throw new IllegalStateException(id + " Transaction(" + txType + ") not committed correctly", t);
+ transaction.getIdentifier(), throwable);
+ throw new IllegalStateException(
+ id + " Transaction(" + txType + ") not committed correctly", throwable);
}
});
private final SchemalessMessageTransformer schemalessTransformer;
private final RemoteDeviceId deviceId;
- public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId, final RemoteDeviceCommunicator<NetconfMessage> listener,
+ public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId,
+ final RemoteDeviceCommunicator<NetconfMessage> listener,
final BaseRpcSchemalessTransformer baseRpcTransformer,
final SchemalessMessageTransformer messageTransformer) {
this.deviceId = deviceId;
} else if (isBaseRpc(type)) {
transformer = baseRpcTransformer;
} else {
- return Futures.immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type));
+ return Futures.immediateFailedCheckedFuture(
+ new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type));
}
return handleRpc(type, input, transformer);
}
- private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(@Nonnull final SchemaPath type,
- @Nullable final NormalizedNode<?, ?> input,
- final MessageTransformer<NetconfMessage> transformer) {
+ private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(
+ @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input,
+ final MessageTransformer<NetconfMessage> transformer) {
final NetconfMessage netconfMessage = transformer.toRpcRequest(type, input);
- final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture = listener.sendRequest(netconfMessage, type.getLastComponent());
+ final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture =
+ listener.sendRequest(netconfMessage, type.getLastComponent());
- final ListenableFuture<DOMRpcResult> transformed = Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
- if (input1.isSuccessful()) {
- return transformer.toRpcResult(input1.getResult(), type);
- } else {
- return new DefaultDOMRpcResult(input1.getErrors());
- }
- });
+ final ListenableFuture<DOMRpcResult> transformed =
+ Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
+ if (input1.isSuccessful()) {
+ return transformer.toRpcResult(input1.getResult(), type);
+ } else {
+ return new DefaultDOMRpcResult(input1.getErrors());
+ }
+ });
return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
@Nullable
@Override
- public DOMRpcException apply(@Nullable final Exception e) {
- return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s on device %s", type, deviceId);
+ public DOMRpcException apply(@Nullable final Exception exception) {
+ return new DOMRpcImplementationNotAvailableException(
+ exception, "Unable to invoke rpc %s on device %s", type, deviceId);
}
});
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
throw new UnsupportedOperationException("Not available for netconf 1.0");
}
@Override
public synchronized boolean cancel() {
- if(isFinished()) {
+ if (isFinished()) {
return false;
}
listeners.forEach(listener -> listener.onTransactionCancelled(this));
}
@Override
- public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
checkEditable(store);
- // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
- if(containsOnlyNonVisibleData(path, data)) {
+ // Trying to write only mixin nodes (not visible when serialized).
+ // Ignoring. Some devices cannot handle empty edit-config rpc
+ if (containsOnlyNonVisibleData(path, data)) {
LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
return;
}
- final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.of(ModifyAction.REPLACE), path);
+ final DataContainerChild<?, ?> editStructure =
+ netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+ Optional.of(ModifyAction.REPLACE), path);
editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
}
@Override
- public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
checkEditable(store);
- // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
+ // Trying to write only mixin nodes (not visible when serialized).
+ // Ignoring. Some devices cannot handle empty edit-config rpc
if (containsOnlyNonVisibleData(path, data)) {
LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
return;
}
- final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.<ModifyAction>absent(), path);
+ final DataContainerChild<?, ?> editStructure =
+ netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+ Optional.<ModifyAction>absent(), path);
editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
}
/**
- * Check whether the data to be written consists only from mixins
+ * Check whether the data to be written consists only from mixins.
*/
- private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
// There's only one such case:top level list (pathArguments == 1 && data is Mixin)
// any other mixin nodes are contained by a "regular" node thus visible when serialized
return path.getPathArguments().size() == 1 && data instanceof MixinNode;
@Override
public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
checkEditable(store);
- final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(), Optional.of(ModifyAction.DELETE), path);
- editConfig(path, Optional.<NormalizedNode<?, ?>>absent(), editStructure, Optional.of(ModifyAction.NONE), "delete");
+ final DataContainerChild<?, ?> editStructure =
+ netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
+ Optional.of(ModifyAction.DELETE), path);
+ editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
+ editStructure, Optional.of(ModifyAction.NONE), "delete");
}
@Override
if (result != null && result.isSuccessful()) {
listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
} else {
- final TransactionCommitFailedException cause = new TransactionCommitFailedException("Transaction failed", result.getErrors().toArray(new RpcError[result.getErrors().size()]));
+ final TransactionCommitFailedException cause =
+ new TransactionCommitFailedException("Transaction failed",
+ result.getErrors().toArray(new RpcError[result.getErrors().size()]));
listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
}
}
@Override
- public void onFailure(final Throwable t) {
- listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, t));
+ public void onFailure(final Throwable throwable) {
+ listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
}
});
return result;
private void checkEditable(final LogicalDatastoreType store) {
checkNotFinished();
- Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store);
+ Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
+ "Can edit only configuration data, not %s", store);
}
- protected abstract void editConfig(final YangInstanceIdentifier path, final Optional<NormalizedNode<?, ?>> data, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final String operation);
+ protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
+ DataContainerChild<?, ?> editStructure,
+ Optional<ModifyAction> defaultOperation, String operation);
protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
@Override
public void onSuccess(final List<DOMRpcResult> domRpcResults) {
domRpcResults.forEach(domRpcResult -> {
- if(!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
+ if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
final NetconfDocumentedException exception =
new NetconfDocumentedException(id + ":RPC during tx failed",
DocumentedException.ErrorType.APPLICATION,
}
});
- if(!transformed.isDone()) {
+ if (!transformed.isDone()) {
transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
}
}
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
final LogicalDatastoreType store, final YangInstanceIdentifier path) {
switch (store) {
- case CONFIGURATION: {
- return readConfigurationData(path);
- }
- case OPERATIONAL: {
- return readOperationalData(path);
- }
+ case CONFIGURATION: {
+ return readConfigurationData(path);
+ }
+ case OPERATIONAL: {
+ return readOperationalData(path);
+ }
+ default: {
+ LOG.info("Unknown datastore type: {}.", store);
+ }
}
- throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
+ throw new IllegalArgumentException(String.format(
+ "%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
}
@Override
- public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> data = read(store, path);
final ListenableFuture<Boolean> result =
- Futures.transform(data, (Optional<NormalizedNode<?, ?>> a) -> a != null && a.isPresent());
+ Futures.transform(data, (Optional<NormalizedNode<?, ?>> optionalNode) ->
+ optionalNode != null && optionalNode.isPresent());
return MappingCheckedFuture.create(result, ReadFailedException.MAPPER);
}
}
@Override
- public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
delegateWriteTx.put(store, path, data);
}
@Override
- public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
delegateWriteTx.merge(store, path, data);
}
currentTransaction = null;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void removePendingTx(final AbstractWriteTx transaction) {
try {
pendingTransactions.remove(transaction).close();
import org.slf4j.LoggerFactory;
/**
- * Tx implementation for netconf devices that support only candidate datastore and writable running
+ * Tx implementation for netconf devices that support only candidate datastore and writable running.
* The sequence goes exactly as with only candidate supported, with one addition:
* <ul>
* <li>Running datastore is locked as the first thing and this lock has to succeed</li>
private static final Logger LOG = LoggerFactory.getLogger(WriteCandidateRunningTx.class);
- public WriteCandidateRunningTx(final RemoteDeviceId id, final NetconfBaseOps netOps, final boolean rollbackSupport) {
+ public WriteCandidateRunningTx(final RemoteDeviceId id, final NetconfBaseOps netOps,
+ final boolean rollbackSupport) {
super(id, netOps, rollbackSupport);
}
}
/**
- * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+ * This has to be non blocking since it is called from a callback on commit
+ * and its netty threadpool that is really sensitive to blocking calls.
*/
private void unlockRunning() {
netOps.unlockRunning(new NetconfRpcFutureCallback("Unlock running", id));
import org.slf4j.LoggerFactory;
/**
- * Tx implementation for netconf devices that support only candidate datastore and no writable running
+ * Tx implementation for netconf devices that support only candidate datastore and no writable running.
* The sequence goes as:
* <ol>
* <li>Lock candidate datastore on tx construction
* </li>
* <li>Edit-config in candidate N times
* <ul>
- * <li>If any issue occurs during edit, datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async</li>
+ * <li>If any issue occurs during edit,
+ * datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async</li>
* </ul>
* </li>
* <li>Commit and Unlock candidate datastore async</li>
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Lock candidate operation failed. {}", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Lock candidate operation failed. {}", throwable);
discardChanges();
}
};
@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
- final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
- @Override
- public Void apply(final RpcResult<TransactionStatus> input) {
- Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(), "Submit failed with errors: %s", input.getErrors());
- return null;
- }
- });
+ final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
+ new Function<RpcResult<TransactionStatus>, Void>() {
+ @Override
+ public Void apply(final RpcResult<TransactionStatus> input) {
+ Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
+ "Submit failed with errors: %s", input.getErrors());
+ return null;
+ }
+ });
return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
@Override
public TransactionCommitFailedException apply(final Exception input) {
- return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
+ return new TransactionCommitFailedException(
+ "Submit of transaction " + getIdentifier() + " failed", input);
}
});
}
/**
- * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+ * This has to be non blocking since it is called from a callback on commit
+ * and its netty threadpool that is really sensitive to blocking calls.
*/
private void discardChanges() {
netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
// TODO If lock is cause of this failure cleanup will issue warning log
// cleanup is trying to do unlock, but this will fail
cleanup();
}
/**
- * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+ * This has to be non blocking since it is called from a callback on commit
+ * and its netty threadpool that is really sensitive to blocking calls.
*/
private void unlock() {
netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
import org.slf4j.LoggerFactory;
/**
- * Tx implementation for netconf devices that support only writable-running with no candidate
+ * Tx implementation for netconf devices that support only writable-running with no candidate.
* The sequence goes as:
* <ol>
* <li>Lock running datastore on tx construction
@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
- final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
- @Override
- public Void apply(final RpcResult<TransactionStatus> input) {
- return null;
- }
- });
+ final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(),
+ new Function<RpcResult<TransactionStatus>, Void>() {
+ @Override
+ public Void apply(final RpcResult<TransactionStatus> input) {
+ return null;
+ }
+ });
return Futures.makeChecked(commmitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
@Override
public TransactionCommitFailedException apply(final Exception input) {
- return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
+ return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
+ input);
}
});
}
final boolean rollbackSupport) {
final NetconfRpcFutureCallback editConfigCallback = new NetconfRpcFutureCallback("Edit running", id);
if (defaultOperation.isPresent()) {
- return netOps.editConfigRunning(editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport);
+ return netOps.editConfigRunning(
+ editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport);
} else {
return netOps.editConfigRunning(editConfigCallback, editStructure, rollbackSupport);
}
private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
"schemaDownload", SchemaSourceException.class) {
@Override
- protected SchemaSourceException newWithCause(final String s, final Throwable throwable) {
- return new SchemaSourceException(s, throwable);
+ protected SchemaSourceException newWithCause(final String message, final Throwable throwable) {
+ return new SchemaSourceException(message, throwable);
}
};
this.rpc = Preconditions.checkNotNull(rpc);
}
- private static final NodeIdentifier FORMAT_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format").intern());
- private static final NodeIdentifier GET_SCHEMA_PATHARG = new NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME);
- private static final NodeIdentifier IDENTIFIER_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier").intern());
- private static final NodeIdentifier VERSION_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version").intern());
+ private static final NodeIdentifier FORMAT_PATHARG =
+ new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format").intern());
+ private static final NodeIdentifier GET_SCHEMA_PATHARG =
+ new NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME);
+ private static final NodeIdentifier IDENTIFIER_PATHARG =
+ new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier").intern());
+ private static final NodeIdentifier VERSION_PATHARG =
+ new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version").intern());
- private static final LeafNode<?> FORMAT_LEAF = Builders.leafBuilder().withNodeIdentifier(FORMAT_PATHARG).withValue(Yang.QNAME).build();
+ private static final LeafNode<?> FORMAT_LEAF =
+ Builders.leafBuilder().withNodeIdentifier(FORMAT_PATHARG).withValue(Yang.QNAME).build();
- private static final QName NETCONF_DATA = QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()).intern();
+ private static final QName NETCONF_DATA =
+ QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()).intern();
private static final NodeIdentifier NETCONF_DATA_PATHARG = toId(NETCONF_DATA);
public static ContainerNode createGetSchemaRequest(final String moduleName, final Optional<String> revision) {
- final LeafNode<?> identifier = Builders.leafBuilder().withNodeIdentifier(IDENTIFIER_PATHARG).withValue(moduleName).build();
+ final LeafNode<?> identifier =
+ Builders.leafBuilder().withNodeIdentifier(IDENTIFIER_PATHARG).withValue(moduleName).build();
final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = Builders.containerBuilder()
.withNodeIdentifier(GET_SCHEMA_PATHARG).withChild(identifier).withChild(FORMAT_LEAF);
if (revision.isPresent()) {
- builder.withChild(Builders.leafBuilder().withNodeIdentifier(VERSION_PATHARG).withValue(revision.get()).build());
+ builder.withChild(Builders.leafBuilder()
+ .withNodeIdentifier(VERSION_PATHARG).withValue(revision.get()).build());
}
return builder.build();
return Optional.absent();
}
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
Preconditions.checkState(child.isPresent() && child.get() instanceof AnyXmlNode,
"%s Unexpected response to get-schema, expected response with one child %s, but was %s", id,
}
@Override
- public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
+ public CheckedFuture<YangTextSchemaSource, SchemaSourceException> 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
rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER);
+ final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked =
+ Futures.makeChecked(transformed, MAPPER);
return checked;
}
/**
- * Transform composite node to string schema representation and then to ASTSchemaSource
+ * Transform composite node to string schema representation and then to ASTSchemaSource.
*/
private static final class ResultToYangSourceTransformer implements
Function<DOMRpcResult, YangTextSchemaSource> {
private final String moduleName;
private final Optional<String> revision;
- public ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
+ ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
final String moduleName, final Optional<String> revision) {
this.id = id;
this.sourceIdentifier = sourceIdentifier;
final Optional<String> schemaString = getSchemaFromRpc(id, input.getResult());
Preconditions.checkState(schemaString.isPresent(),
- "%s: Unexpected response to get-schema, schema not present in message for: %s", id, sourceIdentifier);
+ "%s: Unexpected response to get-schema, schema not present in message for: %s",
+ id, sourceIdentifier);
LOG.debug("{}: YANG Schema successfully retrieved for {}:{}",
id, moduleName, revision);
private final RemoteDeviceId id;
private final Optional<String> schemaString;
- public NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sId, final Optional<String> schemaString) {
- super(sId);
+ NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
+ final Optional<String> schemaString) {
+ super(sourceIdentifier);
this.id = id;
this.schemaString = schemaString;
}
import org.slf4j.LoggerFactory;
/**
- * Provides YANG schema sources from yang library
+ * Provides YANG schema sources from yang library.
*/
public final class YangLibrarySchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
return download(sourceIdentifier);
}
- private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(final SourceIdentifier sId) {
- final URL url = availableSources.get(sId);
- try(final InputStream in = url.openStream()) {
+ private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(
+ final SourceIdentifier sourceIdentifier) {
+ final URL url = availableSources.get(sourceIdentifier);
+ try (InputStream in = url.openStream()) {
final String schemaContent = new String(ByteStreams.toByteArray(in));
final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource =
- new NetconfRemoteSchemaYangSourceProvider.
- NetconfYangTextSchemaSource(id, sId, Optional.of(schemaContent));
- LOG.debug("Source {} downloaded from a yang library's url {}", sId, url);
+ new NetconfRemoteSchemaYangSourceProvider
+ .NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
+ LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url);
return Futures.immediateCheckedFuture(yangSource);
} catch (IOException e) {
- LOG.warn("Unable to download source {} from a yang library's url {}", sId, url, 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 " + sId + " from " + url, e));
+ new SchemaSourceException(
+ "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));
}
}
}
import org.w3c.dom.Element;
/**
- * Transforms base netconf rpcs
+ * Transforms base netconf RPCs.
*/
public class BaseRpcSchemalessTransformer implements MessageTransformer<NetconfMessage> {
- private static final Map<QName, RpcDefinition> mappedRpcs = BaseSchema.BASE_NETCONF_CTX.getMappedRpcs();
- private static final SchemaContext schemaContext = BaseSchema.BASE_NETCONF_CTX.getSchemaContext();
+ private static final Map<QName, RpcDefinition> MAPPED_RPCS = BaseSchema.BASE_NETCONF_CTX.getMappedRpcs();
+ private static final SchemaContext SCHEMA_CONTEXT = BaseSchema.BASE_NETCONF_CTX.getSchemaContext();
private final MessageCounter counter;
// In case no input for rpc is defined, we can simply construct the payload here
final QName rpcQName = rpc.getLastComponent();
- Preconditions.checkNotNull(mappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, mappedRpcs.keySet());
+ Preconditions.checkNotNull(MAPPED_RPCS.get(rpcQName), "Unknown rpc %s, available rpcs: %s",
+ rpcQName, MAPPED_RPCS.keySet());
final DOMResult domResult = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
- if (mappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
+ if (MAPPED_RPCS.get(rpcQName).getInput().getChildNodes().isEmpty()) {
return new NetconfMessage(domResult.getNode().getOwnerDocument());
}
final DOMResult result = domResult;
try {
- NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, inputPath, schemaContext);
+ NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result,
+ inputPath, SCHEMA_CONTEXT);
} catch (final XMLStreamException | IOException | IllegalStateException e) {
throw new IllegalStateException("Unable to serialize " + inputPath, e);
}
final Document data = XmlUtil.newDocument();
data.appendChild(data.importNode(xmlData, true));
AnyXmlNode xmlDataNode = Builders.anyXmlBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
.withValue(new DOMSource(data))
.build();
normalizedNode = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
.withChild(xmlDataNode).build();
} else {
//other base rpcs don't have any output, we can simply construct the payload here
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+@SuppressWarnings("checkstyle:IllegalCatch")
public enum BaseSchema {
BASE_NETCONF_CTX(
Lists.newArrayList(
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+ .base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+ .monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
)
),
BASE_NETCONF_CTX_WITH_NOTIFICATIONS(
Lists.newArrayList(
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+ .monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+ .notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+ .base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+ .notifications.rev120206.$YangModuleInfoImpl.getInstance()
)
);
private static final Function<SchemaNode, QName> QNAME_FUNCTION = rpcDefinition -> rpcDefinition.getQName();
- private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
+ private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION =
+ notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
private final SchemaContext schemaContext;
private final BaseSchema baseSchema;
this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
}
- public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
+ public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
+ final BaseSchema baseSchema) {
this.counter = new MessageCounter();
this.schemaContext = schemaContext;
- parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
+ parserFactory = DomToNormalizedNodeParserFactory
+ .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
this.baseSchema = baseSchema;
final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
final QName notificationNoRev;
try {
- notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
+ notificationNoRev = QName.create(
+ stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
} catch (final MissingNameSpaceException e) {
- throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
+ throw new IllegalArgumentException(
+ "Unable to parse notification " + message + ", cannot find namespace", e);
}
final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
Preconditions.checkArgument(notificationDefinitions.size() > 0,
- "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
+ "Unable to parse notification %s, unknown notification. Available notifications: %s",
+ notificationDefinitions, mappedNotifications.keySet());
final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
- final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
+ final ContainerSchemaNode notificationAsContainerSchemaNode =
+ NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
final Element element = stripped.getValue().getDomElement();
final ContainerNode content;
return new NetconfDeviceNotification(content, stripped.getKey());
}
- private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
- Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
+ private static NotificationDefinition getMostRecentNotification(
+ final Collection<NotificationDefinition> notificationDefinitions) {
+ Comparator<NotificationDefinition> cmp = (o1, o2) ->
+ o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
return Collections.max(notificationDefinitions, cmp);
}
final QName rpcQName = rpc.getLastComponent();
Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
- // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
+ // Determine whether a base netconf operation is being invoked
+ // and also check if the device exposed model for base netconf.
// If no, use pre built base netconf operations model
final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
- if(needToUseBaseCtx) {
+ if (needToUseBaseCtx) {
currentMappedRpcs = baseSchema.getMappedRpcs();
}
- Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
- if(currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
- return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
+ Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
+ "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
+ if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
+ return new NetconfMessage(NetconfMessageTransformUtil
+ .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
}
Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
try {
- // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
+ // If the schema context for netconf device does not contain model for base netconf operations,
+ // use default pre build context with just the base model
// This way operations like lock/unlock are supported even if the source for base model was not provided
SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
}
private static boolean isBaseOrNotificationRpc(final QName rpc) {
- return rpc.getNamespace().equals(NETCONF_URI) ||
- rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
- rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
+ return rpc.getNamespace().equals(NETCONF_URI)
+ || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
+ || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
}
final QName rpcQName = rpc.getLastComponent();
if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
- final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
+ final ContainerSchemaNode schemaForDataRead =
+ NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
final ContainerNode dataNode;
try {
- dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
+ dataNode =
+ parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
}
- normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+ normalizedNode = Builders.containerBuilder()
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
.withChild(dataNode).build();
} else {
Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
- // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
+ // Determine whether a base netconf operation is being invoked
+ // and also check if the device exposed model for base netconf.
// If no, use pre built base netconf operations model
final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
- if(needToUseBaseCtx) {
+ if (needToUseBaseCtx) {
currentMappedRpcs = baseSchema.getMappedRpcs();
}
final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
- Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
+ Preconditions.checkArgument(rpcDefinition != null,
+ "Unable to parse response of %s, the rpc is unknown", rpcQName);
// In case no input for rpc is defined, we can simply construct the payload here
if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
notificationNoRev =
QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
} catch (final MissingNameSpaceException e) {
- throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
+ throw new IllegalArgumentException("Unable to parse notification "
+ + message + ", cannot find namespace", e);
}
final AnyXmlNode notificationPayload = Builders.anyXmlBuilder()
}
/**
- * Transforms reply message to anyXml node. In case, that rpc-reply doesn't contain data and contains only <ok/>
- * element, returns null.
+ * Transforms reply message to anyXml node.
+ * In case, that rpc-reply doesn't contain data and contains only <ok/> element, returns null.
* @param rpcReply reply message
* @return anyxml
*/
public DOMRpcResult toRpcResult(final NetconfMessage rpcReply, final SchemaPath rpc) {
final Document document = rpcReply.getDocument();
final AnyXmlNode result;
- if(BaseRpcSchemalessTransformer.isOkPresent(document)) {
+ if (BaseRpcSchemalessTransformer.isOkPresent(document)) {
result = null;
} else {
result = Builders.anyXmlBuilder()
private void wrapPayload(final Document doc) {
final Element payload = doc.getDocumentElement();
doc.removeChild(payload);
- final Element rpcNS = doc.createElementNS(NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getNamespace().toString(),
+ final Element rpcNS =
+ doc.createElementNS(NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getNamespace().toString(),
NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getLocalName());
// set msg id
- rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(NetconfMessageTransformUtil.MESSAGE_ID_PREFIX));
+ rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR,
+ counter.getNewMessageId(NetconfMessageTransformUtil.MESSAGE_ID_PREFIX));
rpcNS.appendChild(payload);
doc.appendChild(rpcNS);
}
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(datastore));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(datastore));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> lockCandidate(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_CANDIDATE_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_CANDIDATE_QNAME));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> lockRunning(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_RUNNING_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_RUNNING_QNAME));
Futures.addCallback(future, callback);
return future;
}
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(datastore));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(datastore));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> unlockRunning(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_RUNNING_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_RUNNING_QNAME));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> unlockCandidate(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_CANDIDATE_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_CANDIDATE_QNAME));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> commit(final FutureCallback<DOMRpcResult> callback) {
Preconditions.checkNotNull(callback);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+ toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
Futures.addCallback(future, callback);
return future;
}
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME), getValidateContent(datastore));
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+ toPath(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME), getValidateContent(datastore));
Futures.addCallback(future, callback);
return future;
}
return validate(callback, NETCONF_RUNNING_QNAME);
}
- public ListenableFuture<DOMRpcResult> copyConfig(final FutureCallback<DOMRpcResult> callback, final QName source, final QName target) {
+ public ListenableFuture<DOMRpcResult> copyConfig(final FutureCallback<DOMRpcResult> callback,
+ final QName source, final QName target) {
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(target);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME), getCopyConfigContent(source, target));
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+ toPath(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME), getCopyConfigContent(source, target));
Futures.addCallback(future, callback);
return future;
}
return copyConfig(callback, NETCONF_RUNNING_QNAME, NETCONF_CANDIDATE_QNAME);
}
- public ListenableFuture<DOMRpcResult> getConfig(final FutureCallback<DOMRpcResult> callback, final QName datastore, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> getConfig(final FutureCallback<DOMRpcResult> callback, final QName datastore,
+ final Optional<YangInstanceIdentifier> filterPath) {
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
return future;
}
- public ListenableFuture<Optional<NormalizedNode<?, ?>>> getConfigRunningData(final FutureCallback<DOMRpcResult> callback,
- final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<Optional<NormalizedNode<?, ?>>> getConfigRunningData(
+ final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
final ListenableFuture<DOMRpcResult> configRunning = getConfigRunning(callback, filterPath);
return extractData(filterPath, configRunning);
}
return extractData(filterPath, configRunning);
}
- private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(final Optional<YangInstanceIdentifier> path,
- final ListenableFuture<DOMRpcResult> configRunning) {
+ private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(
+ final Optional<YangInstanceIdentifier> path, final ListenableFuture<DOMRpcResult> configRunning) {
return Futures.transform(configRunning, (Function<DOMRpcResult, Optional<NormalizedNode<?, ?>>>) result -> {
- Preconditions.checkArgument(result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
+ Preconditions.checkArgument(
+ result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataNode =
- ((ContainerNode) result.getResult()).getChild(NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
+ ((ContainerNode) result.getResult()).getChild(
+ NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
return transformer.selectFromDataStructure(dataNode, path.get());
});
}
- public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback,
+ final Optional<YangInstanceIdentifier> filterPath) {
return getConfig(callback, NETCONF_RUNNING_QNAME, filterPath);
}
- public ListenableFuture<DOMRpcResult> getConfigCandidate(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> getConfigCandidate(final FutureCallback<DOMRpcResult> callback,
+ final Optional<YangInstanceIdentifier> filterPath) {
return getConfig(callback, NETCONF_CANDIDATE_QNAME, filterPath);
}
- public ListenableFuture<DOMRpcResult> get(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> get(final FutureCallback<DOMRpcResult> callback,
+ final Optional<YangInstanceIdentifier> filterPath) {
Preconditions.checkNotNull(callback);
final ListenableFuture<DOMRpcResult> future;
- future = isFilterPresent(filterPath) ?
- rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext))) :
- rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
+ future = isFilterPresent(filterPath)
+ ? rpc.invokeRpc(toPath(NETCONF_GET_QNAME),
+ NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext)))
+ : rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
Futures.addCallback(future, callback);
return future;
return filterPath.isPresent() && !filterPath.get().isEmpty();
}
- public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final ModifyAction modifyAction, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final ModifyAction modifyAction, final boolean rollback) {
return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.of(modifyAction), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final boolean rollback) {
return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final ModifyAction modifyAction, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final ModifyAction modifyAction, final boolean rollback) {
return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.of(modifyAction), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final boolean rollback) {
return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfig(final FutureCallback<? super DOMRpcResult> callback, final QName datastore, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> modifyAction, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfig(
+ final FutureCallback<? super DOMRpcResult> callback, final QName datastore,
+ final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> modifyAction,
+ final boolean rollback) {
Preconditions.checkNotNull(editStructure);
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_EDIT_CONFIG_QNAME), getEditConfigContent(datastore, editStructure, modifyAction, rollback));
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_EDIT_CONFIG_QNAME),
+ getEditConfigContent(datastore, editStructure, modifyAction, rollback));
Futures.addCallback(future, callback);
return future;
}
- public DataContainerChild<?, ?> createEditConfigStrcture(final Optional<NormalizedNode<?, ?>> lastChild, final Optional<ModifyAction> operation, final YangInstanceIdentifier dataPath) {
+ public DataContainerChild<?, ?> createEditConfigStrcture(final Optional<NormalizedNode<?, ?>> lastChild,
+ final Optional<ModifyAction> operation,
+ final YangInstanceIdentifier dataPath) {
final AnyXmlNode configContent = transformer.createEditConfigStructure(lastChild, dataPath, operation);
return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(configContent).build();
}
- private static ContainerNode getEditConfigContent(final QName datastore,
- final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final boolean rollback) {
+ private static ContainerNode getEditConfigContent(
+ final QName datastore, final DataContainerChild<?, ?> editStructure,
+ final Optional<ModifyAction> defaultOperation, final boolean rollback) {
final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> editBuilder =
Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_EDIT_CONFIG_QNAME));
editBuilder.withChild(getTargetNode(datastore));
// Default operation
- if(defaultOperation.isPresent()) {
+ if (defaultOperation.isPresent()) {
final String opString = defaultOperation.get().name().toLowerCase();
- editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME)).withValue(opString).build());
+ editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME))
+ .withValue(opString).build());
}
// Error option
- if(rollback) {
- editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_ERROR_OPTION_QNAME)).withValue(ROLLBACK_ON_ERROR_OPTION).build());
+ if (rollback) {
+ editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_ERROR_OPTION_QNAME))
+ .withValue(ROLLBACK_ON_ERROR_OPTION).build());
}
// Edit content
public static final String MESSAGE_ID_PREFIX = "m";
public static final String MESSAGE_ID_ATTR = "message-id";
- public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
+ public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
+ QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
private static final String SUBTREE = "subtree";
// Blank document used for creation of new DOM nodes
private NetconfMessageTransformUtil() {}
- public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
+ public static final QName IETF_NETCONF_MONITORING =
+ QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
-
- public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
-
- public static final QName NETCONF_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
+ QName.create(IETF_NETCONF_MONITORING, "format").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
+ QName.create(IETF_NETCONF_MONITORING, "location").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
+ QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
+ QName.create(IETF_NETCONF_MONITORING, "version").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
+ QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
+
+ public static final QName IETF_NETCONF_NOTIFICATIONS =
+ QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
+
+ public static final QName NETCONF_QNAME =
+ QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
- public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
+ public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
+ QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
public static final DataContainerChild<?, ?> EMPTY_FILTER;
static {
- final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+ final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+ Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
- final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
- element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
+ final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
+ Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+ element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
+ NETCONF_TYPE_QNAME.getLocalName(), "subtree");
anyXmlBuilder.withValue(new DOMSource(element));
EMPTY_FILTER = anyXmlBuilder.build();
}
- public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
- final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+ public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
+ final SchemaContext ctx) {
+ final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+ Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
- final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
- element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
+ final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
+ Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+ element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
+ "subtree");
try {
NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
- if(inputMsgId.equals(outputMsgId) == false) {
- final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
- .put( "actual-message-id", outputMsgId )
- .put( "expected-message-id", inputMsgId )
+ if (inputMsgId.equals(outputMsgId) == false) {
+ final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
+ .put("actual-message-id", outputMsgId)
+ .put("expected-message-id", inputMsgId)
.build();
- throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
+ throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
null, NetconfDocumentedException.ErrorType.PROTOCOL,
NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
}
public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
- if(NetconfMessageUtil.isErrorMessage(output)) {
+ if (NetconfMessageUtil.isErrorMessage(output)) {
throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
}
}
- public static RpcError toRpcError( final NetconfDocumentedException ex ) {
+ public static RpcError toRpcError(final NetconfDocumentedException ex) {
final StringBuilder infoBuilder = new StringBuilder();
final Map<String, String> errorInfo = ex.getErrorInfo();
- if(errorInfo != null) {
- for( final Entry<String,String> e: errorInfo.entrySet() ) {
- infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
- .append( "</" ).append( e.getKey() ).append( '>' );
+ if (errorInfo != null) {
+ for (final Entry<String, String> e : errorInfo.entrySet()) {
+ infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
+ .append("</").append(e.getKey()).append('>');
}
}
- final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
- return severity == ErrorSeverity.ERROR ?
- RpcResultBuilder.newError(
- toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
- ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
- RpcResultBuilder.newWarning(
- toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
- ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
+ final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
+ return severity == ErrorSeverity.ERROR
+ ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
+ ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
+ : RpcResultBuilder.newWarning(
+ toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
+ ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
}
- private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
+ private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
switch (severity) {
case WARNING:
return RpcError.ErrorSeverity.WARNING;
private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
switch (type) {
case PROTOCOL:
- return RpcError.ErrorType.PROTOCOL;
+ return RpcError.ErrorType.PROTOCOL;
case RPC:
- return RpcError.ErrorType.RPC;
+ return RpcError.ErrorType.RPC;
case TRANSPORT:
- return RpcError.ErrorType.TRANSPORT;
- default:
- return RpcError.ErrorType.APPLICATION;
+ return RpcError.ErrorType.TRANSPORT;
+ default:
+ return RpcError.ErrorType.APPLICATION;
}
}
return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
}
- public static AnyXmlNode createEditConfigAnyxml(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
- final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+ public static AnyXmlNode createEditConfigAnyxml(
+ final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+ final Optional<NormalizedNode<?, ?>> lastChildOverride) {
final NormalizedNode<?, ?> configContent;
if (dataPath.isEmpty()) {
- Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
+ Preconditions.checkArgument(lastChildOverride.isPresent(),
+ "Data has to be present when creating structure for top level element");
Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
- "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
+ "Data has to be either container or a list node when creating structure for top level element, "
+ + "but was: %s", lastChildOverride.get());
configContent = lastChildOverride.get();
} else {
- final Entry<QName, ModifyAction> modifyOperation =
- operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
- configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
+ final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
+ ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
+ configContent = ImmutableNodes
+ .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
}
- final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
+ final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
+ Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
try {
NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
} catch (IOException | XMLStreamException e) {
return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
}
- public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
- final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+ public static DataContainerChild<?, ?> createEditConfigStructure(
+ final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+ final Optional<NormalizedNode<?, ?>> lastChildOverride) {
return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
.withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
}
public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
final List<XmlElement> childElements = xmlElement.getChildElements();
- Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format.\nExpected 2 childElements," +
- " actual childElements size is %s", message, childElements.size());
+ Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
+ + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
final XmlElement eventTimeElement;
final XmlElement notificationElement;
if (childElements.get(0).getName().equals(EVENT_TIME)) {
eventTimeElement = childElements.get(0);
notificationElement = childElements.get(1);
- }
- else if(childElements.get(1).getName().equals(EVENT_TIME)) {
+ } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
eventTimeElement = childElements.get(1);
notificationElement = childElements.get(0);
} else {
} catch (final DocumentedException e) {
throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
} catch (final DateTimeParseException e) {
- LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
+ LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
+ NetconfNotification.UNKNOWN_EVENT_TIME, e);
return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
}
}
return new DOMResult(elementNS);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
- final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
+ final SchemaPath schemaPath,
+ final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
try {
- try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
+ try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
- try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
+ try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
normalizedNodeWriter.write(value);
try {
writer.close();
} catch (final Exception e) {
- LOG.warn("Unable to close resource properly", e);
+ LOG.warn("Unable to close resource properly", e);
}
}
}
import org.slf4j.LoggerFactory;
/**
- * Simple Netconf rpc logging callback
+ * Simple Netconf RPC logging callback.
*/
public class NetconfRpcFutureCallback implements FutureCallback<DOMRpcResult> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfRpcFutureCallback.class);
@Override
public void onSuccess(final DOMRpcResult result) {
- if(result.getErrors().isEmpty()) {
+ if (result.getErrors().isEmpty()) {
LOG.trace("{}: {} invoked successfully", id, type);
} else {
onUnsuccess(result);
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("{}: {} failed.", id, type, t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("{}: {} failed.", id, type, throwable);
}
}
}
@Override
- public Optional<NormalizedNode<?, ?>> selectFromDataStructure(final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
- final YangInstanceIdentifier path) {
+ public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
+ final YangInstanceIdentifier path) {
return NormalizedNodes.findNode(data, path.getPathArguments());
}
@Override
public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
- final YangInstanceIdentifier dataPath, Optional<ModifyAction> operation) {
+ final YangInstanceIdentifier dataPath,
+ Optional<ModifyAction> operation) {
return NetconfMessageTransformUtil.createEditConfigAnyxml(schemaContext, dataPath, operation, data);
}
import org.opendaylight.yangtools.yang.model.api.UsesNode;
/**
- * Simple proxy for container like schema nodes, where user provides a collection of children schema nodes
+ * Simple proxy for container like schema nodes, where user provides a collection of children schema nodes.
*/
public final class NodeContainerProxy implements ContainerSchemaNode {
private final Map<QName, DataSchemaNode> childNodes;
- private final QName qName;
+ private final QName qualifiedName;
private final Set<AugmentationSchema> availableAugmentations;
- public NodeContainerProxy(final QName qName, final Map<QName, DataSchemaNode> childNodes, final Set<AugmentationSchema> availableAugmentations) {
+ public NodeContainerProxy(final QName qualifiedName, final Map<QName, DataSchemaNode> childNodes,
+ final Set<AugmentationSchema> availableAugmentations) {
this.availableAugmentations = availableAugmentations;
this.childNodes = Preconditions.checkNotNull(childNodes, "childNodes");
- this.qName = qName;
+ this.qualifiedName = qualifiedName;
}
- public NodeContainerProxy(final QName qName, final Collection<DataSchemaNode> childNodes) {
- this(qName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
+ public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes) {
+ this(qualifiedName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
}
- public NodeContainerProxy(final QName qName, final Collection<DataSchemaNode> childNodes, final Set<AugmentationSchema> availableAugmentations) {
- this(qName, asMap(childNodes), availableAugmentations);
+ public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes,
+ final Set<AugmentationSchema> availableAugmentations) {
+ this(qualifiedName, asMap(childNodes), availableAugmentations);
}
private static Map<QName, DataSchemaNode> asMap(final Collection<DataSchemaNode> childNodes) {
}
@Override
- public DataSchemaNode getDataChildByName(final QName qName) {
- return childNodes.get(qName);
+ public DataSchemaNode getDataChildByName(final QName qualifiedName) {
+ return childNodes.get(qualifiedName);
}
@Override
@Override
public QName getQName() {
- return qName;
+ return qualifiedName;
}
@Override
* @param path path to select
* @return selected data
*/
- Optional<NormalizedNode<?, ?>> selectFromDataStructure(DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
- YangInstanceIdentifier path);
+ Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+ DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data, YangInstanceIdentifier path);
}
* @return selected data
*/
@Override
- public Optional<NormalizedNode<?, ?>> selectFromDataStructure(final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
- final YangInstanceIdentifier path) {
+ public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
+ final YangInstanceIdentifier path) {
Preconditions.checkArgument(data instanceof AnyXmlNode);
final List<XmlElement> xmlElements = selectMatchingNodes(getSourceElement(((AnyXmlNode)data).getValue()), path);
final Document result = XmlUtil.newDocument();
final QName dataQName = NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
- final Element dataElement = result.createElementNS(dataQName.getNamespace().toString(), dataQName.getLocalName());
+ final Element dataElement =
+ result.createElementNS(dataQName.getNamespace().toString(), dataQName.getLocalName());
result.appendChild(dataElement);
for (XmlElement xmlElement : xmlElements) {
dataElement.appendChild(result.importNode(xmlElement.getDomElement(), true));
*/
@Override
public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
- final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation) {
+ final YangInstanceIdentifier dataPath,
+ final Optional<ModifyAction> operation) {
Preconditions.checkArgument(data.isPresent());
Preconditions.checkArgument(data.get() instanceof AnyXmlNode);
} else {
final List<YangInstanceIdentifier.PathArgument> pathArguments = dataPath.getPathArguments();
//last will be appended later
- final List<YangInstanceIdentifier.PathArgument> pathWithoutLast = pathArguments.subList(0, pathArguments.size() - 1);
+ final List<YangInstanceIdentifier.PathArgument> pathWithoutLast =
+ pathArguments.subList(0, pathArguments.size() - 1);
parentXmlStructure = instanceIdToXmlStructure(pathWithoutLast, configElement);
}
if (operation.isPresent()) {
public DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier path) {
final Document document = XmlUtil.newDocument();
final QName filterQname = NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
- final Element filter = document.createElementNS(filterQname.getNamespace().toString(), filterQname.getLocalName());
+ final Element filter =
+ document.createElementNS(filterQname.getNamespace().toString(), filterQname.getLocalName());
final Attr a = document.createAttributeNS(filterQname.getNamespace().toString(), "type");
a.setTextContent("subtree");
filter.setAttributeNode(a);
final XmlElement dataElement = XmlElement.fromDomElement(dataNode);
final YangInstanceIdentifier.PathArgument lastPathArgument = dataPath.getLastPathArgument();
final QName nodeType = lastPathArgument.getNodeType();
- if (!nodeType.getNamespace().toString().equals(dataNode.getNamespaceURI()) ||
- !nodeType.getLocalName().equals(dataElement.getName())) {
+ if (!nodeType.getNamespace().toString().equals(dataNode.getNamespaceURI())
+ || !nodeType.getLocalName().equals(dataElement.getName())) {
throw new IllegalStateException(
String.format("Can't write data '%s' to path %s", dataNode.getTagName(), dataPath));
}
final YangInstanceIdentifier.NodeIdentifierWithPredicates keyedId =
(YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument;
final Map<QName, Object> keyValues = keyedId.getKeyValues();
- for (QName qName : keyValues.keySet()) {
+ for (QName qualifiedName : keyValues.keySet()) {
final List<XmlElement> key =
- dataElement.getChildElementsWithinNamespace(qName.getLocalName(), qName.getNamespace().toString());
+ dataElement.getChildElementsWithinNamespace(qualifiedName.getLocalName(),
+ qualifiedName.getNamespace().toString());
if (key.isEmpty()) {
throw new IllegalStateException("No key present in xml");
}
} catch (DocumentedException e) {
throw new IllegalStateException("Key value not present in key element");
}
- if (!keyValues.get(qName).equals(textContent)) {
+ if (!keyValues.get(qualifiedName).equals(textContent)) {
throw new IllegalStateException("Key value in path not equal to key value in xml");
}
}
parent.appendChild(element);
//if path argument is list id, add also keys to resulting xml
if (pathArgument instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
- YangInstanceIdentifier.NodeIdentifierWithPredicates listNode = (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
+ YangInstanceIdentifier.NodeIdentifierWithPredicates listNode =
+ (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
for (Map.Entry<QName, Object> key : listNode.getKeyValues().entrySet()) {
- final Element keyElement = doc.createElementNS(key.getKey().getNamespace().toString(), key.getKey().getLocalName());
+ final Element keyElement =
+ doc.createElementNS(key.getKey().getNamespace().toString(), key.getKey().getLocalName());
keyElement.setTextContent(key.getValue().toString());
element.appendChild(keyElement);
}
public class MessageCounter {
final AtomicInteger messageId = new AtomicInteger(0);
- private static final String messageIdBlueprint = "%s-%s";
+ private static final String MESSAGE_ID_BLUEPRINT = "%s-%s";
public String getNewMessageId(final String prefix) {
Preconditions.checkArgument(Strings.isNullOrEmpty(prefix) == false, "Null or empty prefix");
- return String.format(messageIdBlueprint, prefix, getNewMessageId());
+ return String.format(MESSAGE_ID_BLUEPRINT, prefix, getNewMessageId());
}
public String getNewMessageId() {
private final InstanceIdentifier<Node> bindingPath;
private final NodeKey key;
private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier topologyPath;
- private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
+ private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
private InetSocketAddress address;
private Host host;
private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPath(final String name) {
final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
- builder.node(Nodes.QNAME).node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
+ builder.node(Nodes.QNAME).node(Node.QNAME)
+ .nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
return builder.build();
}
- private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
- final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.builder(NetworkTopology.class).build();
- final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
+ private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network
+ .topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
+ final InstanceIdentifier<NetworkTopology> networkTopology =
+ InstanceIdentifier.builder(NetworkTopology.class).build();
+ final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology
+ .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
return topology
- .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class,
- new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey(
- new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId(key.getId().getValue())));
+ .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.class,
+ new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network
+ .topology.topology.NodeKey(new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.NodeId(key.getId().getValue())));
}
- private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(final String name) {
+ private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(
+ final String name) {
final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
builder
.node(NetworkTopology.QNAME)
.node(Topology.QNAME)
- .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME.getLocalName())
- .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME)
- .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME,
- QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
+ .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"),
+ TopologyNetconf.QNAME.getLocalName())
+ .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.QNAME)
+ .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.QNAME,
+ QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
return builder.build();
}
return key;
}
- public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
+ public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
return topologyBindingPath;
}
@Override
public String toString() {
- return "RemoteDevice{" + name +'}';
+ return "RemoteDevice{" + name + '}';
}
@Override
- public boolean equals(final Object o) {
- if (this == o) {
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (!(o instanceof RemoteDeviceId)) {
+ if (!(obj instanceof RemoteDeviceId)) {
return false;
}
- final RemoteDeviceId that = (RemoteDeviceId) o;
+ final RemoteDeviceId that = (RemoteDeviceId) obj;
if (!name.equals(that.name)) {
return false;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
+import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
+import org.xml.sax.SAXException;
+@SuppressWarnings("checkstyle:IllegalCatch")
public class NetconfDeviceTest {
- private static final NetconfMessage notification;
+ private static final NetconfMessage NOTIFICATION;
- private static final ContainerNode compositeNode;
+ private static final ContainerNode COMPOSITE_NODE;
static {
try {
- compositeNode = mockClass(ContainerNode.class);
+ COMPOSITE_NODE = mockClass(ContainerNode.class);
} catch (final Exception e) {
throw new RuntimeException(e);
}
try {
- notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
- } catch (Exception e) {
+ NOTIFICATION = new NetconfMessage(XmlUtil
+ .readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
+ } catch (SAXException | IOException e) {
throw new ExceptionInInitializerError(e);
}
}
- private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
+ private static final DOMRpcResult RPC_RESULT = new DefaultDOMRpcResult(COMPOSITE_NODE);
public static final String TEST_NAMESPACE = "test:namespace";
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));
- public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + 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));
- public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
+ public static final String TEST_CAPABILITY2 =
+ TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
- private static final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
+ private static final NetconfDeviceSchemasResolver STATE_SCHEMAS_RESOLVER =
+ (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
@Test
public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
final Module first = Iterables.getFirst(schema.getModules(), null);
final QName qName = QName.create(first.getQNameModule(), first.getName());
final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
- final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
+ final NetconfStateSchemas.RemoteYangSchema source2 =
+ new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
};
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+ .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSalFacade(facade)
.build();
// Monitoring supported
- final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
+ final NetconfSessionPreferences sessionCaps =
+ getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
}
schemaResolutionException))
.when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+ .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
final SchemaRepository schemaRepository = getSchemaRepository();
// Make fallback attempt to fail due to empty resolved sources
- final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
- doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
+ final MissingSchemaSourceException schemaResolutionException =
+ new MissingSchemaSourceException("fail first", TEST_SID);
+ doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException))
+ .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
doAnswer(invocation -> {
if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
return Futures.immediateFailedCheckedFuture(schemaResolutionException);
final Module first = Iterables.getFirst(schema.getModules(), null);
final QName qName = QName.create(first.getQNameModule(), first.getName());
final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
- final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
+ final NetconfStateSchemas.RemoteYangSchema source2 =
+ new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
};
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+ .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSalFacade(facade)
.build();
// Monitoring supported
- final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
+ final NetconfSessionPreferences sessionCaps =
+ getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
}
final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
doNothing().when(mockReg).close();
- doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
+ doReturn(mockReg).when(mock).registerSchemaSource(
+ any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class),
+ any(PotentialSchemaSource.class));
return mock;
}
private static SchemaRepository getSchemaRepository() {
final SchemaRepository mock = mock(SchemaRepository.class);
final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
- doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
+ doReturn(Futures.immediateCheckedFuture(mockRep))
+ .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
return mock;
}
final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
final NetconfDeviceCommunicator listener = getListener();
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+ getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
.setSalFacade(facade)
.build();
- device.onNotification(notification);
- device.onNotification(notification);
+ device.onNotification(NOTIFICATION);
+ device.onNotification(NOTIFICATION);
verify(facade, times(0)).onNotification(any(DOMNotification.class));
final DOMRpcService deviceRpc = mock(DOMRpcService.class);
- device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
+ device.handleSalInitializationSuccess(
+ NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
- device.onNotification(notification);
+ device.onNotification(NOTIFICATION);
verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
}
final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+ getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
device.onRemoteSessionUp(sessionCaps, listener);
verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
- verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ verify(facade, timeout(5000)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
device.onRemoteSessionDown();
verify(facade, timeout(5000)).onDeviceDisconnected();
device.onRemoteSessionUp(sessionCaps, listener);
verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
- verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ verify(facade, timeout(5000).times(2)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
}
@Test
final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+ getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
- moduleBasedCaps.put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
+ moduleBasedCaps
+ .put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
- verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
- NetconfDeviceCapabilities netconfDeviceCaps = ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
-
- netconfDeviceCaps.getResolvedCapabilities().forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
- moduleBasedCaps.get(QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
+ verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(
+ any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
+ NetconfDeviceCapabilities netconfDeviceCaps =
+ ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
+
+ netconfDeviceCaps.getResolvedCapabilities()
+ .forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
+ moduleBasedCaps.get(
+ QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
}
private static SchemaContextFactory getSchemaFactory() throws Exception {
final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
- doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
+ doReturn(Futures.immediateCheckedFuture(getSchema()))
+ .when(schemaFactory).createSchemaContext(any(Collection.class));
return schemaFactory;
}
}
private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
- final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
- doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
+ mockCloseableClass(RemoteDeviceHandler.class);
+ doNothing().when(remoteDeviceHandler).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
return remoteDeviceHandler;
public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
- doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
- doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
- doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
+ doReturn(NOTIFICATION).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
+ doReturn(RPC_RESULT).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
+ doReturn(COMPOSITE_NODE).when(messageTransformer).toNotification(any(NetconfMessage.class));
return messageTransformer;
}
- public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
+ public NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
+ final Collection<String> additionalCapabilities) {
final ArrayList<String> capabilities = Lists.newArrayList(
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
- if(addMonitor) {
+ if (addMonitor) {
capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
}
public NetconfDeviceCommunicator getListener() throws Exception {
final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
-// doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
+// doReturn(Futures.immediateFuture(rpcResult))
+// .when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
return remoteDeviceCommunicator;
}
}
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class NetconfStateSchemasTest {
- private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04"));
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemasTest.class);
+
+ private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton(
+ "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04"));
private final RemoteDeviceId deviceId = new RemoteDeviceId("device", new InetSocketAddress(99));
+ private final int numberOfSchemas = 73;
+ private final int numberOfLegalSchemas = numberOfSchemas - 3;
private ContainerNode compositeNodeSchemas;
- private final int NUMBER_OF_SCHEMAS = 73;
- private final int NUMBER_OF_LEGAL_SCHEMAS = NUMBER_OF_SCHEMAS - 3;
@Mock
private DOMRpcService rpc;
final DataSchemaNode schemasNode =
((ContainerSchemaNode) schemaContext
.getDataChildByName(NetconfState.QNAME)).getDataChildByName(Schemas.QNAME);
- final Document schemasXml = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
- final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
- compositeNodeSchemas = containerNodeParser.parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
+ final Document schemasXml =
+ XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
+ final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser =
+ DomToNormalizedNodeParserFactory
+ .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
+ compositeNodeSchemas = containerNodeParser
+ .parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
}
final NetconfStateSchemas schemas = NetconfStateSchemas.create(deviceId, compositeNodeSchemas);
final Set<QName> availableYangSchemasQNames = schemas.getAvailableYangSchemasQNames();
- assertEquals(NUMBER_OF_LEGAL_SCHEMAS, availableYangSchemasQNames.size());
+ assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
assertThat(availableYangSchemasQNames,
hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
.withChild(compositeNodeSchemas)
.build();
final ContainerNode data = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
.withChild(netconfState)
.build();
final ContainerNode rpcReply = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
.withChild(data)
.build();
- when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
+ when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
+ .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
- assertEquals(NUMBER_OF_LEGAL_SCHEMAS, availableYangSchemasQNames.size());
+ assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
assertThat(availableYangSchemasQNames,
hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
@Test
public void testCreateRpcError() throws Exception {
final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, "fail", "fail");
- when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
+ when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
+ .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
Assert.assertTrue(availableYangSchemasQNames.isEmpty());
}
+ @SuppressWarnings("checkstyle:IllegalThrows")
@Test(expected = RuntimeException.class)
public void testCreateInterrupted() throws Throwable {
//NetconfStateSchemas.create calls Thread.currentThread().interrupt(), so it must run in its own thread
when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(checkedFuture);
NetconfStateSchemas.create(rpc, CAPS, deviceId);
} catch (final InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ LOG.info("Operation failed.", e);
}
});
@Test
public void testRemoteYangSchemaEquals() throws Exception {
- final NetconfStateSchemas.RemoteYangSchema schema1 = new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
- final NetconfStateSchemas.RemoteYangSchema schema2 = new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
- final NetconfStateSchemas.RemoteYangSchema schema3 = new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
+ final NetconfStateSchemas.RemoteYangSchema schema1 =
+ new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
+ final NetconfStateSchemas.RemoteYangSchema schema2 =
+ new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
+ final NetconfStateSchemas.RemoteYangSchema schema3 =
+ new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
Assert.assertEquals(schema1, schema2);
Assert.assertEquals(schema2, schema1);
Assert.assertNotEquals(schema1, schema3);
userNotification = new NetconfMessage(doc);
}
- static SchemaContext getNotificationSchemaContext(final Class<?> loadClass, final boolean getExceptionTest) throws Exception {
+ static SchemaContext getNotificationSchemaContext(final Class<?> loadClass,
+ final boolean getExceptionTest) throws Exception {
final List<InputStream> modelsToParse = new ArrayList<>();
if (getExceptionTest) {
public class NetconfToRpcRequestTest {
- private final static String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
- private final static String REVISION = "2014-07-14";
- private final static QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
- private final static QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
- private final static QName SUBSCRIBE_RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
-
- private final static String CONFIG_TEST_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:config:defs";
- private final static String CONFIG_TEST_REVISION = "2014-07-21";
- private final static QName EDIT_CONFIG_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "edit-config");
- private final static QName GET_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get");
- private final static QName GET_CONFIG_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get-config");
+ private static final String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
+ private static final String REVISION = "2014-07-14";
+ private static final QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
+ private static final QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
+ private static final QName SUBSCRIBE_RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
+
+ private static final String CONFIG_TEST_NAMESPACE =
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:config:defs";
+ private static final String CONFIG_TEST_REVISION = "2014-07-21";
+ private static final QName EDIT_CONFIG_QNAME =
+ QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "edit-config");
+ private static final QName GET_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get");
+ private static final QName GET_CONFIG_QNAME =
+ QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get-config");
static SchemaContext cfgCtx;
static NetconfMessageTransformer messageTransformer;
@BeforeClass
public static void setup() throws Exception {
- List<InputStream> modelsToParse = Collections
- .singletonList(NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
+ List<InputStream> modelsToParse = Collections.singletonList(
+ NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
final Set<Module> notifModules = YangParserTestUtils.parseYangStreams(modelsToParse).getModules();
assertTrue(!notifModules.isEmpty());
@Test
public void testUserDefinedRpcCall() throws Exception {
- final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> rootBuilder = Builders.containerBuilder();
+ final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> rootBuilder =
+ Builders.containerBuilder();
rootBuilder.withNodeIdentifier(toId(SUBSCRIBE_RPC_NAME));
rootBuilder.withChild(buildLeaf(STREAM_NAME, "NETCONF"));
@Test(expected = IllegalArgumentException.class)
public void testRpcResponse() throws Exception {
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
- "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-5\">\n" +
- "<data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">" +
- "module schema" +
- "</data>\n" +
- "</rpc-reply>\n"
+ "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-5\">\n"
+ + "<data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">"
+ + "module schema"
+ + "</data>\n"
+ + "</rpc-reply>\n"
));
messageTransformer.toRpcResult(response, toPath(EDIT_CONFIG_QNAME));
final NetconfMessage netconfMessage = mock(NetconfMessage.class);
device.onRemoteSessionUp(sessionCaps, listener);
- verify(facade).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ verify(facade).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
device.onNotification(netconfMessage);
verify(facade).onNotification(any(DOMNotification.class));
@SuppressWarnings("unchecked")
private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
- final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
- doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
+ mockCloseableClass(RemoteDeviceHandler.class);
+ doNothing().when(remoteDeviceHandler).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
return remoteDeviceHandler;
}
- private static <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
+ private static <T extends AutoCloseable> T mockCloseableClass(
+ final Class<T> remoteDeviceHandlerClass) throws Exception {
final T mock = mockClass(remoteDeviceHandlerClass);
doNothing().when(mock).close();
return mock;
return mock;
}
- private static NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
+ private static NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
+ final Collection<String> additionalCapabilities) {
final ArrayList<String> capabilities = Lists.newArrayList(
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
- if(addMonitor) {
+ if (addMonitor) {
capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
}
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class NetconfDeviceCommunicatorTest {
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicatorTest.class);
+
@Mock
NetconfClientSession mockSession;
@Before
public void setUp() throws Exception {
- MockitoAnnotations.initMocks( this );
+ MockitoAnnotations.initMocks(this);
- communicator = new NetconfDeviceCommunicator( new RemoteDeviceId( "test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
+ communicator = new NetconfDeviceCommunicator(
+ new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
}
void setupSession() {
}
private ListenableFuture<RpcResult<NetconfMessage>> sendRequest() throws Exception {
- return sendRequest( UUID.randomUUID().toString(), true );
+ return sendRequest(UUID.randomUUID().toString(), true);
}
@SuppressWarnings("unchecked")
- private ListenableFuture<RpcResult<NetconfMessage>> sendRequest( final String messageID, final boolean doLastTest ) throws Exception {
+ private ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final String messageID,
+ final boolean doLastTest) throws Exception {
Document doc = UntrustedXML.newDocumentBuilder().newDocument();
- Element element = doc.createElement( "request" );
- element.setAttribute( "message-id", messageID );
- doc.appendChild( element );
- NetconfMessage message = new NetconfMessage( doc );
+ Element element = doc.createElement("request");
+ element.setAttribute("message-id", messageID);
+ doc.appendChild(element);
+ NetconfMessage message = new NetconfMessage(doc);
- ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
- doReturn( mockChannelFuture ).when( mockChannelFuture )
- .addListener( any( (GenericFutureListener.class ) ) );
- doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+ ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+ doReturn(mockChannelFuture).when(mockChannelFuture)
+ .addListener(any((GenericFutureListener.class)));
+ doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
ListenableFuture<RpcResult<NetconfMessage>> resultFuture =
- communicator.sendRequest( message, QName.create( "mock rpc" ) );
- if(doLastTest) {
+ communicator.sendRequest(message, QName.create("mock rpc"));
+ if (doLastTest) {
assertNotNull("ListenableFuture is null", resultFuture);
}
return resultFuture;
public void testOnSessionUp() {
String testCapability = "urn:opendaylight:params:xml:ns:test?module=test-module&revision=2014-06-02";
Collection<String> serverCapabilities =
- Sets.newHashSet( NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
- NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
- testCapability );
- doReturn( serverCapabilities ).when( mockSession ).getServerCapabilities();
-
- ArgumentCaptor<NetconfSessionPreferences> NetconfSessionPreferences =
- ArgumentCaptor.forClass( NetconfSessionPreferences.class );
- doNothing().when( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
-
- communicator.onSessionUp( mockSession );
-
- verify( mockSession ).getServerCapabilities();
- verify( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
-
- NetconfSessionPreferences actualCapabilites = NetconfSessionPreferences.getValue();
- assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
- NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
- assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
- assertEquals( "getModuleBasedCaps", Sets.newHashSet(
- QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
- actualCapabilites.getModuleBasedCaps());
- assertEquals( "isRollbackSupported", true, actualCapabilites.isRollbackSupported() );
- assertEquals( "isMonitoringSupported", true, actualCapabilites.isMonitoringSupported() );
+ Sets.newHashSet(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
+ NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
+ testCapability);
+ doReturn(serverCapabilities).when(mockSession).getServerCapabilities();
+
+ ArgumentCaptor<NetconfSessionPreferences> netconfSessionPreferences =
+ ArgumentCaptor.forClass(NetconfSessionPreferences.class);
+ doNothing().when(mockDevice).onRemoteSessionUp(netconfSessionPreferences.capture(), eq(communicator));
+
+ communicator.onSessionUp(mockSession);
+
+ verify(mockSession).getServerCapabilities();
+ verify(mockDevice).onRemoteSessionUp(netconfSessionPreferences.capture(), eq(communicator));
+
+ NetconfSessionPreferences actualCapabilites = netconfSessionPreferences.getValue();
+ assertEquals("containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
+ NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()));
+ assertEquals("containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability));
+ assertEquals("getModuleBasedCaps", Sets.newHashSet(
+ QName.create("urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module")),
+ actualCapabilites.getModuleBasedCaps());
+ assertEquals("isRollbackSupported", true, actualCapabilites.isRollbackSupported());
+ assertEquals("isMonitoringSupported", true, actualCapabilites.isMonitoringSupported());
}
@SuppressWarnings("unchecked")
- @Test(timeout=5000)
+ @Test(timeout = 5000)
public void testOnSessionDown() throws Exception {
setupSession();
ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
+ final ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
- doNothing().when( mockDevice ).onRemoteSessionDown();
+ doNothing().when(mockDevice).onRemoteSessionDown();
- communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
+ communicator.onSessionDown(mockSession, new Exception("mock ex"));
- verifyErrorRpcResult( resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
- verifyErrorRpcResult( resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
+ verifyErrorRpcResult(resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed");
+ verifyErrorRpcResult(resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed");
- verify( mockDevice ).onRemoteSessionDown();
+ verify(mockDevice).onRemoteSessionDown();
- reset( mockDevice );
+ reset(mockDevice);
- communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
+ communicator.onSessionDown(mockSession, new Exception("mock ex"));
- verify( mockDevice, never() ).onRemoteSessionDown();
+ verify(mockDevice, never()).onRemoteSessionDown();
}
@Test
ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest();
- doNothing().when( mockDevice ).onRemoteSessionDown();
+ doNothing().when(mockDevice).onRemoteSessionDown();
String reasonText = "testing terminate";
- NetconfTerminationReason reason = new NetconfTerminationReason( reasonText );
- communicator.onSessionTerminated( mockSession, reason );
+ NetconfTerminationReason reason = new NetconfTerminationReason(reasonText);
+ communicator.onSessionTerminated(mockSession, reason);
- RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.TRANSPORT,
- "operation-failed" );
- assertEquals( "RpcError message", reasonText, rpcError.getMessage() );
+ RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.TRANSPORT,
+ "operation-failed");
+ assertEquals("RpcError message", reasonText, rpcError.getMessage());
- verify( mockDevice ).onRemoteSessionDown();
+ verify(mockDevice).onRemoteSessionDown();
}
@Test
public void testClose() throws Exception {
communicator.close();
- verify( mockDevice, never() ).onRemoteSessionDown();
+ verify(mockDevice, never()).onRemoteSessionDown();
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ @SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testSendRequest() throws Exception {
setupSession();
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create( "mock rpc" );
+ QName rpc = QName.create("mock rpc");
ArgumentCaptor<GenericFutureListener> futureListener =
- ArgumentCaptor.forClass( GenericFutureListener.class );
+ ArgumentCaptor.forClass(GenericFutureListener.class);
- ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
- doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
- doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+ ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+ doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
+ doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
- verify( mockSession ).sendMessage( same( message ) );
+ verify(mockSession).sendMessage(same(message));
- assertNotNull( "ListenableFuture is null", resultFuture );
+ assertNotNull("ListenableFuture is null", resultFuture);
- verify( mockChannelFuture ).addListener( futureListener.capture() );
- Future<Void> operationFuture = mock( Future.class );
- doReturn( true ).when( operationFuture ).isSuccess();
- doReturn( true ).when( operationFuture ).isDone();
- futureListener.getValue().operationComplete( operationFuture );
+ verify(mockChannelFuture).addListener(futureListener.capture());
+ Future<Void> operationFuture = mock(Future.class);
+ doReturn(true).when(operationFuture).isSuccess();
+ doReturn(true).when(operationFuture).isDone();
+ futureListener.getValue().operationComplete(operationFuture);
try {
- resultFuture.get( 1, TimeUnit.MILLISECONDS ); // verify it's not cancelled or has an error set
- }
- catch( TimeoutException e ) {} // expected
+ resultFuture.get(1, TimeUnit.MILLISECONDS); // verify it's not cancelled or has an error set
+ } catch (TimeoutException e) {
+ LOG.info("Operation failed due timeout.");
+ } // expected
}
@Test
public void testSendRequestWithNoSession() throws Exception {
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create( "mock rpc" );
+ QName rpc = QName.create("mock rpc");
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
- assertNotNull( "ListenableFuture is null", resultFuture );
+ assertNotNull("ListenableFuture is null", resultFuture);
// Should have an immediate result
- RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
+ RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
+
+ verifyErrorRpcResult(rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed");
+ }
- verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
+ private static NetconfMessage createSuccessResponseMessage(final String messageID)
+ throws ParserConfigurationException {
+ Document doc = UntrustedXML.newDocumentBuilder().newDocument();
+ Element rpcReply =
+ doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
+ rpcReply.setAttribute("message-id", messageID);
+ Element element = doc.createElementNS("ns", "data");
+ element.setTextContent(messageID);
+ rpcReply.appendChild(element);
+ doc.appendChild(rpcReply);
+
+ return new NetconfMessage(doc);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
setupSession();
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create( "mock rpc" );
+ QName rpc = QName.create("mock rpc");
ArgumentCaptor<GenericFutureListener> futureListener =
- ArgumentCaptor.forClass( GenericFutureListener.class );
+ ArgumentCaptor.forClass(GenericFutureListener.class);
- ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
- doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
- doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+ ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+ doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
+ doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
- assertNotNull( "ListenableFuture is null", resultFuture );
+ assertNotNull("ListenableFuture is null", resultFuture);
- verify( mockChannelFuture ).addListener( futureListener.capture() );
+ verify(mockChannelFuture).addListener(futureListener.capture());
- Future<Void> operationFuture = mock( Future.class );
- doReturn( false ).when( operationFuture ).isSuccess();
- doReturn( true ).when( operationFuture ).isDone();
- doReturn( new Exception( "mock error" ) ).when( operationFuture ).cause();
- futureListener.getValue().operationComplete( operationFuture );
+ Future<Void> operationFuture = mock(Future.class);
+ doReturn(false).when(operationFuture).isSuccess();
+ doReturn(true).when(operationFuture).isDone();
+ doReturn(new Exception("mock error")).when(operationFuture).cause();
+ futureListener.getValue().operationComplete(operationFuture);
// Should have an immediate result
- RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
-
- RpcError rpcError = verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
- assertEquals( "RpcError message contains \"mock error\"", true,
- rpcError.getMessage().contains( "mock error" ) );
- }
+ RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
- private static NetconfMessage createSuccessResponseMessage( final String messageID ) throws ParserConfigurationException {
- Document doc = UntrustedXML.newDocumentBuilder().newDocument();
- Element rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
- rpcReply.setAttribute( "message-id", messageID );
- Element element = doc.createElementNS( "ns", "data" );
- element.setTextContent( messageID );
- rpcReply.appendChild( element );
- doc.appendChild( rpcReply );
-
- return new NetconfMessage( doc );
+ RpcError rpcError = verifyErrorRpcResult(rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed");
+ assertEquals("RpcError message contains \"mock error\"", true,
+ rpcError.getMessage().contains("mock error"));
}
//Test scenario verifying whether missing message is handled
setupSession();
String messageID1 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest(messageID1, true);
String messageID2 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest(messageID2, true);
String messageID3 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest( messageID3, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest(messageID3, true);
//response messages 1,2 are omitted
- communicator.onMessage( mockSession, createSuccessResponseMessage( messageID3 ) );
+ communicator.onMessage(mockSession, createSuccessResponseMessage(messageID3));
- verifyResponseMessage( resultFuture3.get(), messageID3 );
+ verifyResponseMessage(resultFuture3.get(), messageID3);
}
@Test
setupSession();
String messageID1 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest(messageID1, true);
String messageID2 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
+ final ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest(messageID2, true);
- communicator.onMessage( mockSession, createSuccessResponseMessage( messageID1 ) );
- communicator.onMessage( mockSession, createSuccessResponseMessage( messageID2 ) );
+ communicator.onMessage(mockSession, createSuccessResponseMessage(messageID1));
+ communicator.onMessage(mockSession, createSuccessResponseMessage(messageID2));
- verifyResponseMessage( resultFuture1.get(), messageID1 );
- verifyResponseMessage( resultFuture2.get(), messageID2 );
+ verifyResponseMessage(resultFuture1.get(), messageID1);
+ verifyResponseMessage(resultFuture2.get(), messageID2);
}
@Test
setupSession();
String messageID = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID, true);
- communicator.onMessage( mockSession, createErrorResponseMessage( messageID ) );
+ communicator.onMessage(mockSession, createErrorResponseMessage(messageID));
- RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.RPC,
- "missing-attribute" );
- assertEquals( "RpcError message", "Missing attribute", rpcError.getMessage() );
+ RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.RPC,
+ "missing-attribute");
+ assertEquals("RpcError message", "Missing attribute", rpcError.getMessage());
String errorInfo = rpcError.getInfo();
- assertNotNull( "RpcError info is null", errorInfo );
- assertEquals( "Error info contains \"foo\"", true,
- errorInfo.contains( "<bad-attribute>foo</bad-attribute>" ) );
- assertEquals( "Error info contains \"bar\"", true,
- errorInfo.contains( "<bad-element>bar</bad-element>" ) );
+ assertNotNull("RpcError info is null", errorInfo);
+ assertEquals("Error info contains \"foo\"", true,
+ errorInfo.contains("<bad-attribute>foo</bad-attribute>"));
+ assertEquals("Error info contains \"bar\"", true,
+ errorInfo.contains("<bad-element>bar</bad-element>"));
}
/**
- * Test whether reconnect is scheduled properly
+ * Test whether reconnect is scheduled properly.
*/
@Test
public void testNetconfDeviceReconnectInCommunicator() throws Exception {
- final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(RemoteDevice.class);
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device =
+ mock(RemoteDevice.class);
- final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
+ final TimedReconnectStrategy timedReconnectStrategy =
+ new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
@Override
public int getConnectTimeout() throws Exception {
final EventLoopGroup group = new NioEventLoopGroup();
final Timer time = new HashedWheelTimer();
try {
- final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
+ final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(
+ new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
.withAddress(new InetSocketAddress("localhost", 65000))
.withReconnectStrategy(reconnectStrategy)
listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);
- verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
+ verify(reconnectStrategy,
+ timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
} finally {
time.stop();
group.shutdownGracefully();
setupSession();
String messageID = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID, true);
- communicator.onMessage( mockSession, createSuccessResponseMessage( UUID.randomUUID().toString() ) );
+ communicator.onMessage(mockSession, createSuccessResponseMessage(UUID.randomUUID().toString()));
- RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.PROTOCOL,
- "bad-attribute" );
- assertEquals( "RpcError message non-empty", true,
- !Strings.isNullOrEmpty( rpcError.getMessage() ) );
+ RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.PROTOCOL,
+ "bad-attribute");
+ assertEquals("RpcError message non-empty", true,
+ !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" ) );
+ 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"));
}
@Test
assertNotNull("ListenableFuture is null", resultFuture);
}
- private static NetconfMessage createErrorResponseMessage( final String messageID ) throws Exception {
- String xmlStr =
- "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" +
- " message-id=\"" + messageID + "\">" +
- " <rpc-error>" +
- " <error-type>rpc</error-type>" +
- " <error-tag>missing-attribute</error-tag>" +
- " <error-severity>error</error-severity>" +
- " <error-message>Missing attribute</error-message>" +
- " <error-info>" +
- " <bad-attribute>foo</bad-attribute>" +
- " <bad-element>bar</bad-element>" +
- " </error-info>" +
- " </rpc-error>" +
- "</rpc-reply>";
-
- ByteArrayInputStream bis = new ByteArrayInputStream( xmlStr.getBytes() );
+ private static NetconfMessage createErrorResponseMessage(final String messageID) throws Exception {
+ String xmlStr = "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""
+ + " message-id=\"" + messageID + "\">"
+ + " <rpc-error>"
+ + " <error-type>rpc</error-type>"
+ + " <error-tag>missing-attribute</error-tag>"
+ + " <error-severity>error</error-severity>"
+ + " <error-message>Missing attribute</error-message>"
+ + " <error-info>"
+ + " <bad-attribute>foo</bad-attribute>"
+ + " <bad-element>bar</bad-element>"
+ + " </error-info>"
+ + " </rpc-error>"
+ + "</rpc-reply>";
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(xmlStr.getBytes());
Document doc = UntrustedXML.newDocumentBuilder().parse(bis);
- return new NetconfMessage( doc );
+ return new NetconfMessage(doc);
}
- private static void verifyResponseMessage( final RpcResult<NetconfMessage> rpcResult, final String dataText ) {
- assertNotNull( "RpcResult is null", rpcResult );
- assertEquals( "isSuccessful", true, rpcResult.isSuccessful() );
+ private static void verifyResponseMessage(final RpcResult<NetconfMessage> rpcResult, final String dataText) {
+ assertNotNull("RpcResult is null", rpcResult);
+ assertEquals("isSuccessful", true, rpcResult.isSuccessful());
NetconfMessage messageResult = rpcResult.getResult();
- assertNotNull( "getResult", messageResult );
+ assertNotNull("getResult", messageResult);
// List<SimpleNode<?>> nodes = messageResult.getSimpleNodesByName(
// QName.create( URI.create( "ns" ), null, "data" ) );
// assertNotNull( "getSimpleNodesByName", nodes );
// assertEquals( "SimpleNode value", dataText, nodes.iterator().next().getValue() );
}
- private static RpcError verifyErrorRpcResult( final RpcResult<NetconfMessage> rpcResult,
- final RpcError.ErrorType expErrorType, final String expErrorTag ) {
- assertNotNull( "RpcResult is null", rpcResult );
- assertEquals( "isSuccessful", false, rpcResult.isSuccessful() );
- assertNotNull( "RpcResult errors is null", rpcResult.getErrors() );
- assertEquals( "Errors size", 1, rpcResult.getErrors().size() );
+ private static RpcError verifyErrorRpcResult(final RpcResult<NetconfMessage> rpcResult,
+ final RpcError.ErrorType expErrorType, final String expErrorTag) {
+ assertNotNull("RpcResult is null", rpcResult);
+ assertEquals("isSuccessful", false, rpcResult.isSuccessful());
+ assertNotNull("RpcResult errors is null", rpcResult.getErrors());
+ assertEquals("Errors size", 1, rpcResult.getErrors().size());
RpcError rpcError = rpcResult.getErrors().iterator().next();
- assertEquals( "getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity() );
- assertEquals( "getErrorType", expErrorType, rpcError.getErrorType() );
- assertEquals( "getErrorTag", expErrorTag, rpcError.getTag() );
+ assertEquals("getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity());
+ assertEquals("getErrorType", expErrorType, rpcError.getErrorType());
+ assertEquals("getErrorTag", expErrorTag, rpcError.getTag());
final String msg = rpcError.getMessage();
assertNotNull("getMessage is null", msg);
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0"
);
final NetconfSessionPreferences merged = sessionCaps1.addModuleCaps(sessionCaps2);
assertCaps(merged, 2, 2 + 1 /*Preserved monitoring*/ + 2 /*already present*/);
- for (final QName qName : sessionCaps2.getModuleBasedCaps()) {
- assertThat(merged.getModuleBasedCaps(), hasItem(qName));
+ for (final QName qualifiedName : sessionCaps2.getModuleBasedCaps()) {
+ assertThat(merged.getModuleBasedCaps(), hasItem(qualifiedName));
}
assertThat(merged.getModuleBasedCaps(), hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0"
);
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0"
final NetconfSessionPreferences merged = sessionCaps1.addNonModuleCaps(sessionCaps2);
- assertCaps(merged, 3+2, 3);
+ assertCaps(merged, 3 + 2, 3);
for (final String capability : sessionCaps2.getNonModuleCaps()) {
assertThat(merged.getNonModuleCaps(), hasItem(capability));
}
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0"
public class KeepaliveSalFacadeTest {
- private static final RemoteDeviceId REMOTE_DEVICE_ID = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
+ private static final RemoteDeviceId REMOTE_DEVICE_ID =
+ new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
@Mock
private RemoteDeviceHandler<NetconfSessionPreferences> underlyingSalFacade;
invocationOnMock.callRealMethod();
return currentKeepalive;
}
- }).when(executorServiceSpy).schedule(Mockito.<Runnable> any(),
- Mockito.anyLong(), Matchers.<TimeUnit> any());
+ }).when(executorServiceSpy).schedule(Mockito.<Runnable>any(),
+ Mockito.anyLong(), Matchers.<TimeUnit>any());
Mockito.when(currentKeepalive.isDone()).thenReturn(true);
}
final DOMRpcResult result = new DefaultDOMRpcResult(Builders.containerBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME)).build());
- doReturn(Futures.immediateCheckedFuture(result)).when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
+ 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);
proxyRpc = (DOMRpcService) invocationOnMock.getArguments()[2];
return null;
}
- }).when(underlyingSalFacade).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ }).when(underlyingSalFacade).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state")))
.when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class MountInstanceTest {
+ private static final Logger LOG = LoggerFactory.getLogger(MountInstanceTest.class);
+
private static SchemaContext SCHEMA_CONTEXT;
@Mock
private NetconfDeviceSalProvider.MountInstance mountInstance;
@BeforeClass
- public static void suiteSetUp() throws Exception{
+ public static void suiteSetUp() throws Exception {
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- moduleInfoBackedContext.addModuleInfos(
- Lists.newArrayList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
+ moduleInfoBackedContext.addModuleInfos(Lists.newArrayList(org.opendaylight.yang.gen
+ .v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
SCHEMA_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
}
when(service.createMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountPointBuilder);
when(mountPointBuilder.register()).thenReturn(registration);
- mountInstance = new NetconfDeviceSalProvider.MountInstance(service, new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830)));
+ mountInstance = new NetconfDeviceSalProvider.MountInstance(
+ service, new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830)));
}
try {
mountInstance.onTopologyDeviceConnected(SCHEMA_CONTEXT, broker, rpcService, notificationService);
} catch (final IllegalStateException e) {
- e.printStackTrace();
+ LOG.warn("Operation failed.", e);
Assert.fail("Topology registration still present after disconnect ");
}
}
MockitoAnnotations.initMocks(this);
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
moduleInfoBackedContext.addModuleInfos(
- Lists.newArrayList(
- $YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
+ Lists.newArrayList($YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
+ .netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get();
DOMRpcResult result = new DefaultDOMRpcResult();
- when(rpcService.invokeRpc(any(SchemaPath.class), any(NormalizedNode.class))).thenReturn(Futures.immediateCheckedFuture(result));
+ when(rpcService.invokeRpc(any(SchemaPath.class), any(NormalizedNode.class)))
+ .thenReturn(Futures.immediateCheckedFuture(result));
dataBroker = getDataBroker(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
@Test
public void testWritableRunningCandidateWriteTransaction() throws Exception {
- testWriteTransaction(WriteCandidateRunningTx.class, NetconfMessageTransformUtil.NETCONF_RUNNING_WRITABLE_URI.toString(),
+ testWriteTransaction(
+ WriteCandidateRunningTx.class, NetconfMessageTransformUtil.NETCONF_RUNNING_WRITABLE_URI.toString(),
NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
private NetconfDeviceDataBroker getDataBroker(String... caps) {
NetconfSessionPreferences prefs = NetconfSessionPreferences.fromStrings(Arrays.asList(caps));
- final RemoteDeviceId id = new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
+ final RemoteDeviceId id =
+ new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
return new NetconfDeviceDataBroker(id, schemaContext, rpcService, prefs);
}
schema = getSchema();
NetconfMessageTransformer transformer = new NetconfMessageTransformer(schema, true);
final NetconfMessage reply = new NetconfMessage(XmlUtil.readXmlToDocument(
- "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
- "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n" +
- "<data>\n" +
- "</data>\n" +
- "</rpc-reply>"));
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
+ + "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n"
+ + "<data>\n"
+ + "</data>\n"
+ + "</rpc-reply>"));
RpcResult<NetconfMessage> result = RpcResultBuilder.success(reply).build();
- doReturn(Futures.immediateFuture(result)).when(communicator).sendRequest(any(NetconfMessage.class), any(QName.class));
+ doReturn(Futures.immediateFuture(result))
+ .when(communicator).sendRequest(any(NetconfMessage.class), any(QName.class));
rpc = new NetconfDeviceRpc(schema, communicator, transformer);
- path = SchemaPath.create(true, QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config"));
+ path = SchemaPath
+ .create(true, QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config"));
expectedReply = transformer.toRpcResult(reply, path);
}
}
private static ContainerNode createNode(String namespace, String date, String localName) {
- return Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, date, localName))).build();
+ return Builders.containerBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, date, localName))).build();
}
private static SchemaContext getSchema() {
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class, NetconfSessionPreferences.class})
+@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class,
+ NetconfSessionPreferences.class})
public class NetconfDeviceSalFacadeTest {
private NetconfDeviceSalFacade deviceFacade;
private NetconfDeviceSalProvider salProvider;
@Before
- public void setUp() throws Exception{
+ public void setUp() throws Exception {
initMocks(this);
final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("test", address);
mountInstance = PowerMockito.mock(NetconfDeviceSalProvider.MountInstance.class);
doReturn(netconfDeviceTopologyAdapter).when(salProvider).getTopologyDatastoreAdapter();
- doNothing().when(netconfDeviceTopologyAdapter).updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
+ doNothing().when(netconfDeviceTopologyAdapter)
+ .updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
doReturn(mountInstance).when(salProvider).getMountInstance();
doNothing().when(mountInstance).onTopologyDeviceDisconnected();
public void testOnDeviceConnected() {
final SchemaContext schemaContext = mock(SchemaContext.class);
- final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(getCapabilities());
+ final NetconfSessionPreferences netconfSessionPreferences =
+ NetconfSessionPreferences.fromStrings(getCapabilities());
final DOMRpcService deviceRpc = mock(DOMRpcService.class);
deviceFacade.onDeviceConnected(schemaContext, netconfSessionPreferences, deviceRpc);
- verify(mountInstance, times(1)).onTopologyDeviceConnected(eq(schemaContext), any(DOMDataBroker.class), eq(deviceRpc), any(NetconfDeviceNotificationService.class));
- verify(netconfDeviceTopologyAdapter, times(1)).updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
+ verify(mountInstance, times(1)).onTopologyDeviceConnected(eq(schemaContext),
+ any(DOMDataBroker.class), eq(deviceRpc), any(NetconfDeviceNotificationService.class));
+ verify(netconfDeviceTopologyAdapter,
+ times(1)).updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
}
@Test
verify(mountInstance).publish(domNotification);
}
- private static List<String> getCapabilities() {
+ private static List<String> getCapabilities() {
return Arrays.asList(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
}
private DataBroker dataBroker;
- private ConcurrentDOMDataBroker cDOMDataBroker;
+ private ConcurrentDOMDataBroker concurrentDOMDataBroker;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doReturn(txChain).when(broker).createTransactionChain(any(TransactionChainListener.class));
doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
- doNothing().when(writeTx).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
- doNothing().when(writeTx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ doNothing().when(writeTx)
+ .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ doNothing().when(writeTx)
+ .merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
doReturn(txIdent).when(writeTx).getIdentifier();
ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
16, 16, "CommitFutures");
- cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
+ concurrentDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
final ClassPool pool = ClassPool.getDefault();
final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
+ codecRegistry.onBindingRuntimeContextUpdated(
+ BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
- final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
+ final BindingToNormalizedNodeCodec bindingToNormalized =
+ new BindingToNormalizedNodeCodec(loading, codecRegistry);
bindingToNormalized.onGlobalContextUpdated(schemaContext);
- dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
+ dataBroker = new BindingDOMDataBrokerAdapter(concurrentDOMDataBroker, bindingToNormalized);
transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() {
@Override
- public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction, Throwable cause) {
+ public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction,
+ Throwable cause) {
}
adapter.setDeviceAsFailed(null);
verify(txChain, times(2)).newWriteOnlyTransaction();
- verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ verify(writeTx, times(1))
+ .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
adapter.close();
adapter = new NetconfDeviceTopologyAdapter(id, transactionChain); //not a mock
adapter.setDeviceAsFailed(null);
- Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
+ Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
assertEquals("Netconf node should be presented.", true, netconfNode.isPresent());
- assertEquals("Connection status should be failed.", NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(), netconfNode.get().getConnectionStatus().getName());
+ assertEquals("Connection status should be failed.",
+ NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(),
+ netconfNode.get().getConnectionStatus().getName());
}
adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
verify(txChain, times(2)).newWriteOnlyTransaction();
- verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ verify(writeTx, times(1))
+ .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class));
}
NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, transactionChain);
- QName nTestLeafQname = QName.create("urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
+ QName netconfTestLeafQname = QName.create(
+ "urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
- YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME).
- node(Topology.QNAME).nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf").
- node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test").node(nTestLeafQname).build();
+ YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME)
+ .node(Topology.QNAME)
+ .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf")
+ .node(Node.QNAME)
+ .nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test")
+ .node(netconfTestLeafQname).build();
- NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId).withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(nTestLeafQname)).build();
+ NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId)
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(netconfTestLeafQname)).build();
- DOMDataWriteTransaction writeTx = cDOMDataBroker.newWriteOnlyTransaction();
+ DOMDataWriteTransaction writeTx = concurrentDOMDataBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode);
writeTx.submit();
adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
- Optional<NormalizedNode<?, ?>> testNode = cDOMDataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
+ Optional<NormalizedNode<?, ?>> testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
+ .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
assertEquals("Augmented node data should be still present after device update.", true, testNode.isPresent());
assertEquals("Augmented data should be the same as before update node.", dataTestId, testNode.get().getValue());
adapter.setDeviceAsFailed(null);
- testNode = cDOMDataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
+ testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
+ .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
assertEquals("Augmented node data should be still present after device failed.", true, testNode.isPresent());
- assertEquals("Augmented data should be the same as before failed device.", dataTestId, testNode.get().getValue());
+ assertEquals("Augmented data should be the same as before failed device.",
+ dataTestId, testNode.get().getValue());
}
private List<InputStream> getYangSchemas() {
final List<String> 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");
+ "/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<InputStream> schemas = new ArrayList<>();
for (String schemaPath : schemaPaths) {
}
@Override
- public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+ final SchemaContextListener listener) {
listener.onGlobalContextUpdated(getGlobalContext());
return new ListenerRegistration<SchemaContextListener>() {
@Override
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SchemalessNetconfDeviceRpcTest {
+ private static final Logger LOG = LoggerFactory.getLogger(SchemalessNetconfDeviceRpcTest.class);
+
@Mock
private RemoteDeviceCommunicator<NetconfMessage> listener;
public void testInvokeRpc() throws Exception {
final QName qName = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config");
SchemaPath type = SchemaPath.create(true, qName);
- DOMSource src = new DOMSource(XmlUtil.readXmlToDocument("<get-config xmlns=\"dd\">\n" +
- " <source>\n" +
- " <running/>\n" +
- " </source>\n" +
- " <filter type=\"subtree\">\n" +
- " <mainroot xmlns=\"urn:dummy:mod-0\">\n" +
- " <maincontent/>\n" +
- "<choiceList></choiceList>\n" +
- " </mainroot>\n" +
- " </filter>\n" +
- " </get-config>"));
+ DOMSource src = new DOMSource(XmlUtil.readXmlToDocument("<get-config xmlns=\"dd\">\n"
+ + " <source>\n"
+ + " <running/>\n"
+ + " </source>\n"
+ + " <filter type=\"subtree\">\n"
+ + " <mainroot xmlns=\"urn:dummy:mod-0\">\n"
+ + " <maincontent/>\n"
+ + "<choiceList></choiceList>\n"
+ + " </mainroot>\n"
+ + " </filter>\n"
+ + " </get-config>"));
NormalizedNode<?, ?> input = Builders.anyXmlBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(qName))
.withValue(src)
deviceRpc.invokeRpc(type, input);
ArgumentCaptor<NetconfMessage> msgCaptor = ArgumentCaptor.forClass(NetconfMessage.class);
- ArgumentCaptor<QName> qNameCaptor = ArgumentCaptor.forClass(QName.class);
- verify(listener).sendRequest(msgCaptor.capture(), qNameCaptor.capture());
- System.out.println(XmlUtil.toString(msgCaptor.getValue().getDocument()));
+ ArgumentCaptor<QName> qnameCaptor = ArgumentCaptor.forClass(QName.class);
+ verify(listener).sendRequest(msgCaptor.capture(), qnameCaptor.capture());
+ LOG.info(XmlUtil.toString(msgCaptor.getValue().getDocument()));
}
}
final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, mock(SchemaContext.class)),
false);
final MapNode emptyList = ImmutableNodes.mapNodeBuilder(NETCONF_FILTER_QNAME).build();
- tx.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
- tx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
+ tx.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier
+ .create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
+ tx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier
+ .create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
verify(rpc, atMost(1)).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
}
} catch (final TransactionCommitFailedException e) {
// verify discard changes was sent
final InOrder inOrder = inOrder(rpc);
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), NetconfBaseOps.getLockContent(NETCONF_CANDIDATE_QNAME));
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
- inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)), any(NormalizedNode.class));
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME), NetconfBaseOps.getUnLockContent(NETCONF_CANDIDATE_QNAME));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME),
+ NetconfBaseOps.getLockContent(NETCONF_CANDIDATE_QNAME));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+ NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)),
+ any(NormalizedNode.class));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME),
+ NetconfBaseOps.getUnLockContent(NETCONF_CANDIDATE_QNAME));
return;
}
@Test
public void testFailedCommit() throws Exception {
- final CheckedFuture<DefaultDOMRpcResult, Exception> rpcErrorFuture =
- Futures.immediateCheckedFuture(new DefaultDOMRpcResult(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "a", "m")));
+ final CheckedFuture<DefaultDOMRpcResult, Exception> rpcErrorFuture = Futures.immediateCheckedFuture(
+ new DefaultDOMRpcResult(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "a", "m")));
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(((NormalizedNode<?, ?>) null))))
.doReturn(rpcErrorFuture).when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
.doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("Failed tx")))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteRunningTx tx = new WriteRunningTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()),
- false);
+ final WriteRunningTx tx = new WriteRunningTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()), false);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
tx.submit();
// verify discard changes was sent
final InOrder inOrder = inOrder(rpc);
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), NetconfBaseOps.getLockContent(NETCONF_RUNNING_QNAME));
- inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any(NormalizedNode.class));
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME), NetconfBaseOps.getUnLockContent(NETCONF_RUNNING_QNAME));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME),
+ NetconfBaseOps.getLockContent(NETCONF_RUNNING_QNAME));
+ inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)),
+ any(NormalizedNode.class));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME),
+ NetconfBaseOps.getUnLockContent(NETCONF_RUNNING_QNAME));
}
@Test
public void testListenerSuccess() throws Exception {
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult((NormalizedNode<?, ?>) null)))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+ final WriteCandidateTx tx = new WriteCandidateTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
final TxListener listener = mock(TxListener.class);
tx.addListener(listener);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
public void testListenerCancellation() throws Exception {
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult((NormalizedNode<?, ?>) null)))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+ final WriteCandidateTx tx = new WriteCandidateTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
final TxListener listener = mock(TxListener.class);
tx.addListener(listener);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
final IllegalStateException cause = new IllegalStateException("Failed tx");
doReturn(Futures.immediateFailedCheckedFuture(cause))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+ final WriteCandidateTx tx = new WriteCandidateTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
final TxListener listener = mock(TxListener.class);
tx.addListener(listener);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
public class ReadOnlyTxTest {
- private static final YangInstanceIdentifier path = YangInstanceIdentifier.create();
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.create();
@Mock
private DOMRpcService rpc;
public void testRead() throws Exception {
final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
- final ReadOnlyTx readOnlyTx = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx readOnlyTx =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
readOnlyTx.read(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create());
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
- readOnlyTx.read(LogicalDatastoreType.OPERATIONAL, path);
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
+ readOnlyTx.read(LogicalDatastoreType.OPERATIONAL, PATH);
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
}
@Test
public void testExists() throws Exception {
final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
- final ReadOnlyTx readOnlyTx = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx readOnlyTx =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
readOnlyTx.exists(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create());
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
- readOnlyTx.exists(LogicalDatastoreType.OPERATIONAL, path);
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
+ readOnlyTx.exists(LogicalDatastoreType.OPERATIONAL, PATH);
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
}
@Test
public void testIdentifier() throws Exception {
final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
- final ReadOnlyTx tx1 = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
- final ReadOnlyTx tx2 = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx tx1 =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx tx2 =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
Assert.assertNotEquals(tx1.getIdentifier(), tx2.getIdentifier());
}
}
\ No newline at end of file
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(broker.newReadOnlyTransaction()).thenReturn(readOnlyTx);
- when(broker.newWriteOnlyTransaction()).thenReturn(writeOnlyTx1).thenReturn(writeOnlyTx2).thenReturn(writeOnlyTx3);
+ when(broker.newWriteOnlyTransaction()).thenReturn(writeOnlyTx1)
+ .thenReturn(writeOnlyTx2).thenReturn(writeOnlyTx3);
when(writeOnlyTx1.addListener(any())).thenReturn(registration1);
when(writeOnlyTx2.addListener(any())).thenReturn(registration2);
when(writeOnlyTx3.addListener(any())).thenReturn(registration3);
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+ final SchemaContext schemaContext =
+ YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/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));
public void testSubmit() throws Exception {
final WriteCandidateRunningTx tx = new WriteCandidateRunningTx(id, netconfOps, true);
//check, if lock is called
- final ContainerNode candidateLock = getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
- final ContainerNode runningLock = getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
+ final ContainerNode candidateLock =
+ getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
+ final ContainerNode runningLock =
+ getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), runningLock);
verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), candidateLock);
tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
//check, if both edits are called
- verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, times(2)).invokeRpc(
+ eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
tx.submit().get();
//check, if unlock is called
- verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
- final ContainerNode candidateUnlock = getLockContent(NETCONF_UNLOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
- final ContainerNode runningUnlock = getLockContent(NETCONF_UNLOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
+ verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+ NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ final ContainerNode candidateUnlock = getLockContent(NETCONF_UNLOCK_QNAME,
+ NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
+ final ContainerNode runningUnlock = getLockContent(NETCONF_UNLOCK_QNAME,
+ NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
verify(rpc).invokeRpc(SchemaPath.create(true, NETCONF_UNLOCK_QNAME), candidateUnlock);
verify(rpc).invokeRpc(SchemaPath.create(true, NETCONF_UNLOCK_QNAME), runningUnlock);
}
tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
//check, if both edits are called
- verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, times(2))
+ .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
tx.submit().get();
//check, if unlock is called
- verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+ NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
verify(rpc).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)), any());
}
tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
//check, if no edit-config is called before submit
- verify(rpc, never()).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, never())
+ .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
tx.submit().get();
//check, if both edits are called
- verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, times(2))
+ .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
//check, if unlock is called
verify(rpc).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)), any());
}
CheckedFuture<DOMRpcResult, DOMRpcException> response = Futures.immediateCheckedFuture(value);
doReturn(response).when(service).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- provider = new NetconfRemoteSchemaYangSourceProvider(new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)), service);
+ provider = new NetconfRemoteSchemaYangSourceProvider(
+ new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)), service);
}
@Test
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.of(identifier.getRevision()))
);
}
Element root = xmlDoc.createElement("data");
root.setTextContent("module test {}");
final DOMSource v = new DOMSource(root);
- DataContainerChild<?, ?> child = ImmutableAnyXmlNodeBuilder.create().withNodeIdentifier(childId).withValue(v).build();
+ DataContainerChild<?, ?> child =
+ ImmutableAnyXmlNodeBuilder.create().withNodeIdentifier(childId).withValue(v).build();
return ImmutableContainerNodeBuilder.create().withNodeIdentifier(id).withChild(child).build();
}
XMLUnit.setIgnoreAttributeOrder(true);
}
- private static final String EXP_RPC = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- " <edit-config>\n" +
- " <target>\n" +
- " <candidate/>\n" +
- " </target>\n" +
- " <config>\n" +
- " <top xmlns=\"http://example.com/schema/1.2/config\">\n" +
- " <users xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:operation=\"replace\">\n" +
- " <user>\n" +
- " <name>fred</name>\n" +
- " </user>\n" +
- " </users>\n" +
- " </top>\n" +
- " </config>\n" +
- " </edit-config>\n" +
- "</rpc>\n";
+ private static final String EXP_RPC = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + " <edit-config>\n"
+ + " <target>\n"
+ + " <candidate/>\n"
+ + " </target>\n"
+ + " <config>\n"
+ + " <top xmlns=\"http://example.com/schema/1.2/config\">\n"
+ + " <users xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:operation=\"replace\">\n"
+ + " <user>\n"
+ + " <name>fred</name>\n"
+ + " </user>\n"
+ + " </users>\n"
+ + " </top>\n"
+ + " </config>\n"
+ + " </edit-config>\n"
+ + "</rpc>\n";
BaseRpcSchemalessTransformer transformer;
@Test(expected = UnsupportedOperationException.class)
public void toNotification() throws Exception {
- transformer.toNotification(new NetconfMessage(XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"))));
+ transformer.toNotification(new NetconfMessage(
+ XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"))));
}
@Test
public void toRpcRequest() throws Exception {
- final Document doc = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/edit-config/container.xml"));
+ final Document doc =
+ XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/edit-config/container.xml"));
final AnyXmlNode xml = Builders.anyXmlBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(
+ NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME))
.withValue(new DOMSource(doc.getDocumentElement()))
.build();
final ChoiceNode editContent = Builders.choiceBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(EditContent.QNAME))
.withChild(xml)
.build();
- final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
- .withChild(Builders.leafBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
+ final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
+ .withChild(Builders.leafBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
.build();
final DataContainerChild<?, ?> target = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_TARGET_QNAME))
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_TARGET_QNAME))
.withChild(candidate)
.build();
final ContainerNode editConfig = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME))
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME))
.withChild(editContent)
.withChild(target)
.build();
- final NetconfMessage msg = transformer.toRpcRequest(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), editConfig);
+ final NetconfMessage msg = transformer.toRpcRequest(
+ SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), editConfig);
final Diff diff = XMLUnit.compareXML(EXP_RPC, XmlUtil.toString(msg.getDocument()));
Assert.assertTrue(diff.toString(), diff.similar());
}
@Test
public void toRpcResult() throws Exception {
- final Document doc = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
+ final Document doc = XmlUtil.readXmlToDocument(
+ "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
final InputStream stream = getClass().getResourceAsStream("/schemaless/get-config/container.xml");
final Element dataElement = XmlUtil.readXmlToElement(stream);
final Element element = (Element) doc.importNode(dataElement, true);
doc.getDocumentElement().appendChild(element);
final NetconfMessage msg = new NetconfMessage(doc);
- final DOMRpcResult result = transformer.toRpcResult(msg, SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME));
+ final DOMRpcResult result = transformer.toRpcResult(msg,
+ SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME));
Assert.assertNotNull(result.getResult());
final ContainerNode rpcReply = (ContainerNode) result.getResult();
Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME, rpcReply.getNodeType());
- final Optional dataOpt = rpcReply.getChild(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
+ final Optional dataOpt = rpcReply.getChild(
+ new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
Assert.assertTrue(dataOpt.isPresent());
final AnyXmlNode data = (AnyXmlNode) dataOpt.get();
final Diff diff = XMLUnit.compareXML(dataElement.getOwnerDocument(), (Document) data.getValue().getNode());
@Test
public void testDiscardChangesRequest() throws Exception {
- final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_DISCARD_CHANGES_QNAME), null);
+ final NetconfMessage netconfMessage =
+ netconfMessageTransformer.toRpcRequest(toPath(NETCONF_DISCARD_CHANGES_QNAME), null);
assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("<discard"));
assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("<rpc"));
assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("message-id"));
public void tesGetSchemaRequest() throws Exception {
final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(GET_SCHEMA_QNAME),
NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")));
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<format>yang</format>\n" +
- "<identifier>module</identifier>\n" +
- "<version>2012-12-12</version>\n" +
- "</get-schema>\n" +
- "</rpc>");
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<format>yang</format>\n"
+ + "<identifier>module</identifier>\n"
+ + "<version>2012-12-12</version>\n"
+ + "</get-schema>\n"
+ + "</rpc>");
}
@Test
public void tesGetSchemaResponse() throws Exception {
final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
- "<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<data\n" +
- "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
- "Random YANG SCHEMA\n" +
- "</xs:schema>\n" +
- "</data>\n" +
- "</rpc-reply>"
+ "<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<data\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n"
+ + "Random YANG SCHEMA\n"
+ + "</xs:schema>\n"
+ + "</data>\n"
+ + "</rpc-reply>"
));
- final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
+ final DOMRpcResult compositeNodeRpcResult =
+ netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNotNull(compositeNodeRpcResult.getResult());
- final DOMSource schemaContent = ((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
- assertThat(((Element) schemaContent.getNode()).getTextContent(), CoreMatchers.containsString("Random YANG SCHEMA"));
+ final DOMSource schemaContent =
+ ((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
+ assertThat(((Element) schemaContent.getNode()).getTextContent(),
+ CoreMatchers.containsString("Random YANG SCHEMA"));
}
@Test
public void testGetConfigResponse() throws Exception {
- final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<data>\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<schemas>\n" +
- "<schema>\n" +
- "<identifier>module</identifier>\n" +
- "<version>2012-12-12</version>\n" +
- "<format xmlns:x=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">x:yang</format>\n" +
- "</schema>\n" +
- "</schemas>\n" +
- "</netconf-state>\n" +
- "</data>\n" +
- "</rpc-reply>"));
+ final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<data>\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<schemas>\n"
+ + "<schema>\n"
+ + "<identifier>module</identifier>\n"
+ + "<version>2012-12-12</version>\n"
+ + "<format xmlns:x=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">x:yang</format>\n"
+ + "</schema>\n"
+ + "</schemas>\n"
+ + "</netconf-state>\n"
+ + "</data>\n"
+ + "</rpc-reply>"));
final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
- final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
+ final DOMRpcResult compositeNodeRpcResult =
+ netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNotNull(compositeNodeRpcResult.getResult());
final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> values = Lists.newArrayList(
- NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
+ NetconfRemoteSchemaYangSourceProvider
+ .createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
final Map<QName, Object> keys = Maps.newHashMap();
for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> value : values) {
keys.put(value.getNodeType(), value.getValue());
}
- final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
- final MapEntryNode schemaNode = Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates =
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
+ final MapEntryNode schemaNode =
+ Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
- final ContainerNode data = (ContainerNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getChild(toId(NETCONF_DATA_QNAME)).get();
+ final ContainerNode data = (ContainerNode) ((ContainerNode) compositeNodeRpcResult
+ .getResult()).getChild(toId(NETCONF_DATA_QNAME)).get();
final ContainerNode state = (ContainerNode) data.getChild(toId(NetconfState.QNAME)).get();
final ContainerNode schemas = (ContainerNode) state.getChild(toId(Schemas.QNAME)).get();
final MapNode schemaParent = (MapNode) schemas.getChild(toId(Schema.QNAME)).get();
final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_GET_CONFIG_QNAME),
NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, source, filter));
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<schemas/>\n" +
- "</netconf-state>" +
- "</filter>\n" +
- "<source>\n" +
- "<running/>\n" +
- "</source>\n" +
- "</get-config>" +
- "</rpc>");
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<schemas/>\n"
+ + "</netconf-state>"
+ + "</filter>\n"
+ + "<source>\n"
+ + "<running/>\n"
+ + "</source>\n"
+ + "</get-config>"
+ + "</rpc>");
}
@Test
public void testEditConfigRequest() throws Exception {
final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> values = Lists.newArrayList(
- NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
+ NetconfRemoteSchemaYangSourceProvider
+ .createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
final Map<QName, Object> keys = Maps.newHashMap();
for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> value : values) {
keys.put(value.getNodeType(), value.getValue());
}
- final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
- final MapEntryNode schemaNode = Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates =
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
+ final MapEntryNode schemaNode =
+ Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
- final YangInstanceIdentifier id = YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).node(Schema.QNAME).nodeWithKey(Schema.QNAME, keys).build();
- final DataContainerChild<?, ?> editConfigStructure = createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id, Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
+ final YangInstanceIdentifier id = YangInstanceIdentifier.builder()
+ .node(NetconfState.QNAME).node(Schemas.QNAME).node(Schema.QNAME)
+ .nodeWithKey(Schema.QNAME, keys).build();
+ final DataContainerChild<?, ?> editConfigStructure =
+ createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id,
+ Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
final DataContainerChild<?, ?> target = NetconfBaseOps.getTargetNode(NETCONF_CANDIDATE_QNAME);
- final ContainerNode wrap = NetconfMessageTransformUtil.wrap(NETCONF_EDIT_CONFIG_QNAME, editConfigStructure, target);
- final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_EDIT_CONFIG_QNAME), wrap);
-
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<edit-config>\n" +
- "<target>\n" +
- "<candidate/>\n" +
- "</target>\n" +
- "<config>\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<schemas>\n" +
- "<schema>\n" +
- "<identifier>module</identifier>\n" +
- "<version>2012-12-12</version>\n" +
- "<format>yang</format>\n" +
- "</schema>\n" +
- "</schemas>\n" +
- "</netconf-state>\n" +
- "</config>\n" +
- "</edit-config>\n" +
- "</rpc>");
+ final ContainerNode wrap =
+ NetconfMessageTransformUtil.wrap(NETCONF_EDIT_CONFIG_QNAME, editConfigStructure, target);
+ final NetconfMessage netconfMessage =
+ netconfMessageTransformer.toRpcRequest(toPath(NETCONF_EDIT_CONFIG_QNAME), wrap);
+
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<edit-config>\n"
+ + "<target>\n"
+ + "<candidate/>\n"
+ + "</target>\n"
+ + "<config>\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<schemas>\n"
+ + "<schema>\n"
+ + "<identifier>module</identifier>\n"
+ + "<version>2012-12-12</version>\n"
+ + "<format>yang</format>\n"
+ + "</schema>\n"
+ + "</schemas>\n"
+ + "</netconf-state>\n"
+ + "</config>\n"
+ + "</edit-config>\n"
+ + "</rpc>");
}
private static void assertSimilarXml(final NetconfMessage netconfMessage, final String xmlContent)
final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_GET_QNAME),
NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, filter));
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<capabilities>\n" +
- "<capability>a:b:c</capability>\n" +
- "</capabilities>\n" +
- "</netconf-state>" +
- "</filter>\n" +
- "</get>" +
- "</rpc>");
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
+ + "<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<capabilities>\n"
+ + "<capability>a:b:c</capability>\n"
+ + "</capabilities>\n"
+ + "</netconf-state>"
+ + "</filter>\n"
+ + "</get>"
+ + "</rpc>");
}
private static NetconfMessageTransformer getTransformer(final SchemaContext schema) {
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
"<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><ok/></rpc-reply>"
));
- final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_COMMIT_QNAME));
+ final DOMRpcResult compositeNodeRpcResult =
+ netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_COMMIT_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNull(compositeNodeRpcResult.getResult());
}
public SchemaContext getSchema(final boolean addBase) {
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- if(addBase) {
+ if (addBase) {
moduleInfoBackedContext.addModuleInfos(Collections.singleton($YangModuleInfoImpl.getInstance()));
}
- moduleInfoBackedContext.addModuleInfos(Collections.singleton(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.$YangModuleInfoImpl.getInstance()));
+ moduleInfoBackedContext
+ .addModuleInfos(Collections.singleton(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
+ .netconf.monitoring.rev101004.$YangModuleInfoImpl.getInstance()));
return moduleInfoBackedContext.tryToCreateSchemaContext().get();
}
}
XMLUnit.setIgnoreWhitespace(true);
}
- private static final String EXP_REQUEST = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<test-rpc xmlns=\"test-ns\">\n" +
- "<input>aaa</input>\n" +
- "</test-rpc>\n" +
- "</rpc>";
- private static final String EXP_REPLY = "<rpc-reply message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<output xmlns=\"test-ns\">aaa</output>\n" +
- "</rpc-reply>";
- private static final String OK_REPLY = "<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<ok/>\n" +
- "</rpc-reply>\n";
+ private static final String EXP_REQUEST =
+ "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<test-rpc xmlns=\"test-ns\">\n"
+ + "<input>aaa</input>\n"
+ + "</test-rpc>\n"
+ + "</rpc>";
+ private static final String EXP_REPLY =
+ "<rpc-reply message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<output xmlns=\"test-ns\">aaa</output>\n"
+ + "</rpc-reply>";
+ private static final String OK_REPLY = "<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<ok/>\n"
+ + "</rpc-reply>\n";
private SchemalessMessageTransformer transformer;
private static final QName TEST_RPC = QName.create("test-ns", "2016-10-13", "test-rpc");
final Document payload = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"));
final NetconfMessage netconfMessage = new NetconfMessage(payload);
final DOMNotification domNotification = transformer.toNotification(netconfMessage);
- Assert.assertEquals(domNotification.getType().getLastComponent(), SchemalessMessageTransformer.SCHEMALESS_NOTIFICATION_PAYLOAD.getNodeType());
- final QName qName = QName.create("org:opendaylight:notification:test:ns:yang:user-notification", "user-visited-page");
+ Assert.assertEquals(domNotification.getType().getLastComponent(),
+ SchemalessMessageTransformer.SCHEMALESS_NOTIFICATION_PAYLOAD.getNodeType());
+ final QName qName =
+ QName.create("org:opendaylight:notification:test:ns:yang:user-notification", "user-visited-page");
final AnyXmlNode dataContainerChild =
(AnyXmlNode) domNotification.getBody().getChild(new YangInstanceIdentifier.NodeIdentifier(qName)).get();
final Diff diff = XMLUnit.compareXML(payload, dataContainerChild.getValue().getNode().getOwnerDocument());
@Test
public void toEmptyRpcResult() throws Exception {
final Document doc = XmlUtil.readXmlToDocument(OK_REPLY);
- final DOMRpcResult result = transformer.toRpcResult(new NetconfMessage(doc), SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME));
+ final DOMRpcResult result = transformer.toRpcResult(
+ new NetconfMessage(doc), SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME));
Assert.assertNull(result.getResult());
}
private final SchemalessRpcStructureTransformer adapter = new SchemalessRpcStructureTransformer();
private final String testDataset;
- public SchemalessRpcStructureTransformerTest(YangInstanceIdentifier path, String testDataset, Class<? extends Exception> expectedException) throws IOException, SAXException, URISyntaxException {
+ public SchemalessRpcStructureTransformerTest(
+ YangInstanceIdentifier path, String testDataset,
+ Class<? extends Exception> expectedException) throws IOException, SAXException, URISyntaxException {
this.path = path;
this.testDataset = testDataset;
this.expectedException = expectedException;
- this.source = new DOMSource(XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/data/" + testDataset)).getDocumentElement());
- this.expectedConfig = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/edit-config/" + testDataset).toURI())));
- this.expectedFilter = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/filter/" + testDataset).toURI())));
- this.getConfigData = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/get-config/" + testDataset).toURI())));
+ this.source = new DOMSource(XmlUtil.readXmlToDocument(getClass()
+ .getResourceAsStream("/schemaless/data/" + testDataset)).getDocumentElement());
+ this.expectedConfig = new String(Files.readAllBytes(
+ Paths.get(getClass().getResource("/schemaless/edit-config/" + testDataset).toURI())));
+ this.expectedFilter = new String(Files.readAllBytes(
+ Paths.get(getClass().getResource("/schemaless/filter/" + testDataset).toURI())));
+ this.getConfigData = new String(Files.readAllBytes(
+ Paths.get(getClass().getResource("/schemaless/get-config/" + testDataset).toURI())));
}
@Parameterized.Parameters
{YangInstanceIdentifier.builder()
.node(createNodeId("top"))
.node(createNodeId("users"))
- .node(createListNodeId("user", ImmutableMap.of(QName.create(NAMESPACE, "key1"), "k1", QName.create(NAMESPACE, "key2"), "k2")))
+ .node(createListNodeId("user", ImmutableMap.of(QName.create(NAMESPACE, "key1"), "k1",
+ QName.create(NAMESPACE, "key2"), "k2")))
.build(), "keyed-list-compound-key.xml", null},
{YangInstanceIdentifier.builder()
.node(createNodeId("top"))
@Test
public void testCreateEditConfigStructure() throws Exception {
- if(expectedException != null) {
+ if (expectedException != null) {
thrown.expect(expectedException);
}
AnyXmlNode data = Builders.anyXmlBuilder()
.withNodeIdentifier(createNodeId(path.getLastPathArgument().getNodeType().getLocalName()))
.withValue(source)
.build();
- final AnyXmlNode anyXmlNode = adapter.createEditConfigStructure(Optional.of(data), path, Optional.of(ModifyAction.REPLACE));
+ final AnyXmlNode anyXmlNode =
+ adapter.createEditConfigStructure(Optional.of(data), path, Optional.of(ModifyAction.REPLACE));
final String s = XmlUtil.toString((Element) anyXmlNode.getValue().getNode());
Diff diff = new Diff(expectedConfig, s);
Assert.assertTrue(String.format("Input %s: %s", testDataset, diff.toString()), diff.similar());
return new YangInstanceIdentifier.NodeIdentifier(QName.create(NAMESPACE, name));
}
- private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(String nodeName, String keyName, String id) {
- return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), QName.create(NAMESPACE, keyName), id);
+ private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(
+ String nodeName, String keyName, String id) {
+ return new YangInstanceIdentifier
+ .NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), QName.create(NAMESPACE, keyName), id);
}
- private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(String nodeName, Map<QName, Object> keys) {
+ private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(
+ String nodeName, Map<QName, Object> keys) {
return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), keys);
}
}