<scope>test</scope>
</dependency>
</dependencies>
+
+ <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>
* AuthProvider implementation delegating to AAA CredentialAuth<PasswordCredentials> instance.
*/
public final class CredentialServiceAuthProvider implements AuthProvider, AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(CredentialServiceAuthProvider.class);
+ private static final Logger LOG = LoggerFactory.getLogger(CredentialServiceAuthProvider.class);
/**
- * Singleton instance with delayed instantiation
+ * Singleton instance with delayed instantiation.
*/
public static volatile Map.Entry<BundleContext, CredentialServiceAuthProvider> INSTANCE;
public CredentialServiceAuthProvider(final BundleContext bundleContext) {
- final ServiceTrackerCustomizer<CredentialAuth, CredentialAuth> customizer = new ServiceTrackerCustomizer<CredentialAuth, CredentialAuth>() {
+ final ServiceTrackerCustomizer<CredentialAuth, CredentialAuth> customizer =
+ new ServiceTrackerCustomizer<CredentialAuth, CredentialAuth>() {
@Override
public CredentialAuth addingService(final ServiceReference<CredentialAuth> reference) {
- logger.trace("Credential service {} added", reference);
+ LOG.trace("Credential service {} added", reference);
nullableCredService = bundleContext.getService(reference);
return nullableCredService;
}
@Override
- public void modifiedService(final ServiceReference<CredentialAuth> reference, final CredentialAuth service) {
- logger.trace("Replacing modified Credential service {}", reference);
+ public void modifiedService(final ServiceReference<CredentialAuth> reference,
+ final CredentialAuth service) {
+ LOG.trace("Replacing modified Credential service {}", reference);
nullableCredService = service;
}
@Override
public void removedService(final ServiceReference<CredentialAuth> reference, final CredentialAuth service) {
- logger.trace("Removing Credential service {}. This AuthProvider will fail to authenticate every time", reference);
+ LOG.trace("Removing Credential service {}. "
+ + "This AuthProvider will fail to authenticate every time", reference);
synchronized (CredentialServiceAuthProvider.this) {
nullableCredService = null;
}
}
/**
- * Authenticate user. This implementation tracks CredentialAuth<PasswordCredentials> and delegates the decision to it. If the service is not
- * available, IllegalStateException is thrown.
+ * Authenticate user. This implementation tracks CredentialAuth<PasswordCredentials>
+ * and delegates the decision to it. If the service is not available, IllegalStateException is thrown.
*/
@Override
public synchronized boolean authenticated(final String username, final String password) {
if (nullableCredService == null) {
- logger.warn("Cannot authenticate user '{}', Credential service is missing", username);
+ LOG.warn("Cannot authenticate user '{}', Credential service is missing", username);
throw new IllegalStateException("Credential service is not available");
}
try {
claim = nullableCredService.authenticate(new PasswordCredentialsWrapper(username, password));
} catch (AuthenticationException e) {
- logger.debug("Authentication failed for user '{}' : {}", username, e);
+ LOG.debug("Authentication failed for user '{}' : {}", username, e);
return false;
}
- logger.debug("Authentication result for user '{}' : {}", username, claim.domain());
+ LOG.debug("Authentication result for user '{}' : {}", username, claim.domain());
return true;
}
/**
- * Invoke by blueprint
+ * Invoked by blueprint.
*/
@Override
public void close() {
private final String username;
private final String password;
- public PasswordCredentialsWrapper(final String username, final String password) {
+ PasswordCredentialsWrapper(final String username, final String password) {
this.username = username;
this.password = password;
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.aaa.odl;
import static org.junit.Assert.assertFalse;
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.topology.AbstractNetconfTopology;
import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
protected DOMMountPointService mountPointService = null;
- BaseCallHomeTopology(String topologyId, NetconfClientDispatcher clientDispatcher,
- BindingAwareBroker bindingAwareBroker,
- Broker domBroker,
- EventExecutor eventExecutor,
- ScheduledThreadPool keepaliveExecutor,
- ThreadPool processingExecutor,
- SchemaRepositoryProvider schemaRepositoryProvider,
- DataBroker dataBroker,
- DOMMountPointService mountPointService) {
- super(topologyId, clientDispatcher, bindingAwareBroker, domBroker, eventExecutor, keepaliveExecutor,
- processingExecutor, schemaRepositoryProvider, dataBroker);
+ BaseCallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
+ final EventExecutor eventExecutor,
+ final ScheduledThreadPool keepaliveExecutor,
+ final ThreadPool processingExecutor,
+ final SchemaRepositoryProvider schemaRepositoryProvider,
+ final DataBroker dataBroker,
+ final DOMMountPointService mountPointService) {
+ super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
+ processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService);
this.mountPointService = mountPointService;
}
}
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.callhome.mount.CallHomeMountSessionContext.CloseCallback;
import org.opendaylight.netconf.callhome.protocol.CallHomeChannelActivator;
import org.opendaylight.netconf.callhome.protocol.CallHomeNetconfSubsystemListener;
private final static Logger LOG = LoggerFactory.getLogger(CallHomeMountDispatcher.class);
private final String topologyId;
- private final BindingAwareBroker bindingAwareBroker;
private final EventExecutor eventExecutor;
private final ScheduledThreadPool keepaliveExecutor;
private final ThreadPool processingExecutor;
private final SchemaRepositoryProvider schemaRepositoryProvider;
- private final org.opendaylight.controller.sal.core.api.Broker domBroker;
private final CallHomeMountSessionManager sessionManager;
private final DataBroker dataBroker;
private final DOMMountPointService mountService;
private final CloseCallback onCloseHandler = new CloseCallback() {
@Override
- public void onClosed(CallHomeMountSessionContext deviceContext) {
+ public void onClosed(final CallHomeMountSessionContext deviceContext) {
LOG.info("Removing {} from Netconf Topology.", deviceContext.getId());
topology.disconnectNode(deviceContext.getId());
}
};
- public CallHomeMountDispatcher(String topologyId, BindingAwareBroker bindingAwareBroker,
- EventExecutor eventExecutor,
- ScheduledThreadPool keepaliveExecutor,
- ThreadPool processingExecutor,
- SchemaRepositoryProvider schemaRepositoryProvider,
- Broker domBroker, DataBroker dataBroker,
- DOMMountPointService mountService) {
+ public CallHomeMountDispatcher(final String topologyId,
+ final EventExecutor eventExecutor,
+ final ScheduledThreadPool keepaliveExecutor,
+ final ThreadPool processingExecutor,
+ final SchemaRepositoryProvider schemaRepositoryProvider,
+ final DataBroker dataBroker,
+ final DOMMountPointService mountService) {
this.topologyId = topologyId;
- this.bindingAwareBroker = bindingAwareBroker;
this.eventExecutor = eventExecutor;
this.keepaliveExecutor = keepaliveExecutor;
this.processingExecutor = processingExecutor;
this.schemaRepositoryProvider = schemaRepositoryProvider;
- this.domBroker = domBroker;
this.sessionManager = new CallHomeMountSessionManager();
this.dataBroker = dataBroker;
this.mountService = mountService;
}
@Override
- public Future<NetconfClientSession> createClient(NetconfClientConfiguration clientConfiguration) {
+ public Future<NetconfClientSession> createClient(final NetconfClientConfiguration clientConfiguration) {
return activateChannel(clientConfiguration);
}
@Override
- public Future<Void> createReconnectingClient(NetconfReconnectingClientConfiguration clientConfiguration) {
+ public Future<Void> createReconnectingClient(final NetconfReconnectingClientConfiguration clientConfiguration) {
return activateChannel(clientConfiguration);
}
- private <V> Future<V> activateChannel(NetconfClientConfiguration conf) {
- InetSocketAddress remoteAddr = conf.getAddress();
- CallHomeMountSessionContext context = getSessionManager().getByAddress(remoteAddr);
+ private <V> Future<V> activateChannel(final NetconfClientConfiguration conf) {
+ final InetSocketAddress remoteAddr = conf.getAddress();
+ final CallHomeMountSessionContext context = getSessionManager().getByAddress(remoteAddr);
LOG.info("Activating NETCONF channel for ip {} device context {}", remoteAddr, context);
if (context == null) {
return new FailedFuture<>(eventExecutor, new NullPointerException());
}
void createTopology() {
- this.topology = new CallHomeTopology(topologyId, this, bindingAwareBroker, domBroker, eventExecutor,
+ this.topology = new CallHomeTopology(topologyId, this, eventExecutor,
keepaliveExecutor, processingExecutor, schemaRepositoryProvider, dataBroker, mountService);
}
@Override
- public void onNetconfSubsystemOpened(CallHomeProtocolSessionContext session,
- CallHomeChannelActivator activator) {
- CallHomeMountSessionContext deviceContext = getSessionManager().createSession(session, activator, onCloseHandler);
- NodeId nodeId = deviceContext.getId();
- Node configNode = deviceContext.getConfigNode();
+ public void onNetconfSubsystemOpened(final CallHomeProtocolSessionContext session,
+ final CallHomeChannelActivator activator) {
+ final CallHomeMountSessionContext deviceContext = getSessionManager().createSession(session, activator, onCloseHandler);
+ final NodeId nodeId = deviceContext.getId();
+ final Node configNode = deviceContext.getConfigNode();
LOG.info("Provisioning fake config {}", configNode);
topology.connectNode(nodeId, configNode);
}
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
public class CallHomeTopology extends BaseCallHomeTopology {
- public CallHomeTopology(String topologyId, NetconfClientDispatcher clientDispatcher,
- BindingAwareBroker bindingAwareBroker,
- Broker domBroker, EventExecutor eventExecutor,
- ScheduledThreadPool keepaliveExecutor, ThreadPool processingExecutor,
- SchemaRepositoryProvider schemaRepositoryProvider,
- DataBroker dataBroker, DOMMountPointService mountPointService) {
- super(topologyId, clientDispatcher, bindingAwareBroker, domBroker, eventExecutor,
+ public CallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
+ final EventExecutor eventExecutor,
+ final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor,
+ final SchemaRepositoryProvider schemaRepositoryProvider,
+ final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+ super(topologyId, clientDispatcher, eventExecutor,
keepaliveExecutor, processingExecutor, schemaRepositoryProvider,
dataBroker, mountPointService);
}
@Override
- protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(RemoteDeviceId id,
- Broker domBroker,
- BindingAwareBroker bindingBroker) {
- return new NetconfDeviceSalFacade(id, domBroker, bindingAwareBroker);
+ protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id) {
+ return new NetconfDeviceSalFacade(id, mountPointService, dataBroker);
}
}
xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
odl:use-default-for-reference-types="true">
- <reference id="bindingAwareBroker"
- interface="org.opendaylight.controller.sal.binding.api.BindingAwareBroker"/>
<reference id="keepAliveExecutor"
interface="org.opendaylight.controller.config.threadpool.ScheduledThreadPool"
odl:type="global-netconf-ssh-scheduled-executor"/>
<reference id="processingExecutor"
interface="org.opendaylight.controller.config.threadpool.ThreadPool"
odl:type="global-netconf-processing-executor"/>
- <reference id="domBroker"
- interface="org.opendaylight.controller.sal.core.api.Broker"/>
<reference id="eventExecutor"
interface="io.netty.util.concurrent.EventExecutor"
odl:type="global-event-executor"/>
<bean id="callhomeDispatcher" class="org.opendaylight.netconf.callhome.mount.CallHomeMountDispatcher">
<argument value="topology-netconf"/>
- <argument ref="bindingAwareBroker"/>
<argument ref="eventExecutor"/>
<argument ref="keepAliveExecutor"/>
<argument ref="processingExecutor"/>
<argument ref="schemaRepository"/>
- <argument ref="domBroker"/>
<argument ref="dataBroker"/>
<argument ref="domMountPointService"/>
</bean>
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
-
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.netconf.callhome.protocol.CallHomeChannelActivator;
import org.opendaylight.netconf.callhome.protocol.CallHomeProtocolSessionContext;
public class CallHomeMountDispatcherTest {
private String topologyId;
- private BindingAwareBroker mockBroker;
private EventExecutor mockExecutor;
private ScheduledThreadPool mockKeepAlive;
private ThreadPool mockProcessingExecutor;
private SchemaRepositoryProvider mockSchemaRepoProvider;
- private Broker mockDomBroker;
private CallHomeMountDispatcher instance;
private DataBroker mockDataBroker;
@Before
public void setup() {
topologyId = "";
- mockBroker = mock(BindingAwareBroker.class);
mockExecutor = mock(EventExecutor.class);
mockKeepAlive = mock(ScheduledThreadPool.class);
mockProcessingExecutor = mock(ThreadPool.class);
mockSchemaRepoProvider = mock(SchemaRepositoryProvider.class);
- mockDomBroker = mock(Broker.class);
mockDataBroker = mock(DataBroker.class);
mockMount = mock(DOMMountPointService.class);
mockSessMgr = mock(CallHomeMountSessionManager.class);
mockTopology = mock(CallHomeTopology.class);
mockProtoSess = mock(CallHomeProtocolSessionContext.class);
- instance = new CallHomeMountDispatcher(topologyId, mockBroker, mockExecutor, mockKeepAlive,
- mockProcessingExecutor, mockSchemaRepoProvider, mockDomBroker, mockDataBroker, mockMount) {
+ instance = new CallHomeMountDispatcher(topologyId, mockExecutor, mockKeepAlive,
+ mockProcessingExecutor, mockSchemaRepoProvider, mockDataBroker, mockMount) {
@Override
public CallHomeMountSessionManager getSessionManager() {
return mockSessMgr;
};
}
- NetconfClientConfiguration someConfiguration(InetSocketAddress address) {
+ NetconfClientConfiguration someConfiguration(final InetSocketAddress address) {
// NetconfClientConfiguration has mostly final methods, making it un-mock-able
- NetconfClientConfiguration.NetconfClientProtocol protocol =
+ final NetconfClientConfiguration.NetconfClientProtocol protocol =
NetconfClientConfiguration.NetconfClientProtocol.SSH;
- NetconfHelloMessageAdditionalHeader additionalHeader = mock(NetconfHelloMessageAdditionalHeader.class);
- NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
- ReconnectStrategy reconnectStrategy = mock(ReconnectStrategy.class);
- AuthenticationHandler authHandler = mock(AuthenticationHandler.class);
+ final NetconfHelloMessageAdditionalHeader additionalHeader = mock(NetconfHelloMessageAdditionalHeader.class);
+ final NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
+ final ReconnectStrategy reconnectStrategy = mock(ReconnectStrategy.class);
+ final AuthenticationHandler authHandler = mock(AuthenticationHandler.class);
return NetconfClientConfigurationBuilder.create().withProtocol(protocol).withAddress(address)
.withConnectionTimeoutMillis(0).withAdditionalHeader(additionalHeader)
@Test
public void canCreateASessionFromAConfiguration() {
// given
- CallHomeMountSessionContext mockContext = mock(CallHomeMountSessionContext.class);
- InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
+ final CallHomeMountSessionContext mockContext = mock(CallHomeMountSessionContext.class);
+ final InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
doReturn(mockContext).when(mockSessMgr).getByAddress(eq(someAddress));
- NetconfClientConfiguration someCfg = someConfiguration(someAddress);
+ final NetconfClientConfiguration someCfg = someConfiguration(someAddress);
// when
instance.createClient(someCfg);
// then
@Test
public void noSessionIsCreatedWithoutAContextAvailableForAGivenAddress() {
// given
- InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
- NetconfClientConfiguration someCfg = someConfiguration(someAddress);
+ final InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
+ final NetconfClientConfiguration someCfg = someConfiguration(someAddress);
// when
- Future<NetconfClientSession> future = instance.createClient(someCfg);
+ final Future<NetconfClientSession> future = instance.createClient(someCfg);
// then
assertFalse(future.isSuccess());
}
@Test
public void nodeIsInsertedIntoTopologyWhenSubsystemIsOpened() throws UnknownHostException {
// given
- NodeId mockNodeId = mock(NodeId.class);
- Node mockNode = mock(Node.class);
- CallHomeMountSessionContext mockDevCtxt = mock(CallHomeMountSessionContext.class);
+ final NodeId mockNodeId = mock(NodeId.class);
+ final Node mockNode = mock(Node.class);
+ final CallHomeMountSessionContext mockDevCtxt = mock(CallHomeMountSessionContext.class);
doReturn(mockNodeId).when(mockDevCtxt).getId();
doReturn(mockNode).when(mockDevCtxt).getConfigNode();
doReturn(mockDevCtxt).when(mockSessMgr).createSession(any(CallHomeProtocolSessionContext.class),
any(CallHomeChannelActivator.class), any(CallHomeMountSessionContext.CloseCallback.class));
- CallHomeChannelActivator activator = mock(CallHomeChannelActivator.class);
+ final CallHomeChannelActivator activator = mock(CallHomeChannelActivator.class);
instance.createTopology();
// when
instance.onNetconfSubsystemOpened(mockProtoSess, activator);
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
private static final Logger LOG = LoggerFactory.getLogger(DiscardChanges.class);
- public DiscardChanges(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ public DiscardChanges(final ConfigSubsystemFacade configSubsystemFacade,
+ final String netconfSessionIdForReporting) {
super(configSubsystemFacade, netconfSessionIdForReporting);
}
return DISCARD;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement xml) throws DocumentedException {
fromXml(xml);
try {
getConfigSubsystemFacade().abortConfiguration();
/**
* Simple Lock implementation that pretends to lock candidate datastore.
- * Candidate datastore is allocated per session and is private so no real locking is needed (JMX is the only possible interference)
+ * Candidate datastore is allocated per session and is private so no real locking is needed
+ * (JMX is the only possible interference)
*/
public class Lock extends AbstractLastNetconfOperation {
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
- if(targetDatastore == Datastore.candidate) {
- // Since candidate datastore instances are allocated per session and not accessible anywhere else, no need to lock
+ if (targetDatastore == Datastore.candidate) {
+ // Since candidate datastore instances are allocated per session and not accessible anywhere else,
+ // no need to lock
LOG.debug("Locking {} datastore on session: {}", targetDatastore, getNetconfSessionIdForReporting());
// TODO should this fail if we are already locked ?
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
// Not supported running lock
- throw new DocumentedException("Unable to lock " + Datastore.running + " datastore", DocumentedException.ErrorType.APPLICATION,
+ throw new DocumentedException("Unable to lock " + Datastore.running + " datastore",
+ DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
}
/**
* Simple unlock implementation that pretends to unlock candidate datastore.
- * Candidate datastore is allocated per session and is private so no real locking is needed (JMX is the only possible interference)
+ * Candidate datastore is allocated per session and is private so no real locking is needed
+ * (JMX is the only possible interference)
*/
public class UnLock extends AbstractLastNetconfOperation {
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
- if(targetDatastore == Datastore.candidate) {
- // Since candidate datastore instances are allocated per session and not accessible anywhere else, no need to lock
+ if (targetDatastore == Datastore.candidate) {
+ // Since candidate datastore instances are allocated per session and not accessible anywhere else,
+ // no need to lock
LOG.debug("Unlocking {} datastore on session: {}", targetDatastore, getNetconfSessionIdForReporting());
// TODO this should fail if we are not locked
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
}
// Not supported running lock
- throw new DocumentedException("Unable to unlock " + Datastore.running + " datastore", DocumentedException.ErrorType.APPLICATION,
+ throw new DocumentedException("Unable to unlock " + Datastore.running + " datastore",
+ DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
}
final String datastoreValue = sourceChildNode.getName();
final Datastore sourceDatastore = Datastore.valueOf(datastoreValue);
- if (sourceDatastore != Datastore.candidate){
- throw new DocumentedException( "Only " + Datastore.candidate
- + " is supported as source for " + VALIDATE + " but was " + datastoreValue, ErrorType.APPLICATION, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
+ if (sourceDatastore != Datastore.candidate) {
+ throw new DocumentedException("Only " + Datastore.candidate
+ + " is supported as source for " + VALIDATE + " but was " + datastoreValue, ErrorType.APPLICATION,
+ ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
}
}
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement xml) throws DocumentedException {
checkXml(xml);
try {
getConfigSubsystemFacade().validateConfiguration();
final Map<String, String> errorInfo = new HashMap<>();
errorInfo
.put(ErrorTag.OPERATION_FAILED.name(),
- "Datastore is not present. Use 'get-config' or 'edit-config' before triggering 'operations' operation");
+ "Datastore is not present. "
+ + "Use 'get-config' or 'edit-config' before triggering 'operations' operation");
throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
ErrorSeverity.ERROR, errorInfo);
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
- // FIXME config mapping getter works on dynamic yang store service and so does later executeConfigExecution method
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement xml) throws DocumentedException {
+ // FIXME config mapping getter works on dynamic yang store service
+ // and so does later executeConfigExecution method
// They might have different view of current yangs in ODL and might cause race conditions
final Config cfg = getConfigSubsystemFacade().getConfigMapping();
final ConfigExecution configExecution = editConfigXmlParser.fromXml(xml, cfg);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- XmlElement targetElement = null;
- XmlElement targetChildNode = null;
+ XmlElement targetElement;
+ XmlElement targetChildNode;
targetElement = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
LOG.debug("Setting {} to '{}'", EditConfigXmlParser.TARGET_KEY, targetDatastore);
// check target
- if (targetDatastore != Datastore.candidate){
+ if (targetDatastore != Datastore.candidate) {
throw new DocumentedException(String.format(
"Only %s datastore supported for edit config but was: %s",
Datastore.candidate,
.getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.ERROR_OPTION_KEY);
if (errorOptionElement.isPresent()) {
final String errorOptionParsed = errorOptionElement.get().getTextContent();
- if (!errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION)){
+ if (!errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION)) {
throw new UnsupportedOperationException("Only " + EditConfigXmlParser.DEFAULT_ERROR_OPTION
+ " supported for " + EditConfigXmlParser.ERROR_OPTION_KEY + ", was " + errorOptionParsed);
}
editStrategyType = EditStrategyType.valueOf(mergeStrategyString);
}
- XmlElement configElement = null;
+ XmlElement configElement;
configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
return new ConfigExecution(cfgMapping, configElement, testOption, editStrategyType);
private static final Logger LOG = LoggerFactory.getLogger(GetConfig.class);
- public GetConfig(final ConfigSubsystemFacade configSubsystemFacade, final Optional<String> maybeNamespace, final String netconfSessionIdForReporting) {
+ public GetConfig(final ConfigSubsystemFacade configSubsystemFacade, final Optional<String> maybeNamespace,
+ final String netconfSessionIdForReporting) {
super(configSubsystemFacade, netconfSessionIdForReporting);
this.maybeNamespace = maybeNamespace;
}
final Optional<XmlElement> contextInstanceElement = operationElement
.getOnlyChildElementOptionally(RpcFacade.CONTEXT_INSTANCE);
- if (!contextInstanceElement.isPresent()){
+ if (!contextInstanceElement.isPresent()) {
return HandlingPriority.CANNOT_HANDLE;
}
execution.getAttributes());
final Object result = getConfigSubsystemFacade().getRpcFacade().executeOperation(execution);
- LOG.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.getOperationName(),
- execution.getOn(), execution.getAttributes(), result);
+ LOG.trace("Operation {} called successfully on {} with arguments {} with result {}",
+ execution.getOperationName(), execution.getOn(), execution.getAttributes(), result);
if (execution.isVoid()) {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
@Override
public void start(final BundleContext context) throws Exception {
- ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
+ ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory,
+ ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer =
+ new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
@Override
- public ConfigSubsystemFacadeFactory addingService(ServiceReference<ConfigSubsystemFacadeFactory> reference) {
+ public ConfigSubsystemFacadeFactory addingService(
+ ServiceReference<ConfigSubsystemFacadeFactory> reference) {
LOG.debug("Got addingService(SchemaContextProvider) event");
// Yang store service should not be registered multiple times
- ConfigSubsystemFacadeFactory configSubsystemFacade = reference.getBundle().getBundleContext().getService(reference);
+ ConfigSubsystemFacadeFactory configSubsystemFacade =
+ reference.getBundle().getBundleContext().getService(reference);
osgiRegistration = startNetconfServiceFactory(configSubsystemFacade, context);
return configSubsystemFacade;
}
@Override
- public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+ public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference,
+ ConfigSubsystemFacadeFactory service) {
LOG.warn("Config manager facade was modified unexpectedly");
}
@Override
- public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+ public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference,
+ ConfigSubsystemFacadeFactory service) {
LOG.warn("Config manager facade was removed unexpectedly");
}
};
}
}
- private ServiceRegistration<NetconfOperationServiceFactory> startNetconfServiceFactory(final ConfigSubsystemFacadeFactory configSubsystemFacade, final BundleContext context) {
- final NetconfOperationServiceFactoryImpl netconfOperationServiceFactory = new NetconfOperationServiceFactoryImpl(configSubsystemFacade);
+ private ServiceRegistration<NetconfOperationServiceFactory> startNetconfServiceFactory(
+ final ConfigSubsystemFacadeFactory configSubsystemFacade, final BundleContext context) {
+ final NetconfOperationServiceFactoryImpl netconfOperationServiceFactory =
+ new NetconfOperationServiceFactoryImpl(configSubsystemFacade);
// Add properties to autowire with netconf-impl instance for cfg subsystem
final Dictionary<String, String> properties = new Hashtable<>();
properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.CONFIG_NETCONF_CONNECTOR);
- return context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
+ return context.registerService(NetconfOperationServiceFactory.class,
+ netconfOperationServiceFactory, properties);
}
}
final class NetconfOperationProvider {
private final Set<NetconfOperation> operations;
- NetconfOperationProvider(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ NetconfOperationProvider(final ConfigSubsystemFacade configSubsystemFacade,
+ final String netconfSessionIdForReporting) {
operations = setUpOperations(configSubsystemFacade, netconfSessionIdForReporting);
}
@Override
public NetconfOperationServiceImpl createService(String netconfSessionIdForReporting) {
- return new NetconfOperationServiceImpl(configFacadeFactory.createFacade(netconfSessionIdForReporting), netconfSessionIdForReporting);
+ return new NetconfOperationServiceImpl(configFacadeFactory.createFacade(netconfSessionIdForReporting),
+ netconfSessionIdForReporting);
}
@Override
private static final String INSTANCE_NAME = "instance-from-code";
private static final String NETCONF_SESSION_ID = "foo";
- private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
+ private static final String TEST_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
private NetconfTestImplModuleFactory factory;
private DepTestImplModuleFactory factory2;
private IdentityTestModuleFactory factory3;
@Override
public String fromYang(final String enumType, final String enumYangValue) {
return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
- "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping());
+ "Unable to resolve enum value %s, for enum %s with mappings %s",
+ enumYangValue, enumType, getEnumMapping());
}
@Override
public String toYang(final String enumType, final String enumYangValue) {
return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
- "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping().inverse());
+ "Unable to resolve enum value %s, for enum %s with mappings %s",
+ enumYangValue, enumType, getEnumMapping().inverse());
}
}).when(this.yangStoreSnapshot).getEnumResolver();
factory4 = new TestImplModuleFactory();
doNothing().when(sessionCloseable).close();
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
- this.factory3, factory4));
+ super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory,
+ this.factory2, this.factory3, factory4));
transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
- configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot, "mapping-test");
+ configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot,
+ "mapping-test");
}
- private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
+ private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException,
+ InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
setModule(mxBean, transaction, instanceName + "_dep");
- int i = 1;
- for (final Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
- final ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
+ int index = 1;
+ for (final Class<? extends AbstractServiceInterface> serviceInterface :
+ factory.getImplementedServiceIntefaces()) {
+ final ServiceInterfaceAnnotation annotation =
+ serviceInterface.getAnnotation(ServiceInterfaceAnnotation.class);
transaction.saveServiceReference(
- transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
- on);
+ transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()),
+ "ref_from_code_to_" + instanceName + "_" + index++, on);
}
transaction.commit();
@Override
public void testText(final Text text) throws NodeTestException {
- if(text.getData().equals("ref_dep2")) {
+ if (text.getData().equals("ref_dep2")) {
defaultRefNameCount++;
- } else if(text.getData().equals("ref_dep_user_two")) {
+ } else if (text.getData().equals("ref_dep_user_two")) {
userRefNameCount++;
}
}
nt.performTest(tester, Node.TEXT_NODE);
}
- private static void assertCorrectServiceNames(final Document configCandidate, final Set<String> refNames) throws NodeTestException {
+ private static void assertCorrectServiceNames(final Document configCandidate,
+ final Set<String> refNames) throws NodeTestException {
final Set<String> refNames2 = new HashSet<>(refNames);
final NodeList servicesNodes = configCandidate.getElementsByTagName("services");
assertEquals(1, servicesNodes.getLength());
@Override
public void testElement(final Element element) throws NodeTestException {
- if(element.getNodeName() != null) {
- if(element.getNodeName().equals("name")) {
+ if (element.getNodeName() != null) {
+ if (element.getNodeName().equals("name")) {
final String elmText = element.getTextContent();
- if(refNames2.contains(elmText)) {
+ if (refNames2.contains(elmText)) {
refNames2.remove(elmText);
} else {
throw new NodeTestException("Unexpected services defined: " + elmText);
edit("netconfMessages/editConfig.xml");
commit();
Document response = getConfigRunning();
- final Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
- assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
+ final Element ipElement = readXmlToElement(
+ "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
+ assertContainsElement(response, readXmlToElement(
+ "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
- assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
+ assertContainsElement(response, readXmlToElement("<union-test-attr xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
edit("netconfMessages/editConfig_setUnions.xml");
commit();
response = getConfigRunning();
- assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
- assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
+ assertContainsElement(response, readXmlToElement(
+ "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
+ assertContainsElement(response, readXmlToElement("<union-test-attr xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">"
+ + "randomStringForUnion</union-test-attr>"));
}
commit();
assertXMLEqual(getConfigCandidate(), getConfigRunning());
- final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
+ final Document expectedResult =
+ XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
XMLUnit.setIgnoreWhitespace(true);
assertXMLEqual(expectedResult, getConfigRunning());
assertXMLEqual(expectedResult, getConfigCandidate());
}
private static void checkBigDecimal(final Document response) throws NodeTestException, SAXException, IOException {
- assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
+ assertContainsElement(response, readXmlToElement("<sleep-factor xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
// Default
- assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
+ assertContainsElement(response, readXmlToElement("<sleep-factor xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
}
private void closeSession() throws ParserConfigurationException, SAXException,
executeOp(commitOp, "netconfMessages/commit.xml");
}
- private static Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+ private static Document lockCandidate() throws ParserConfigurationException, SAXException, IOException,
+ DocumentedException {
final Lock commitOp = new Lock(NETCONF_SESSION_ID);
return executeOp(commitOp, "netconfMessages/lock.xml");
}
- private static Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+ private static Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException,
+ DocumentedException {
final UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
return executeOp(commitOp, "netconfMessages/unlock.xml");
}
private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
DocumentedException {
- final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(), NETCONF_SESSION_ID);
+ final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(),
+ NETCONF_SESSION_ID);
return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
}
private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
DocumentedException {
- final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(), NETCONF_SESSION_ID);
+ final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(),
+ NETCONF_SESSION_ID);
return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
}
public void testUnrecognisedConfigElements() throws Exception {
final String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
- final int TESTS_COUNT = 8;
+ final int testsCount = 8;
- for (int i = 0; i < TESTS_COUNT; i++) {
+ for (int i = 0; i < testsCount; i++) {
final String file = String.format(format, i + 1);
LOG.info("Reading {}", file);
try {
return executeOp(discardOp, "netconfMessages/discardChanges.xml");
}
- private static void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
- assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
- assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
+ private static void checkBinaryLeafEdited(final Document response)
+ throws NodeTestException, SAXException, IOException {
+ assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
+ assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
}
private static void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
- assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
+ assertContainsElement(response, readXmlToElement(
+ "<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
// Default
- assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
+ assertContainsElement(response, readXmlToElement(
+ "<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
- assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
+ assertContainsElement(response, readXmlToElement("<extended-twice xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
// Default
- assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
+ assertContainsElement(response, readXmlToElement("<extended-twice xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
- assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
+ assertContainsElement(response, readXmlToElement("<extended-enum xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
// Default
- assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
+ assertContainsElement(response, readXmlToElement("<extended-enum xmlns="
+ + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
}
private static void assertContainsString(final String string, final String substring) {
}
private static String getXpathForNetconfImplSubnode(final String instanceName, final String subnode) {
- return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
- "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
- "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
- "/urn:opendaylight:params:xml:ns:yang:controller:config:module" +
- "[urn:opendaylight:params:xml:ns:yang:controller:config:name='" + instanceName + "']" +
- "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
- "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:" + subnode;
+ return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply"
+ + "/urn:ietf:params:xml:ns:netconf:base:1.0:data"
+ + "/urn:opendaylight:params:xml:ns:yang:controller:config:modules"
+ + "/urn:opendaylight:params:xml:ns:yang:controller:config:module"
+ + "[urn:opendaylight:params:xml:ns:yang:controller:config:name='" + instanceName + "']"
+ + "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf"
+ + "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:" + subnode;
}
private static void checkTypeConfigAttribute(final Document response) throws Exception {
"test2", "default-string");
for (final Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
- getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
+ getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(), "type"),
response);
}
}
final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(yangDependencies);
final YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
- @Override public SchemaContext getSchemaContext() {
+ @Override
+ public SchemaContext getSchemaContext() {
return schemaContext;
}
}, mock(SchemaSourceProvider.class));
assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
assertEquals(8 * 4, getElementsSize(response, "deep3"));
assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
- assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
+ assertEquals(8, getElementsSize(response, "inner-running-data-additional",
+ "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
assertEquals(8, getElementsSize(response, "deep4"));
// TODO assert keys
return response.getElementsByTagNameNS(namespace, elementName).getLength();
}
- private static Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
+ private static Document executeOp(final NetconfOperation op,
+ final String filename) throws ParserConfigurationException,
SAXException, IOException, DocumentedException {
final Document request = XmlFileLoader.xmlFileToDocument(filename);
private List<InputStream> getYangs() {
final List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
- "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
- "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
+ "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
+ "/META-INF/yang/test-types.yang", "/META-INF/yang/test-groups.yang",
+ "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
final Collection<InputStream> yangDependencies = new ArrayList<>();
for (final String path : paths) {
final InputStream is = Preconditions
return Lists.newArrayList(yangDependencies);
}
- private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, final String depName)
+ private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction,
+ final String depName)
throws InstanceAlreadyExistsException, InstanceNotFoundException {
mxBean.setSimpleInt((long) 44);
- mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
+ mxBean.setBinaryLeaf(new byte[]{8, 7, 9});
final DtoD dtob = getDtoD();
mxBean.setDtoD(dtob);
//
p2.setCoreSize(44L);
p2.setPort("port23");
p2.setSimpleInt3(456);
- mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
+ mxBean.setPeers(Lists.<Peers>newArrayList(p1, p2));
// //
mxBean.setSimpleLong(454545L);
mxBean.setSimpleLong2(44L);
mxBean.setSimpleShort(new Short((short) 4));
mxBean.setSimpleTest(545);
- mxBean.setComplexList(Lists.<ComplexList> newArrayList());
- mxBean.setSimpleList(Lists.<Integer> newArrayList());
+ mxBean.setComplexList(Lists.<ComplexList>newArrayList());
+ mxBean.setSimpleList(Lists.<Integer>newArrayList());
final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
- int i = 1;
- for (final Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
- final ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
+ int index = 1;
+ for (final Class<? extends AbstractServiceInterface> serviceInterface :
+ factory2.getImplementedServiceIntefaces()) {
+ final ServiceInterfaceAnnotation annotation =
+ serviceInterface.getAnnotation(ServiceInterfaceAnnotation.class);
transaction.saveServiceReference(
- transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
- testingDepOn);
+ transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()),
+ "ref_from_code_to_" + depName + "_" + index++, testingDepOn);
}
mxBean.setTestingDep(testingDepOn);
EditConfig edit = new EditConfig(cfgFacade, ValidateTest.NETCONF_SESSION_ID_FOR_REPORTING);
EditConfigStrategy editStrat = mock(EditConfigStrategy.class);
- doNothing().when(editStrat).executeConfiguration(anyString(), anyString(), anyMapOf(String.class, AttributeConfigElement.class),
+ doNothing().when(editStrat).executeConfiguration(anyString(), anyString(), anyMapOf(String.class,
+ AttributeConfigElement.class),
any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
ConfigExecution editConfigExecution = mockExecution(editStrat);
verify(provider).getOrCreateTransaction();
// For every instance execute strat
- verify(editStrat, times(2/* Test */+ 2/* Set */ + 2/*Handle missing instance Test*/ + 2 /*Handle missing instance Set*/)).executeConfiguration(anyString(),
+ verify(editStrat, times(2/* Test */ + 2/* Set */ + 2/*Handle missing instance Test*/
+ + 2 /*Handle missing instance Set*/)).executeConfiguration(anyString(),
anyString(), anyMapOf(String.class, AttributeConfigElement.class),
any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
}
}
private Object getMappingDefinition(EditConfigStrategy editStrat) {
- Map<String, Multimap<String, ModuleElementDefinition>> result = Maps.newHashMap();
+ final Map<String, Multimap<String, ModuleElementDefinition>> result = Maps.newHashMap();
Multimap<String, ModuleElementDefinition> innerMultimap = HashMultimap.create();
Map<String, AttributeConfigElement> attributes = getSimpleAttributes();
}
private Map<String, Multimap<String, ModuleElementResolved>> getMapping(EditConfigStrategy editStrat) {
- Map<String, Multimap<String, ModuleElementResolved>> result = Maps.newHashMap();
+ final Map<String, Multimap<String, ModuleElementResolved>> result = Maps.newHashMap();
Multimap<String, ModuleElementResolved> innerMultimap = HashMultimap.create();
Map<String, AttributeConfigElement> attributes = getSimpleAttributes();
}
static Map<String, AttributeConfigElement> getSimpleAttributes() {
- Map<String, AttributeConfigElement> attributes = Maps.newHashMap();
+ final Map<String, AttributeConfigElement> attributes = Maps.newHashMap();
AttributeConfigElement ace1 = mock(AttributeConfigElement.class);
doReturn("abcd").when(ace1).getResolvedDefaultValue();
- doReturn(Optional.<String> of("abc")).when(ace1).getResolvedValue();
+ doReturn(Optional.<String>of("abc")).when(ace1).getResolvedValue();
doReturn("mockedAce1").when(ace1).toString();
doReturn("jmxNameAce1").when(ace1).getJmxName();
attributes.put("a1", ace1);
import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
public class MergeEditConfigStrategyTest extends AbstractConfigTest {
- private static final MultipleDependenciesModuleFactory factory = new MultipleDependenciesModuleFactory();
+ private static final MultipleDependenciesModuleFactory FACTORY = new MultipleDependenciesModuleFactory();
+ private static final String FACTORY_NAME = FACTORY.getImplementationName();
public static final String PARENT = "parent";
public static final String D1 = "d1";
public static final String D2 = "d2";
public static final String D3 = "d3";
- private static final String factoryName = factory.getImplementationName();
-
@Before
public void setUp() throws Exception {
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));
+ super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORY));
ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName d1 = transaction.createModule(factoryName, D1);
- ObjectName d2 = transaction.createModule(factoryName, D2);
- ObjectName parent = transaction.createModule(factoryName, PARENT);
+ ObjectName d1 = transaction.createModule(FACTORY_NAME, D1);
+ ObjectName d2 = transaction.createModule(FACTORY_NAME, D2);
+ ObjectName parent = transaction.createModule(FACTORY_NAME, PARENT);
MultipleDependenciesModuleMXBean multipleDependenciesModuleMXBean = transaction.newMXBeanProxy(parent,
MultipleDependenciesModuleMXBean.class);
multipleDependenciesModuleMXBean.setTestingDeps(asList(d1, d2));
- transaction.createModule(factoryName, D3);
+ transaction.createModule(FACTORY_NAME, D3);
transaction.commit();
}
@Test
public void testMergingOfObjectNames() throws Exception {
- MergeEditConfigStrategy strategy = new MergeEditConfigStrategy();
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+ final MergeEditConfigStrategy strategy = new MergeEditConfigStrategy();
+ final ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
// add D3
AttributeConfigElement attributeConfigElement = mock(AttributeConfigElement.class);
- doReturn(Optional.of(new ObjectName[] {createReadOnlyModuleON(factoryName, D3)})).when(attributeConfigElement).getResolvedValue();
+ doReturn(Optional.of(new ObjectName[] {createReadOnlyModuleON(FACTORY_NAME, D3)}))
+ .when(attributeConfigElement).getResolvedValue();
doReturn("mocked").when(attributeConfigElement).toString();
String attributeName = MultipleDependenciesModule.testingDepsJmxAttribute.getAttributeName();
doReturn(attributeName).when(attributeConfigElement).getJmxName();
attributeName,
attributeConfigElement);
- strategy.executeConfiguration(factoryName, PARENT, configuration, transaction,
+ strategy.executeConfiguration(FACTORY_NAME, PARENT, configuration, transaction,
mock(ServiceRegistryWrapper.class));
transaction.commit();
// parent's attribute should contain d1,d2,d3
MultipleDependenciesModuleMXBean proxy = configRegistryClient.newMXBeanProxy(
- createReadOnlyModuleON(factoryName, PARENT),
+ createReadOnlyModuleON(FACTORY_NAME, PARENT),
MultipleDependenciesModuleMXBean.class);
List<ObjectName> testingDeps = proxy.getTestingDeps();
- List<ObjectName> expected = asList(createReadOnlyModuleON(factoryName, D1),
- createReadOnlyModuleON(factoryName, D2),
- createReadOnlyModuleON(factoryName, D3));
+ List<ObjectName> expected = asList(createReadOnlyModuleON(FACTORY_NAME, D1),
+ createReadOnlyModuleON(FACTORY_NAME, D2),
+ createReadOnlyModuleON(FACTORY_NAME, D3));
assertEquals(expected, testingDeps);
}
}
<artifactId>yang-test-util</artifactId>
</dependency>
</dependencies>
-
+
+ <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>
\ No newline at end of file
/**
* Listens for updates on global schema context, transforms context to ietf-yang-library:modules-state and
- * writes this state to operational data store
+ * writes this state to operational data store.
*/
// TODO Implement also yang-library-change notfication
public class SchemaServiceToMdsalWriter implements SchemaContextListener, AutoCloseable {
}
/**
- * Invoke by blueprint
+ * Invoked by blueprint.
*/
public void start() {
schemaService.registerSchemaContextListener(this);
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Failed to update modules state", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Failed to update modules state", throwable);
}
});
}
private ModulesState createModuleStateFromModules(final Set<Module> modules) {
final ModulesStateBuilder modulesStateBuilder = new ModulesStateBuilder();
- final List<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module> moduleList =
+ final List<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list
+ .Module> moduleList =
Lists.newArrayList();
for (final Module module : modules) {
moduleList.add(createModuleEntryFromModule(module));
}
- return modulesStateBuilder.setModule(moduleList).setModuleSetId(String.valueOf(moduleSetId.getAndIncrement())).build();
+ return modulesStateBuilder.setModule(moduleList).setModuleSetId(String.valueOf(moduleSetId.getAndIncrement()))
+ .build();
}
- private org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module createModuleEntryFromModule(final Module module) {
+ private org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module
+ createModuleEntryFromModule(final Module module) {
final ModuleBuilder moduleBuilder = new ModuleBuilder();
// TODO Conformance type is always set to Implement value, but it should it really be like this?
submodulesList.add(subModuleEntryBuilder.build());
}
- return new SubmodulesBuilder().setSubmodule(submodulesList).build();
+ return new SubmodulesBuilder().setSubmodule(submodulesList).build();
}
}
when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
doNothing().when(writeTransaction).put(eq(LogicalDatastoreType.OPERATIONAL), any(), any());
when(writeTransaction.submit()).thenReturn(Futures.immediateCheckedFuture(null));
- when(schemaService.registerSchemaContextListener(any())).thenReturn(new ListenerRegistration<SchemaContextListener>() {
- @Override
- public void close() {
-
- }
-
- @Override
- public SchemaContextListener getInstance() {
- return null;
- }
- });
+ when(schemaService.registerSchemaContextListener(any())).thenReturn(
+ new ListenerRegistration<SchemaContextListener>() {
+ @Override
+ public void close() {
+
+ }
+
+ @Override
+ public SchemaContextListener getInstance() {
+ return null;
+ }
+ });
schemaServiceToMdsalWriter = new SchemaServiceToMdsalWriter(schemaService, dataBroker);
}
schemaServiceToMdsalWriter.start();
schemaServiceToMdsalWriter.onGlobalContextUpdated(getSchema());
- verify(writeTransaction).put(eq(LogicalDatastoreType.OPERATIONAL), eq(MODULES_STATE_INSTANCE_IDENTIFIER), eq(createTestModuleState()));
+ verify(writeTransaction).put(eq(LogicalDatastoreType.OPERATIONAL),
+ eq(MODULES_STATE_INSTANCE_IDENTIFIER), eq(createTestModuleState()));
}
private SchemaContext getSchema() throws Exception {
.setSubmodules(new SubmodulesBuilder().setSubmodule(Lists.newArrayList(sub)).build())
.setConformanceType(Module.ConformanceType.Implement)
.build();
- return new ModulesStateBuilder().setModuleSetId("0")
+ return new ModulesStateBuilder().setModuleSetId("0")
.setModule(Lists.newArrayList(module)).build();
}
}
\ No newline at end of file
<artifactId>mockito-configuration</artifactId>
</dependency>
</dependencies>
+
+ <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>
private final NetconfMessage startExiMessage;
public NetconfClientSessionPreferences(final NetconfHelloMessage helloMessage,
- final NetconfMessage startExiMessage) {
+ final NetconfMessage startExiMessage) {
super(helloMessage);
this.startExiMessage = startExiMessage;
}
/**
+ * Getter for {@code NetconfMessage}.
+ *
* @return the startExiMessage
*/
public NetconfMessage getStartExiMessage() {
super(message);
}
- public NetconfDeserializerException(final String message, final Exception e) {
- super(message, e);
+ public NetconfDeserializerException(final String message, final Exception exception) {
+ super(message, exception);
}
}
super(message);
}
- public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
super(message, errorType, errorTag, errorSeverity);
}
- public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
super(message, errorType, errorTag, errorSeverity, errorInfo);
}
- public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
super(message, cause, errorType, errorTag, errorSeverity);
}
- public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity,
+ final Map<String, String> errorInfo) {
super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
}
- public NetconfDocumentedException(DocumentedException e) {
- super(e.getMessage(), (Exception) e.getCause(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+ public NetconfDocumentedException(DocumentedException exception) {
+ super(exception.getMessage(), (Exception) exception.getCause(), exception.getErrorType(),
+ exception.getErrorTag(), exception.getErrorSeverity(), exception.getErrorInfo());
}
- public static NetconfDocumentedException fromXMLDocument( Document fromDoc) {
+ public static NetconfDocumentedException fromXMLDocument(Document fromDoc) {
return new NetconfDocumentedException(DocumentedException.fromXMLDocument(fromDoc));
}
}
package org.opendaylight.netconf.api;
/**
- * Session capable of exi communication according to http://tools.ietf.org/html/draft-varga-netconf-exi-capability-02
+ * Session capable of exi communication according to http://tools.ietf.org/html/draft-varga-netconf-exi-capability-02.
*/
public interface NetconfExiSession {
/**
- * Start exi communication with parameters included in start-exi message
+ * Start exi communication with parameters included in start-exi message.
+ *
* @param startExiMessage start exi message
*/
void startExiCommunication(NetconfMessage startExiMessage);
/**
- * Stop exi communication, initiated by stop-exi message
+ * Stop exi communication, initiated by stop-exi message.
*/
void stopExiCommunication();
}
private final long sessionId;
- public NetconfServerSessionPreferences(final NetconfHelloMessage helloMessage,
- long sessionId) {
+ public NetconfServerSessionPreferences(final NetconfHelloMessage helloMessage, long sessionId) {
super(helloMessage);
this.sessionId = sessionId;
}
import org.opendaylight.protocol.framework.SessionListener;
-public interface NetconfSessionListener<S extends NetconfSession> extends SessionListener<NetconfMessage, S, NetconfTerminationReason> {
+public interface NetconfSessionListener
+ <S extends NetconfSession> extends SessionListener<NetconfMessage, S, NetconfTerminationReason> {
}
}
/**
+ * Getter for {@code NetconfHelloMessage}.
+ *
* @return the helloMessage
*/
public NetconfHelloMessage getHelloMessage() {
import org.w3c.dom.Element;
/**
- * NetconfMessage that can carry additional header with session metadata. See {@link NetconfHelloMessageAdditionalHeader}
+ * NetconfMessage that can carry additional header with session metadata.
+ * See {@link NetconfHelloMessageAdditionalHeader}
*/
public final class NetconfHelloMessage extends NetconfMessage {
private final NetconfHelloMessageAdditionalHeader additionalHeader;
- public NetconfHelloMessage(Document doc, NetconfHelloMessageAdditionalHeader additionalHeader) throws NetconfDocumentedException {
+ public NetconfHelloMessage(Document doc, NetconfHelloMessageAdditionalHeader additionalHeader)
+ throws NetconfDocumentedException {
super(doc);
checkHelloMessage(doc);
this.additionalHeader = additionalHeader;
}
public Optional<NetconfHelloMessageAdditionalHeader> getAdditionalHeader() {
- return additionalHeader== null ? Optional.<NetconfHelloMessageAdditionalHeader>absent() : Optional.of(additionalHeader);
+ return additionalHeader == null ? Optional.<NetconfHelloMessageAdditionalHeader>absent()
+ : Optional.of(additionalHeader);
}
private static void checkHelloMessage(Document doc) {
}
public static NetconfHelloMessage createClientHello(Iterable<String> capabilities,
- Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) throws NetconfDocumentedException {
+ Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) throws NetconfDocumentedException {
Document doc = createHelloMessageDoc(capabilities);
return additionalHeaderOptional.isPresent() ? new NetconfHelloMessage(doc, additionalHeaderOptional.get())
: new NetconfHelloMessage(doc);
return doc;
}
- public static NetconfHelloMessage createServerHello(Set<String> capabilities, long sessionId) throws NetconfDocumentedException {
+ public static NetconfHelloMessage createServerHello(Set<String> capabilities, long sessionId)
+ throws NetconfDocumentedException {
Document doc = createHelloMessageDoc(capabilities);
Element sessionIdElement = doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
XmlNetconfConstants.SESSION_ID);
XmlElement element = XmlElement.fromDomElement(document.getDocumentElement());
try {
// accept even if hello has no namespace
- return element.getName().equals(HELLO_TAG) &&
- (!element.hasNamespace() || element.getNamespace().equals(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ return element.getName().equals(HELLO_TAG)
+ && (!element.hasNamespace()
+ || element.getNamespace().equals(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
} catch (DocumentedException e) {
// Cannot happen, since we check for hasNamespace
throw new IllegalStateException(e);
private final String transport;
private final String sessionIdentifier;
- public NetconfHelloMessageAdditionalHeader(String userName, String hostAddress, String port, String transport, String sessionIdentifier) {
+ public NetconfHelloMessageAdditionalHeader(String userName, String hostAddress, String port,
+ String transport, String sessionIdentifier) {
this.userName = userName;
this.hostAddress = hostAddress;
this.port = port;
}
/**
- * Format additional header into a string suitable as a prefix for netconf hello message
+ * Format additional header into a string suitable as a prefix for netconf hello message.
*/
public String toFormattedString() {
Preconditions.checkNotNull(userName);
private static final Pattern PATTERN = Pattern
.compile("\\[(?<username>[^;]+);(?<address>.+)[:/](?<port>[0-9]+);(?<transport>[a-z]+)[^\\]]+\\]");
private static final Pattern CUSTOM_HEADER_PATTERN = Pattern
- .compile("\\[(?<username>[^;]+);(?<address>.+)[:/](?<port>[0-9]+);(?<transport>[a-z]+);(?<sessionIdentifier>[a-z]+)[^\\]]+\\]");
+ .compile("\\[(?<username>[^;]+);"
+ + "(?<address>.+)[:/](?<port>[0-9]+);(?<transport>[a-z]+);(?<sessionIdentifier>[a-z]+)[^\\]]+\\]");
/**
- * Parse additional header from a formatted string
+ * Parse additional header from a formatted string.
*/
public static NetconfHelloMessageAdditionalHeader fromString(String additionalHeader) {
String additionalHeaderTrimmed = additionalHeader.trim();
Sessions getSessions();
/**
- * Returns session monitoring service session listener, which is used to notify monitoring service about state of session.
+ * Returns session monitoring service session listener, which is used to notify monitoring service about state of
+ * session.
+ *
* @return session listener
*/
SessionListener getSessionListener();
Capabilities getCapabilities();
/**
- * Allows push based capabilities information transfer. After the listener is registered, current state is pushed to the listener.
+ * Allows push based capabilities information transfer. After the listener is registered, current state is pushed
+ * to the listener.
+ *
* @param listener Monitoring listener
* @return listener registration
*/
/**
* Allows push based sessions information transfer.
+ *
* @param listener Monitoring listener
* @return listener registration
*/
interface CapabilitiesListener {
/**
- * Callback used to notify about a change in used capabilities
+ * Callback used to notify about a change in used capabilities.
+ *
* @param capabilities resulting capabilities
*/
void onCapabilitiesChanged(Capabilities capabilities);
/**
- * Callback used to notify about a change in used schemas
+ * Callback used to notify about a change in used schemas.
+ *
* @param schemas resulting schemas
*/
void onSchemasChanged(Schemas schemas);
interface SessionsListener {
/**
- * Callback used to notify about netconf session start
+ * Callback used to notify about netconf session start.
+ *
* @param session started session
*/
void onSessionStarted(Session session);
/**
- * Callback used to notify about netconf session end
+ * Callback used to notify about netconf session end.
+ *
* @param session ended session
*/
void onSessionEnded(Session session);
* Callback used to notify about activity in netconf session, like
* rpc or notification. It is triggered at regular time interval. Session parameter
* contains only sessions which state was changed.
+ *
* @param sessions updated sessions
*/
void onSessionsUpdated(Collection<Session> sessions);
}
/**
- * Returns session, where event occurred
+ * Returns session, where event occurred.
+ *
* @return session
*/
public NetconfManagementSession getSession() {
}
/**
- * Returns event type
+ * Returns event type.
+ *
* @return type
*/
public Type getType() {
}
/**
- * Session event type
+ * Session event type.
*/
public enum Type {
/**
- * Correct rpc message received
+ * Correct rpc message received.
*/
IN_RPC_SUCCESS,
/**
- * Incorrect rpc message received
+ * Incorrect rpc message received.
*/
IN_RPC_FAIL,
OUT_RPC_ERROR,
/**
- * Notification message sent
+ * Notification message sent.
*/
NOTIFICATION
}
public interface SessionListener {
/**
- * Callback used to notify about netconf session start
+ * Callback used to notify about netconf session start.
+ *
* @param session started session
*/
void onSessionUp(NetconfManagementSession session);
/**
- * Callback used to notify about netconf session end
+ * Callback used to notify about netconf session end.
+ *
* @param session ended session
*/
void onSessionDown(NetconfManagementSession session);
/**
* Callback used to notify about activity in netconf session, like
- * rpc or notification
+ * rpc or notification.
+ *
* @param event session event, contains session and type of event
*/
void onSessionEvent(SessionEvent event);
/**
* These constants mark operation service factories that are auto wired with netconf endpoint
- * for config subsystem
+ * for config subsystem.
*/
public final class NetconfConstants {
/*
public static final String NETCONF_MONITORING = "ietf-netconf-monitoring";
public static final String NETCONF_NOTIFICATION = "ietf-netconf-notifications";
- public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR, NETCONF_MONITORING, NETCONF_NOTIFICATION);
+ public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
+ NETCONF_MONITORING, NETCONF_NOTIFICATION);
}
public static final String GET = "get";
public static final String GET_CONFIG = "get-config";
- public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+ public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 =
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
public static final String URN_IETF_PARAMS_NETCONF_BASE_1_0 = "urn:ietf:params:netconf:base:1.0";
public static final String URN_IETF_PARAMS_NETCONF_BASE_1_1 = "urn:ietf:params:netconf:base:1.1";
public static final String URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0 = "urn:ietf:params:xml:ns:netconf:exi:1.0";
- public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0 = "urn:ietf:params:netconf:capability:notification:1.0";
+ public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0 =
+ "urn:ietf:params:netconf:capability:notification:1.0";
- public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0 = "urn:ietf:params:netconf:capability:exi:1.0";
- public static final String URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
+ public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0 =
+ "urn:ietf:params:netconf:capability:exi:1.0";
+ public static final String URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING =
+ "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
}
public void setUp() throws Exception {
final XPathFactory xPathfactory = XPathFactory.newInstance();
xpath = xPathfactory.newXPath();
- xpath.setNamespaceContext( new NamespaceContext() {
+ xpath.setNamespaceContext(new NamespaceContext() {
@Override
public Iterator<?> getPrefixes(final String namespaceURI) {
- return Collections.singletonList( "netconf" ).iterator();
+ return Collections.singletonList("netconf").iterator();
}
@Override
public String getNamespaceURI(final String prefix) {
return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
}
- } );
+ });
}
@Test
public void testToAndFromXMLDocument() throws XPathExpressionException {
final String errorMessage = "mock error message";
- DocumentedException ex = new NetconfDocumentedException( errorMessage, null,
+ DocumentedException ex = new NetconfDocumentedException(errorMessage, null,
DocumentedException.ErrorType.PROTOCOL,
DocumentedException.ErrorTag.DATA_EXISTS,
DocumentedException.ErrorSeverity.WARNING,
- ImmutableMap.of( "foo", "bar" ) );
+ ImmutableMap.of("foo", "bar"));
final Document doc = ex.toXMLDocument();
- assertNotNull( "Document is null", doc );
+ assertNotNull("Document is null", doc);
final Node rootNode = doc.getDocumentElement();
- assertEquals( "getNamespaceURI", "urn:ietf:params:xml:ns:netconf:base:1.0", rootNode.getNamespaceURI() );
- assertEquals( "getLocalName", "rpc-reply", rootNode.getLocalName() );
+ assertEquals("getNamespaceURI", "urn:ietf:params:xml:ns:netconf:base:1.0", rootNode.getNamespaceURI());
+ assertEquals("getLocalName", "rpc-reply", rootNode.getLocalName());
final Node rpcErrorNode = getNode("/netconf:rpc-reply/netconf:rpc-error", rootNode);
- assertNotNull( "rpc-error not found", rpcErrorNode );
+ assertNotNull("rpc-error not found", rpcErrorNode);
final Node errorTypeNode = getNode("netconf:error-type", rpcErrorNode);
- assertNotNull( "error-type not found", errorTypeNode );
+ assertNotNull("error-type not found", errorTypeNode);
assertEquals("error-type", DocumentedException.ErrorType.PROTOCOL.getTypeValue(),
- errorTypeNode.getTextContent() );
+ errorTypeNode.getTextContent());
final Node errorTagNode = getNode("netconf:error-tag", rpcErrorNode);
- assertNotNull( "error-tag not found", errorTagNode );
+ assertNotNull("error-tag not found", errorTagNode);
assertEquals("error-tag", DocumentedException.ErrorTag.DATA_EXISTS.getTagValue(),
- errorTagNode.getTextContent() );
+ errorTagNode.getTextContent());
final Node errorSeverityNode = getNode("netconf:error-severity", rpcErrorNode);
- assertNotNull( "error-severity not found", errorSeverityNode );
+ assertNotNull("error-severity not found", errorSeverityNode);
assertEquals("error-severity", DocumentedException.ErrorSeverity.WARNING.getSeverityValue(),
- errorSeverityNode.getTextContent() );
+ errorSeverityNode.getTextContent());
final Node errorInfoNode = getNode("netconf:error-info/netconf:foo", rpcErrorNode);
- assertNotNull( "foo not found", errorInfoNode );
- assertEquals( "foo", "bar", errorInfoNode.getTextContent() );
+ assertNotNull("foo not found", errorInfoNode);
+ assertEquals("foo", "bar", errorInfoNode.getTextContent());
final Node errorMsgNode = getNode("netconf:error-message", rpcErrorNode);
- assertNotNull( "error-message not found", errorMsgNode );
- assertEquals( "error-message", errorMessage, errorMsgNode.getTextContent() );
+ assertNotNull("error-message not found", errorMsgNode);
+ assertEquals("error-message", errorMessage, errorMsgNode.getTextContent());
// Test fromXMLDocument
- ex = DocumentedException.fromXMLDocument( doc );
+ ex = DocumentedException.fromXMLDocument(doc);
- assertNotNull( "NetconfDocumentedException is null", ex );
+ assertNotNull("NetconfDocumentedException is null", ex);
assertEquals("getErrorSeverity", DocumentedException.ErrorSeverity.WARNING, ex.getErrorSeverity());
assertEquals("getErrorTag", DocumentedException.ErrorTag.DATA_EXISTS, ex.getErrorTag());
assertEquals("getErrorType", DocumentedException.ErrorType.PROTOCOL, ex.getErrorType());
- assertEquals( "getLocalizedMessage", errorMessage, ex.getLocalizedMessage() );
- assertEquals( "getErrorInfo", ImmutableMap.of( "foo", "bar" ), ex.getErrorInfo() );
+ assertEquals("getLocalizedMessage", errorMessage, ex.getLocalizedMessage());
+ assertEquals("getErrorInfo", ImmutableMap.of("foo", "bar"), ex.getErrorInfo());
}
@SuppressWarnings("unchecked")
<T> T getNode(final String xpathExp, final Node node) throws XPathExpressionException {
- return (T)xpath.compile( xpathExp ).evaluate( node, XPathConstants.NODE );
+ return (T) xpath.compile(xpathExp).evaluate(node, XPathConstants.NODE);
}
}
@Test
public void testStaticConstructor() throws Exception {
- NetconfHelloMessageAdditionalHeader h = NetconfHelloMessageAdditionalHeader.fromString(customHeader);
- assertEquals(h.toString(), header.toString());
- assertEquals(h.toFormattedString(), header.toFormattedString());
+ NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(customHeader);
+ assertEquals(header.toString(), this.header.toString());
+ assertEquals(header.toFormattedString(), this.header.toFormattedString());
}
}
package org.opendaylight.netconf.api.messages;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Test
public void testConstructor() throws NetconfDocumentedException {
- NetconfHelloMessageAdditionalHeader additionalHeader = new NetconfHelloMessageAdditionalHeader("name","host","1","transp","id");
+ NetconfHelloMessageAdditionalHeader additionalHeader = new NetconfHelloMessageAdditionalHeader("name",
+ "host", "1", "transp", "id");
NetconfHelloMessage message = NetconfHelloMessage.createClientHello(caps, Optional.of(additionalHeader));
assertTrue(NetconfHelloMessage.isHelloMessage(message));
assertEquals(Optional.of(additionalHeader), message.getAdditionalHeader());
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
</project>
/**
* Returns a Hashmap with NETCONF ID as outer key and
- * inner keys representing attributes of a NETCONF device
+ * inner keys representing attributes of a NETCONF device.
* @return :Hashmap with two keys for all NETCONF devices in topology
*/
Map<String, Map<String, String>> listDevices();
Map<String, Map<String, List<String>>> showDevice(String deviceId);
/**
- * Add a NETCONF connector
+ * Add a NETCONF connector.
* @param netconfNode :An instance of {@link NetconfNode} containing
- * all required information
+ * all required information
* @param deviceId :NETCONF node ID
*/
void connectDevice(NetconfNode netconfNode, String deviceId);
/**
- * Disconnect a NETCONF connector
+ * Disconnect a NETCONF connector.
* @param deviceIp :IP address of NETCONF device
* @param devicePort :Port of NETCONF device
* @return :Status of disconnect NETCONF connector
boolean disconnectDevice(String deviceIp, String devicePort);
/**
- * Disconnect a NETCONF connector
+ * Disconnect a NETCONF connector.
* @param deviceId :Node id of NETCONF device
* @return :Status of disconnect NETCONF connector
*/
boolean disconnectDevice(String deviceId);
/**
- * Update the NETCONF device for requested values
+ * Update the NETCONF device for requested values.
* @param deviceId :NETCONF node ID
* @param username :Username for NETCONF device
* @param password :Password for NETCONF device
public class NetconfCommandUtils {
private static final Pattern IP_PATTERN = Pattern.compile(
- "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
- "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
+ "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
public static boolean isPortValid(final String devicePort) {
if (Strings.isNullOrEmpty(devicePort)) {
try {
port = Integer.parseInt(devicePort);
} catch (NumberFormatException e) {
- return false;
+ return false;
}
return port >= 0 && port <= 65535;
}
return null;
}
+ @SuppressWarnings("checkstyle:RegexpSinglelineJava")
private void printDevicesList(@Nonnull final Map<String, Map<String, String>> allDevices) {
final ShellTable table = new ShellTable();
table.column(NetconfConsoleConstants.NETCONF_ID).alignLeft();
return null;
}
+ @SuppressWarnings("checkstyle:RegexpSinglelineJava")
private void printDeviceData(@Nonnull final Map<String, Map<String, List<String>>> devices) {
final ShellTable table = new ShellTable();
table.column(NetconfConsoleConstants.NETCONF_ID).alignLeft();
device.get(NetconfConsoleConstants.NETCONF_IP).get(NetconfConsoleConstants.DEFAULT_INDEX),
device.get(NetconfConsoleConstants.NETCONF_PORT).get(NetconfConsoleConstants.DEFAULT_INDEX),
device.get(NetconfConsoleConstants.STATUS).get(NetconfConsoleConstants.DEFAULT_INDEX),
- device.get(NetconfConsoleConstants.AVAILABLE_CAPABILITIES).get(NetconfConsoleConstants.DEFAULT_INDEX));
+ device.get(NetconfConsoleConstants.AVAILABLE_CAPABILITIES)
+ .get(NetconfConsoleConstants.DEFAULT_INDEX));
formatCapabilities(device, table, NetconfConsoleConstants.AVAILABLE_CAPABILITIES);
}
table.print(System.out);
}
- private void formatCapabilities(final Map<String, List<String>> device, final ShellTable table, final String capabilityName) {
+ private void formatCapabilities(final Map<String, List<String>> device, final ShellTable table,
+ final String capabilityName) {
for (final String availableCapability : device.get(capabilityName)) {
// First row is already added to table with the first available capability
// Process rows other than the first to only have remaining available capabilities
@Override
public Map<String, Map<String, String>> listDevices() {
- final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
+ final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL,
+ NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
if (topology == null) {
return new HashMap<>();
}
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
final Map<String, String> attributes = new HashMap<>();
attributes.put(NetconfConsoleConstants.NETCONF_ID, node.getNodeId().getValue());
- attributes.put(NetconfConsoleConstants.NETCONF_IP, netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
+ attributes.put(NetconfConsoleConstants.NETCONF_IP,
+ netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString());
attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase());
netconfNodes.put(node.getNodeId().getValue(), attributes);
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
final Map<String, List<String>> attributes = new HashMap<>();
attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
- attributes.put(NetconfConsoleConstants.NETCONF_IP, ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
- attributes.put(NetconfConsoleConstants.NETCONF_PORT, ImmutableList.of(netconfNode.getPort().getValue().toString()));
- attributes.put(NetconfConsoleConstants.STATUS, ImmutableList.of(netconfNode.getConnectionStatus().name()));
+ attributes.put(NetconfConsoleConstants.NETCONF_IP,
+ ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
+ attributes.put(NetconfConsoleConstants.NETCONF_PORT,
+ ImmutableList.of(netconfNode.getPort().getValue().toString()));
+ attributes.put(NetconfConsoleConstants.STATUS,
+ ImmutableList.of(netconfNode.getConnectionStatus().name()));
attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES,
- netconfNode.getAvailableCapabilities().getAvailableCapability().stream().map(AvailableCapability::getCapability).collect(Collectors.toList()));
+ netconfNode.getAvailableCapabilities().getAvailableCapability().stream()
+ .map(AvailableCapability::getCapability).collect(Collectors.toList()));
device.put(node.getNodeId().getValue(), attributes);
}
}
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
final Map<String, List<String>> attributes = new HashMap<>();
attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
- attributes.put(NetconfConsoleConstants.NETCONF_IP, ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
- attributes.put(NetconfConsoleConstants.NETCONF_PORT, ImmutableList.of(netconfNode.getPort().getValue().toString()));
- attributes.put(NetconfConsoleConstants.STATUS, ImmutableList.of(netconfNode.getConnectionStatus().name()));
+ attributes.put(NetconfConsoleConstants.NETCONF_IP,
+ ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
+ attributes.put(NetconfConsoleConstants.NETCONF_PORT,
+ ImmutableList.of(netconfNode.getPort().getValue().toString()));
+ attributes.put(NetconfConsoleConstants.STATUS,
+ ImmutableList.of(netconfNode.getConnectionStatus().name()));
attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES,
- netconfNode.getAvailableCapabilities().getAvailableCapability().stream().map(AvailableCapability::getCapability).collect(Collectors.toList()));
+ netconfNode.getAvailableCapabilities().getAvailableCapability().stream()
+ .map(AvailableCapability::getCapability).collect(Collectors.toList()));
device.put(node.getNodeId().getValue(), attributes);
}
}
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Throwable throwable) {
LOG.error("Failed to created NetconfNode={}", netconfNode);
- throw new RuntimeException(t);
+ throw new RuntimeException(throwable);
}
});
}
@Override
public boolean disconnectDevice(final String deviceIp, final String devicePort) {
- final String netconfNodeId = NetconfConsoleUtils.getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker).getNodeId().getValue();
+ final String netconfNodeId = NetconfConsoleUtils
+ .getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker).getNodeId().getValue();
return disconnectDevice(netconfNodeId);
}
@Override
- public String updateDevice(final String netconfNodeId, String username, String password, Map<String, String> updated) {
- final Node node = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.netconfNodeIid(netconfNodeId), dataBroker);
+ public String updateDevice(final String netconfNodeId, String username, String password,
+ Map<String, String> updated) {
+ final Node node = NetconfConsoleUtils
+ .read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.netconfNodeIid(netconfNodeId), dataBroker);
if (node != null && node.getAugmentation(NetconfNode.class) != null) {
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
// Get NETCONF attributes to update if present else get their original values from NetconfNode instance
- final String deviceIp = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_IP)) ?
- netconfNode.getHost().getIpAddress().getIpv4Address().getValue() : updated.get(NetconfConsoleConstants.NETCONF_IP);
- final String devicePort = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_PORT)) ?
- netconfNode.getPort().getValue().toString() : updated.get(NetconfConsoleConstants.NETCONF_PORT);
+ final String deviceIp = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_IP))
+ ? netconfNode.getHost().getIpAddress().getIpv4Address().getValue()
+ : updated.get(NetconfConsoleConstants.NETCONF_IP);
+ final String devicePort = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_PORT))
+ ? netconfNode.getPort().getValue().toString() : updated.get(NetconfConsoleConstants.NETCONF_PORT);
final Boolean tcpOnly = (updated.get(NetconfConsoleConstants.TCP_ONLY).equals("true")) ? true : false;
- final Boolean isSchemaless = (updated.get(NetconfConsoleConstants.SCHEMALESS).equals("true")) ? true : false;
- final String newUsername = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.USERNAME)) ? updated.get(NetconfConsoleConstants.USERNAME) : username;
- final String newPassword = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.PASSWORD)) ? updated.get(NetconfConsoleConstants.PASSWORD) : password;
-
- final Credentials credentials = new LoginPasswordBuilder().setPassword(newPassword).setUsername(newUsername).build();
+ final Boolean isSchemaless =
+ (updated.get(NetconfConsoleConstants.SCHEMALESS).equals("true")) ? true : false;
+ final String newUsername = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.USERNAME))
+ ? updated.get(NetconfConsoleConstants.USERNAME) : username;
+ final String newPassword = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.PASSWORD))
+ ? updated.get(NetconfConsoleConstants.PASSWORD) : password;
+
+ final Credentials credentials =
+ new LoginPasswordBuilder().setPassword(newPassword).setUsername(newUsername).build();
final NetconfNode updatedNetconfNode = new NetconfNodeBuilder()
.setHost(new Host(new IpAddress(new Ipv4Address(deviceIp))))
.setPort(new PortNumber(Integer.decode(devicePort)))
.build();
final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
- transaction.put(LogicalDatastoreType.CONFIGURATION, NetconfIidFactory.netconfNodeIid(updatedNode.getNodeId().getValue()), updatedNode);
+ transaction.put(LogicalDatastoreType.CONFIGURATION,
+ NetconfIidFactory.netconfNodeIid(updatedNode.getNodeId().getValue()), updatedNode);
Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Throwable throwable) {
LOG.error("Failed to updated NetconfNode={}", netconfNode);
- throw new RuntimeException(t);
+ throw new RuntimeException(throwable);
}
});
}
/**
- * Returns a list of NETCONF nodes for the IP
+ * Returns a list of NETCONF nodes for the IP.
* @param deviceIp :IP address of NETCONF device
* @param db :An instance of the {@link DataBroker}
* @return :list on NETCONF nodes
}
/**
- * Returns a list with one NETCONF node for the IP and Port
+ * Returns a list with one NETCONF node for the IP and Port.
* @param deviceIp :IP address of NETCONF device
* @param devicePort :Port of NETCONF device
* @param db :An instance of the {@link DataBroker}
* @return :NETCONF node instance
*/
- public static Node getNetconfNodeFromIpAndPort(final String deviceIp, final String devicePort, final DataBroker db) {
+ public static Node getNetconfNodeFromIpAndPort(final String deviceIp, final String devicePort,
+ final DataBroker db) {
final Topology topology = read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.NETCONF_TOPOLOGY_IID, db);
if (isNetconfNodesPresent(topology)) {
for (Node node : topology.getNode()) {
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
if (netconfNode != null
&& netconfNode.getHost().getIpAddress().getIpv4Address().getValue().equals(deviceIp)
- && devicePort.equals(netconfNode.getPort().getValue().toString()))
+ && devicePort.equals(netconfNode.getPort().getValue().toString())) {
return node;
+ }
}
}
return null;
}
/**
- * Checks if the NETCONF topology contains nodes
+ * Checks if the NETCONF topology contains nodes.
* @param topology :NETCONF topology instance
* @return :<code>true</code> if not empty, else, <code>false</code>
*/
}
/**
- * Wait for datastore to populate NETCONF data
+ * Wait for datastore to populate NETCONF data.
* @param deviceIp :IP address of NETCONF device
*/
public static void waitForUpdate(final String deviceIp) {
}
/**
- * Blocking read transaction
+ * Blocking read transaction.
* @param store :DatastoreType
* @param path :InstanceIdentifier
* @param db :An instance of the {@link DataBroker}
* @return :data read from path
*/
- public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(final LogicalDatastoreType store,
- final InstanceIdentifier<D> path, final DataBroker db) {
+ public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
+ final LogicalDatastoreType store, final InstanceIdentifier<D> path, final DataBroker db) {
D result = null;
final ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
Optional<D> optionalData;
throw new IllegalStateException("Instantiating utility class.");
}
- public static final InstanceIdentifier<Topology> NETCONF_TOPOLOGY_IID = InstanceIdentifier.builder(NetworkTopology.class)
+ public static final InstanceIdentifier<Topology> NETCONF_TOPOLOGY_IID =
+ InstanceIdentifier.builder(NetworkTopology.class)
.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())))
.build();
private NetconfCommands netconfCommands;
@Before
- public void setUp(){
+ public void setUp() {
initMocks(this);
}
@Test
public void testDisconnectDeviceCommand() throws Exception {
- NetconfDisconnectDeviceCommand netconfDisconnectDeviceCommand = new NetconfDisconnectDeviceCommand(netconfCommands);
+ NetconfDisconnectDeviceCommand netconfDisconnectDeviceCommand =
+ new NetconfDisconnectDeviceCommand(netconfCommands);
netconfDisconnectDeviceCommand.doExecute();
verify(netconfCommands, times(0)).connectDevice(any(), any());
netconfUpdateDeviceCommand.doExecute();
- verify(netconfCommands, times(1)).updateDevice(anyString(), anyString(), anyString(), hashMapArgumentCaptor.capture());
+ verify(netconfCommands, times(1)).updateDevice(anyString(), anyString(), anyString(),
+ hashMapArgumentCaptor.capture());
assertTrue(hashMapArgumentCaptor.getValue().containsKey(NetconfConsoleConstants.NETCONF_IP));
assertEquals("192.168.1.1", hashMapArgumentCaptor.getValue().get(NetconfConsoleConstants.NETCONF_IP));
final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
16, 16, "CommitFutures");
- final ConcurrentDOMDataBroker cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
+ final ConcurrentDOMDataBroker cDOMDataBroker =
+ 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);
}
@Test
- public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
- final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
- setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
+ public void testConnectDisconnectDevice()
+ throws InterruptedException, TimeoutException, TransactionCommitFailedException {
+ final NetconfNode netconfNode = new NetconfNodeBuilder()
+ .setPort(new PortNumber(7777)).setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
createTopology(LogicalDatastoreType.CONFIGURATION);
netconfCommands.connectDevice(netconfNode, "netconf-ID");
assertEquals(1, nodes.size());
}
- private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
+ private void createTopology(LogicalDatastoreType dataStoreType)
+ throws TransactionCommitFailedException, TimeoutException {
final List<Node> nodes = new ArrayList<>();
final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
nodes.add(node);
- final Topology topology = new TopologyBuilder().
- setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
- setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
+ final Topology topology = new TopologyBuilder()
+ .setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())))
+ .setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
}
- private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
- String notificationCapabilityPrefix) {
+ private Node getNetconfNode(String nodeIdent, String ip, int portNumber,
+ NetconfNodeConnectionStatus.ConnectionStatus cs, String notificationCapabilityPrefix) {
final Host host = HostBuilder.getDefaultInstance(ip);
final PortNumber port = new PortNumber(portNumber);
avCapList.add(new AvailableCapabilityBuilder()
.setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
.setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
- final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
+ final AvailableCapabilities avCaps =
+ new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
- final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
- setAvailableCapabilities(avCaps).build();
+ final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port)
+ .setAvailableCapabilities(avCaps).build();
final NodeId nodeId = new NodeId(nodeIdent);
final NodeKey nk = new NodeKey(nodeId);
final NodeBuilder nb = new NodeBuilder();
}
@Override
- public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+ final SchemaContextListener listener) {
listener.onGlobalContextUpdated(getGlobalContext());
return new ListenerRegistration<SchemaContextListener>() {
@Override
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
import org.opendaylight.protocol.framework.AbstractDispatcher;
-public class NetconfServerDispatcherImpl extends AbstractDispatcher<NetconfServerSession, NetconfServerSessionListener> implements NetconfServerDispatcher {
+public class NetconfServerDispatcherImpl extends AbstractDispatcher<NetconfServerSession,
+ NetconfServerSessionListener> implements NetconfServerDispatcher {
private final ServerChannelInitializer initializer;
@Override
public ChannelFuture createLocalServer(LocalAddress address) {
- return super.createServer(address, LocalServerChannel.class, new ChannelPipelineInitializer<LocalChannel, NetconfServerSession>() {
+ return super.createServer(address, LocalServerChannel.class, new ChannelPipelineInitializer<LocalChannel,
+ NetconfServerSession>() {
@Override
public void initializeChannel(final LocalChannel ch, final Promise<NetconfServerSession> promise) {
initializer.initialize(ch, promise);
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public final class NetconfServerSession extends AbstractNetconfSession<NetconfServerSession, NetconfServerSessionListener> implements NetconfManagementSession {
+public final class NetconfServerSession extends AbstractNetconfSession<NetconfServerSession,
+ NetconfServerSessionListener> implements NetconfManagementSession {
private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSession.class);
- private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+ private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+ private static final String DATE_TIME_PATTERN_STRING = DateAndTime.PATTERN_CONSTANTS.get(0);
+ private static final Pattern DATE_TIME_PATTERN = Pattern.compile(DATE_TIME_PATTERN_STRING);
private final NetconfHelloMessageAdditionalHeader header;
private final NetconfServerSessionListener sessionListener;
private ZonedDateTime loginTime;
- private long inRpcSuccess, inRpcFail, outRpcError, outNotification;
+ private long inRpcSuccess;
+ private long inRpcFail;
+ private long outRpcError;
+ private long outNotification;
private volatile boolean delayedClose;
- public NetconfServerSession(final NetconfServerSessionListener sessionListener, final Channel channel, final long sessionId,
- final NetconfHelloMessageAdditionalHeader header) {
+ public NetconfServerSession(final NetconfServerSessionListener sessionListener, final Channel channel,
+ final long sessionId, final NetconfHelloMessageAdditionalHeader header) {
super(sessionListener, channel, sessionId);
this.header = header;
this.sessionListener = sessionListener;
sessionListener.onNotification(this, (NetconfNotification) netconfMessage);
}
// delayed close was set, close after the message was sent
- if(delayedClose) {
+ if (delayedClose) {
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
outRpcError++;
}
- private static final String dateTimePatternString = DateAndTime.PATTERN_CONSTANTS.get(0);
- private static final Pattern dateTimePattern = Pattern.compile(dateTimePatternString);
-
@Override
public Session toManagementSession() {
SessionBuilder builder = new SessionBuilder();
builder.setSourceHost(new Host(address));
Preconditions.checkState(DateAndTime.PATTERN_CONSTANTS.size() == 1);
- String formattedDateTime = dateFormatter.format(loginTime);
+ String formattedDateTime = DATE_FORMATTER.format(loginTime);
- Matcher matcher = dateTimePattern.matcher(formattedDateTime);
- Preconditions.checkState(matcher.matches(), "Formatted datetime %s does not match pattern %s", formattedDateTime, dateTimePattern);
+ Matcher matcher = DATE_TIME_PATTERN.matcher(formattedDateTime);
+ Preconditions.checkState(matcher.matches(), "Formatted datetime %s does not match pattern %s",
+ formattedDateTime, DATE_TIME_PATTERN);
builder.setLoginTime(new DateAndTime(formattedDateTime));
builder.setInBadRpcs(new ZeroBasedCounter32(inRpcFail));
}
private static Class<? extends Transport> getTransportForString(final String transport) {
- switch(transport) {
- case "ssh" :
- return NetconfSsh.class;
- case "tcp" :
- return NetconfTcp.class;
- default:
- throw new IllegalArgumentException("Unknown transport type " + transport);
+ switch (transport) {
+ case "ssh":
+ return NetconfSsh.class;
+ case "tcp":
+ return NetconfTcp.class;
+ default:
+ throw new IllegalArgumentException("Unknown transport type " + transport);
}
}
}
@Override
- protected void addExiHandlers(final ByteToMessageDecoder decoder, final MessageToByteEncoder<NetconfMessage> encoder) {
+ protected void addExiHandlers(final ByteToMessageDecoder decoder,
+ final MessageToByteEncoder<NetconfMessage> encoder) {
replaceMessageDecoder(decoder);
replaceMessageEncoderAfterNextMessage(encoder);
}
package org.opendaylight.netconf.impl;
-
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.opendaylight.controller.config.util.xml.DocumentedException;
private final NetconfOperationRouter operationRouter;
private final AutoCloseable onSessionDownCloseable;
- public NetconfServerSessionListener(final NetconfOperationRouter operationRouter, final NetconfMonitoringService monitoringService,
+ public NetconfServerSessionListener(final NetconfOperationRouter operationRouter,
+ final NetconfMonitoringService monitoringService,
final AutoCloseable onSessionDownCloseable) {
this.operationRouter = operationRouter;
this.monitoringSessionListener = monitoringService.getSessionListener();
onDown(netconfNetconfServerSession);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void onDown(final NetconfServerSession netconfNetconfServerSession) {
monitoringSessionListener.onSessionDown(netconfNetconfServerSession);
@Override
public void onSessionTerminated(final NetconfServerSession netconfNetconfServerSession,
- final NetconfTerminationReason netconfTerminationReason) {
+ final NetconfTerminationReason netconfTerminationReason) {
LOG.debug("Session {} terminated, reason: {}", netconfNetconfServerSession,
netconfTerminationReason.getErrorMessage());
onDown(netconfNetconfServerSession);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void onMessage(final NetconfServerSession session, final NetconfMessage netconfMessage) {
try {
monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
throw new IllegalStateException("Unable to process incoming message " + netconfMessage, e);
} catch (final DocumentedException e) {
- LOG.trace("Error occurred while processing message",e);
+ LOG.trace("Error occurred while processing message", e);
session.onOutgoingRpcError();
session.onIncommingRpcFail();
monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
throw new DocumentedException("Unknown tag " + rootNode.getNodeName() + " in message:\n" + netconfMessage,
DocumentedException.ErrorType.PROTOCOL, DocumentedException.ErrorTag.UNKNOWN_ELEMENT,
DocumentedException.ErrorSeverity.ERROR, ImmutableMap.of("bad-element",
- rootNode.getNodeName()));
+ rootNode.getNodeName()));
}
}
final NamedNodeMap attributes = rootNode.getAttributes();
- if(attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.MESSAGE_ID)!=null) {
+ if (attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
+ XmlNetconfConstants.MESSAGE_ID) != null) {
return;
}
- if(attributes.getNamedItem(XmlNetconfConstants.MESSAGE_ID)!=null) {
+ if (attributes.getNamedItem(XmlNetconfConstants.MESSAGE_ID) != null) {
return;
}
import org.slf4j.LoggerFactory;
public class NetconfServerSessionNegotiator
- extends
- AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession, NetconfServerSessionListener> {
+ extends AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession,
+ NetconfServerSessionListener> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiator.class);
}
/**
- * @param socketAddress
- * type of socket address LocalAddress, or
- * InetSocketAddress, for others returns unknown
+ * Get a name of the host.
+ *
+ * @param socketAddress type of socket address LocalAddress, or
+ * InetSocketAddress, for others returns unknown
* @return Two values - port and host of socket address
*/
protected static Map.Entry<String, String> getHostName(
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfHelloMessage, NetconfServerSession, NetconfServerSessionListener> {
+public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfHelloMessage,
+ NetconfServerSession, NetconfServerSessionListener> {
public static final Set<String> DEFAULT_BASE_CAPABILITIES = ImmutableSet.of(
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
private final Set<String> baseCapabilities;
- public NetconfServerSessionNegotiatorFactory(final Timer timer, final NetconfOperationServiceFactory netconfOperationProvider,
+ public NetconfServerSessionNegotiatorFactory(final Timer timer,
+ final NetconfOperationServiceFactory netconfOperationProvider,
final SessionIdProvider idProvider, final long connectionTimeoutMillis,
- final NetconfMonitoringService monitoringService, final Set<String> baseCapabilities) {
+ final NetconfMonitoringService monitoringService,
+ final Set<String> baseCapabilities) {
this.timer = timer;
this.aggregatedOpService = netconfOperationProvider;
this.idProvider = idProvider;
this.connectionTimeoutMillis = connectionTimeoutMillis;
this.monitoringService = monitoringService;
- this.baseCapabilities = validateBaseCapabilities(baseCapabilities == null ? DEFAULT_BASE_CAPABILITIES : baseCapabilities);
+ this.baseCapabilities = validateBaseCapabilities(baseCapabilities == null ? DEFAULT_BASE_CAPABILITIES :
+ baseCapabilities);
}
// Check base capabilities to be supported by the server
final Sets.SetView<String> unknownBaseCaps = Sets.difference(baseCapabilities, DEFAULT_BASE_CAPABILITIES);
Preconditions.checkArgument(unknownBaseCaps.isEmpty(),
- "Base capabilities that will be supported by netconf server have to be subset of %s, unknown base capabilities: %s",
+ "Base capabilities that will be supported by netconf server have to be subset of %s, "
+ + "unknown base capabilities: %s",
DEFAULT_BASE_CAPABILITIES, unknownBaseCaps);
final ImmutableSet.Builder<String> b = ImmutableSet.builder();
}
/**
+ * Get session negotiator.
+ *
* @param defunctSessionListenerFactory will not be taken into account as session listener factory can
* only be created after snapshot is opened, thus this method constructs
* proper session listener factory.
- * @param channel Underlying channel
- * @param promise Promise to be notified
+ * @param channel Underlying channel
+ * @param promise Promise to be notified
* @return session negotiator
*/
@Override
- public SessionNegotiator<NetconfServerSession> getSessionNegotiator(final SessionListenerFactory<NetconfServerSessionListener> defunctSessionListenerFactory,
- final Channel channel, final Promise<NetconfServerSession> promise) {
+ public SessionNegotiator<NetconfServerSession> getSessionNegotiator(
+ final SessionListenerFactory<NetconfServerSessionListener> defunctSessionListenerFactory,
+ final Channel channel, final Promise<NetconfServerSession> promise) {
final long sessionId = idProvider.getNextSessionId();
NetconfServerSessionPreferences proposal;
getListener(Long.toString(sessionId), channel.localAddress()), connectionTimeoutMillis);
}
- private NetconfServerSessionListener getListener(final String netconfSessionIdForReporting, final SocketAddress socketAddress) {
- final NetconfOperationService service = getOperationServiceForAddress(netconfSessionIdForReporting, socketAddress);
+ private NetconfServerSessionListener getListener(final String netconfSessionIdForReporting,
+ final SocketAddress socketAddress) {
+ final NetconfOperationService service = getOperationServiceForAddress(netconfSessionIdForReporting,
+ socketAddress);
final NetconfOperationRouter operationRouter =
new NetconfOperationRouterImpl(service, monitoringService, netconfSessionIdForReporting);
return new NetconfServerSessionListener(operationRouter, monitoringService, service);
}
- protected NetconfOperationService getOperationServiceForAddress(final String netconfSessionIdForReporting, final SocketAddress socketAddress) {
+ protected NetconfOperationService getOperationServiceForAddress(final String netconfSessionIdForReporting,
+ final SocketAddress socketAddress) {
return this.aggregatedOpService.createService(netconfSessionIdForReporting);
}
return aggregatedOpService;
}
- private NetconfHelloMessage createHelloMessage(final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
- return NetconfHelloMessage.createServerHello(Sets.union(transformCapabilities(capabilityProvider.getCapabilities()), baseCapabilities), sessionId);
+ private NetconfHelloMessage createHelloMessage(
+ final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
+ return NetconfHelloMessage.createServerHello(Sets.union(transformCapabilities(capabilityProvider
+ .getCapabilities()), baseCapabilities), sessionId);
}
public static Set<String> transformCapabilities(final Capabilities capabilities) {
return this;
}
- public NetconfServerSessionNegotiatorFactoryBuilder setAggregatedOpService(final NetconfOperationServiceFactory aggregatedOpService) {
+ public NetconfServerSessionNegotiatorFactoryBuilder setAggregatedOpService(
+ final NetconfOperationServiceFactory aggregatedOpService) {
this.aggregatedOpService = aggregatedOpService;
return this;
}
return this;
}
- public NetconfServerSessionNegotiatorFactoryBuilder setMonitoringService(final NetconfMonitoringService monitoringService) {
+ public NetconfServerSessionNegotiatorFactoryBuilder setMonitoringService(
+ final NetconfMonitoringService monitoringService) {
this.monitoringService = monitoringService;
return this;
}
public NetconfServerSessionNegotiatorFactory build() {
validate();
- return new NetconfServerSessionNegotiatorFactory(timer, aggregatedOpService, idProvider, connectionTimeoutMillis, monitoringService, baseCapabilities);
+ return new NetconfServerSessionNegotiatorFactory(timer, aggregatedOpService, idProvider,
+ connectionTimeoutMillis, monitoringService, baseCapabilities);
}
Preconditions.checkArgument(connectionTimeoutMillis > 0, "connection time out <=0");
Preconditions.checkNotNull(monitoringService, "NetconfMonitoringService not initialized");
- baseCapabilities = (baseCapabilities == null) ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES : baseCapabilities;
+ baseCapabilities = (baseCapabilities == null) ? NetconfServerSessionNegotiatorFactory
+ .DEFAULT_BASE_CAPABILITIES : baseCapabilities;
}
}
/**
* Close netconf operation router associated to this session, which in turn
* closes NetconfOperationServiceSnapshot with all NetconfOperationService
- * instances
+ * instances.
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
throws DocumentedException {
}
@Override
- public void setNetconfSession(final NetconfServerSession s) {
- this.session = s;
+ public void setNetconfSession(final NetconfServerSession netconfServerSession) {
+ this.session = netconfServerSession;
}
}
import org.opendaylight.netconf.impl.NetconfServerSession;
public interface DefaultNetconfOperation {
- void setNetconfSession(NetconfServerSession s);
+ void setNetconfSession(NetconfServerSession netconfServerSession);
}
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
- final Element getSchemaResult = document.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement operationElement) throws DocumentedException {
+ final Element getSchemaResult = document.createElementNS(
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
LOG.trace("{} operation successful", START_EXI);
return getSchemaResult;
}
}
@Override
- public void setNetconfSession(final NetconfServerSession s) {
- netconfSession = s;
+ public void setNetconfSession(final NetconfServerSession netconfServerSession) {
+ netconfSession = netconfServerSession;
}
}
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document,
+ XmlElement operationElement) throws DocumentedException {
LOG.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
netconfSession.stopExiCommunication();
- Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
+ Element getSchemaResult = document.createElementNS(
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
LOG.trace("{} operation successful", STOP_EXI);
return getSchemaResult;
}
}
@Override
- public void setNetconfSession(NetconfServerSession s) {
- this.netconfSession = s;
+ public void setNetconfSession(NetconfServerSession netconfServerSession) {
+ this.netconfSession = netconfServerSession;
}
}
/**
* NetconfOperationService aggregator. Makes a collection of operation services accessible as one.
*/
-public class AggregatedNetconfOperationServiceFactory implements NetconfOperationServiceFactory, NetconfOperationServiceFactoryListener, AutoCloseable {
+public class AggregatedNetconfOperationServiceFactory
+ implements NetconfOperationServiceFactory, NetconfOperationServiceFactoryListener, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(AggregatedNetconfOperationServiceFactory.class);
private final Set<NetconfOperationServiceFactory> factories = new ConcurrentSet<>();
- private final Multimap<NetconfOperationServiceFactory, AutoCloseable> registrations = Multimaps.synchronizedMultimap(HashMultimap.create());
+ private final Multimap<NetconfOperationServiceFactory, AutoCloseable> registrations =
+ Multimaps.synchronizedMultimap(HashMultimap.create());
private final Set<CapabilityListener> listeners = new ConcurrentSet<>();
public AggregatedNetconfOperationServiceFactory() {
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public synchronized void onRemoveNetconfOperationServiceFactory(NetconfOperationServiceFactory service) {
factories.remove(service);
private final Set<NetconfOperationService> services;
- public AggregatedNetconfOperation(final Set<NetconfOperationServiceFactory> factories, final String netconfSessionIdForReporting) {
+ AggregatedNetconfOperation(final Set<NetconfOperationServiceFactory> factories,
+ final String netconfSessionIdForReporting) {
final Builder<NetconfOperationService> b = ImmutableSet.builder();
for (final NetconfOperationServiceFactory factory : factories) {
b.add(factory.createService(netconfSessionIdForReporting));
return operations;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void close() {
try {
private static final Schema.Location NETCONF_LOCATION = new Schema.Location(Schema.Location.Enumeration.NETCONF);
private static final List<Schema.Location> NETCONF_LOCATIONS = ImmutableList.of(NETCONF_LOCATION);
- private static final BasicCapability CANDIDATE_CAPABILITY = new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0");
+ private static final BasicCapability CANDIDATE_CAPABILITY =
+ new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0");
private static final Function<Capability, Uri> CAPABILITY_TO_URI = new Function<Capability, Uri>() {
@Override
public Uri apply(final Capability input) {
netconfOperationProvider.registerCapabilityListener(this);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
synchronized Schemas getSchemas() {
try {
return transformSchemas(netconfOperationProvider.getCapabilities());
synchronized String getSchemaForModuleRevision(final String moduleName, final Optional<String> revision) {
Map<String, String> revisionMapRequest = mappedModulesToRevisionToSchema.get(moduleName);
- Preconditions.checkState(revisionMapRequest != null, "Capability for module %s not present, " + ""
- + "available modules : %s", moduleName, Collections2.transform(capabilities.values(), CAPABILITY_TO_URI));
+ Preconditions.checkState(revisionMapRequest != null,
+ "Capability for module %s not present, available modules : %s",
+ moduleName, Collections2.transform(capabilities.values(), CAPABILITY_TO_URI));
if (revision.isPresent()) {
String schema = revisionMapRequest.get(revision.get());
private void updateCapabilityToSchemaMap(final Set<Capability> added, final Set<Capability> removed) {
for (final Capability cap : added) {
- if (!isValidModuleCapability(cap)){
+ if (!isValidModuleCapability(cap)) {
continue;
}
revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
}
for (final Capability cap : removed) {
- if (!isValidModuleCapability(cap)){
+ if (!isValidModuleCapability(cap)) {
continue;
}
final Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(cap.getModuleName().get());
private static NetconfCapabilityChange computeDiff(final Set<Capability> added, final Set<Capability> removed) {
final NetconfCapabilityChangeBuilder netconfCapabilityChangeBuilder = new NetconfCapabilityChangeBuilder();
- netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build()).build());
- netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2.transform(removed, CAPABILITY_TO_URI)));
- netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2.transform(added, CAPABILITY_TO_URI)));
+ netconfCapabilityChangeBuilder
+ .setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build())
+ .build());
+ netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2
+ .transform(removed, CAPABILITY_TO_URI)));
+ netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2
+ .transform(added, CAPABILITY_TO_URI)));
// TODO modified should be computed ... but why ?
netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
return netconfCapabilityChangeBuilder.build();
private BaseNotificationPublisherRegistration listenerReg;
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void start(final BundleContext context) {
try {
final NetconfMonitoringServiceImpl monitoringService = startMonitoringService(context, factoriesListener);
- NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
- .setAggregatedOpService(factoriesListener)
- .setTimer(timer)
- .setIdProvider(idProvider)
- .setMonitoringService(monitoringService)
- .setConnectionTimeoutMillis(connectionTimeoutMillis)
- .build();
+ NetconfServerSessionNegotiatorFactory serverNegotiatorFactory =
+ new NetconfServerSessionNegotiatorFactoryBuilder()
+ .setAggregatedOpService(factoriesListener)
+ .setTimer(timer)
+ .setIdProvider(idProvider)
+ .setMonitoringService(monitoringService)
+ .setConnectionTimeoutMillis(connectionTimeoutMillis)
+ .build();
eventLoopGroup = new NioEventLoopGroup();
ServerChannelInitializer serverChannelInitializer = new ServerChannelInitializer(
serverNegotiatorFactory);
- NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, eventLoopGroup, eventLoopGroup);
+ NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer,
+ eventLoopGroup, eventLoopGroup);
LocalAddress address = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
LOG.trace("Starting local netconf server at {}", address);
dispatch.createLocalServer(address);
- final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector> notificationServiceTracker =
- new ServiceTracker<>(context, NetconfNotificationCollector.class, new ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>() {
- @Override
- public NetconfNotificationCollector addingService(ServiceReference<NetconfNotificationCollector> reference) {
- Preconditions.checkState(listenerReg == null, "Notification collector service was already added");
- listenerReg = context.getService(reference).registerBaseNotificationPublisher();
- monitoringService.setNotificationPublisher(listenerReg);
- return null;
- }
-
- @Override
- public void modifiedService(ServiceReference<NetconfNotificationCollector> reference, NetconfNotificationCollector service) {
-
- }
-
- @Override
- public void removedService(ServiceReference<NetconfNotificationCollector> reference, NetconfNotificationCollector service) {
- listenerReg.close();
- listenerReg = null;
- monitoringService.setNotificationPublisher(listenerReg);
- }
- });
+ final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector>
+ notificationServiceTracker = new ServiceTracker<>(context, NetconfNotificationCollector.class,
+ new ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>() {
+ @Override
+ public NetconfNotificationCollector addingService(ServiceReference<
+ NetconfNotificationCollector> reference) {
+ Preconditions.checkState(listenerReg == null,
+ "Notification collector service was already added");
+ listenerReg = context.getService(reference).registerBaseNotificationPublisher();
+ monitoringService.setNotificationPublisher(listenerReg);
+ return null;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<NetconfNotificationCollector> reference,
+ NetconfNotificationCollector service) {
+
+ }
+
+ @Override
+ public void removedService(ServiceReference<NetconfNotificationCollector> reference,
+ NetconfNotificationCollector service) {
+ listenerReg.close();
+ listenerReg = null;
+ monitoringService.setNotificationPublisher(listenerReg);
+ }
+ });
notificationServiceTracker.open();
} catch (Exception e) {
LOG.warn("Unable to start NetconfImplActivator", e);
}
}
- private void startOperationServiceFactoryTracker(BundleContext context, NetconfOperationServiceFactoryListener factoriesListener) {
+ private void startOperationServiceFactoryTracker(BundleContext context,
+ NetconfOperationServiceFactoryListener factoriesListener) {
factoriesTracker = new NetconfOperationServiceFactoryTracker(context, factoriesListener);
factoriesTracker.open();
}
- private NetconfMonitoringServiceImpl startMonitoringService(BundleContext context, AggregatedNetconfOperationServiceFactory factoriesListener) {
+ private NetconfMonitoringServiceImpl startMonitoringService(
+ BundleContext context,
+ AggregatedNetconfOperationServiceFactory factoriesListener) {
NetconfMonitoringServiceImpl netconfMonitoringServiceImpl = new NetconfMonitoringServiceImpl(factoriesListener);
Dictionary<String, ?> dic = new Hashtable<>();
regMonitoring = context.registerService(NetconfMonitoringService.class, netconfMonitoringServiceImpl, dic);
allNetconfOperations = ImmutableSet.copyOf(ops);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws DocumentedException {
+ public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws
+ DocumentedException {
Preconditions.checkNotNull(allNetconfOperations, "Operation router was not initialized properly");
final NetconfOperationExecution netconfOperationExecution;
}
throw new DocumentedException(
- String.format("Unable to handle rpc %s on session %s", messageAsString, session),
+ String.format("Unable to handle rpc %s on session %s", messageAsString, session),
e, DocumentedException.ErrorType.APPLICATION,
tag, DocumentedException.ErrorSeverity.ERROR,
- Collections.singletonMap(tag.toString(), e.getMessage()));
+ Collections.singletonMap(tag.toString(), e.getMessage()));
} catch (final RuntimeException e) {
throw handleUnexpectedEx("Unexpected exception during netconf operation sort", e);
}
netconfOperationServiceSnapshot.close();
}
- private static DocumentedException handleUnexpectedEx(final String s, final Exception e) throws DocumentedException {
- LOG.error("{}", s, e);
+ private static DocumentedException handleUnexpectedEx(final String message, final Exception exception) throws
+ DocumentedException {
+ LOG.error("{}", message, exception);
return new DocumentedException("Unexpected error",
DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR,
- Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), e.toString()));
+ Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), exception.toString()));
}
private Document executeOperationWithHighestPriority(final Document message,
- final NetconfOperationExecution netconfOperationExecution)
+ final NetconfOperationExecution netconfOperationExecution)
throws DocumentedException {
if (LOG.isDebugEnabled()) {
- LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution.netconfOperation);
+ LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution
+ .netconfOperation);
}
return netconfOperationExecution.execute(message);
private NetconfOperationExecution getNetconfOperationWithHighestPriority(
final Document message, final NetconfServerSession session) throws DocumentedException {
- final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
+ final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority =
+ getSortedNetconfOperationsWithCanHandle(
message, session);
if (sortedByPriority.isEmpty()) {
throw new IllegalArgumentException(String.format("No %s available to handle message %s",
- NetconfOperation.class.getName(), XmlUtil.toString(message)));
+ NetconfOperation.class.getName(), XmlUtil.toString(message)));
}
return NetconfOperationExecution.createExecutionChain(sortedByPriority, sortedByPriority.lastKey());
}
- private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(final Document message,
- final NetconfServerSession session) throws DocumentedException {
+ private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(
+ final Document message, final NetconfServerSession session) throws DocumentedException {
final TreeMap<HandlingPriority, NetconfOperation> sortedPriority = Maps.newTreeMap();
for (final NetconfOperation netconfOperation : allNetconfOperations) {
if (netconfOperation instanceof DefaultNetconfOperation) {
((DefaultNetconfOperation) netconfOperation).setNetconfSession(session);
}
- if(netconfOperation instanceof SessionAwareNetconfOperation) {
+ if (netconfOperation instanceof SessionAwareNetconfOperation) {
((SessionAwareNetconfOperation) netconfOperation).setSession(session);
}
if (!handlingPriority.equals(HandlingPriority.CANNOT_HANDLE)) {
Preconditions.checkState(!sortedPriority.containsKey(handlingPriority),
"Multiple %s available to handle message %s with priority %s, %s and %s",
- NetconfOperation.class.getName(), message, handlingPriority, netconfOperation, sortedPriority.get(handlingPriority));
+ NetconfOperation.class.getName(), message, handlingPriority, netconfOperation, sortedPriority
+ .get(handlingPriority));
sortedPriority.put(handlingPriority, netconfOperation);
}
}
private final NetconfOperation netconfOperation;
private final NetconfOperationChainedExecution subsequentExecution;
- private NetconfOperationExecution(final NetconfOperation netconfOperation, final NetconfOperationChainedExecution subsequentExecution) {
+ private NetconfOperationExecution(final NetconfOperation netconfOperation,
+ final NetconfOperationChainedExecution subsequentExecution) {
this.netconfOperation = netconfOperation;
this.subsequentExecution = subsequentExecution;
}
}
public static NetconfOperationExecution createExecutionChain(
- final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority, final HandlingPriority handlingPriority) {
+ final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority,
+ final HandlingPriority handlingPriority) {
final NetconfOperation netconfOperation = sortedByPriority.get(handlingPriority);
final HandlingPriority subsequentHandlingPriority = sortedByPriority.lowerKey(handlingPriority);
private final NetconfOperationServiceFactoryListener factoriesListener;
NetconfOperationServiceFactoryTracker(BundleContext context,
- final NetconfOperationServiceFactoryListener factoriesListener) {
+ final NetconfOperationServiceFactoryListener factoriesListener) {
super(context, NetconfOperationServiceFactory.class, null);
this.factoriesListener = factoriesListener;
}
@Override
public void removedService(ServiceReference<NetconfOperationServiceFactory> reference,
- NetconfOperationServiceFactory netconfOperationServiceFactory) {
+ NetconfOperationServiceFactory netconfOperationServiceFactory) {
if (netconfOperationServiceFactory != null) {
factoriesListener.onRemoveNetconfOperationServiceFactory(netconfOperationServiceFactory);
}
import org.slf4j.LoggerFactory;
/**
- * This class implements {@link SessionListener} to receive updates about Netconf sessions. Instance notifies its listeners
+ * This class implements {@link SessionListener} to receive updates about Netconf sessions. Instance notifies its
+ * listeners
* about session start and end. It also publishes on regular interval list of sessions,
* where events like rpc or notification happened.
*/
private boolean running;
/**
- * @param schedulingThreadPool thread pool for scheduling session stats updates. If not present, updates won't be scheduled.
- * @param updateInterval update interval. If is less than 0, updates won't be scheduled
+ * Constructor for {@code NetconfSessionMonitoringService}.
+ *
+ * @param schedulingThreadPool thread pool for scheduling session stats updates. If not present, updates won't be
+ * scheduled.
+ * @param updateInterval update interval. If is less than 0, updates won't be scheduled
*/
NetconfSessionMonitoringService(Optional<ScheduledThreadPool> schedulingThreadPool, long updateInterval) {
this.updateInterval = updateInterval;
if (schedulingThreadPool.isPresent() && updateInterval > 0) {
- this.executor = schedulingThreadPool.get().getExecutor();
+ this.executor = schedulingThreadPool.get().getExecutor();
LOG.info("/netconf-state/sessions will be updated every {} seconds.", updateInterval);
} else {
- LOG.info("Scheduling thread pool is present = {}, update interval {}: /netconf-state/sessions won't be updated.",
+ LOG.info("Scheduling thread pool is present = {}, "
+ + "update interval {}: /netconf-state/sessions won't be updated.",
schedulingThreadPool.isPresent(), updateInterval);
this.executor = null;
}
}
synchronized Sessions getSessions() {
- final Collection<Session> managementSessions = Collections2.transform(sessions, NetconfManagementSession::toManagementSession);
+ final Collection<Session> managementSessions = Collections2.transform(sessions,
+ NetconfManagementSession::toManagementSession);
return new SessionsBuilder().setSession(ImmutableList.copyOf(managementSessions)).build();
}
@Test
public void testParsing() throws Exception {
- String s = "[netconf;10.12.0.102:48528;ssh;;;;;;]";
- NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s);
+ String message = "[netconf;10.12.0.102:48528;ssh;;;;;;]";
+ NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(message);
assertEquals("netconf", header.getUserName());
assertEquals("10.12.0.102", header.getAddress());
assertEquals("ssh", header.getTransport());
@Test
public void testParsing2() throws Exception {
- String s = "[tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]";
- NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s);
+ String message = "[tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]";
+ NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(message);
assertEquals("tomas", header.getUserName());
assertEquals("10.0.0.0", header.getAddress());
assertEquals("tcp", header.getTransport());
@Test(expected = IllegalArgumentException.class)
public void testParsingNoUsername() throws Exception {
- String s = "[10.12.0.102:48528;ssh;;;;;;]";
- NetconfHelloMessageAdditionalHeader.fromString(s);
+ String message = "[10.12.0.102:48528;ssh;;;;;;]";
+ NetconfHelloMessageAdditionalHeader.fromString(message);
}
}
private static ExecutorService clientExecutor;
private static final int CONCURRENCY = 32;
- private static final InetSocketAddress netconfAddress = new InetSocketAddress("127.0.0.1", 8303);
+ private static final InetSocketAddress NETCONF_ADDRESS = new InetSocketAddress("127.0.0.1", 8303);
private int nettyThreads;
private Class<? extends Runnable> clientRunnable;
@Parameterized.Parameters()
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
- {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
- // empty set of capabilities = only base 1.0 netconf capability
- {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
- {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
- {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
- {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
- {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
+ return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class,
+ NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
+ {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
+ // empty set of capabilities = only base 1.0 netconf capability
+ {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
+ {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
+ {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
+ {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
+ {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
});
}
}
}).when(monitoring).registerCapabilitiesListener(any(NetconfMonitoringService.CapabilitiesListener.class));
doReturn(sessionListener).when(monitoring).getSessionListener();
- doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring).getCapabilities();
+ doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring)
+ .getCapabilities();
return monitoring;
}
@BeforeClass
public static void setUpClientExecutor() {
clientExecutor = Executors.newFixedThreadPool(CONCURRENCY, new ThreadFactory() {
- int i = 1;
+ int index = 1;
@Override
- public Thread newThread(final Runnable r) {
- Thread thread = new Thread(r);
- thread.setName("client-" + i++);
+ public Thread newThread(final Runnable runnable) {
+ Thread thread = new Thread(runnable);
+ thread.setName("client-" + index++);
thread.setDaemon(true);
return thread;
}
AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
testingNetconfOperation = new TestingNetconfOperation();
- factoriesListener.onAddNetconfOperationServiceFactory(new TestingOperationServiceFactory(testingNetconfOperation));
+ factoriesListener.onAddNetconfOperationServiceFactory(
+ new TestingOperationServiceFactory(testingNetconfOperation));
SessionIdProvider idProvider = new SessionIdProvider();
- NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
+ NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new
+ NetconfServerSessionNegotiatorFactoryBuilder()
.setTimer(hashedWheelTimer)
.setAggregatedOpService(factoriesListener)
.setIdProvider(idProvider)
.setBaseCapabilities(serverCaps)
.build();
- NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
- final NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
+ NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
+ new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
+ final NetconfServerDispatcherImpl dispatch =
+ new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
- ChannelFuture s = dispatch.createServer(netconfAddress);
- s.await();
+ ChannelFuture server = dispatch.createServer(NETCONF_ADDRESS);
+ server.await();
}
@After
- public void tearDown(){
+ public void tearDown() {
hashedWheelTimer.stop();
try {
nettyGroup.shutdownGracefully().get();
}
/**
- * Responds to all operations except start-exi and counts all requests
+ * Responds to all operations except start-exi and counts all requests.
*/
private static class TestingNetconfOperation implements NetconfOperation {
@Override
public HandlingPriority canHandle(Document message) {
- return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI) ?
- HandlingPriority.CANNOT_HANDLE :
+ return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI)
+ ? HandlingPriority.CANNOT_HANDLE :
HandlingPriority.HANDLE_WITH_MAX_PRIORITY;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
+ public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation)
+ throws DocumentedException {
try {
LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
counter.getAndIncrement();
}
/**
- * Hardcoded operation service factory
+ * Hardcoded operation service factory.
*/
private static class TestingOperationServiceFactory implements NetconfOperationServiceFactory {
private final NetconfOperation[] operations;
- public TestingOperationServiceFactory(final NetconfOperation... operations) {
+ TestingOperationServiceFactory(final NetconfOperation... operations) {
this.operations = operations;
}
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- return new AutoCloseable(){
+ return new AutoCloseable() {
@Override
- public void close() throws Exception {}
+ public void close() throws Exception {
+ }
};
}
}
@Override
- public void close() {}
+ public void close() {
+ }
};
}
}
/**
- * Pure socket based blocking client
+ * Pure socket based blocking client.
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
public final class BlockingClientRunnable implements Runnable {
@Override
private void run2() throws Exception {
InputStream clientHello = checkNotNull(XmlFileLoader
.getResourceAsStream("netconfMessages/client_hello.xml"));
- InputStream getConfig = checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
+ final InputStream getConfig =
+ checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
- Socket clientSocket = new Socket(netconfAddress.getHostString(), netconfAddress.getPort());
+ Socket clientSocket = new Socket(NETCONF_ADDRESS.getHostString(), NETCONF_ADDRESS.getPort());
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
InputStreamReader inFromServer = new InputStreamReader(clientSocket.getInputStream());
}
/**
- * TestingNetconfClient based runnable
+ * TestingNetconfClient based runnable.
*/
public final class TestingNetconfClientRunnable implements Runnable {
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void run() {
try {
final TestingNetconfClient netconfClient =
- new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher, getClientConfig());
+ new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher,
+ getClientConfig());
long sessionId = netconfClient.getSessionId();
LOG.info("Client with session id {}: hello exchanged", sessionId);
private NetconfClientConfiguration getClientConfig() {
final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
- b.withAddress(netconfAddress);
+ b.withAddress(NETCONF_ADDRESS);
b.withAdditionalHeader(new NetconfHelloMessageAdditionalHeader("uname", "10.10.10.1", "830", "tcp",
"client"));
b.withSessionListener(new SimpleNetconfClientSessionListener());
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.util.test.XmlFileLoader;
-public class ExiEncodeDecodeTest {
+public class ExiEncodeDecodeTest {
@Test
- public void encodeExi() throws Exception{
+ public void encodeExi() throws Exception {
String startExiString = XmlFileLoader.xmlFileToString("netconfMessages/startExi.xml");
assertNotNull(startExiString);
/*
ExiParameters exiParams = new ExiParameters();
- exiParams.setParametersFromXmlElement(XmlElement.fromDomElement(startExiMessage.getDocument().getDocumentElement()));
+ exiParams.setParametersFromXmlElement(XmlElement.fromDomElement(startExiMessage.getDocument()
+ .getDocumentElement()));
assertNotNull(exiParams);
ByteBuf encodedBuf = Unpooled.buffer();
if (i == chunkCount) {
exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
- recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length,
- eom);
+ recievedOutbound
+ .getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom);
assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
}
ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound();
byte[] eom = new byte[NetconfMessageConstants.END_OF_MESSAGE.length];
- recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length, eom);
+ recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length,
+ eom);
assertArrayEquals(NetconfMessageConstants.END_OF_MESSAGE, eom);
testChunkChannel.writeInbound(recievedOutbound);
}
private static long getHeaderLength(byte[] bytes) {
- byte[] HEADER_START = new byte[] { (byte) 0x0a, (byte) 0x23 };
+ byte[] headerStart = new byte[]{(byte) 0x0a, (byte) 0x23};
return Long.parseLong(StandardCharsets.US_ASCII.decode(
- ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1)).toString());
+ ByteBuffer.wrap(bytes, headerStart.length, bytes.length - headerStart.length - 1)).toString());
}
}
SessionIdProvider idProvider = new SessionIdProvider();
hashedWheelTimer = new HashedWheelTimer();
- NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
- .setAggregatedOpService(factoriesListener)
- .setTimer(hashedWheelTimer)
- .setIdProvider(idProvider)
- .setMonitoringService(ConcurrentClientsTest.createMockedMonitoringService())
- .setConnectionTimeoutMillis(5000)
- .build();
+ NetconfServerSessionNegotiatorFactory serverNegotiatorFactory =
+ new NetconfServerSessionNegotiatorFactoryBuilder()
+ .setAggregatedOpService(factoriesListener)
+ .setTimer(hashedWheelTimer)
+ .setIdProvider(idProvider)
+ .setMonitoringService(ConcurrentClientsTest.createMockedMonitoringService())
+ .setConnectionTimeoutMillis(5000)
+ .build();
- NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
+ NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
+ new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
dispatch = new NetconfServerDispatcherImpl(
serverChannelInitializer, nettyGroup, nettyGroup);
@Test
public void test() throws Exception {
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8333);
- ChannelFuture s = dispatch.createServer(addr);
- s.get();
+ ChannelFuture server = dispatch.createServer(addr);
+ server.get();
}
}
@Test
public void testOnMessage() throws Exception {
- final Document reply = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" " +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc-reply>");
+ final Document reply = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" "
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc-reply>");
doReturn(reply).when(router).onNetconfMessage(any(), any());
- final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"101\" " +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc>"));
+ final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"101\" "
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc>"));
listener.onMessage(session, msg);
verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.IN_RPC_SUCCESS)));
channel.runPendingTasks();
public void testOnMessageRuntimeFail() throws Exception {
doThrow(new RuntimeException("runtime fail")).when(router).onNetconfMessage(any(), any());
final Document reply =
- XmlUtil.readXmlToDocument("<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<example/></rpc>");
+ XmlUtil.readXmlToDocument("<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
+ + "<example/></rpc>");
final NetconfMessage msg = new NetconfMessage(reply);
try {
listener.onMessage(session, msg);
}
}
+ @SuppressWarnings("checkstyle:RegexpSinglelineJava")
@Test
public void testOnMessageDocumentedFail() throws Exception {
final Document reply =
- XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<rpc-error>\n" +
- "<error-type>protocol</error-type>\n" +
- "<error-tag>unknown-element</error-tag>\n" +
- "<error-severity>error</error-severity>\n" +
- "<error-message>Unknown tag bad-rpc in message:\n" +
- "<bad-rpc/>\n" +
- "</error-message>\n" +
- "<error-info>\n" +
- "<bad-element>bad-rpc</bad-element>\n" +
- "</error-info>\n" +
- "</rpc-error>\n" +
- "</rpc-reply>");
+ XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<rpc-error>\n"
+ + "<error-type>protocol</error-type>\n"
+ + "<error-tag>unknown-element</error-tag>\n"
+ + "<error-severity>error</error-severity>\n"
+ + "<error-message>Unknown tag bad-rpc in message:\n"
+ + "<bad-rpc/>\n"
+ + "</error-message>\n"
+ + "<error-info>\n"
+ + "<bad-element>bad-rpc</bad-element>\n"
+ + "</error-info>\n"
+ + "</rpc-error>\n"
+ + "</rpc-reply>");
final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<bad-rpc/>"));
listener.onMessage(session, msg);
verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.IN_RPC_FAIL)));
AutoCloseable res = mock(AutoCloseable.class);
doNothing().when(res).close();
DefaultCloseSession close = new DefaultCloseSession("", res);
- Document doc = XmlUtil.newDocument();
- XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
+ final Document doc = XmlUtil.newDocument();
+ final XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
final Channel channel = mock(Channel.class);
doReturn("channel").when(channel).toString();
mockEventLoop(channel);
doReturn(sendFuture).when(channel).writeAndFlush(anyObject());
doReturn(true).when(sendFuture).isSuccess();
final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
- doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
+ doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class),
+ any(NetconfTerminationReason.class));
final NetconfServerSession session =
new NetconfServerSession(listener, channel, 1L,
NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
close.setNetconfSession(session);
close.handleWithNoSubsequentOperations(doc, elem);
// Fake close response to trigger delayed close
- session.sendMessage(new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<ok/>\n" +
- "</rpc-reply>")));
+ session.sendMessage(new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<ok/>\n"
+ + "</rpc-reply>")));
verify(channel).close();
verify(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
}
public class DefaultStopExiTest {
@Test
public void testHandleWithNoSubsequentOperations() throws Exception {
- DefaultStopExi exi = new DefaultStopExi("");
- Document doc = XmlUtil.newDocument();
+ final DefaultStopExi exi = new DefaultStopExi("");
+ final Document doc = XmlUtil.newDocument();
Channel channel = mock(Channel.class);
doReturn("mockChannel").when(channel).toString();
ChannelPipeline pipeline = mock(ChannelPipeline.class);
NetconfServerSession serverSession = new NetconfServerSession(null, channel, 2L, null);
exi.setNetconfSession(serverSession);
- assertNotNull(exi.handleWithNoSubsequentOperations(doc, XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"))));
+ assertNotNull(exi.handleWithNoSubsequentOperations(doc,
+ XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"))));
verify(pipeline, times(1)).replace(anyString(), anyString(), any(ChannelHandler.class));
}
}
private static final String TEST_MODULE_CONTENT2 = "content2";
private static final String TEST_MODULE_REV = "1970-01-01";
private static final String TEST_MODULE_REV2 = "1970-01-02";
- private static final Uri TEST_MODULE_NAMESPACE = new Uri("testModuleNamespace");
+ private static final Uri TEST_MODULE_NAMESPACE = new Uri("testModuleNamespace");
private static final String TEST_MODULE_NAME = "testModule";
private static Date TEST_MODULE_DATE;
private static Date TEST_MODULE_DATE2;
.build();
private int capabilitiesSize;
- private final Set<Capability> CAPABILITIES = new HashSet<>();
+ private final Set<Capability> capabilities = new HashSet<>();
@Mock
private Module moduleMock;
@BeforeClass
public static void suiteSetUp() throws Exception {
TEST_MODULE_DATE = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV);
- TEST_MODULE_DATE2= SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV2);
+ TEST_MODULE_DATE2 = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV2);
}
@Before
doReturn(TEST_MODULE_DATE).when(moduleMock).getRevision();
moduleCapability1 = new YangModuleCapability(moduleMock, TEST_MODULE_CONTENT);
- CAPABILITIES.add(moduleCapability1);
+ capabilities.add(moduleCapability1);
doReturn(new URI(TEST_MODULE_NAMESPACE.getValue())).when(moduleMock2).getNamespace();
doReturn(TEST_MODULE_NAME).when(moduleMock2).getName();
doReturn(TEST_MODULE_DATE2).when(moduleMock2).getRevision();
moduleCapability2 = new YangModuleCapability(moduleMock2, TEST_MODULE_CONTENT2);
- CAPABILITIES.add(new BasicCapability("urn:ietf:params:netconf:base:1.0"));
- CAPABILITIES.add(new BasicCapability("urn:ietf:params:netconf:base:1.1"));
- CAPABILITIES.add(new BasicCapability("urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&revision=2010-09-24"));
+ capabilities.add(new BasicCapability("urn:ietf:params:netconf:base:1.0"));
+ capabilities.add(new BasicCapability("urn:ietf:params:netconf:base:1.1"));
+ capabilities.add(new BasicCapability("urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&"
+ + "revision=2010-09-24"));
- doReturn(CAPABILITIES).when(operationServiceFactoryMock).getCapabilities();
- doReturn(null).when(operationServiceFactoryMock).registerCapabilityListener(any(NetconfCapabilityMonitoringService.class));
+ doReturn(capabilities).when(operationServiceFactoryMock).getCapabilities();
+ doReturn(null).when(operationServiceFactoryMock)
+ .registerCapabilityListener(any(NetconfCapabilityMonitoringService.class));
doReturn(SESSION).when(sessionMock).toManagementSession();
doNothing().when(listener).onCapabilitiesChanged(any());
doNothing().when(notificationPublisher).onSessionEnded(any());
monitoringService = new NetconfCapabilityMonitoringService(operationServiceFactoryMock);
- monitoringService.onCapabilitiesChanged(CAPABILITIES, Collections.emptySet());
+ monitoringService.onCapabilitiesChanged(capabilities, Collections.emptySet());
monitoringService.setNotificationPublisher(notificationPublisher);
monitoringService.registerListener(listener);
capabilitiesSize = monitoringService.getCapabilities().getCapability().size();
public void testGetSchemaForCapability() throws Exception {
//test multiple revisions of the same capability
monitoringService.onCapabilitiesChanged(Collections.singleton(moduleCapability2), Collections.emptySet());
- final String schema = monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV));
+ final String schema =
+ monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV));
Assert.assertEquals(TEST_MODULE_CONTENT, schema);
- final String schema2 = monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV2));
+ final String schema2 =
+ monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV2));
Assert.assertEquals(TEST_MODULE_CONTENT2, schema2);
//remove one revision
monitoringService.onCapabilitiesChanged(Collections.emptySet(), Collections.singleton(moduleCapability1));
public void testGetCapabilities() throws Exception {
Capabilities actual = monitoringService.getCapabilities();
List<Uri> exp = new ArrayList<>();
- for (Capability capability : CAPABILITIES) {
+ for (Capability capability : capabilities) {
exp.add(new Uri(capability.getCapabilityUri()));
}
//candidate is added by monitoring service automatically
final Uri uri = new Uri(capUri);
final HashSet<Capability> testCaps = new HashSet<>();
testCaps.add(new BasicCapability(capUri));
- final ArgumentCaptor<NetconfCapabilityChange> capabilityChangeCaptor = ArgumentCaptor.forClass(NetconfCapabilityChange.class);
+ final ArgumentCaptor<NetconfCapabilityChange> capabilityChangeCaptor =
+ ArgumentCaptor.forClass(NetconfCapabilityChange.class);
final ArgumentCaptor<Capabilities> monitoringListenerCaptor = ArgumentCaptor.forClass(Capabilities.class);
//add capability
monitoringService.onCapabilitiesChanged(testCaps, Collections.emptySet());
doReturn(refs).when(bundle).getServiceReferences(anyString(), anyString());
doReturn(Arrays.asList(refs)).when(bundle).getServiceReferences(any(Class.class), anyString());
doReturn("").when(bundle).getProperty(anyString());
- doReturn(registration).when(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
+ doReturn(registration).when(bundle).registerService(any(Class.class),
+ any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
doNothing().when(registration).unregister();
doNothing().when(bundle).removeServiceListener(any(ServiceListener.class));
}
public void testStart() throws Exception {
NetconfImplActivator activator = new NetconfImplActivator();
activator.start(bundle);
- verify(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
+ verify(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class),
+ any(Dictionary.class));
activator.stop(bundle);
}
}
public class NetconfOperationRouterImplTest {
- private static final String TEST_RPC = "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><test/></rpc>\n";
+ private static final String TEST_RPC = "<rpc message-id=\"101\" "
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><test/></rpc>\n";
private static final String MAX_PRIORITY_REPLY = "<high/>";
private static final String DEFAULT_PRIORITY_REPLY = "<default/>";
MockitoAnnotations.initMocks(this);
doReturn(HandlingPriority.HANDLE_WITH_MAX_PRIORITY).when(maxPrioMock).canHandle(any(Document.class));
- doReturn(XmlUtil.readXmlToDocument(MAX_PRIORITY_REPLY)).when(maxPrioMock).handle(any(Document.class), any(NetconfOperationChainedExecution.class));
+ doReturn(XmlUtil.readXmlToDocument(MAX_PRIORITY_REPLY)).when(maxPrioMock).handle(any(Document.class),
+ any(NetconfOperationChainedExecution.class));
doReturn(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY).when(defaultPrioMock).canHandle(any(Document.class));
- doReturn(XmlUtil.readXmlToDocument(DEFAULT_PRIORITY_REPLY)).when(defaultPrioMock).handle(any(Document.class), any(NetconfOperationChainedExecution.class));
+ doReturn(XmlUtil.readXmlToDocument(DEFAULT_PRIORITY_REPLY)).when(defaultPrioMock).handle(any(Document.class),
+ any(NetconfOperationChainedExecution.class));
final Set<NetconfOperation> operations = new HashSet<>();
operations.add(maxPrioMock);
@Test
public void testOnNetconfMessage() throws Exception {
- final ArgumentCaptor<NetconfOperationChainedExecution> highPriorityChainEx = ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
- final ArgumentCaptor<NetconfOperationChainedExecution> defaultPriorityChainEx = ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
+ final ArgumentCaptor<NetconfOperationChainedExecution> highPriorityChainEx =
+ ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
+ final ArgumentCaptor<NetconfOperationChainedExecution> defaultPriorityChainEx =
+ ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
final Document document = operationRouter.onNetconfMessage(TEST_RPC_DOC, null);
@Test
public void testOnNetconfMessageFail() throws Exception {
- try{
+ try {
emptyOperationRouter.onNetconfMessage(TEST_RPC_DOC, null);
Assert.fail("Exception expected");
} catch (final DocumentedException e) {
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
+
+ <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>
public interface BaseNetconfNotificationListener {
/**
- * Callback used to notify about a change in used capabilities
+ * Callback used to notify about a change in used capabilities.
*/
- void onCapabilityChanged(final NetconfCapabilityChange capabilityChange);
+ void onCapabilityChanged(NetconfCapabilityChange capabilityChange);
/**
- * Callback used to notify about netconf session start
+ * Callback used to notify about netconf session start.
*/
void onSessionStarted(NetconfSessionStart start);
/**
- * Callback used to notify about netconf session end
+ * Callback used to notify about netconf session end.
*/
void onSessionEnded(NetconfSessionEnd end);
package org.opendaylight.netconf.notifications;
/**
- * Registration for base notification publisher. This registration allows for publishing of base netconf notifications using generated classes
+ * Registration for base notification publisher.
+ * This registration allows for publishing of base netconf notifications using generated classes
*/
-public interface BaseNotificationPublisherRegistration extends NotificationRegistration, BaseNetconfNotificationListener {
+public interface BaseNotificationPublisherRegistration
+ extends NotificationRegistration, BaseNetconfNotificationListener {
}
while (reminderBuilder.charAt(reminderBuilder.length() - 1) == '0') {
reminderBuilder.deleteCharAt(reminderBuilder.length() - 1);
}
- LOG.warn("Fraction of second is cut to three digits. Value that was cut {}", reminderBuilder.toString());
+ LOG.warn("Fraction of second is cut to three digits. Value that was cut {}",
+ reminderBuilder.toString());
}
return Date.from(Instant.from(localDateTime));
* conversion is applied, replacing the second-of-minute of 60 with 59.
*
* @param time {@link String} representation of a time
- * @return {@code null} if time isn't ISO compliant or if the time doesn't have a leap second
- * else a {@link Date} as per as the RFC3339_DATE_PARSER.
+ * @return {@code null} if time isn't ISO compliant or if the time doesn't have a leap second
+ * else a {@link Date} as per as the RFC3339_DATE_PARSER.
*/
private static Date handlePotentialLeapSecond(final String time) {
// Parse the string from offset 0, so we get the whole value.
return null;
}
- LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}", time);
+ LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}",
+ time);
// Applying simple conversion replacing the second-of-minute of 60 with 59.
}
/**
+ * Get value asociated with {@code ChronoField}.
+ *
* @param accessor The {@link TemporalAccessor}
* @param field The {@link ChronoField} to get
* @return the value associated with the {@link ChronoField} for the given {@link TemporalAccessor} if present,
- * else 0.
+ * else 0.
*/
private static int getFieldFromTemporalAccessor(final TemporalAccessor accessor, final ChronoField field) {
return accessor.isSupported(field) ? (int) accessor.getLong(field) : 0;
public static final String EVENT_TIME = "eventTime";
/**
- * Used for unknown/un-parse-able event-times
+ * Used for unknown/un-parse-able event-times.
*/
public static final Date UNKNOWN_EVENT_TIME = new Date(0);
private final Date eventTime;
/**
- * Create new notification and capture the timestamp in the constructor
+ * Create new notification and capture the timestamp in the constructor.
*/
public NetconfNotification(final Document notificationContent) {
this(notificationContent, new Date());
}
/**
- * Create new notification with provided timestamp
+ * Create new notification with provided timestamp.
*/
public NetconfNotification(final Document notificationContent, final Date eventTime) {
super(wrapNotification(notificationContent, eventTime));
}
/**
+ * Get the time of the event.
+ *
* @return notification event time
*/
public Date getEventTime() {
public interface NetconfNotificationCollector {
/**
- * Add notification publisher for a particular stream
+ * Add notification publisher for a particular stream.
*
+ * <p>
* Implementations should allow for multiple publishers of a single stream
* and its up to implementations to decide how to merge metadata (e.g. description)
* for the same stream when providing information about available stream
NotificationPublisherRegistration registerNotificationPublisher(Stream stream);
/**
- * Register base notification publisher
+ * Register base notification publisher.
*/
BaseNotificationPublisherRegistration registerBaseNotificationPublisher();
* Users of the registry have an option to get notification each time new notification stream gets registered
* This allows for a push model in addition to pull model for retrieving information about available streams.
*
+ * <p>
* The listener should receive callbacks for each stream available prior to the registration when its registered
*/
NotificationRegistration registerStreamListener(NetconfNotificationStreamListener listener);
/**
- * Simple listener that receives notifications about changes in stream availability
+ * Simple listener that receives notifications about changes in stream availability.
*/
public interface NetconfNotificationStreamListener {
/**
- * Stream becomes available in the collector (first publisher is registered)
+ * Stream becomes available in the collector (first publisher is registered).
*/
void onStreamRegistered(Stream stream);
/**
- * Stream is not available anymore in the collector (last publisher is unregistered)
+ * Stream is not available anymore in the collector (last publisher is unregistered).
*/
void onStreamUnregistered(StreamNameType stream);
}
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
/**
- * Generic listener for netconf notifications
+ * Generic listener for netconf notifications.
*/
public interface NetconfNotificationListener {
/**
- * Callback used to notify the listener about any new notification
+ * Callback used to notify the listener about any new notification.
*/
void onNotification(StreamNameType stream, NetconfNotification notification);
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
-/**
- *
- */
public interface NetconfNotificationRegistry {
/**
- * Add listener for a certain notification type
+ * Add listener for a certain notification type.
*/
- NotificationListenerRegistration registerNotificationListener(StreamNameType stream, NetconfNotificationListener listener);
+ NotificationListenerRegistration registerNotificationListener(StreamNameType stream,
+ NetconfNotificationListener listener);
/**
- * Check stream availability
+ * Check stream availability.
*/
boolean isStreamAvailable(StreamNameType streamNameType);
/**
- * Get all the streams available
+ * Get all the streams available.
*/
Streams getNotificationPublishers();
package org.opendaylight.netconf.notifications;
/**
- * Manages the registration of a single listener
+ * Manages the registration of a single listener.
*/
public interface NotificationListenerRegistration extends NotificationRegistration {
package org.opendaylight.netconf.notifications;
/**
- * Generic registration, used as a base for other registration types
+ * Generic registration, used as a base for other registration types.
*/
public interface NotificationRegistration extends AutoCloseable {
</instructions>
</configuration>
</plugin>
+ <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;
@ThreadSafe
-public class NetconfNotificationManager implements NetconfNotificationCollector, NetconfNotificationRegistry, NetconfNotificationListener, AutoCloseable {
+public class NetconfNotificationManager implements NetconfNotificationCollector, NetconfNotificationRegistry,
+ NetconfNotificationListener, AutoCloseable {
public static final StreamNameType BASE_STREAM_NAME = new StreamNameType("NETCONF");
public static final Stream BASE_NETCONF_STREAM;
private static final Logger LOG = LoggerFactory.getLogger(NetconfNotificationManager.class);
- // TODO excessive synchronization provides thread safety but is most likely not optimal (combination of concurrent collections might improve performance)
- // And also calling callbacks from a synchronized block is dangerous since the listeners/publishers can block the whole notification processing
+ // TODO excessive synchronization provides thread safety but is most likely not optimal
+ // (combination of concurrent collections might improve performance)
+ // And also calling callbacks from a synchronized block is dangerous
+ // since the listeners/publishers can block the whole notification processing
@GuardedBy("this")
- private final Multimap<StreamNameType, GenericNotificationListenerReg> notificationListeners = HashMultimap.create();
+ private final Multimap<StreamNameType, GenericNotificationListenerReg> notificationListeners =
+ HashMultimap.create();
@GuardedBy("this")
private final Set<NetconfNotificationStreamListener> streamListeners = Sets.newHashSet();
}
@Override
- public synchronized NotificationListenerRegistration registerNotificationListener(final StreamNameType stream, final NetconfNotificationListener listener) {
+ public synchronized NotificationListenerRegistration registerNotificationListener(
+ final StreamNameType stream,
+ final NetconfNotificationListener listener) {
Preconditions.checkNotNull(stream);
Preconditions.checkNotNull(listener);
LOG.trace("Notification listener registered for stream: {}", stream);
- final GenericNotificationListenerReg genericNotificationListenerReg = new GenericNotificationListenerReg(listener) {
+ final GenericNotificationListenerReg genericNotificationListenerReg =
+ new GenericNotificationListenerReg(listener) {
@Override
public void close() {
synchronized (NetconfNotificationManager.this) {
}
@Override
- public synchronized NotificationRegistration registerStreamListener(final NetconfNotificationStreamListener listener) {
+ public synchronized NotificationRegistration registerStreamListener(
+ final NetconfNotificationStreamListener listener) {
streamListeners.add(listener);
// Notify about all already available
}
if (streamMetadata.containsKey(streamName)) {
- LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName, streamMetadata.get(streamName));
+ LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName,
+ streamMetadata.get(streamName));
} else {
streamMetadata.put(streamName, stream);
}
availableStreams.add(streamName);
- final GenericNotificationPublisherReg genericNotificationPublisherReg = new GenericNotificationPublisherReg(this, streamName) {
+ final GenericNotificationPublisherReg genericNotificationPublisherReg =
+ new GenericNotificationPublisherReg(this, streamName) {
@Override
public void close() {
synchronized (NetconfNotificationManager.this) {
return genericNotificationPublisherReg;
}
- private void unregisterNotificationPublisher(final StreamNameType streamName, final GenericNotificationPublisherReg genericNotificationPublisherReg) {
+ private void unregisterNotificationPublisher(
+ final StreamNameType streamName,
+ final GenericNotificationPublisherReg genericNotificationPublisherReg) {
availableStreams.remove(streamName);
notificationPublishers.remove(genericNotificationPublisherReg);
@Override
public BaseNotificationPublisherRegistration registerBaseNotificationPublisher() {
- final NotificationPublisherRegistration notificationPublisherRegistration = registerNotificationPublisher(BASE_NETCONF_STREAM);
+ final NotificationPublisherRegistration notificationPublisherRegistration =
+ registerNotificationPublisher(BASE_NETCONF_STREAM);
return new BaseNotificationPublisherReg(notificationPublisherRegistration);
}
private NetconfNotificationManager baseListener;
private final StreamNameType registeredStream;
- public GenericNotificationPublisherReg(final NetconfNotificationManager baseListener, final StreamNameType registeredStream) {
+ GenericNotificationPublisherReg(final NetconfNotificationManager baseListener,
+ final StreamNameType registeredStream) {
this.baseListener = baseListener;
this.registeredStream = registeredStream;
}
private final NotificationPublisherRegistration baseRegistration;
- public BaseNotificationPublisherReg(final NotificationPublisherRegistration baseRegistration) {
+ BaseNotificationPublisherReg(final NotificationPublisherRegistration baseRegistration) {
this.baseRegistration = baseRegistration;
}
@Override
public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
- baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(capabilityChange, CAPABILITY_CHANGE_SCHEMA_PATH));
+ baseRegistration.onNotification(BASE_STREAM_NAME,
+ serializeNotification(capabilityChange, CAPABILITY_CHANGE_SCHEMA_PATH));
}
@Override
private class GenericNotificationListenerReg implements NotificationListenerRegistration {
private final NetconfNotificationListener listener;
- public GenericNotificationListenerReg(final NetconfNotificationListener listener) {
+ GenericNotificationListenerReg(final NetconfNotificationListener listener) {
this.listener = listener;
}
import org.w3c.dom.Element;
/**
- * Create subscription listens for create subscription requests and registers notification listeners into notification registry.
+ * Create subscription listens for create subscription requests
+ * and registers notification listeners into notification registry.
* Received notifications are sent to the client right away
*/
-public class CreateSubscription extends AbstractSingletonNetconfOperation implements SessionAwareNetconfOperation, AutoCloseable {
+public class CreateSubscription extends AbstractSingletonNetconfOperation
+ implements SessionAwareNetconfOperation, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(CreateSubscription.class);
private final List<NotificationListenerRegistration> subscriptions = Lists.newArrayList();
private NetconfSession netconfSession;
- public CreateSubscription(final String netconfSessionIdForReporting, final NetconfNotificationRegistry notifications) {
+ public CreateSubscription(final String netconfSessionIdForReporting,
+ final NetconfNotificationRegistry notifications) {
super(netconfSessionIdForReporting);
this.notifications = notifications;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document,
+ final XmlElement operationElement) throws DocumentedException {
operationElement.checkName(CREATE_SUBSCRIPTION);
operationElement.checkNamespace(CreateSubscriptionInput.QNAME.getNamespace().toString());
// FIXME reimplement using CODEC_REGISTRY and parse everything into generated class instance
final Optional<XmlElement> filter = operationElement.getOnlyChildElementWithSameNamespaceOptionally("filter");
// Replay not supported
- final Optional<XmlElement> startTime = operationElement.getOnlyChildElementWithSameNamespaceOptionally("startTime");
+ final Optional<XmlElement> startTime =
+ operationElement.getOnlyChildElementWithSameNamespaceOptionally("startTime");
Preconditions.checkArgument(startTime.isPresent() == false, "StartTime element not yet supported");
// Stop time not supported
- final Optional<XmlElement> stopTime = operationElement.getOnlyChildElementWithSameNamespaceOptionally("stopTime");
+ final Optional<XmlElement> stopTime =
+ operationElement.getOnlyChildElementWithSameNamespaceOptionally("stopTime");
Preconditions.checkArgument(stopTime.isPresent() == false, "StopTime element not yet supported");
final StreamNameType streamNameType = parseStreamIfPresent(operationElement);
Preconditions.checkNotNull(netconfSession);
// Premature streams are allowed (meaning listener can register even if no provider is available yet)
- if(notifications.isStreamAvailable(streamNameType) == false) {
- LOG.warn("Registering premature stream {}. No publisher available yet for session {}", streamNameType, getNetconfSessionIdForReporting());
+ if (notifications.isStreamAvailable(streamNameType) == false) {
+ LOG.warn("Registering premature stream {}. No publisher available yet for session {}", streamNameType,
+ getNetconfSessionIdForReporting());
}
- final NotificationListenerRegistration notificationListenerRegistration =
- notifications.registerNotificationListener(streamNameType, new NotificationSubscription(netconfSession, filter));
+ final NotificationListenerRegistration notificationListenerRegistration = notifications
+ .registerNotificationListener(streamNameType, new NotificationSubscription(netconfSession, filter));
subscriptions.add(notificationListenerRegistration);
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
private static StreamNameType parseStreamIfPresent(final XmlElement operationElement) throws DocumentedException {
final Optional<XmlElement> stream = operationElement.getOnlyChildElementWithSameNamespaceOptionally("stream");
- return stream.isPresent() ? new StreamNameType(stream.get().getTextContent()) : NetconfNotificationManager.BASE_STREAM_NAME;
+ return stream.isPresent() ? new StreamNameType(stream.get().getTextContent())
+ : NetconfNotificationManager.BASE_STREAM_NAME;
}
@Override
private final NetconfSession currentSession;
private final Optional<XmlElement> filter;
- public NotificationSubscription(final NetconfSession currentSession, final Optional<XmlElement> filter) {
+ NotificationSubscription(final NetconfSession currentSession, final Optional<XmlElement> filter) {
this.currentSession = currentSession;
this.filter = filter;
}
public void onNotification(final StreamNameType stream, final NetconfNotification notification) {
if (filter.isPresent()) {
try {
- final Optional<Document> filtered = SubtreeFilter.applySubtreeNotificationFilter(this.filter.get(), notification.getDocument());
+ final Optional<Document> filtered =
+ SubtreeFilter.applySubtreeNotificationFilter(this.filter.get(), notification.getDocument());
if (filtered.isPresent()) {
final Date eventTime = notification.getEventTime();
currentSession.sendMessage(new NetconfNotification(filtered.get(), eventTime));
public class Get extends AbstractNetconfOperation implements AutoCloseable {
private static final String GET = "get";
- private static final InstanceIdentifier<Netconf> NETCONF_SUBTREE_INSTANCE_IDENTIFIER = InstanceIdentifier.builder(Netconf.class).build();
+ private static final InstanceIdentifier<Netconf> NETCONF_SUBTREE_INSTANCE_IDENTIFIER =
+ InstanceIdentifier.builder(Netconf.class).build();
private final NetconfNotificationRegistry notificationRegistry;
}
@Override
- public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
+ protected Element handle(final Document document, final XmlElement message,
+ final NetconfOperationChainedExecution subsequentOperation)
+ throws DocumentedException {
+ throw new UnsupportedOperationException("Never gets called");
+ }
+
+ @Override
+ public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
+ throws DocumentedException {
final Document partialResponse = subsequentOperation.execute(requestMessage);
final Streams availableStreams = notificationRegistry.getNotificationPublishers();
- if(availableStreams.getStream().isEmpty() == false) {
+ if (availableStreams.getStream().isEmpty() == false) {
serializeStreamsSubtree(partialResponse, availableStreams);
}
return partialResponse;
}
- static void serializeStreamsSubtree(final Document partialResponse, final Streams availableStreams) throws DocumentedException {
+ static void serializeStreamsSubtree(final Document partialResponse, final Streams availableStreams)
+ throws DocumentedException {
final Netconf netconfSubtree = new NetconfBuilder().setStreams(availableStreams).build();
final NormalizedNode<?, ?> normalized = toNormalized(netconfSubtree);
final DOMResult result = new DOMResult(getPlaceholder(partialResponse));
try {
- NetconfUtil.writeNormalizedNode(normalized, result, SchemaPath.ROOT, NotificationsTransformUtil.NOTIFICATIONS_SCHEMA_CTX);
+ NetconfUtil.writeNormalizedNode(normalized, result, SchemaPath.ROOT,
+ NotificationsTransformUtil.NOTIFICATIONS_SCHEMA_CTX);
} catch (final XMLStreamException | IOException e) {
throw new IllegalStateException("Unable to serialize " + netconfSubtree, e);
}
private static Element getPlaceholder(final Document innerResult)
throws DocumentedException {
- final XmlElement rootElement = XmlElement.fromDomElementWithExpected(
- innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ final XmlElement rootElement = XmlElement.fromDomElementWithExpected(innerResult.getDocumentElement(),
+ XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
}
private static NormalizedNode<?, ?> toNormalized(final Netconf netconfSubtree) {
- return NotificationsTransformUtil.CODEC_REGISTRY.toNormalizedNode(NETCONF_SUBTREE_INSTANCE_IDENTIFIER, netconfSubtree).getValue();
- }
-
- @Override
- protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation)
- throws DocumentedException {
- throw new UnsupportedOperationException("Never gets called");
+ return NotificationsTransformUtil.CODEC_REGISTRY
+ .toNormalizedNode(NETCONF_SUBTREE_INSTANCE_IDENTIFIER, netconfSubtree).getValue();
}
@Override
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
moduleInfoBackedContext.addModuleInfos(Collections.singletonList($YangModuleInfoImpl.getInstance()));
- moduleInfoBackedContext.addModuleInfos(Collections.singletonList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()));
+ moduleInfoBackedContext.addModuleInfos(Collections.singletonList(org.opendaylight.yang.gen.v1.urn.ietf.params
+ .xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()));
final Optional<SchemaContext> schemaContextOptional = moduleInfoBackedContext.tryToCreateSchemaContext();
Preconditions.checkState(schemaContextOptional.isPresent());
NOTIFICATIONS_SCHEMA_CTX = schemaContextOptional.get();
final JavassistUtils javassist = JavassistUtils.forClassPool(ClassPool.getDefault());
CODEC_REGISTRY = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(javassist));
- CODEC_REGISTRY.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, NOTIFICATIONS_SCHEMA_CTX));
+ CODEC_REGISTRY.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext,
+ NOTIFICATIONS_SCHEMA_CTX));
}
private static RpcDefinition findCreateSubscriptionRpc() {
- return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(), new Predicate<RpcDefinition>() {
- @Override
- public boolean apply(final RpcDefinition input) {
- return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
- }
- }), null);
+ return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(),
+ new Predicate<RpcDefinition>() {
+ @Override
+ public boolean apply(final RpcDefinition input) {
+ return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
+ }
+ }), null);
}
/**
- * Transform base notification for capabilities into NetconfNotification
+ * Transform base notification for capabilities into NetconfNotification.
*/
public static NetconfNotification transform(final Notification notification, SchemaPath path) {
return transform(notification, Optional.<Date>absent(), path);
}
- public static NetconfNotification transform(final Notification notification, final Date eventTime, SchemaPath path) {
+ public static NetconfNotification transform(final Notification notification,
+ final Date eventTime, SchemaPath path) {
return transform(notification, Optional.fromNullable(eventTime), path);
}
- private static NetconfNotification transform(final Notification notification, final Optional<Date> eventTime, SchemaPath path) {
+ private static NetconfNotification transform(final Notification notification,
+ final Optional<Date> eventTime, SchemaPath path) {
final ContainerNode containerNode = CODEC_REGISTRY.toNormalizedNodeNotification(notification);
final DOMResult result = new DOMResult(XmlUtil.newDocument());
try {
NetconfUtil.writeNormalizedNode(containerNode, result, path, NOTIFICATIONS_SCHEMA_CTX);
- } catch (final XMLStreamException| IOException e) {
+ } catch (final XMLStreamException | IOException e) {
throw new IllegalStateException("Unable to serialize " + notification, e);
}
final Document node = (Document) result.getNode();
- return eventTime.isPresent() ?
- new NetconfNotification(node, eventTime.get()):
- new NetconfNotification(node);
+ return eventTime.isPresent() ? new NetconfNotification(node, eventTime.get()) : new NetconfNotification(node);
}
}
// Add properties to autowire with netconf-impl instance for cfg subsystem
final Dictionary<String, String> props = new Hashtable<>();
props.put(NetconfConstants.SERVICE_NAME, NetconfConstants.NETCONF_NOTIFICATION);
- netconfNotificationCollectorServiceRegistration = context.registerService(NetconfNotificationCollector.class, netconfNotificationManager, new Hashtable<String, Object>());
+ netconfNotificationCollectorServiceRegistration = context.registerService(NetconfNotificationCollector.class,
+ netconfNotificationManager, new Hashtable<String, Object>());
final NetconfOperationServiceFactory netconfOperationServiceFactory = new NetconfOperationServiceFactory() {
- private final Set<Capability> capabilities = Collections.<Capability>singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
+ private final Set<Capability> capabilities =
+ Collections.<Capability>singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
@Override
public Set<Capability> getCapabilities() {
public NetconfOperationService createService(final String netconfSessionIdForReporting) {
return new NetconfOperationService() {
- private final CreateSubscription createSubscription = new CreateSubscription(netconfSessionIdForReporting, netconfNotificationManager);
+ private final CreateSubscription createSubscription =
+ new CreateSubscription(netconfSessionIdForReporting, netconfNotificationManager);
@Override
public Set<NetconfOperation> getNetconfOperations() {
final Dictionary<String, String> properties = new Hashtable<>();
properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.NETCONF_MONITORING);
- operationaServiceRegistration = context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
+ operationaServiceRegistration = context.registerService(NetconfOperationServiceFactory.class,
+ netconfOperationServiceFactory, properties);
}
@Override
public void stop(final BundleContext context) throws Exception {
- if(netconfNotificationCollectorServiceRegistration != null) {
+ if (netconfNotificationCollectorServiceRegistration != null) {
netconfNotificationCollectorServiceRegistration.unregister();
netconfNotificationCollectorServiceRegistration = null;
}
)) {
try {
final Date apply = NetconfNotification.RFC3339_DATE_PARSER.apply(time);
- final Date parse = new SimpleDateFormat(RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT).parse(iterator.next());
+ final Date parse =
+ new SimpleDateFormat(RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT).parse(iterator.next());
assertEquals(parse.getTime(), apply.getTime());
// Testing that we're consistent from formatting to parsing.
final String dateString = NetconfNotification.RFC3339_DATE_FORMATTER.apply(apply);
final NetconfNotificationListener listener = mock(NetconfNotificationListener.class);
doNothing().when(listener).onNotification(any(StreamNameType.class), any(NetconfNotification.class));
- final NotificationListenerRegistration notificationListenerRegistration = netconfNotificationManager.registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
+ final NotificationListenerRegistration notificationListenerRegistration = netconfNotificationManager
+ .registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
final NetconfCapabilityChange notification = capabilityChangedBuilder.build();
baseNotificationPublisherRegistration.onCapabilityChanged(notification);
public void testClose() throws Exception {
final NetconfNotificationManager netconfNotificationManager = new NetconfNotificationManager();
- final BaseNotificationPublisherRegistration baseNotificationPublisherRegistration = netconfNotificationManager.registerBaseNotificationPublisher();
+ final BaseNotificationPublisherRegistration baseNotificationPublisherRegistration =
+ netconfNotificationManager.registerBaseNotificationPublisher();
final NetconfNotificationListener listener = mock(NetconfNotificationListener.class);
doNothing().when(listener).onNotification(any(StreamNameType.class), any(NetconfNotification.class));
- netconfNotificationManager.registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
+ netconfNotificationManager
+ .registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
final NetconfNotificationCollector.NetconfNotificationStreamListener streamListener =
mock(NetconfNotificationCollector.NetconfNotificationStreamListener.class);
public void testStreamListeners() throws Exception {
final NetconfNotificationManager netconfNotificationManager = new NetconfNotificationManager();
- final NetconfNotificationCollector.NetconfNotificationStreamListener streamListener = mock(NetconfNotificationCollector.NetconfNotificationStreamListener.class);
+ final NetconfNotificationCollector.NetconfNotificationStreamListener streamListener =
+ mock(NetconfNotificationCollector.NetconfNotificationStreamListener.class);
doNothing().when(streamListener).onStreamRegistered(any(Stream.class));
doNothing().when(streamListener).onStreamUnregistered(any(StreamNameType.class));
public class CreateSubscriptionTest {
- private static final String CREATE_SUBSCRIPTION_XML = "<create-subscription\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<stream>TESTSTREAM</stream>" +
- "</create-subscription>";
+ private static final String CREATE_SUBSCRIPTION_XML = "<create-subscription\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\" "
+ + "xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<stream>TESTSTREAM</stream>"
+ + "</create-subscription>";
@Mock
private NetconfNotificationRegistry notificationRegistry;
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doReturn(true).when(notificationRegistry).isStreamAvailable(any(StreamNameType.class));
- doReturn(mock(NotificationListenerRegistration.class)).when(notificationRegistry).registerNotificationListener(any(StreamNameType.class), any(NetconfNotificationListener.class));
+ doReturn(mock(NotificationListenerRegistration.class)).when(notificationRegistry)
+ .registerNotificationListener(any(StreamNameType.class), any(NetconfNotificationListener.class));
}
@Test
final Element e = XmlUtil.readXmlToElement(CREATE_SUBSCRIPTION_XML);
final XmlElement operationElement = XmlElement.fromDomElement(e);
- final Element element = createSubscription.handleWithNoSubsequentOperations(XmlUtil.newDocument(), operationElement);
+ final Element element =
+ createSubscription.handleWithNoSubsequentOperations(XmlUtil.newDocument(), operationElement);
Assert.assertThat(XmlUtil.toString(element), CoreMatchers.containsString("ok"));
}
final Document response = getBlankResponse();
Get.serializeStreamsSubtree(response, streams);
NotificationsTransformUtilTest.compareXml(XmlUtil.toString(response),
- "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<data>\n" +
- "<netconf xmlns=\"urn:ietf:params:xml:ns:netmod:notification\">\n" +
- "<streams>\n" +
- "<stream>\n" +
- "<name>base</name>\n" +
- "<description>description</description>\n" +
- "<replaySupport>false</replaySupport>\n" +
- "</stream>\n" +
- "</streams>\n" +
- "</netconf>\n" +
- "</data>\n" +
- "</rpc-reply>\n");
+ "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<data>\n"
+ + "<netconf xmlns=\"urn:ietf:params:xml:ns:netmod:notification\">\n"
+ + "<streams>\n"
+ + "<stream>\n"
+ + "<name>base</name>\n"
+ + "<description>description</description>\n"
+ + "<replaySupport>false</replaySupport>\n"
+ + "</stream>\n"
+ + "</streams>\n"
+ + "</netconf>\n"
+ + "</data>\n"
+ + "</rpc-reply>\n");
}
private static Document getBlankResponse() throws IOException, SAXException {
- return XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<data>\n" +
- "</data>\n" +
- "</rpc-reply>");
+ return XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<data>\n"
+ + "</data>\n"
+ + "</rpc-reply>");
}
}
\ No newline at end of file
public class NotificationsTransformUtilTest {
private static final Date DATE = new Date();
- private static final String innerNotification = "<netconf-capability-change xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-notifications\">" +
- "<deleted-capability>uri4</deleted-capability>" +
- "<deleted-capability>uri3</deleted-capability>" +
- "<added-capability>uri1</added-capability>" +
- "</netconf-capability-change>";
+ private static final String INNER_NOTIFICATION =
+ "<netconf-capability-change xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-notifications\">"
+ + "<deleted-capability>uri4</deleted-capability>"
+ + "<deleted-capability>uri3</deleted-capability>"
+ + "<added-capability>uri1</added-capability>"
+ + "</netconf-capability-change>";
- private static final String expectedNotification =
+ private static final String EXPECTED_NOTIFICATION =
"<notification xmlns=\"urn:ietf:params:netconf:capability:notification:1.0\">"
- + innerNotification
+ + INNER_NOTIFICATION
+ "<eventTime>"
- + NetconfNotification.RFC3339_DATE_FORMATTER.apply(DATE)
- + "</eventTime>" +
- "</notification>";
+ + NetconfNotification.RFC3339_DATE_FORMATTER.apply(DATE)
+ + "</eventTime>"
+ + "</notification>";
@Test
public void testTransform() throws Exception {
netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(new Uri("uri4"), new Uri("uri3")));
final NetconfCapabilityChange capabilityChange = netconfCapabilityChangeBuilder.build();
- final NetconfNotification transform = NotificationsTransformUtil.transform(capabilityChange, DATE, SchemaPath.create(true, NetconfCapabilityChange.QNAME));
+ final NetconfNotification transform = NotificationsTransformUtil.transform(capabilityChange, DATE,
+ SchemaPath.create(true, NetconfCapabilityChange.QNAME));
final String serialized = XmlUtil.toString(transform.getDocument());
- compareXml(expectedNotification, serialized);
+ compareXml(EXPECTED_NOTIFICATION, serialized);
}
static void compareXml(final String expected, final String actual) throws SAXException, IOException {
@Test
public void testTransformFromDOM() throws Exception {
- final NetconfNotification netconfNotification = new NetconfNotification(XmlUtil.readXmlToDocument(innerNotification), DATE);
+ final NetconfNotification netconfNotification =
+ new NetconfNotification(XmlUtil.readXmlToDocument(INNER_NOTIFICATION), DATE);
XMLUnit.setIgnoreWhitespace(true);
- compareXml(expectedNotification, netconfNotification.toString());
+ compareXml(EXPECTED_NOTIFICATION, netconfNotification.toString());
}
}
final ServiceRegistration operationaServiceRegistration = mock(ServiceRegistration.class);
// test registering services
- doReturn(netconfNotificationCollectorServiceRegistration).when(context).
- registerService(eq(NetconfNotificationCollector.class), any(NetconfNotificationManager.class), any());
- doReturn(operationaServiceRegistration).when(context).
- registerService(eq(NetconfOperationServiceFactory.class), any(NetconfOperationServiceFactory.class), any());
+ doReturn(netconfNotificationCollectorServiceRegistration).when(context)
+ .registerService(eq(NetconfNotificationCollector.class), any(NetconfNotificationManager.class), any());
+ doReturn(operationaServiceRegistration).when(context).registerService(eq(NetconfOperationServiceFactory.class),
+ any(NetconfOperationServiceFactory.class), any());
activator.start(context);
// test service factory argument requisites
final NetconfOperationServiceFactory serviceFactory = serviceFactoryArgumentCaptor.getValue();
- final Set<Capability> capabilities = Collections.singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
+ final Set<Capability> capabilities =
+ Collections.singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
- assertEquals(capabilities.iterator().next().getCapabilityUri(), serviceFactory.getCapabilities().iterator().next().getCapabilityUri());
- assertEquals(capabilities.iterator().next().getCapabilitySchema(), serviceFactory.getCapabilities().iterator().next().getCapabilitySchema());
- assertEquals(capabilities.iterator().next().getModuleNamespace(), serviceFactory.getCapabilities().iterator().next().getModuleNamespace());
- assertEquals(capabilities.iterator().next().getModuleName(), serviceFactory.getCapabilities().iterator().next().getModuleName());
+ assertEquals(capabilities.iterator().next()
+ .getCapabilityUri(), serviceFactory.getCapabilities().iterator().next().getCapabilityUri());
+ assertEquals(capabilities.iterator().next()
+ .getCapabilitySchema(), serviceFactory.getCapabilities().iterator().next().getCapabilitySchema());
+ assertEquals(capabilities.iterator().next()
+ .getModuleNamespace(), serviceFactory.getCapabilities().iterator().next().getModuleNamespace());
+ assertEquals(capabilities.iterator().next()
+ .getModuleName(), serviceFactory.getCapabilities().iterator().next().getModuleName());
final CapabilityListener listener = mock(CapabilityListener.class);
final NetconfOperationService netconfOperationService = serviceFactory.createService("id");
final Set<NetconfOperation> netconfOperations = netconfOperationService.getNetconfOperations();
- final CreateSubscription createSubscription = new CreateSubscription("id", activator.getNetconfNotificationManager());
+ final CreateSubscription createSubscription =
+ new CreateSubscription("id", activator.getNetconfNotificationManager());
netconfOperations.forEach(
- operation -> {
- if (operation instanceof CreateSubscription) {
- assertEquals(createSubscription.toString(), operation.toString());
- }
- if (operation instanceof Get) {
- assertEquals("id", ((Get) operation).getNetconfSessionIdForReporting());
- }
+ operation -> {
+ if (operation instanceof CreateSubscription) {
+ assertEquals(createSubscription.toString(), operation.toString());
}
+ if (operation instanceof Get) {
+ assertEquals("id", ((Get) operation).getNetconfSessionIdForReporting());
+ }
+ }
);
// test unregister after stop
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
private InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
try {
IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
- final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null ?
- ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
+ final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null
+ ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
return new InetSocketAddress(inetAd, Integer.valueOf(portNumber));
} catch (final UnknownHostException e) {
throw new IllegalArgumentException("Unable to bind netconf tcp endpoint to address " + bindingAddress, e);
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.netconf.tcp.netty;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ProxyClientHandler extends ChannelInboundHandlerAdapter {
+ private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
+
+ private final ChannelHandlerContext remoteCtx;
+ private ChannelHandlerContext localCtx;
+
+ ProxyClientHandler(ChannelHandlerContext remoteCtx) {
+ this.remoteCtx = remoteCtx;
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) {
+ checkState(this.localCtx == null);
+ LOG.trace("Client channel active");
+ this.localCtx = ctx;
+ }
+
+ @Override
+ public void channelRead(ChannelHandlerContext ctx, Object msg) {
+ LOG.trace("Forwarding message");
+ remoteCtx.write(msg);
+ }
+
+ @Override
+ public void channelReadComplete(ChannelHandlerContext ctx) {
+ LOG.trace("Flushing remote ctx");
+ remoteCtx.flush();
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ // Close the connection when an exception is raised.
+ LOG.warn("Unexpected exception from downstream", cause);
+ checkState(this.localCtx.equals(ctx));
+ ctx.close();
+ }
+
+ // called both when local or remote connection dies
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) {
+ LOG.trace("channelInactive() called, closing remote client ctx");
+ remoteCtx.close();
+ }
+
+}
package org.opendaylight.netconf.tcp.netty;
-import static com.google.common.base.Preconditions.checkState;
-
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
}
}
-class ProxyClientHandler extends ChannelInboundHandlerAdapter {
- private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
-
- private final ChannelHandlerContext remoteCtx;
- private ChannelHandlerContext localCtx;
-
- public ProxyClientHandler(ChannelHandlerContext remoteCtx) {
- this.remoteCtx = remoteCtx;
- }
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) {
- checkState(this.localCtx == null);
- LOG.trace("Client channel active");
- this.localCtx = ctx;
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- LOG.trace("Forwarding message");
- remoteCtx.write(msg);
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) {
- LOG.trace("Flushing remote ctx");
- remoteCtx.flush();
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- // Close the connection when an exception is raised.
- LOG.warn("Unexpected exception from downstream", cause);
- checkState(this.localCtx.equals(ctx));
- ctx.close();
- }
-
- // called both when local or remote connection dies
- @Override
- public void channelInactive(ChannelHandlerContext ctx) {
- LOG.trace("channelInactive() called, closing remote client ctx");
- remoteCtx.close();
- }
-
-}
final InetSocketAddress address = netconfConfiguration.getTcpServerAddress();
if (address.getAddress().isAnyLocalAddress()) {
- LOG.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. " +
- "Consider changing tcp-address in netconf.cfg to 127.0.0.1");
+ LOG.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. "
+ + "Consider changing tcp-address in netconf.cfg to 127.0.0.1");
}
LOG.info("Starting TCP netconf server at {}", address);
proxyServer = new ProxyServer(address, NetconfConfiguration.NETCONF_LOCAL_ADDRESS);
<reference id="clientDispatcherDependency"
interface="org.opendaylight.netconf.client.NetconfClientDispatcher"
odl:type="netconf-client-dispatcher"/>
- <reference id="bindingAwareBroker"
- interface="org.opendaylight.controller.sal.binding.api.BindingAwareBroker"/>
<reference id="keepAliveExecutor"
interface="org.opendaylight.controller.config.threadpool.ScheduledThreadPool"
odl:type="global-netconf-ssh-scheduled-executor"/>
<reference id="processingExecutor"
interface="org.opendaylight.controller.config.threadpool.ThreadPool"
odl:type="global-netconf-processing-executor"/>
- <reference id="domBroker"
- interface="org.opendaylight.controller.sal.core.api.Broker"/>
<reference id="eventExecutor"
interface="io.netty.util.concurrent.EventExecutor"
odl:type="global-event-executor"/>
<reference id="dataBroker"
interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"/>
+ <reference id="mountPointService"
+ interface="org.opendaylight.controller.md.sal.dom.api.DOMMountPointService"
+ odl:type="default"/>
<bean id="schemaRepository" class="org.opendaylight.netconf.topology.impl.SchemaRepositoryProviderImpl">
<argument value="shared-schema-repository-impl"/>
destroy-method="close">
<argument value="topology-netconf"/>
<argument ref="clientDispatcherDependency"/>
- <argument ref="bindingAwareBroker"/>
- <argument ref="domBroker"/>
<argument ref="eventExecutor"/>
<argument ref="keepAliveExecutor"/>
<argument ref="processingExecutor"/>
<argument ref="schemaRepository"/>
<argument ref="dataBroker"/>
+ <argument ref="mountPointService"/>
</bean>
<bean id="netconfConnectorFactory" class="org.opendaylight.netconf.topology.impl.NetconfConnectorFactoryImpl"/>
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.stream.Collectors;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
private final RemoteDeviceId id;
private final Timeout actorResponseWaitTime;
+ private final NetconfDeviceSalProvider salProvider;
+ private final ActorRef masterActorRef;
+ private final ActorSystem actorSystem;
private SchemaContext remoteSchemaContext = null;
private NetconfSessionPreferences netconfSessionPreferences = null;
private DOMRpcService deviceRpc = null;
- private final NetconfDeviceSalProvider salProvider;
-
- private final ActorRef masterActorRef;
- private final ActorSystem actorSystem;
private DOMDataBroker deviceDataBroker = null;
MasterSalFacade(final RemoteDeviceId id,
- final Broker domBroker,
- final BindingAwareBroker bindingBroker,
final ActorSystem actorSystem,
final ActorRef masterActorRef,
- final Timeout actorResponseWaitTime) {
+ final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountService,
+ final DataBroker dataBroker) {
this.id = id;
- this.salProvider = new NetconfDeviceSalProvider(id);
+ this.salProvider = new NetconfDeviceSalProvider(id, mountService, dataBroker);
this.actorSystem = actorSystem;
this.masterActorRef = masterActorRef;
this.actorResponseWaitTime = actorResponseWaitTime;
-
- registerToSal(domBroker, bindingBroker);
- }
-
- private void registerToSal(final Broker domRegistryDependency, final BindingAwareBroker bindingBroker) {
- // TODO: remove use of provider, there is possible directly create mount instance and
- // TODO: NetconfDeviceTopologyAdapter in constructor = less complexity
-
- domRegistryDependency.registerProvider(salProvider);
- bindingBroker.registerProvider(salProvider);
}
@Override
import java.util.Collection;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService;
import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeManager.class);
+ private final Timeout actorResponseWaitTime;
+ private final DOMMountPointService mountPointService;
+ private final SchemaSourceRegistry schemaRegistry;
+ private final SchemaRepository schemaRepository;
+
private NetconfTopologySetup setup;
private ListenerRegistration<NetconfNodeManager> dataChangeListenerRegistration;
private RemoteDeviceId id;
- private final SchemaSourceRegistry schemaRegistry;
- private final SchemaRepository schemaRepository;
private ActorRef slaveActorRef;
- private final Timeout actorResponseWaitTime;
+
NetconfNodeManager(final NetconfTopologySetup setup,
- final RemoteDeviceId id, final Timeout actorResponseWaitTime) {
+ final RemoteDeviceId id, final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountPointService) {
this.setup = setup;
this.id = id;
this.schemaRegistry = setup.getSchemaResourcesDTO().getSchemaRegistry();
this.schemaRepository = setup.getSchemaResourcesDTO().getSchemaRepository();
this.actorResponseWaitTime = actorResponseWaitTime;
+ this.mountPointService = mountPointService;
}
@Override
private void createActorRef() {
if (slaveActorRef == null) {
slaveActorRef = setup.getActorSystem().actorOf(NetconfNodeActor.props(setup, id, schemaRegistry,
- schemaRepository, actorResponseWaitTime), id.getName());
+ schemaRepository, actorResponseWaitTime, mountPointService), id.getName());
}
}
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
private final ServiceGroupIdentifier serviceGroupIdent;
private final Timeout actorResponseWaitTime;
+ private final DOMMountPointService mountService;
+
private NetconfTopologySetup netconfTopologyDeviceSetup;
private RemoteDeviceId remoteDeviceId;
private RemoteDeviceConnector remoteDeviceConnector;
private NetconfNodeManager netconfNodeManager;
+ private ActorRef masterActorRef;
private boolean finalClose = false;
private boolean closed = false;
private boolean isMaster;
- private ActorRef masterActorRef;
-
NetconfTopologyContext(final NetconfTopologySetup netconfTopologyDeviceSetup,
final ServiceGroupIdentifier serviceGroupIdent,
- final Timeout actorResponseWaitTime) {
+ final Timeout actorResponseWaitTime, final DOMMountPointService mountService) {
this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
this.serviceGroupIdent = serviceGroupIdent;
this.actorResponseWaitTime = actorResponseWaitTime;
+ this.mountService = mountService;
remoteDeviceId = NetconfTopologyUtils.createRemoteDeviceId(netconfTopologyDeviceSetup.getNode().getNodeId(),
netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class));
remoteDeviceConnector = new RemoteDeviceConnectorImpl(netconfTopologyDeviceSetup, remoteDeviceId,
- actorResponseWaitTime);
+ actorResponseWaitTime, mountService);
netconfNodeManager = createNodeDeviceManager();
}
final String masterAddress = Cluster.get(netconfTopologyDeviceSetup.getActorSystem()).selfAddress().toString();
masterActorRef = netconfTopologyDeviceSetup.getActorSystem().actorOf(NetconfNodeActor.props(
netconfTopologyDeviceSetup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
- actorResponseWaitTime),
+ actorResponseWaitTime, mountService),
NetconfTopologyUtils.createMasterActorName(remoteDeviceId.getName(), masterAddress));
remoteDeviceConnector.startRemoteDeviceConnection(masterActorRef);
private NetconfNodeManager createNodeDeviceManager() {
final NetconfNodeManager ndm =
- new NetconfNodeManager(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime);
+ new NetconfNodeManager(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime, mountService);
ndm.registerDataTreeChangeListener(netconfTopologyDeviceSetup.getTopologyId(),
netconfTopologyDeviceSetup.getNode().getKey());
if (!isMaster) {
netconfNodeManager.refreshDevice(netconfTopologyDeviceSetup, remoteDeviceId);
}
- remoteDeviceConnector = new RemoteDeviceConnectorImpl(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime);
+ remoteDeviceConnector = new RemoteDeviceConnectorImpl(netconfTopologyDeviceSetup, remoteDeviceId,
+ actorResponseWaitTime, mountService);
if (isMaster) {
final Future<Object> future = Patterns.ask(masterActorRef, new RefreshSetupMasterActorData(
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
private final Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration>
clusterRegistrations = new HashMap<>();
- private ListenerRegistration<NetconfTopologyManager> dataChangeListenerRegistration;
-
private final DataBroker dataBroker;
private final RpcProviderRegistry rpcProviderRegistry;
private final ClusterSingletonServiceProvider clusterSingletonServiceProvider;
- private final BindingAwareBroker bindingAwareBroker;
private final ScheduledThreadPool keepaliveExecutor;
private final ThreadPool processingExecutor;
- private final Broker domBroker;
private final ActorSystem actorSystem;
private final EventExecutor eventExecutor;
private final NetconfClientDispatcher clientDispatcher;
private final String topologyId;
private final Duration writeTxIdleTimeout;
+ private final DOMMountPointService mountPointService;
+
+ private ListenerRegistration<NetconfTopologyManager> dataChangeListenerRegistration;
public NetconfTopologyManager(final DataBroker dataBroker, final RpcProviderRegistry rpcProviderRegistry,
final ClusterSingletonServiceProvider clusterSingletonServiceProvider,
- final BindingAwareBroker bindingAwareBroker,
final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor,
- final Broker domBroker, final ActorSystemProvider actorSystemProvider,
+ final ActorSystemProvider actorSystemProvider,
final EventExecutor eventExecutor, final NetconfClientDispatcher clientDispatcher,
- final String topologyId, final Config config) {
+ final String topologyId, final Config config,
+ final DOMMountPointService mountPointService) {
this.dataBroker = Preconditions.checkNotNull(dataBroker);
this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry);
this.clusterSingletonServiceProvider = Preconditions.checkNotNull(clusterSingletonServiceProvider);
- this.bindingAwareBroker = Preconditions.checkNotNull(bindingAwareBroker);
this.keepaliveExecutor = Preconditions.checkNotNull(keepaliveExecutor);
this.processingExecutor = Preconditions.checkNotNull(processingExecutor);
- this.domBroker = Preconditions.checkNotNull(domBroker);
this.actorSystem = Preconditions.checkNotNull(actorSystemProvider).getActorSystem();
this.eventExecutor = Preconditions.checkNotNull(eventExecutor);
this.clientDispatcher = Preconditions.checkNotNull(clientDispatcher);
this.topologyId = Preconditions.checkNotNull(topologyId);
this.writeTxIdleTimeout = Duration.apply(config.getWriteTransactionIdleTimeout(), TimeUnit.SECONDS);
+ this.mountPointService = mountPointService;
}
// Blueprint init method
final NetconfTopologyContext newNetconfTopologyContext =
new NetconfTopologyContext(createSetup(instanceIdentifier, node), serviceGroupIdent,
- actorResponseWaitTime);
+ actorResponseWaitTime, mountPointService);
- final ClusterSingletonServiceRegistration clusterSingletonServiceRegistration =
+ final ClusterSingletonServiceRegistration clusterSingletonServiceRegistration =
clusterSingletonServiceProvider.registerClusterSingletonService(newNetconfTopologyContext);
clusterRegistrations.put(instanceIdentifier, clusterSingletonServiceRegistration);
LOG.debug("Registering datastore listener");
return dataBroker.registerDataTreeChangeListener(
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
- NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this);
+ new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
+ NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this);
}
private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType, final String topologyId) {
.setInstanceIdentifier(instanceIdentifier)
.setRpcProviderRegistry(rpcProviderRegistry)
.setNode(node)
- .setBindingAwareBroker(bindingAwareBroker)
.setActorSystem(actorSystem)
.setEventExecutor(eventExecutor)
- .setDomBroker(domBroker)
.setKeepaliveExecutor(keepaliveExecutor)
.setProcessingExecutor(processingExecutor)
.setTopologyId(topologyId)
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
-import org.opendaylight.netconf.sal.connect.netconf.sal.tx.ReadWriteTx;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.tx.ProxyReadTransaction;
+import org.opendaylight.netconf.topology.singleton.impl.tx.ProxyReadWriteTransaction;
import org.opendaylight.netconf.topology.singleton.impl.tx.ProxyWriteTransaction;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionReply;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionReply;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
* @param actorSystem system
* @param id id
* @param masterNode {@link org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor} ref
- * @param askTimeout ask timeout
+ * @param askTimeout ask timeout
*/
public ProxyDOMDataBroker(final ActorSystem actorSystem, final RemoteDeviceId id,
final ActorRef masterNode, final Timeout askTimeout) {
@Override
public DOMDataReadWriteTransaction newReadWriteTransaction() {
- return new ReadWriteTx(newReadOnlyTransaction(), newWriteOnlyTransaction());
+ final Future<Object> txActorFuture = Patterns.ask(masterNode, new NewReadWriteTransactionRequest(), askTimeout);
+ try {
+ final Object msg = Await.result(txActorFuture, askTimeout.duration());
+ if (msg instanceof Throwable) {
+ throw (Throwable) msg;
+ }
+ Preconditions.checkState(msg instanceof NewReadWriteTransactionReply);
+ final NewReadWriteTransactionReply reply = (NewReadWriteTransactionReply) msg;
+ return new ProxyReadWriteTransaction(reply.getTxActor(), id, actorSystem, askTimeout);
+ } catch (final Throwable t) {
+ throw new IllegalStateException("Can't create ProxyReadTransaction", t);
+ }
}
@Override
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
- private final Timeout actorResponseWaitTime;
-
// Initializes default constant instances for the case when the default schema repository
// directory cache/schema is used.
private final NetconfTopologySetup netconfTopologyDeviceSetup;
private final RemoteDeviceId remoteDeviceId;
+ private final DOMMountPointService mountService;
+ private final Timeout actorResponseWaitTime;
+
private NetconfConnectorDTO deviceCommunicatorDTO;
public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
- final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime) {
+ final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountService) {
this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
this.remoteDeviceId = remoteDeviceId;
this.actorResponseWaitTime = actorResponseWaitTime;
+ this.mountService = mountService;
}
@Override
? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
- netconfTopologyDeviceSetup.getDomBroker(), netconfTopologyDeviceSetup.getBindingAwareBroker(),
- netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime);
+ netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
+ mountService, netconfTopologyDeviceSetup.getDataBroker());
if (keepaliveDelay > 0) {
LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.util.Timeout;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceNotificationService;
import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalProvider;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
private final RemoteDeviceId id;
private final NetconfDeviceSalProvider salProvider;
-
private final ActorSystem actorSystem;
private final Timeout actorResponseWaitTime;
public SlaveSalFacade(final RemoteDeviceId id,
- final Broker domBroker,
final ActorSystem actorSystem,
- final Timeout actorResponseWaitTime) {
+ final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountPointService) {
this.id = id;
- this.salProvider = new NetconfDeviceSalProvider(id);
+ this.salProvider = new NetconfDeviceSalProvider(id, mountPointService);
this.actorSystem = actorSystem;
this.actorResponseWaitTime = actorResponseWaitTime;
-
- registerToSal(domBroker);
- }
-
- private void registerToSal(final Broker domRegistryDependency) {
- domRegistryDependency.registerProvider(salProvider);
-
}
public void registerSlaveMountPoint(final SchemaContext remoteSchemaContext, final DOMRpcService deviceRpc,
import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyResultResponse;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionReply;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionReply;
import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
private final SchemaRepository schemaRepository;
private final Timeout actorResponseWaitTime;
private final Duration writeTxIdleTimeout;
+ private final DOMMountPointService mountPointService;
private RemoteDeviceId id;
private NetconfTopologySetup setup;
public static Props props(final NetconfTopologySetup setup,
final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
- final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime) {
+ final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountPointService) {
return Props.create(NetconfNodeActor.class, () ->
- new NetconfNodeActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime));
+ new NetconfNodeActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime,
+ mountPointService));
}
private NetconfNodeActor(final NetconfTopologySetup setup,
final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
- final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime) {
+ final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountPointService) {
this.setup = setup;
this.id = id;
this.schemaRegistry = schemaRegistry;
this.schemaRepository = schemaRepository;
this.actorResponseWaitTime = actorResponseWaitTime;
this.writeTxIdleTimeout = setup.getIdleTimeout();
+ this.mountPointService = mountPointService;
}
@Override
sender().tell(t, self());
}
+ } else if (message instanceof NewReadWriteTransactionRequest) {
+ try {
+ final DOMDataReadWriteTransaction tx = deviceDataBroker.newReadWriteTransaction();
+ final ActorRef txActor = context().actorOf(ReadWriteTransactionActor.props(tx, writeTxIdleTimeout));
+ sender().tell(new NewReadWriteTransactionReply(txActor), self());
+ } catch (final Throwable t) {
+ sender().tell(t, self());
+ }
} else if (message instanceof InvokeRpcMessage) { // master
final InvokeRpcMessage invokeRpcMessage = ((InvokeRpcMessage) message);
slaveSalManager.close();
}
closeSchemaSourceRegistrations();
- slaveSalManager = new SlaveSalFacade(id, setup.getDomBroker(), setup.getActorSystem(), actorResponseWaitTime);
+ slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime,
+ mountPointService);
final CheckedFuture<SchemaContext, SchemaResolutionException> remoteSchemaContext =
getSchemaContext(masterReference);
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.actors;
+
+import akka.actor.ActorRef;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+class ReadAdapter {
+
+ private final DOMDataReadTransaction tx;
+
+ public ReadAdapter(final DOMDataReadTransaction tx) {
+ this.tx = tx;
+ }
+
+ public void handle(final Object message, final ActorRef sender, final ActorRef self) throws Throwable {
+ if (message instanceof ReadRequest) {
+
+ final ReadRequest readRequest = (ReadRequest) message;
+ final YangInstanceIdentifier path = readRequest.getPath();
+ final LogicalDatastoreType store = readRequest.getStore();
+ read(path, store, sender, self);
+
+ } else if (message instanceof ExistsRequest) {
+ final ExistsRequest readRequest = (ExistsRequest) message;
+ final YangInstanceIdentifier path = readRequest.getPath();
+ final LogicalDatastoreType store = readRequest.getStore();
+ exists(path, store, sender, self);
+ }
+ }
+
+ private void read(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
+ final ActorRef self) {
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(store, path);
+ Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
+
+ @Override
+ public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
+ if (!result.isPresent()) {
+ sender.tell(new EmptyReadResponse(), self);
+ return;
+ }
+ sender.tell(new NormalizedNodeMessage(path, result.get()), self);
+ }
+
+ @Override
+ public void onFailure(@Nonnull final Throwable throwable) {
+ sender.tell(throwable, self);
+ }
+ });
+ }
+
+ private void exists(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
+ final ActorRef self) {
+ final CheckedFuture<Boolean, ReadFailedException> readFuture = tx.exists(store, path);
+ Futures.addCallback(readFuture, new FutureCallback<Boolean>() {
+ @Override
+ public void onSuccess(final Boolean result) {
+ if (result == null) {
+ sender.tell(false, self);
+ } else {
+ sender.tell(result, self);
+ }
+ }
+
+ @Override
+ public void onFailure(@Nonnull final Throwable throwable) {
+ sender.tell(throwable, self);
+ }
+ });
+ }
+}
package org.opendaylight.netconf.topology.singleton.impl.actors;
-import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import javax.annotation.Nonnull;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadActorMessage;
/**
* ReadTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes.
*/
public class ReadTransactionActor extends UntypedActor {
- private final DOMDataReadOnlyTransaction tx;
+ private final ReadAdapter readAdapter;
+
+ private ReadTransactionActor(final DOMDataReadOnlyTransaction tx) {
+ readAdapter = new ReadAdapter(tx);
+ }
/**
* Creates new actor Props.
return Props.create(ReadTransactionActor.class, () -> new ReadTransactionActor(tx));
}
- private ReadTransactionActor(final DOMDataReadOnlyTransaction tx) {
- this.tx = tx;
- }
-
@Override
public void onReceive(final Object message) throws Throwable {
- if (message instanceof ReadRequest) {
-
- final ReadRequest readRequest = (ReadRequest) message;
- final YangInstanceIdentifier path = readRequest.getPath();
- final LogicalDatastoreType store = readRequest.getStore();
- read(path, store, sender(), self());
-
- } else if (message instanceof ExistsRequest) {
- final ExistsRequest readRequest = (ExistsRequest) message;
- final YangInstanceIdentifier path = readRequest.getPath();
- final LogicalDatastoreType store = readRequest.getStore();
- exists(path, store, sender(), self());
-
+ if (message instanceof ReadActorMessage) {
+ readAdapter.handle(message, sender(), self());
} else {
unhandled(message);
}
}
- private void read(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
- final ActorRef self) {
- final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(store, path);
- Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
-
- @Override
- public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
- if (!result.isPresent()) {
- sender.tell(new EmptyReadResponse(), self);
- return;
- }
- sender.tell(new NormalizedNodeMessage(path, result.get()), self);
- }
-
- @Override
- public void onFailure(@Nonnull final Throwable throwable) {
- sender.tell(throwable, self);
- }
- });
- }
-
- private void exists(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
- final ActorRef self) {
- final CheckedFuture<Boolean, ReadFailedException> readFuture = tx.exists(store, path);
- Futures.addCallback(readFuture, new FutureCallback<Boolean>() {
- @Override
- public void onSuccess(final Boolean result) {
- if (result == null) {
- sender.tell(false, self);
- } else {
- sender.tell(result, self);
- }
- }
-
- @Override
- public void onFailure(@Nonnull final Throwable throwable) {
- sender.tell(throwable, self);
- }
- });
- }
}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.actors;
+
+import akka.actor.Props;
+import akka.actor.ReceiveTimeout;
+import akka.actor.UntypedActor;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadActorMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.WriteActorMessage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+public class ReadWriteTransactionActor extends UntypedActor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ReadWriteTransactionActor.class);
+
+ private final DOMDataReadWriteTransaction tx;
+ private final long idleTimeout;
+ private final ReadAdapter readAdapter;
+ private final WriteAdapter writeAdapter;
+
+ private ReadWriteTransactionActor(final DOMDataReadWriteTransaction tx, final Duration idleTimeout) {
+ this.tx = tx;
+ this.idleTimeout = idleTimeout.toSeconds();
+ if (this.idleTimeout > 0) {
+ context().setReceiveTimeout(idleTimeout);
+ }
+ readAdapter = new ReadAdapter(tx);
+ writeAdapter = new WriteAdapter(tx);
+ }
+
+ /**
+ * Creates new actor Props.
+ *
+ * @param tx delegate device read write transaction
+ * @param idleTimeout idle time in seconds, after which transaction is closed automatically
+ * @return props
+ */
+ static Props props(final DOMDataReadWriteTransaction tx, final Duration idleTimeout) {
+ return Props.create(ReadWriteTransactionActor.class, () -> new ReadWriteTransactionActor(tx, idleTimeout));
+ }
+
+ @Override
+ public void onReceive(final Object message) throws Throwable {
+ if (message instanceof ReadActorMessage) {
+ readAdapter.handle(message, sender(), self());
+ } else if (message instanceof WriteActorMessage) {
+ writeAdapter.handle(message, sender(), context(), self());
+ } else if (message instanceof ReceiveTimeout) {
+ LOG.warn("Haven't received any message for {} seconds, cancelling transaction and stopping actor",
+ idleTimeout);
+ tx.cancel();
+ context().stop(self());
+ } else {
+ unhandled(message);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.actors;
+
+import akka.actor.ActorContext;
+import akka.actor.ActorRef;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+
+class WriteAdapter {
+ private final DOMDataWriteTransaction tx;
+
+ public WriteAdapter(final DOMDataWriteTransaction tx) {
+ this.tx = tx;
+ }
+
+ private void cancel(final ActorContext context, final ActorRef sender, final ActorRef self) {
+ final boolean cancelled = tx.cancel();
+ sender.tell(cancelled, self);
+ context.stop(self);
+ }
+
+ private void submit(final ActorRef requester, final ActorRef self, final ActorContext context) {
+ final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ context.stop(self);
+ Futures.addCallback(submitFuture, new FutureCallback<Void>() {
+ @Override
+ public void onSuccess(final Void result) {
+ requester.tell(new SubmitReply(), self);
+ }
+
+ @Override
+ public void onFailure(@Nonnull final Throwable throwable) {
+ requester.tell(throwable, self);
+ }
+ });
+ }
+
+ public void handle(final Object message, final ActorRef sender, final ActorContext context, final ActorRef self) {
+ if (message instanceof MergeRequest) {
+ final MergeRequest mergeRequest = (MergeRequest) message;
+ final NormalizedNodeMessage data = mergeRequest.getNormalizedNodeMessage();
+ tx.merge(mergeRequest.getStore(), data.getIdentifier(), data.getNode());
+ } else if (message instanceof PutRequest) {
+ final PutRequest putRequest = (PutRequest) message;
+ final NormalizedNodeMessage data = putRequest.getNormalizedNodeMessage();
+ tx.put(putRequest.getStore(), data.getIdentifier(), data.getNode());
+ } else if (message instanceof DeleteRequest) {
+ final DeleteRequest deleteRequest = (DeleteRequest) message;
+ tx.delete(deleteRequest.getStore(), deleteRequest.getPath());
+ } else if (message instanceof CancelRequest) {
+ cancel(context, sender, self);
+ } else if (message instanceof SubmitRequest) {
+ submit(sender, self, context);
+ }
+ }
+}
package org.opendaylight.netconf.topology.singleton.impl.actors;
-import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.ReceiveTimeout;
import akka.actor.UntypedActor;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import javax.annotation.Nonnull;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.WriteActorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;
private final DOMDataWriteTransaction tx;
private final long idleTimeout;
+ private final WriteAdapter writeAdapter;
+
+ private WriteTransactionActor(final DOMDataWriteTransaction tx, final Duration idleTimeout) {
+ this.tx = tx;
+ this.idleTimeout = idleTimeout.toSeconds();
+ if (this.idleTimeout > 0) {
+ context().setReceiveTimeout(idleTimeout);
+ }
+ writeAdapter = new WriteAdapter(tx);
+ }
/**
* Creates new actor Props.
*
- * @param tx delegate device write transaction
+ * @param tx delegate device write transaction
* @param idleTimeout idle time in seconds, after which transaction is closed automatically
* @return props
*/
return Props.create(WriteTransactionActor.class, () -> new WriteTransactionActor(tx, idleTimeout));
}
- private WriteTransactionActor(final DOMDataWriteTransaction tx, final Duration idleTimeout) {
- this.tx = tx;
- this.idleTimeout = idleTimeout.toSeconds();
- if (this.idleTimeout > 0) {
- context().setReceiveTimeout(idleTimeout);
- }
- }
-
@Override
public void onReceive(final Object message) throws Throwable {
- if (message instanceof MergeRequest) {
- final MergeRequest mergeRequest = (MergeRequest) message;
- final NormalizedNodeMessage data = mergeRequest.getNormalizedNodeMessage();
- tx.merge(mergeRequest.getStore(), data.getIdentifier(), data.getNode());
- } else if (message instanceof PutRequest) {
- final PutRequest putRequest = (PutRequest) message;
- final NormalizedNodeMessage data = putRequest.getNormalizedNodeMessage();
- tx.put(putRequest.getStore(), data.getIdentifier(), data.getNode());
- } else if (message instanceof DeleteRequest) {
- final DeleteRequest deleteRequest = (DeleteRequest) message;
- tx.delete(deleteRequest.getStore(), deleteRequest.getPath());
- } else if (message instanceof CancelRequest) {
- cancel();
- } else if (message instanceof SubmitRequest) {
- submit(sender(), self());
+ if (message instanceof WriteActorMessage) {
+ writeAdapter.handle(message, sender(), context(), self());
} else if (message instanceof ReceiveTimeout) {
LOG.warn("Haven't received any message for {} seconds, cancelling transaction and stopping actor",
idleTimeout);
}
}
- private void cancel() {
- final boolean cancelled = tx.cancel();
- sender().tell(cancelled, self());
- context().stop(self());
- }
-
- private void submit(final ActorRef requester, final ActorRef self) {
- final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
- context().stop(self);
- Futures.addCallback(submitFuture, new FutureCallback<Void>() {
- @Override
- public void onSuccess(final Void result) {
- requester.tell(new SubmitReply(), self);
- }
- @Override
- public void onFailure(@Nonnull final Throwable throwable) {
- requester.tell(throwable, self);
- }
- });
- }
}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.tx;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.dispatch.OnComplete;
+import akka.pattern.Patterns;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.SettableFuture;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.Future;
+
+class ProxyReadAdapter {
+ private static final Logger LOG = LoggerFactory.getLogger(ProxyReadAdapter.class);
+
+ private final ActorRef masterTxActor;
+ private final RemoteDeviceId id;
+ private final ActorSystem actorSystem;
+ private final Timeout askTimeout;
+
+ public ProxyReadAdapter(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
+ final Timeout askTimeout) {
+ this.masterTxActor = masterTxActor;
+ this.id = id;
+ this.actorSystem = actorSystem;
+ this.askTimeout = askTimeout;
+ }
+
+ public void close() {
+ //noop
+ }
+
+ public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ LOG.trace("{}: Read {} via NETCONF: {}", id, store, path);
+
+ final Future<Object> future = Patterns.ask(masterTxActor, new ReadRequest(store, path), askTimeout);
+ final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create();
+ future.onComplete(new OnComplete<Object>() {
+ @Override
+ public void onComplete(final Throwable failure,
+ final Object success) throws Throwable {
+ if (failure != null) { // ask timeout
+ final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
+ settableFuture.setException(exception);
+ return;
+ }
+ if (success instanceof Throwable) { // Error sended by master
+ settableFuture.setException((Throwable) success);
+ return;
+ }
+ if (success instanceof EmptyReadResponse) {
+ settableFuture.set(Optional.absent());
+ return;
+ }
+ if (success instanceof NormalizedNodeMessage) {
+ final NormalizedNodeMessage data = (NormalizedNodeMessage) success;
+ settableFuture.set(Optional.of(data.getNode()));
+ }
+ }
+ }, actorSystem.dispatcher());
+ return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+ }
+
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ final Future<Object> existsScalaFuture =
+ Patterns.ask(masterTxActor, new ExistsRequest(store, path), askTimeout);
+
+ LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);
+
+ final SettableFuture<Boolean> settableFuture = SettableFuture.create();
+ existsScalaFuture.onComplete(new OnComplete<Object>() {
+ @Override
+ public void onComplete(final Throwable failure, final Object success) throws Throwable {
+ if (failure != null) { // ask timeout
+ final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
+ settableFuture.setException(exception);
+ return;
+ }
+ if (success instanceof Throwable) {
+ settableFuture.setException((Throwable) success);
+ return;
+ }
+ settableFuture.set((Boolean) success);
+ }
+ }, actorSystem.dispatcher());
+ return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+ }
+
+}
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
-import akka.dispatch.OnComplete;
-import akka.pattern.Patterns;
import akka.util.Timeout;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.SettableFuture;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
/**
* ProxyReadTransaction uses provided {@link ActorRef} to delegate method calls to master
*/
public class ProxyReadTransaction implements DOMDataReadOnlyTransaction {
- private static final Logger LOG = LoggerFactory.getLogger(ProxyReadTransaction.class);
-
- private final ActorRef masterTxActor;
- private final RemoteDeviceId id;
- private final ActorSystem actorSystem;
- private final Timeout askTimeout;
+ private final ProxyReadAdapter delegate;
/**
* @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadTransactionActor} ref
*/
public ProxyReadTransaction(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
final Timeout askTimeout) {
- this.masterTxActor = masterTxActor;
- this.id = id;
- this.actorSystem = actorSystem;
- this.askTimeout = askTimeout;
+ delegate = new ProxyReadAdapter(masterTxActor, id, actorSystem, askTimeout);
}
@Override
public void close() {
- //noop
+ delegate.close();
}
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
final YangInstanceIdentifier path) {
- LOG.trace("{}: Read {} via NETCONF: {}", id, store, path);
-
- final Future<Object> future = Patterns.ask(masterTxActor, new ReadRequest(store, path), askTimeout);
- final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create();
- future.onComplete(new OnComplete<Object>() {
- @Override
- public void onComplete(final Throwable failure,
- final Object success) throws Throwable {
- if (failure != null) { // ask timeout
- final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
- settableFuture.setException(exception);
- return;
- }
- if (success instanceof Throwable) { // Error sended by master
- settableFuture.setException((Throwable) success);
- return;
- }
- if (success instanceof EmptyReadResponse) {
- settableFuture.set(Optional.absent());
- return;
- }
- if (success instanceof NormalizedNodeMessage) {
- final NormalizedNodeMessage data = (NormalizedNodeMessage) success;
- settableFuture.set(Optional.of(data.getNode()));
- }
- }
- }, actorSystem.dispatcher());
- return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+ return delegate.read(store, path);
}
@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
final YangInstanceIdentifier path) {
- final Future<Object> existsScalaFuture =
- Patterns.ask(masterTxActor, new ExistsRequest(store, path), askTimeout);
-
- LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);
-
- final SettableFuture<Boolean> settableFuture = SettableFuture.create();
- existsScalaFuture.onComplete(new OnComplete<Object>() {
- @Override
- public void onComplete(final Throwable failure, final Object success) throws Throwable {
- if (failure != null) { // ask timeout
- final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
- settableFuture.setException(exception);
- return;
- }
- if (success instanceof Throwable) {
- settableFuture.setException((Throwable) success);
- return;
- }
- settableFuture.set((Boolean) success);
- }
- }, actorSystem.dispatcher());
- return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+ return delegate.exists(store, path);
}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.tx;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * ProxyReadWriteTransaction uses provided {@link ActorRef} to delegate method calls to master
+ * {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadWriteTransactionActor}.
+ */
+public class ProxyReadWriteTransaction implements DOMDataReadWriteTransaction {
+
+ private final ProxyReadAdapter delegateRead;
+ private final ProxyWriteAdapter delegateWrite;
+
+ /**
+ * @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadWriteTransactionActor} ref
+ * @param id device id
+ * @param actorSystem system
+ * @param askTimeout
+ */
+ public ProxyReadWriteTransaction(final ActorRef masterTxActor, final RemoteDeviceId id,
+ final ActorSystem actorSystem, final Timeout askTimeout) {
+ delegateRead = new ProxyReadAdapter(masterTxActor, id, actorSystem, askTimeout);
+ delegateWrite = new ProxyWriteAdapter(masterTxActor, id, actorSystem, askTimeout);
+ }
+
+ @Override
+ public boolean cancel() {
+ return delegateWrite.cancel();
+ }
+
+ @Override
+ public ListenableFuture<RpcResult<TransactionStatus>> commit() {
+ return delegateWrite.commit(getIdentifier());
+ }
+
+ @Override
+ public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ return delegateRead.read(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ return delegateRead.exists(store, path);
+ }
+
+ @Override
+ public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ delegateWrite.delete(store, path);
+ }
+
+ @Override
+ public CheckedFuture<Void, TransactionCommitFailedException> submit() {
+ return delegateWrite.submit(getIdentifier());
+ }
+
+ @Override
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
+ delegateWrite.put(store, path, data, getIdentifier());
+ }
+
+ @Override
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
+ delegateWrite.merge(store, path, data, getIdentifier());
+ }
+
+ @Override
+ public Object getIdentifier() {
+ return this;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.tx;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.dispatch.OnComplete;
+import akka.pattern.Patterns;
+import akka.util.Timeout;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.annotation.Nullable;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitFailedReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+
+public class ProxyWriteAdapter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProxyWriteAdapter.class);
+
+ private final ActorRef masterTxActor;
+ private final RemoteDeviceId id;
+ private final ActorSystem actorSystem;
+ private final AtomicBoolean opened = new AtomicBoolean(true);
+ private final Timeout askTimeout;
+
+ public ProxyWriteAdapter(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
+ final Timeout askTimeout) {
+ this.masterTxActor = masterTxActor;
+ this.id = id;
+ this.actorSystem = actorSystem;
+ this.askTimeout = askTimeout;
+ }
+
+ public boolean cancel() {
+ if (!opened.compareAndSet(true, false)) {
+ return false;
+ }
+ final Future<Object> cancelScalaFuture =
+ Patterns.ask(masterTxActor, new CancelRequest(), askTimeout);
+
+ LOG.trace("{}: Cancel {} via NETCONF", id);
+
+ try {
+ // here must be Await because AsyncWriteTransaction do not return future
+ return (boolean) Await.result(cancelScalaFuture, askTimeout.duration());
+ } catch (final Exception e) {
+ return false;
+ }
+ }
+
+ public CheckedFuture<Void, TransactionCommitFailedException> submit(final Object identifier) {
+ if (!opened.compareAndSet(true, false)) {
+ throw new IllegalStateException(id + ": Transaction" + identifier + " is closed");
+ }
+ final Future<Object> submitScalaFuture =
+ Patterns.ask(masterTxActor, new SubmitRequest(), askTimeout);
+
+ LOG.trace("{}: Submit {} via NETCONF", id);
+
+ final SettableFuture<Void> settableFuture = SettableFuture.create();
+ submitScalaFuture.onComplete(new OnComplete<Object>() {
+ @Override
+ public void onComplete(final Throwable failure, final Object success) throws Throwable {
+ if (failure != null) { // ask timeout
+ final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
+ settableFuture.setException(exception);
+ return;
+ }
+ if (success instanceof Throwable) {
+ settableFuture.setException((Throwable) success);
+ } else {
+ if (success instanceof SubmitFailedReply) {
+ LOG.error("{}: Transaction was not submitted because already closed.", id);
+ }
+ settableFuture.set(null);
+ }
+ }
+ }, actorSystem.dispatcher());
+
+ return Futures.makeChecked(settableFuture, new Function<Exception, TransactionCommitFailedException>() {
+ @Nullable
+ @Override
+ public TransactionCommitFailedException apply(@Nullable final Exception input) {
+ final String message = "Submit of transaction " + identifier + " failed";
+ return new TransactionCommitFailedException(message, input);
+ }
+ });
+ }
+
+ public ListenableFuture<RpcResult<TransactionStatus>> commit(final Object identifier) {
+ LOG.trace("{}: Commit", id);
+
+ final CheckedFuture<Void, TransactionCommitFailedException> submit = submit(identifier);
+ return Futures.transform(submit, new Function<Void, RpcResult<TransactionStatus>>() {
+ @Nullable
+ @Override
+ public RpcResult<TransactionStatus> apply(@Nullable final Void input) {
+ return RpcResultBuilder.success(TransactionStatus.SUBMITED).build();
+ }
+ });
+ }
+
+ public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier identifier) {
+ Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, identifier);
+ LOG.trace("{}: Delete {} via NETCONF: {}", id, store, identifier);
+ masterTxActor.tell(new DeleteRequest(store, identifier), ActorRef.noSender());
+ }
+
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data, final Object identifier) {
+ Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, identifier);
+ final NormalizedNodeMessage msg = new NormalizedNodeMessage(path, data);
+ LOG.trace("{}: Put {} via NETCONF: {} with payload {}", id, store, path, data);
+ masterTxActor.tell(new PutRequest(store, msg), ActorRef.noSender());
+ }
+
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data, final Object identifier) {
+ Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, identifier);
+ final NormalizedNodeMessage msg = new NormalizedNodeMessage(path, data);
+ LOG.trace("{}: Merge {} via NETCONF: {} with payload {}", id, store, path, data);
+ masterTxActor.tell(new MergeRequest(store, msg), ActorRef.noSender());
+ }
+
+}
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
-import akka.dispatch.OnComplete;
-import akka.pattern.Patterns;
import akka.util.Timeout;
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitFailedReply;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Await;
-import scala.concurrent.Future;
/**
* ProxyWriteTransaction uses provided {@link ActorRef} to delegate method calls to master
*/
public class ProxyWriteTransaction implements DOMDataWriteTransaction {
- private static final Logger LOG = LoggerFactory.getLogger(ProxyWriteTransaction.class);
-
- private final ActorRef masterTxActor;
- private final RemoteDeviceId id;
- private final ActorSystem actorSystem;
- private final AtomicBoolean opened = new AtomicBoolean(true);
- private final Timeout askTimeout;
+ private final ProxyWriteAdapter proxyWriteAdapter;
/**
* @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.WriteTransactionActor} ref
*/
public ProxyWriteTransaction(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
final Timeout askTimeout) {
- this.masterTxActor = masterTxActor;
- this.id = id;
- this.actorSystem = actorSystem;
- this.askTimeout = askTimeout;
+ proxyWriteAdapter = new ProxyWriteAdapter(masterTxActor, id, actorSystem, askTimeout);
}
@Override
public boolean cancel() {
- if (!opened.compareAndSet(true, false)) {
- return false;
- }
- final Future<Object> cancelScalaFuture =
- Patterns.ask(masterTxActor, new CancelRequest(), askTimeout);
-
- LOG.trace("{}: Cancel {} via NETCONF", id);
-
- try {
- // here must be Await because AsyncWriteTransaction do not return future
- return (boolean) Await.result(cancelScalaFuture, askTimeout.duration());
- } catch (final Exception e) {
- return false;
- }
+ return proxyWriteAdapter.cancel();
}
@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit() {
- if (!opened.compareAndSet(true, false)) {
- throw new IllegalStateException(id + ": Transaction" + getIdentifier() + " is closed");
- }
- final Future<Object> submitScalaFuture =
- Patterns.ask(masterTxActor, new SubmitRequest(), askTimeout);
-
- LOG.trace("{}: Submit {} via NETCONF", id);
-
- final SettableFuture<Void> settableFuture = SettableFuture.create();
- submitScalaFuture.onComplete(new OnComplete<Object>() {
- @Override
- public void onComplete(final Throwable failure, final Object success) throws Throwable {
- if (failure != null) { // ask timeout
- final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
- settableFuture.setException(exception);
- return;
- }
- if (success instanceof Throwable) {
- settableFuture.setException((Throwable) success);
- } else {
- if (success instanceof SubmitFailedReply) {
- LOG.error("{}: Transaction was not submitted because already closed.", id);
- }
- settableFuture.set(null);
- }
- }
- }, actorSystem.dispatcher());
-
- return Futures.makeChecked(settableFuture, new Function<Exception, TransactionCommitFailedException>() {
- @Nullable
- @Override
- public TransactionCommitFailedException apply(@Nullable final Exception input) {
- final String message = "Submit of transaction " + getIdentifier() + " failed";
- return new TransactionCommitFailedException(message, input);
- }
- });
+ return proxyWriteAdapter.submit(getIdentifier());
}
@Override
public ListenableFuture<RpcResult<TransactionStatus>> commit() {
- LOG.trace("{}: Commit", id);
-
- final CheckedFuture<Void, TransactionCommitFailedException> submit = submit();
- return Futures.transform(submit, new Function<Void, RpcResult<TransactionStatus>>() {
- @Nullable
- @Override
- public RpcResult<TransactionStatus> apply(@Nullable final Void input) {
- return RpcResultBuilder.success(TransactionStatus.SUBMITED).build();
- }
- });
+ return proxyWriteAdapter.commit(getIdentifier());
}
@Override
public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier identifier) {
- Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, getIdentifier());
- LOG.trace("{}: Delete {} via NETCONF: {}", id, store, identifier);
- masterTxActor.tell(new DeleteRequest(store, identifier), ActorRef.noSender());
+ proxyWriteAdapter.delete(store, identifier);
}
@Override
public void put(final LogicalDatastoreType store, final YangInstanceIdentifier identifier,
final NormalizedNode<?, ?> data) {
- Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, getIdentifier());
- final NormalizedNodeMessage msg = new NormalizedNodeMessage(identifier, data);
- LOG.trace("{}: Put {} via NETCONF: {} with payload {}", id, store, identifier, data);
- masterTxActor.tell(new PutRequest(store, msg), ActorRef.noSender());
+ proxyWriteAdapter.put(store, identifier, data, getIdentifier());
}
@Override
public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier identifier,
final NormalizedNode<?, ?> data) {
- Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, getIdentifier());
- final NormalizedNodeMessage msg = new NormalizedNodeMessage(identifier, data);
- LOG.trace("{}: Merge {} via NETCONF: {} with payload {}", id, store, identifier, data);
- masterTxActor.tell(new MergeRequest(store, msg), ActorRef.noSender());
+ proxyWriteAdapter.merge(store, identifier, data, getIdentifier());
}
@Override
import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
private final DataBroker dataBroker;
private final InstanceIdentifier<Node> instanceIdentifier;
private final Node node;
- private final BindingAwareBroker bindingAwareBroker;
private final ScheduledThreadPool keepaliveExecutor;
private final ThreadPool processingExecutor;
- private final Broker domBroker;
private final ActorSystem actorSystem;
private final EventExecutor eventExecutor;
private final NetconfClientDispatcher netconfClientDispatcher;
this.dataBroker = builder.getDataBroker();
this.instanceIdentifier = builder.getInstanceIdentifier();
this.node = builder.getNode();
- this.bindingAwareBroker = builder.getBindingAwareBroker();
this.keepaliveExecutor = builder.getKeepaliveExecutor();
this.processingExecutor = builder.getProcessingExecutor();
- this.domBroker = builder.getDomBroker();
this.actorSystem = builder.getActorSystem();
this.eventExecutor = builder.getEventExecutor();
this.netconfClientDispatcher = builder.getNetconfClientDispatcher();
return node;
}
- public BindingAwareBroker getBindingAwareBroker() {
- return bindingAwareBroker;
- }
-
public ThreadPool getProcessingExecutor() {
return processingExecutor;
}
return keepaliveExecutor;
}
- public Broker getDomBroker() {
- return domBroker;
- }
-
public ActorSystem getActorSystem() {
return actorSystem;
}
private DataBroker dataBroker;
private InstanceIdentifier<Node> instanceIdentifier;
private Node node;
- private BindingAwareBroker bindingAwareBroker;
private ScheduledThreadPool keepaliveExecutor;
private ThreadPool processingExecutor;
- private Broker domBroker;
private ActorSystem actorSystem;
private EventExecutor eventExecutor;
private String topologyId;
return new NetconfTopologySetup(this);
}
- private BindingAwareBroker getBindingAwareBroker() {
- return bindingAwareBroker;
- }
-
- public NetconfTopologySetupBuilder setBindingAwareBroker(final BindingAwareBroker bindingAwareBroker) {
- this.bindingAwareBroker = bindingAwareBroker;
- return this;
- }
-
private ScheduledThreadPool getKeepaliveExecutor() {
return keepaliveExecutor;
}
return this;
}
- private Broker getDomBroker() {
- return domBroker;
- }
-
- public NetconfTopologySetupBuilder setDomBroker(final Broker domBroker) {
- this.domBroker = domBroker;
- return this;
- }
-
private ActorSystem getActorSystem() {
return actorSystem;
}
package org.opendaylight.netconf.topology.singleton.messages.transactions;
-public class CancelRequest implements TransactionRequest {
+public class CancelRequest implements WriteActorMessage {
private static final long serialVersionUID = 1L;
}
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-public class DeleteRequest implements TransactionRequest {
+public class DeleteRequest implements WriteActorMessage {
private static final long serialVersionUID = 1L;
private final LogicalDatastoreType store;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-public class ExistsRequest implements TransactionRequest {
+public class ExistsRequest implements ReadActorMessage {
private static final long serialVersionUID = 1L;
private final LogicalDatastoreType store;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-public class MergeRequest implements TransactionRequest {
+public class MergeRequest implements WriteActorMessage {
private static final long serialVersionUID = 1L;
private final NormalizedNodeMessage data;
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.messages.transactions;
+
+import akka.actor.ActorRef;
+import java.io.Serializable;
+
+public class NewReadWriteTransactionReply implements Serializable {
+
+ private final ActorRef txActor;
+
+ public NewReadWriteTransactionReply(final ActorRef txActor) {
+ this.txActor = txActor;
+ }
+
+ public ActorRef getTxActor() {
+ return txActor;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.messages.transactions;
+
+import java.io.Serializable;
+
+public class NewReadWriteTransactionRequest implements Serializable {
+ private static final long serialVersionUID = 1L;
+}
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-public class PutRequest implements TransactionRequest {
+public class PutRequest implements WriteActorMessage {
private static final long serialVersionUID = 1L;
private final LogicalDatastoreType store;
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.messages.transactions;
+
+public interface ReadActorMessage extends TransactionRequest {
+}
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-public class ReadRequest implements TransactionRequest {
+public class ReadRequest implements ReadActorMessage {
private static final long serialVersionUID = 1L;
private final LogicalDatastoreType store;
package org.opendaylight.netconf.topology.singleton.messages.transactions;
-public class SubmitRequest implements TransactionRequest {
+public class SubmitRequest implements WriteActorMessage {
private static final long serialVersionUID = 1L;
}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.messages.transactions;
+
+public interface WriteActorMessage extends TransactionRequest {
+}
interface="org.opendaylight.controller.sal.binding.api.RpcProviderRegistry"/>
<reference id="clusterSingletonService"
interface="org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider"/>
- <reference id="bindingAwareBroker"
- interface="org.opendaylight.controller.sal.binding.api.BindingAwareBroker"/>
<reference id="keepAliveExecutor"
interface="org.opendaylight.controller.config.threadpool.ScheduledThreadPool"
odl:type="global-netconf-ssh-scheduled-executor"/>
<reference id="processingExecutor"
interface="org.opendaylight.controller.config.threadpool.ThreadPool"
odl:type="global-netconf-processing-executor"/>
- <reference id="domBroker"
- interface="org.opendaylight.controller.sal.core.api.Broker"/>
<reference id="actorSystemProvider"
interface="org.opendaylight.controller.cluster.ActorSystemProvider"/>
<reference id="eventExecutor"
<reference id="clientDispatcherDependency"
interface="org.opendaylight.netconf.client.NetconfClientDispatcher"
odl:type="netconf-client-dispatcher"/>
+ <reference id="mountPointService"
+ interface="org.opendaylight.controller.md.sal.dom.api.DOMMountPointService"
+ odl:type="default"/>
<odl:clustered-app-config
id="singletonConfig"
binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config"
<argument ref="dataBroker"/>
<argument ref="rpcRegistry"/>
<argument ref="clusterSingletonService"/>
- <argument ref="bindingAwareBroker"/>
<argument ref="keepAliveExecutor"/>
<argument ref="processingExecutor"/>
- <argument ref="domBroker"/>
<argument ref="actorSystemProvider"/>
<argument ref="eventExecutor"/>
<argument ref="clientDispatcherDependency"/>
<argument value="topology-netconf"/>
<argument ref="singletonConfig"/>
+ <argument ref="mountPointService"/>
</bean>
<service ref="netconfTopologyManager"
interface="org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService"/>
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
@Mock
private DOMRpcService domRpcService;
+ @Mock
+ private DOMMountPointService mountPointService;
+ @Mock
+ private DataBroker dataBroker;
@Before
public void setup() throws UnknownHostException {
final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
- DEFAULT_SCHEMA_REPOSITORY, TIMEOUT);
+ DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
system = ActorSystem.create();
@Test
public void testReceiveRegisterMountpoint() throws Exception {
final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
- doReturn(mock(Broker.class)).when(setup).getDomBroker();
final RevisionSourceIdentifier yang1 = RevisionSourceIdentifier.create("yang1");
final RevisionSourceIdentifier yang2 = RevisionSourceIdentifier.create("yang2");
final SchemaSourceRegistry registry = mock(SchemaSourceRegistry.class);
Futures.makeChecked(schemaContextFuture, e -> new SchemaResolutionException("fail", e));
doReturn(checkedFuture).when(schemaContextFactory).createSchemaContext(any());
final ActorRef slaveRef =
- system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, registry, schemaRepository, TIMEOUT));
+ system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, registry, schemaRepository, TIMEOUT,
+ mountPointService));
final List<SourceIdentifier> sources = ImmutableList.of(yang1, yang2);
slaveRef.tell(new RegisterMountPoint(sources), masterRef);
final SchemaRepository schemaRepository = mock(SchemaRepository.class);
final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID", Optional.absent());
final Props props = NetconfNodeActor.props(mock(NetconfTopologySetup.class), remoteDeviceId,
- DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT);
+ DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT, mountPointService);
final ActorRef actorRefSchemaRepo = TestActorRef.create(system, props, "master_mocked_schema_repository");
final ActorContext actorContext = mock(ActorContext.class);
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
initMocks(this);
final RpcProviderRegistry rpcProviderRegistry = mock(RpcProviderRegistry.class);
- final BindingAwareBroker bindingAwareBroker = mock(BindingAwareBroker.class);
final ScheduledThreadPool keepaliveExecutor = mock(ScheduledThreadPool.class);
final ThreadPool processingExecutor = mock(ThreadPool.class);
- final Broker domBroker = mock(Broker.class);
final ActorSystemProvider actorSystemProvider = mock(ActorSystemProvider.class);
final EventExecutor eventExecutor = mock(EventExecutor.class);
final NetconfClientDispatcher clientDispatcher = mock(NetconfClientDispatcher.class);
+ final DOMMountPointService mountPointService = mock(DOMMountPointService.class);
final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
netconfTopologyManager = new NetconfTopologyManager(dataBroker, rpcProviderRegistry,
- clusterSingletonServiceProvider, bindingAwareBroker, keepaliveExecutor, processingExecutor, domBroker,
- actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config);
+ clusterSingletonServiceProvider, keepaliveExecutor, processingExecutor,
+ actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config, mountPointService);
}
@Test
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.util.Timeout;
+import com.google.common.util.concurrent.Futures;
import io.netty.util.concurrent.EventExecutor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.mockito.Mock;
import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
import org.opendaylight.controller.config.threadpool.ThreadPool;
+import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
@Mock
private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
- @Mock
- private BindingAwareBroker bindingAwareBroker;
-
@Mock
private ScheduledThreadPool keepaliveExecutor;
@Mock
private ThreadPool processingExecutor;
- @Mock
- private Broker domBroker;
-
@Mock
private ActorSystem actorSystem;
@Mock
private NetconfClientDispatcher clientDispatcher;
+ @Mock
+ private DOMMountPointService mountPointService;
+
+ @Mock
+ private BindingTransactionChain txChain;
+
+ @Mock
+ private WriteTransaction writeTx;
+
private NetconfTopologySetup.NetconfTopologySetupBuilder builder;
private RemoteDeviceId remoteDeviceId;
remoteDeviceId = new RemoteDeviceId(TOPOLOGY_ID,
new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+ doReturn(txChain).when(dataBroker).createTransactionChain(any(TransactionChainListener.class));
+ doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
+ doNothing().when(writeTx).merge(eq(LogicalDatastoreType.OPERATIONAL), any(), any());
+ doReturn("Some object").when(writeTx).getIdentifier();
+ doReturn(Futures.immediateCheckedFuture(null)).when(writeTx).submit();
builder = new NetconfTopologySetup.NetconfTopologySetupBuilder();
builder.setDataBroker(dataBroker);
builder.setRpcProviderRegistry(rpcProviderRegistry);
builder.setClusterSingletonServiceProvider(clusterSingletonServiceProvider);
- builder.setBindingAwareBroker(bindingAwareBroker);
builder.setKeepaliveExecutor(keepaliveExecutor);
builder.setProcessingExecutor(processingExecutor);
- builder.setDomBroker(domBroker);
builder.setActorSystem(actorSystem);
builder.setEventExecutor(eventExecutor);
builder.setNetconfClientDispatcher(clientDispatcher);
final RemoteDeviceHandler salFacade = mock(RemoteDeviceHandler.class);
final TestingRemoteDeviceConnectorImpl remoteDeviceConnection =
- new TestingRemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, communicator, salFacade, TIMEOUT);
+ new TestingRemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, communicator, salFacade, TIMEOUT,
+ mountPointService);
final ActorRef masterRef = mock(ActorRef.class);
final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node));
final RemoteDeviceConnectorImpl remoteDeviceConnection =
- new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT);
+ new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT, mountPointService);
final ActorRef masterRef = mock(ActorRef.class);
builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node));
final RemoteDeviceConnectorImpl remoteDeviceConnection =
- new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT);
+ new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT, mountPointService);
final ActorRef masterRef = mock(ActorRef.class);
.build();
final RemoteDeviceConnectorImpl remoteDeviceConnection =
- new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT);
+ new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT, mountPointService);
final NetconfReconnectingClientConfiguration defaultClientConfig =
remoteDeviceConnection.getClientConfig(listener, testingNode);
import akka.actor.ActorRef;
import akka.util.Timeout;
import com.google.common.util.concurrent.Futures;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
final RemoteDeviceId remoteDeviceId,
final NetconfDeviceCommunicator communicator,
final RemoteDeviceHandler salFacade,
- final Timeout actorResponseWaitTime) {
- super(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime);
+ final Timeout actorResponseWaitTime,
+ final DOMMountPointService mountPointService) {
+ super(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime, mountPointService);
this.communicator = communicator;
this.salFacade = salFacade;
}
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.actors;
+
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import akka.actor.ActorSystem;
+import akka.pattern.Patterns;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestActorRef;
+import akka.testkit.TestProbe;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.Futures;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+import scala.concurrent.duration.Duration;
+
+public class ReadWriteTransactionActorTest {
+
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.EMPTY;
+ private static final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
+ private static final Timeout TIMEOUT = Timeout.apply(5, TimeUnit.SECONDS);
+
+ @Mock
+ private DOMDataReadWriteTransaction deviceReadWriteTx;
+ private TestProbe probe;
+ private ActorSystem system;
+ private TestActorRef<WriteTransactionActor> actorRef;
+ private NormalizedNode<?, ?> node;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ system = ActorSystem.apply();
+ probe = TestProbe.apply(system);
+ node = Builders.containerBuilder()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .build();
+ actorRef = TestActorRef.create(system, ReadWriteTransactionActor.props(deviceReadWriteTx,
+ Duration.apply(2, TimeUnit.SECONDS)), "testA");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ JavaTestKit.shutdownActorSystem(system, null, true);
+ }
+
+ @Test
+ public void testRead() throws Exception {
+ final ContainerNode node = Builders.containerBuilder()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .build();
+ when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
+ actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+ verify(deviceReadWriteTx).read(STORE, PATH);
+ probe.expectMsgClass(NormalizedNodeMessage.class);
+ }
+
+ @Test
+ public void testReadEmpty() throws Exception {
+ when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.absent()));
+ actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+ verify(deviceReadWriteTx).read(STORE, PATH);
+ probe.expectMsgClass(EmptyReadResponse.class);
+ }
+
+ @Test
+ public void testReadFailure() throws Exception {
+ final ReadFailedException cause = new ReadFailedException("fail");
+ when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+ actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+ verify(deviceReadWriteTx).read(STORE, PATH);
+ probe.expectMsg(cause);
+ }
+
+ @Test
+ public void testExists() throws Exception {
+ when(deviceReadWriteTx.exists(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(true));
+ actorRef.tell(new ExistsRequest(STORE, PATH), probe.ref());
+ verify(deviceReadWriteTx).exists(STORE, PATH);
+ probe.expectMsg(true);
+ }
+
+ @Test
+ public void testExistsFailure() throws Exception {
+ final ReadFailedException cause = new ReadFailedException("fail");
+ when(deviceReadWriteTx.exists(STORE, PATH)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+ actorRef.tell(new ExistsRequest(STORE, PATH), probe.ref());
+ verify(deviceReadWriteTx).exists(STORE, PATH);
+ probe.expectMsg(cause);
+ }
+
+ @Test
+ public void testPut() throws Exception {
+ final NormalizedNodeMessage normalizedNodeMessage = new NormalizedNodeMessage(PATH, node);
+ actorRef.tell(new PutRequest(STORE, normalizedNodeMessage), probe.ref());
+ verify(deviceReadWriteTx).put(STORE, PATH, node);
+ }
+
+ @Test
+ public void testMerge() throws Exception {
+ final NormalizedNodeMessage normalizedNodeMessage = new NormalizedNodeMessage(PATH, node);
+ actorRef.tell(new MergeRequest(STORE, normalizedNodeMessage), probe.ref());
+ verify(deviceReadWriteTx).merge(STORE, PATH, node);
+ }
+
+ @Test
+ public void testDelete() throws Exception {
+ actorRef.tell(new DeleteRequest(STORE, PATH), probe.ref());
+ verify(deviceReadWriteTx).delete(STORE, PATH);
+ }
+
+ @Test
+ public void testCancel() throws Exception {
+ when(deviceReadWriteTx.cancel()).thenReturn(true);
+ final Future<Object> cancelFuture = Patterns.ask(actorRef, new CancelRequest(), TIMEOUT);
+ final Object result = Await.result(cancelFuture, TIMEOUT.duration());
+ Preconditions.checkState(result instanceof Boolean);
+ verify(deviceReadWriteTx).cancel();
+ Assert.assertTrue((Boolean) result);
+ }
+
+ @Test
+ public void testSubmit() throws Exception {
+ when(deviceReadWriteTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
+ final Future<Object> submitFuture = Patterns.ask(actorRef, new SubmitRequest(), TIMEOUT);
+ final Object result = Await.result(submitFuture, TIMEOUT.duration());
+ Assert.assertTrue(result instanceof SubmitReply);
+ verify(deviceReadWriteTx).submit();
+ }
+
+ @Test
+ public void testSubmitFail() throws Exception {
+ final RpcError rpcError =
+ RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "fail", "fail");
+ final TransactionCommitFailedException cause = new TransactionCommitFailedException("fail", rpcError);
+ when(deviceReadWriteTx.submit()).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+ final Future<Object> submitFuture = Patterns.ask(actorRef, new SubmitRequest(), TIMEOUT);
+ final Object result = Await.result(submitFuture, TIMEOUT.duration());
+ Assert.assertEquals(cause, result);
+ verify(deviceReadWriteTx).submit();
+ }
+
+ @Test
+ public void testIdleTimeout() throws Exception {
+ final TestProbe probe = new TestProbe(system);
+ probe.watch(actorRef);
+ verify(deviceReadWriteTx, timeout(3000)).cancel();
+ probe.expectTerminated(actorRef, TIMEOUT.duration());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.tx;
+
+import akka.actor.ActorSystem;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestProbe;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.net.InetSocketAddress;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+
+public class ProxyReadWriteTransactionTest {
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.EMPTY;
+ private static final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
+
+ private ActorSystem system;
+ private TestProbe masterActor;
+ private ContainerNode node;
+ private ProxyReadWriteTransaction tx;
+
+ @Before
+ public void setUp() throws Exception {
+ system = ActorSystem.apply();
+ masterActor = new TestProbe(system);
+ final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830));
+ node = Builders.containerBuilder()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+ .build();
+ tx = new ProxyReadWriteTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ JavaTestKit.shutdownActorSystem(system, null, true);
+ }
+
+ @Test
+ public void testCancel() throws Exception {
+ final Future<Boolean> submit = Executors.newSingleThreadExecutor().submit(() -> tx.cancel());
+ masterActor.expectMsgClass(CancelRequest.class);
+ masterActor.reply(true);
+ Assert.assertTrue(submit.get());
+ }
+
+ @Test
+ public void testCancelSubmitted() throws Exception {
+ final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ masterActor.expectMsgClass(SubmitRequest.class);
+ masterActor.reply(new SubmitReply());
+ submitFuture.checkedGet();
+ final Future<Boolean> submit = Executors.newSingleThreadExecutor().submit(() -> tx.cancel());
+ masterActor.expectNoMsg();
+ Assert.assertFalse(submit.get());
+ }
+
+ @Test
+ public void testSubmit() throws Exception {
+ final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ masterActor.expectMsgClass(SubmitRequest.class);
+ masterActor.reply(new SubmitReply());
+ submitFuture.checkedGet();
+ }
+
+ @Test
+ public void testDoubleSubmit() throws Exception {
+ final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ masterActor.expectMsgClass(SubmitRequest.class);
+ masterActor.reply(new SubmitReply());
+ submitFuture.checkedGet();
+ try {
+ tx.submit().checkedGet();
+ Assert.fail("Should throw IllegalStateException");
+ } catch (final IllegalStateException e) {
+ masterActor.expectNoMsg();
+ }
+ }
+
+ @Test
+ public void testCommit() throws Exception {
+ final ListenableFuture<RpcResult<TransactionStatus>> submitFuture = tx.commit();
+ masterActor.expectMsgClass(SubmitRequest.class);
+ masterActor.reply(new SubmitReply());
+ Assert.assertEquals(TransactionStatus.SUBMITED, submitFuture.get().getResult());
+ }
+
+ @Test
+ public void testDelete() throws Exception {
+ tx.delete(STORE, PATH);
+ masterActor.expectMsgClass(DeleteRequest.class);
+ }
+
+ @Test
+ public void testDeleteClosed() throws Exception {
+ submit();
+ try {
+ tx.delete(STORE, PATH);
+ Assert.fail("Should throw IllegalStateException");
+ } catch (final IllegalStateException e) {
+ masterActor.expectNoMsg();
+ }
+ }
+
+ @Test
+ public void testPut() throws Exception {
+ tx.put(STORE, PATH, node);
+ masterActor.expectMsgClass(PutRequest.class);
+ }
+
+ @Test
+ public void testPutClosed() throws Exception {
+ submit();
+ try {
+ tx.put(STORE, PATH, node);
+ Assert.fail("Should throw IllegalStateException");
+ } catch (final IllegalStateException e) {
+ masterActor.expectNoMsg();
+ }
+ }
+
+ @Test
+ public void testMerge() throws Exception {
+ tx.merge(STORE, PATH, node);
+ masterActor.expectMsgClass(MergeRequest.class);
+ }
+
+ @Test
+ public void testMergeClosed() throws Exception {
+ submit();
+ try {
+ tx.merge(STORE, PATH, node);
+ Assert.fail("Should throw IllegalStateException");
+ } catch (final IllegalStateException e) {
+ masterActor.expectNoMsg();
+ }
+ }
+
+ @Test
+ public void testGetIdentifier() throws Exception {
+ Assert.assertEquals(tx, tx.getIdentifier());
+ }
+
+ private void submit() throws TransactionCommitFailedException {
+ final CheckedFuture<Void, TransactionCommitFailedException> submit = tx.submit();
+ masterActor.expectMsgClass(SubmitRequest.class);
+ masterActor.reply(new SubmitReply());
+ submit.checkedGet();
+ }
+
+ @Test
+ public void testRead() throws Exception {
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+ masterActor.expectMsgClass(ReadRequest.class);
+ masterActor.reply(new NormalizedNodeMessage(PATH, node));
+ final Optional<NormalizedNode<?, ?>> result = read.checkedGet();
+ Assert.assertTrue(result.isPresent());
+ Assert.assertEquals(node, result.get());
+ }
+
+ @Test
+ public void testReadEmpty() throws Exception {
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+ masterActor.expectMsgClass(ReadRequest.class);
+ masterActor.reply(new EmptyReadResponse());
+ final Optional<NormalizedNode<?, ?>> result = read.checkedGet();
+ Assert.assertFalse(result.isPresent());
+ }
+
+ @Test(expected = ReadFailedException.class)
+ public void testReadFail() throws Exception {
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+ masterActor.expectMsgClass(ReadRequest.class);
+ masterActor.reply(new RuntimeException("fail"));
+ read.checkedGet();
+ }
+
+ @Test
+ public void testExists() throws Exception {
+ final CheckedFuture<Boolean, ReadFailedException> read = tx.exists(STORE, PATH);
+ masterActor.expectMsgClass(ExistsRequest.class);
+ masterActor.reply(true);
+ final Boolean result = read.checkedGet();
+ Assert.assertTrue(result);
+ }
+
+ @Test(expected = ReadFailedException.class)
+ public void testExistsFail() throws Exception {
+ final CheckedFuture<Boolean, ReadFailedException> read = tx.exists(STORE, PATH);
+ masterActor.expectMsgClass(ExistsRequest.class);
+ masterActor.reply(new RuntimeException("fail"));
+ read.checkedGet();
+ }
+
+ @Test
+ public void testMasterDownRead() throws Exception {
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+ masterActor.expectMsgClass(ReadRequest.class);
+ //master doesn't reply
+ try {
+ read.checkedGet();
+ Assert.fail("Exception should be thrown");
+ } catch (final ReadFailedException e) {
+ final Throwable cause = e.getCause();
+ Assert.assertTrue(cause instanceof DocumentedException);
+ final DocumentedException de = (DocumentedException) cause;
+ Assert.assertEquals(DocumentedException.ErrorSeverity.WARNING, de.getErrorSeverity());
+ Assert.assertEquals(DocumentedException.ErrorTag.OPERATION_FAILED, de.getErrorTag());
+ Assert.assertEquals(DocumentedException.ErrorType.APPLICATION, de.getErrorType());
+ }
+ }
+}
\ No newline at end of file
import com.google.common.util.concurrent.Futures;
import java.net.InetAddress;
import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMDataBroker;
private ActorRef masterRef;
private ProxyDOMDataBroker slaveDataBroker;
private List<SourceIdentifier> sourceIdentifiers;
+ private YangInstanceIdentifier instanceIdentifier;
+ private LogicalDatastoreType storeType;
@Mock
private DOMDataBroker deviceDataBroker;
@Mock
private DOMDataReadOnlyTransaction readTx;
@Mock
private DOMRpcService domRpcService;
+ @Mock
+ private DOMMountPointService mountPointService;
+
@Before
- public void setup() throws UnknownHostException {
+ public void setup() throws Exception {
initMocks(this);
system = ActorSystem.create();
final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
- DEFAULT_SCHEMA_REPOSITORY, TIMEOUT);
+ DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
masterRef = TestActorRef.create(system, props, "master_read");
sourceIdentifiers = Lists.newArrayList();
//device read tx
- readTx = mock(DOMDataReadOnlyTransaction.class);
doReturn(readTx).when(deviceDataBroker).newReadOnlyTransaction();
// Create slave data broker for testing proxy
slaveDataBroker =
new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
+ initializeDataTest();
+ instanceIdentifier = YangInstanceIdentifier.EMPTY;
+ storeType = LogicalDatastoreType.CONFIGURATION;
}
@After
@Test
public void testRead() throws Exception {
+ // Message: NormalizedNodeMessage
+ final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
+ Futures.immediateCheckedFuture(Optional.of(outputNode));
+ doReturn(resultNormalizedNodeMessage).when(readTx).read(storeType, instanceIdentifier);
- /* Initialize data on master */
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNodeMessageResponse =
+ slaveDataBroker.newReadOnlyTransaction().read(storeType, instanceIdentifier);
- initializeDataTest();
+ final Optional<NormalizedNode<?, ?>> resultNodeMessage =
+ resultNodeMessageResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
- final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
- final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
+ assertTrue(resultNodeMessage.isPresent());
+ assertEquals(resultNodeMessage.get(), outputNode);
+ }
+ @Test
+ public void testReadEmpty() throws Exception {
// Message: EmptyReadResponse
-
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmpty =
Futures.immediateCheckedFuture(Optional.absent());
-
doReturn(resultEmpty).when(readTx).read(storeType, instanceIdentifier);
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmptyResponse =
resultEmptyResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
assertEquals(resultEmptyMessage, Optional.absent());
+ }
- // Message: NormalizedNodeMessage
-
- final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
-
- final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
- Futures.immediateCheckedFuture(Optional.of(outputNode));
-
- doReturn(resultNormalizedNodeMessage).when(readTx).read(storeType, instanceIdentifier);
-
- final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNodeMessageResponse =
- slaveDataBroker.newReadOnlyTransaction().read(storeType, instanceIdentifier);
-
- final Optional<NormalizedNode<?, ?>> resultNodeMessage =
- resultNodeMessageResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
- assertTrue(resultNodeMessage.isPresent());
- assertEquals(resultNodeMessage.get(), outputNode);
-
+ @Test
+ public void testReadFail() throws Exception {
// Message: Throwable
-
final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultThrowable =
Futures.immediateFailedCheckedFuture(readFailedException);
exception.expect(ReadFailedException.class);
resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
}
@Test
public void testExist() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
-
- final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
- final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-
// Message: True
-
final CheckedFuture<Boolean, ReadFailedException> resultTrue =
Futures.immediateCheckedFuture(true);
-
doReturn(resultTrue).when(readTx).exists(storeType, instanceIdentifier);
final CheckedFuture<Boolean, ReadFailedException> trueResponse =
final Boolean trueMessage = trueResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
assertEquals(true, trueMessage);
+ }
- // Message: False
-
- final CheckedFuture<Boolean, ReadFailedException> resultFalse = Futures.immediateCheckedFuture(false);
-
- doReturn(resultFalse).when(readTx).exists(storeType, instanceIdentifier);
-
- final CheckedFuture<Boolean, ReadFailedException> falseResponse =
- slaveDataBroker.newReadOnlyTransaction().exists(storeType,
- instanceIdentifier);
-
- final Boolean falseMessage = falseResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
- assertEquals(false, falseMessage);
-
+ @Test
+ public void testExistsNull() throws Exception {
// Message: False, result null
-
final CheckedFuture<Boolean, ReadFailedException> resultNull = Futures.immediateCheckedFuture(null);
-
doReturn(resultNull).when(readTx).exists(storeType, instanceIdentifier);
final CheckedFuture<Boolean, ReadFailedException> nullResponse =
final Boolean nullFalseMessage = nullResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
assertEquals(false, nullFalseMessage);
+ }
- // Message: Throwable
+ @Test
+ public void testExistsFalse() throws Exception {
+ // Message: False
+ final CheckedFuture<Boolean, ReadFailedException> resultFalse = Futures.immediateCheckedFuture(false);
+ doReturn(resultFalse).when(readTx).exists(storeType, instanceIdentifier);
+
+ final CheckedFuture<Boolean, ReadFailedException> falseResponse =
+ slaveDataBroker.newReadOnlyTransaction().exists(storeType,
+ instanceIdentifier);
+
+ final Boolean falseMessage = falseResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+ assertEquals(false, falseMessage);
+ }
+
+ @Test
+ public void testExistsFail() throws Exception {
+ // Message: Throwable
final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
final CheckedFuture<Boolean, ReadFailedException> resultThrowable =
Futures.immediateFailedCheckedFuture(readFailedException);
-
doReturn(resultThrowable).when(readTx).exists(storeType, instanceIdentifier);
final CheckedFuture<Boolean, ReadFailedException> resultThrowableResponse =
exception.expect(ReadFailedException.class);
resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
}
private void initializeDataTest() throws Exception {
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.netconf.topology.singleton.impl.tx;
+
+import static junit.framework.TestCase.assertNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.MockitoAnnotations.initMocks;
+import static org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Props;
+import akka.pattern.Patterns;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestActorRef;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.Mock;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMDataBroker;
+import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
+import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
+import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+import scala.concurrent.duration.Duration;
+
+public class ReadWriteTransactionTest {
+ private static final Timeout TIMEOUT = new Timeout(Duration.create(5, "seconds"));
+ private static final int TIMEOUT_SEC = 5;
+ private static ActorSystem system;
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ @Mock
+ private DOMDataBroker deviceDataBroker;
+ @Mock
+ private DOMDataReadWriteTransaction readWriteTx;
+ @Mock
+ private DOMRpcService domRpcService;
+ @Mock
+ private DOMMountPointService mountPointService;
+ private ActorRef masterRef;
+ private ProxyDOMDataBroker slaveDataBroker;
+ private List<SourceIdentifier> sourceIdentifiers;
+ private NormalizedNode<?, ?> testNode;
+ private YangInstanceIdentifier instanceIdentifier;
+ private LogicalDatastoreType storeType;
+
+ @Before
+ public void setup() throws Exception {
+ initMocks(this);
+
+ system = ActorSystem.create();
+
+ final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("netconf-topology",
+ new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+
+ final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
+ doReturn(Duration.apply(0, TimeUnit.SECONDS)).when(setup).getIdleTimeout();
+ final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
+ DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
+
+ masterRef = TestActorRef.create(system, props, "master_read");
+
+ sourceIdentifiers = Lists.newArrayList();
+
+ doReturn(readWriteTx).when(deviceDataBroker).newReadWriteTransaction();
+ doNothing().when(readWriteTx).put(storeType, instanceIdentifier, testNode);
+ doNothing().when(readWriteTx).merge(storeType, instanceIdentifier, testNode);
+ doNothing().when(readWriteTx).delete(storeType, instanceIdentifier);
+
+ // Create slave data broker for testing proxy
+ slaveDataBroker =
+ new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
+ initializeDataTest();
+ testNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ instanceIdentifier = YangInstanceIdentifier.EMPTY;
+ storeType = LogicalDatastoreType.CONFIGURATION;
+ }
+
+ @After
+ public void teardown() {
+ JavaTestKit.shutdownActorSystem(system, null, true);
+ system = null;
+ }
+
+ @Test
+ public void testPut() throws Exception {
+ // Test of invoking put on master through slave proxy
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ wTx.put(storeType, instanceIdentifier, testNode);
+
+ verify(readWriteTx, timeout(2000)).put(storeType, instanceIdentifier, testNode);
+
+ wTx.cancel();
+ }
+
+ @Test
+ public void testMerge() throws Exception {
+ // Test of invoking merge on master through slave proxy
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ wTx.merge(storeType, instanceIdentifier, testNode);
+
+ verify(readWriteTx, timeout(2000)).merge(storeType, instanceIdentifier, testNode);
+
+ wTx.cancel();
+ }
+
+ @Test
+ public void testDelete() throws Exception {
+ final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
+ final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
+
+ // Test of invoking delete on master through slave proxy
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ wTx.delete(storeType, instanceIdentifier);
+ wTx.cancel();
+
+ verify(readWriteTx, timeout(2000)).delete(storeType, instanceIdentifier);
+ }
+
+ @Test
+ public void testSubmit() throws Exception {
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmit = Futures.immediateCheckedFuture(null);
+ doReturn(resultSubmit).when(readWriteTx).submit();
+
+ // Without Tx
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitResponse = wTx.submit();
+
+ final Object result = resultSubmitResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertNull(result);
+ }
+
+ @Test
+ public void testSubmitWithOperation() throws Exception {
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
+ doReturn(resultSubmitTx).when(readWriteTx).submit();
+ // With Tx
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ wTx.delete(LogicalDatastoreType.CONFIGURATION,
+ YangInstanceIdentifier.EMPTY);
+
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTxResponse = wTx.submit();
+
+ final Object resultTx = resultSubmitTxResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertNull(resultTx);
+ }
+
+ @Test
+ public void testSubmitFail() throws Exception {
+ final TransactionCommitFailedException throwable = new TransactionCommitFailedException("Fail", null);
+ final CheckedFuture<Void, TransactionCommitFailedException> resultThrowable =
+ Futures.immediateFailedCheckedFuture(throwable);
+ doReturn(resultThrowable).when(readWriteTx).submit();
+
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ wTx.delete(LogicalDatastoreType.CONFIGURATION,
+ YangInstanceIdentifier.EMPTY);
+ final CheckedFuture<Void, TransactionCommitFailedException> resultThrowableResponse =
+ wTx.submit();
+ exception.expect(TransactionCommitFailedException.class);
+ resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+ }
+
+ @Test
+ public void testCancel() throws Exception {
+ doReturn(true).when(readWriteTx).cancel();
+
+ // Without Tx
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ final Boolean resultFalseNoTx = wTx.cancel();
+ assertEquals(true, resultFalseNoTx);
+ }
+
+ @Test
+ public void testCancelWithOperation() throws Exception {
+ doReturn(true).when(readWriteTx).cancel();
+
+ // With Tx, readWriteTx test
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+ wTx.delete(LogicalDatastoreType.CONFIGURATION,
+ YangInstanceIdentifier.EMPTY);
+
+ final Boolean resultTrue = wTx.cancel();
+ assertEquals(true, resultTrue);
+
+ final Boolean resultFalse = wTx.cancel();
+ assertEquals(false, resultFalse);
+ }
+
+ @Test
+ public void testRead() throws Exception {
+ // Message: NormalizedNodeMessage
+ final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
+ Futures.immediateCheckedFuture(Optional.of(outputNode));
+ doReturn(resultNormalizedNodeMessage).when(readWriteTx).read(storeType, instanceIdentifier);
+
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNodeMessageResponse =
+ slaveDataBroker.newReadWriteTransaction().read(storeType, instanceIdentifier);
+
+ final Optional<NormalizedNode<?, ?>> resultNodeMessage =
+ resultNodeMessageResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertTrue(resultNodeMessage.isPresent());
+ assertEquals(resultNodeMessage.get(), outputNode);
+ }
+
+ @Test
+ public void testReadEmpty() throws Exception {
+ // Message: EmptyReadResponse
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmpty =
+ Futures.immediateCheckedFuture(Optional.absent());
+ doReturn(resultEmpty).when(readWriteTx).read(storeType, instanceIdentifier);
+
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmptyResponse =
+ slaveDataBroker.newReadWriteTransaction().read(storeType,
+ instanceIdentifier);
+
+ final Optional<NormalizedNode<?, ?>> resultEmptyMessage =
+ resultEmptyResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertEquals(resultEmptyMessage, Optional.absent());
+ }
+
+ @Test
+ public void testReadFail() throws Exception {
+ // Message: Throwable
+ final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultThrowable =
+ Futures.immediateFailedCheckedFuture(readFailedException);
+
+ doReturn(resultThrowable).when(readWriteTx).read(storeType, instanceIdentifier);
+
+ final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultThrowableResponse =
+ slaveDataBroker.newReadWriteTransaction().read(storeType, instanceIdentifier);
+
+ exception.expect(ReadFailedException.class);
+ resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+ }
+
+ @Test
+ public void testExist() throws Exception {
+ // Message: True
+ final CheckedFuture<Boolean, ReadFailedException> resultTrue =
+ Futures.immediateCheckedFuture(true);
+ doReturn(resultTrue).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+ final CheckedFuture<Boolean, ReadFailedException> trueResponse =
+ slaveDataBroker.newReadWriteTransaction().exists(storeType, instanceIdentifier);
+
+ final Boolean trueMessage = trueResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertEquals(true, trueMessage);
+ }
+
+ @Test
+ public void testExistsNull() throws Exception {
+ // Message: False, result null
+ final CheckedFuture<Boolean, ReadFailedException> resultNull = Futures.immediateCheckedFuture(null);
+ doReturn(resultNull).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+ final CheckedFuture<Boolean, ReadFailedException> nullResponse =
+ slaveDataBroker.newReadWriteTransaction().exists(storeType,
+ instanceIdentifier);
+
+ final Boolean nullFalseMessage = nullResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertEquals(false, nullFalseMessage);
+ }
+
+ @Test
+ public void testExistsFalse() throws Exception {
+ // Message: False
+ final CheckedFuture<Boolean, ReadFailedException> resultFalse = Futures.immediateCheckedFuture(false);
+ doReturn(resultFalse).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+ final CheckedFuture<Boolean, ReadFailedException> falseResponse =
+ slaveDataBroker.newReadWriteTransaction().exists(storeType,
+ instanceIdentifier);
+
+ final Boolean falseMessage = falseResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+ assertEquals(false, falseMessage);
+ }
+
+ @Test
+ public void testExistsFail() throws Exception {
+ // Message: Throwable
+ final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
+ final CheckedFuture<Boolean, ReadFailedException> resultThrowable =
+ Futures.immediateFailedCheckedFuture(readFailedException);
+ doReturn(resultThrowable).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+ final CheckedFuture<Boolean, ReadFailedException> resultThrowableResponse =
+ slaveDataBroker.newReadWriteTransaction().exists(storeType, instanceIdentifier);
+
+ exception.expect(ReadFailedException.class);
+ resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+ }
+
+ private void initializeDataTest() throws Exception {
+ final Future<Object> initialDataToActor =
+ Patterns.ask(masterRef, new CreateInitialMasterActorData(deviceDataBroker, sourceIdentifiers,
+ domRpcService), TIMEOUT);
+
+ final Object success = Await.result(initialDataToActor, TIMEOUT.duration());
+
+ assertTrue(success instanceof MasterActorDataInitialized);
+ }
+
+}
import static junit.framework.TestCase.assertNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import com.google.common.util.concurrent.Futures;
import java.net.InetAddress;
import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMDataBroker;
@Rule
public final ExpectedException exception = ExpectedException.none();
- private ActorRef masterRef;
- private ProxyDOMDataBroker slaveDataBroker;
- private List<SourceIdentifier> sourceIdentifiers;
@Mock
private DOMDataBroker deviceDataBroker;
@Mock
private DOMDataWriteTransaction writeTx;
@Mock
private DOMRpcService domRpcService;
+ @Mock
+ private DOMMountPointService mountPointService;
+ private ActorRef masterRef;
+ private ProxyDOMDataBroker slaveDataBroker;
+ private List<SourceIdentifier> sourceIdentifiers;
+ private NormalizedNode<?, ?> testNode;
+ private YangInstanceIdentifier instanceIdentifier;
+ private LogicalDatastoreType storeType;
@Before
- public void setup() throws UnknownHostException {
+ public void setup() throws Exception {
initMocks(this);
system = ActorSystem.create();
final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
doReturn(Duration.apply(0, TimeUnit.SECONDS)).when(setup).getIdleTimeout();
final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
- DEFAULT_SCHEMA_REPOSITORY, TIMEOUT);
+ DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
masterRef = TestActorRef.create(system, props, "master_read");
sourceIdentifiers = Lists.newArrayList();
- writeTx = mock(DOMDataWriteTransaction.class);
final DOMDataReadOnlyTransaction readTx = mock(DOMDataReadOnlyTransaction.class);
doReturn(writeTx).when(deviceDataBroker).newWriteOnlyTransaction();
doReturn(readTx).when(deviceDataBroker).newReadOnlyTransaction();
+ doNothing().when(writeTx).put(storeType, instanceIdentifier, testNode);
+ doNothing().when(writeTx).merge(storeType, instanceIdentifier, testNode);
+ doNothing().when(writeTx).delete(storeType, instanceIdentifier);
// Create slave data broker for testing proxy
slaveDataBroker =
new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
+ initializeDataTest();
+ testNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+ .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+ instanceIdentifier = YangInstanceIdentifier.EMPTY;
+ storeType = LogicalDatastoreType.CONFIGURATION;
}
@After
@Test
public void testPut() throws Exception {
- /* Initialize data on master */
-
- initializeDataTest();
-
- final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
- final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
- final NormalizedNode<?, ?> testNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
-
// Test of invoking put on master through slave proxy
-
- doNothing().when(writeTx).put(storeType, instanceIdentifier, testNode);
-
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
wTx.put(storeType, instanceIdentifier, testNode);
verify(writeTx, timeout(2000)).put(storeType, instanceIdentifier, testNode);
wTx.cancel();
-
}
@Test
public void testMerge() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
-
- final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
- final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
- final NormalizedNode<?, ?> testNode = ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
- .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
// Test of invoking merge on master through slave proxy
-
- doNothing().when(writeTx).merge(storeType, instanceIdentifier, testNode);
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
wTx.merge(storeType, instanceIdentifier, testNode);
verify(writeTx, timeout(2000)).merge(storeType, instanceIdentifier, testNode);
wTx.cancel();
-
}
@Test
public void testDelete() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
-
final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
- // Test of invoking delete on master through slave proxy
- doNothing().when(writeTx).delete(storeType, instanceIdentifier);
+ // Test of invoking delete on master through slave proxy
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
wTx.delete(storeType, instanceIdentifier);
wTx.cancel();
verify(writeTx, timeout(2000)).delete(storeType, instanceIdentifier);
-
}
@Test
public void testSubmit() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmit = Futures.immediateCheckedFuture(null);
+ doReturn(resultSubmit).when(writeTx).submit();
// Without Tx
-
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
- final CheckedFuture<Void, TransactionCommitFailedException> resultSubmit = Futures.immediateCheckedFuture(null);
- doReturn(resultSubmit).when(writeTx).submit();
final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitResponse = wTx.submit();
@Test
public void testSubmitWithOperation() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
+ doReturn(resultSubmitTx).when(writeTx).submit();
// With Tx
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
- doNothing().when(writeTx).delete(any(), any());
wTx.delete(LogicalDatastoreType.CONFIGURATION,
YangInstanceIdentifier.EMPTY);
- final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
- doReturn(resultSubmitTx).when(writeTx).submit();
-
final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTxResponse = wTx.submit();
final Object resultTx = resultSubmitTxResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
@Test
public void testSubmitFail() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
- final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
- wTx.delete(LogicalDatastoreType.CONFIGURATION,
- YangInstanceIdentifier.EMPTY);
-
final TransactionCommitFailedException throwable = new TransactionCommitFailedException("Fail", null);
- final CheckedFuture<Void,TransactionCommitFailedException> resultThrowable =
+ final CheckedFuture<Void, TransactionCommitFailedException> resultThrowable =
Futures.immediateFailedCheckedFuture(throwable);
-
doReturn(resultThrowable).when(writeTx).submit();
+ final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
+ wTx.delete(LogicalDatastoreType.CONFIGURATION,
+ YangInstanceIdentifier.EMPTY);
final CheckedFuture<Void, TransactionCommitFailedException> resultThrowableResponse =
wTx.submit();
-
exception.expect(TransactionCommitFailedException.class);
resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
}
@Test
public void testCancel() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
+ doReturn(true).when(writeTx).cancel();
// Without Tx
- doReturn(true).when(writeTx).cancel();
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
final Boolean resultFalseNoTx = wTx.cancel();
assertEquals(true, resultFalseNoTx);
@Test
public void testCancelWithOperation() throws Exception {
-
- /* Initialize data on master */
-
- initializeDataTest();
+ doReturn(true).when(writeTx).cancel();
// With Tx, readWriteTx test
-
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
- doNothing().when(writeTx).delete(any(), any());
wTx.delete(LogicalDatastoreType.CONFIGURATION,
YangInstanceIdentifier.EMPTY);
- doReturn(true).when(writeTx).cancel();
final Boolean resultTrue = wTx.cancel();
assertEquals(true, resultTrue);
final Boolean resultFalse = wTx.cancel();
assertEquals(false, resultFalse);
-
}
private void initializeDataTest() throws Exception {
import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
import org.opendaylight.controller.config.threadpool.ThreadPool;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.client.NetconfClientSessionListener;
protected final String topologyId;
private final NetconfClientDispatcher clientDispatcher;
- protected final BindingAwareBroker bindingAwareBroker;
- protected final Broker domBroker;
private final EventExecutor eventExecutor;
protected final ScheduledThreadPool keepaliveExecutor;
protected final ThreadPool processingExecutor;
protected final SharedSchemaRepository sharedSchemaRepository;
protected final DataBroker dataBroker;
+ protected final DOMMountPointService mountPointService;
protected SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
protected SchemaRepository schemaRepository = DEFAULT_SCHEMA_REPOSITORY;
protected final HashMap<NodeId, NetconfConnectorDTO> activeConnectors = new HashMap<>();
protected AbstractNetconfTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
- final BindingAwareBroker bindingAwareBroker, final Broker domBroker,
final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
- final DataBroker dataBroker) {
+ final DataBroker dataBroker, final DOMMountPointService mountPointService) {
this.topologyId = topologyId;
this.clientDispatcher = clientDispatcher;
- this.bindingAwareBroker = bindingAwareBroker;
- this.domBroker = domBroker;
this.eventExecutor = eventExecutor;
this.keepaliveExecutor = keepaliveExecutor;
this.processingExecutor = processingExecutor;
this.sharedSchemaRepository = schemaRepositoryProvider.getSharedSchemaRepository();
this.dataBroker = dataBroker;
+ this.mountPointService = mountPointService;
}
public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
- createSalFacade(remoteDeviceId, domBroker, bindingAwareBroker);
+ createSalFacade(remoteDeviceId);
if (keepaliveDelay > 0) {
LOG.warn("Adding keepalive facade, for device {}", nodeId);
.build();
}
- protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker);
+ protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id);
private InetSocketAddress getSocketAddress(final Host host, final int port) {
if(host.getDomainName() != null) {
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
private ListenerRegistration<NetconfTopologyImpl> datastoreListenerRegistration = null;
public NetconfTopologyImpl(final String topologyId, final NetconfClientDispatcher clientDispatcher,
- final BindingAwareBroker bindingAwareBroker, final Broker domBroker,
final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
- final DataBroker dataBroker) {
- super(topologyId, clientDispatcher,
- bindingAwareBroker, domBroker, eventExecutor,
- keepaliveExecutor, processingExecutor, schemaRepositoryProvider, dataBroker);
+ final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+ super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor, processingExecutor,
+ schemaRepositoryProvider, dataBroker, mountPointService);
}
@Override
public void close() throws Exception {
// close all existing connectors, delete whole topology in datastore?
- for (NetconfConnectorDTO connectorDTO : activeConnectors.values()) {
+ for (final NetconfConnectorDTO connectorDTO : activeConnectors.values()) {
connectorDTO.close();
}
activeConnectors.clear();
}
@Override
- protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(RemoteDeviceId id, Broker domBroker, BindingAwareBroker bindingBroker) {
- return new NetconfDeviceSalFacade(id, domBroker, bindingAwareBroker);
+ protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id) {
+ return new NetconfDeviceSalFacade(id, mountPointService, dataBroker);
}
/**
initTopology(wtx, LogicalDatastoreType.OPERATIONAL);
Futures.addCallback(wtx.submit(), new FutureCallback<Void>() {
@Override
- public void onSuccess(Void result) {
+ public void onSuccess(final Void result) {
LOG.debug("topology initialization successful");
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(final Throwable t) {
LOG.error("Unable to initialize netconf-topology, {}", t);
}
});
}
@Override
- public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Node>> collection) {
- for (DataTreeModification<Node> change : collection) {
+ public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Node>> collection) {
+ for (final DataTreeModification<Node> change : collection) {
final DataObjectModification<Node> rootNode = change.getRootNode();
switch (rootNode.getModificationType()) {
case SUBTREE_MODIFIED:
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.netconf.client.NetconfClientDispatcher;
import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
private static final NodeId NODE_ID = new NodeId("testing-node");
private static final String TOPOLOGY_ID = "testing-topology";
- @Mock
- private Broker mockedDataBroker;
-
@Mock
private NetconfClientDispatcher mockedClientDispatcher;
- @Mock
- private BindingAwareBroker mockedBindingAwareBroker;
-
@Mock
private EventExecutor mockedEventExecutor;
@Mock
private DataBroker dataBroker;
+ @Mock
+ private DOMMountPointService mountPointService;
+
private TestingNetconfTopologyImpl topology;
private TestingNetconfTopologyImpl spyTopology;
when(mockedSchemaRepositoryProvider.getSharedSchemaRepository()).thenReturn(new SharedSchemaRepository("testingSharedSchemaRepo"));
when(mockedProcessingExecutor.getExecutor()).thenReturn(MoreExecutors.newDirectExecutorService());
- Future future = new SucceededFuture(ImmediateEventExecutor.INSTANCE, new NetconfDeviceCapabilities());
+ final Future future = new SucceededFuture(ImmediateEventExecutor.INSTANCE, new NetconfDeviceCapabilities());
when(mockedClientDispatcher.createReconnectingClient(any(NetconfReconnectingClientConfiguration.class))).thenReturn(future);
- topology = new TestingNetconfTopologyImpl(TOPOLOGY_ID, mockedClientDispatcher, mockedBindingAwareBroker,
- mockedDataBroker, mockedEventExecutor, mockedKeepaliveExecutor, mockedProcessingExecutor, mockedSchemaRepositoryProvider,
- dataBroker);
+ topology = new TestingNetconfTopologyImpl(TOPOLOGY_ID, mockedClientDispatcher,
+ mockedEventExecutor, mockedKeepaliveExecutor, mockedProcessingExecutor, mockedSchemaRepositoryProvider,
+ dataBroker, mountPointService);
spyTopology = spy(topology);
}
@Test
public void testInit() {
- WriteTransaction wtx = mock(WriteTransaction.class);
+ final WriteTransaction wtx = mock(WriteTransaction.class);
when(dataBroker.newWriteOnlyTransaction()).thenReturn(wtx);
doNothing().when(wtx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class));
when(wtx.submit()).thenReturn(Futures.<Void, TransactionCommitFailedException>immediateCheckedFuture(null));
@Test
public void testOnDataTreeChange() {
- DataObjectModification<Node> newNode = mock(DataObjectModification.class);
+ final DataObjectModification<Node> newNode = mock(DataObjectModification.class);
when(newNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.WRITE);
InstanceIdentifier.PathArgument pa = null;
- for (InstanceIdentifier.PathArgument p : TopologyUtil.createTopologyListPath(TOPOLOGY_ID).child(Node.class, new NodeKey(NODE_ID)).getPathArguments()) {
+ for (final InstanceIdentifier.PathArgument p : TopologyUtil.createTopologyListPath(TOPOLOGY_ID).child(Node.class, new NodeKey(NODE_ID)).getPathArguments()) {
pa = p;
}
when(newNode.getIdentifier()).thenReturn(pa);
- NetconfNode testingNode = new NetconfNodeBuilder()
+ final NetconfNode testingNode = new NetconfNodeBuilder()
.setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
.setPort(new PortNumber(9999))
.setReconnectOnChangedSchema(true)
.setCredentials(new LoginPasswordBuilder().setUsername("testuser").setPassword("testpassword").build())
.build();
- NodeBuilder nn = new NodeBuilder().addAugmentation(NetconfNode.class, testingNode);
+ final NodeBuilder nn = new NodeBuilder().addAugmentation(NetconfNode.class, testingNode);
when(newNode.getDataAfter()).thenReturn(nn.build());
-
- Collection<DataTreeModification<Node>> changes = Sets.newHashSet();
- DataTreeModification<Node> ch = mock(DataTreeModification.class);
+ final Collection<DataTreeModification<Node>> changes = Sets.newHashSet();
+ final DataTreeModification<Node> ch = mock(DataTreeModification.class);
when(ch.getRootNode()).thenReturn(newNode);
changes.add(ch);
spyTopology.onDataTreeChanged(changes);
public static class TestingNetconfTopologyImpl extends NetconfTopologyImpl {
- public TestingNetconfTopologyImpl(String topologyId, NetconfClientDispatcher clientDispatcher,
- BindingAwareBroker bindingAwareBroker, Broker domBroker,
- EventExecutor eventExecutor, ScheduledThreadPool keepaliveExecutor,
- ThreadPool processingExecutor, SchemaRepositoryProvider schemaRepositoryProvider,
- DataBroker dataBroker) {
- super(topologyId, clientDispatcher, bindingAwareBroker, domBroker, eventExecutor, keepaliveExecutor,
- processingExecutor, schemaRepositoryProvider, dataBroker);
+ public TestingNetconfTopologyImpl(final String topologyId, final NetconfClientDispatcher clientDispatcher,
+ final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
+ final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
+ final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+ super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
+ processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService);
}
@Override
- public ListenableFuture<NetconfDeviceCapabilities> connectNode(NodeId nodeId, Node configNode) {
+ public ListenableFuture<NetconfDeviceCapabilities> connectNode(final NodeId nodeId, final Node configNode) {
return Futures.immediateFuture(new NetconfDeviceCapabilities());
}
@Override
- public ListenableFuture<Void> disconnectNode(NodeId nodeId) {
+ public ListenableFuture<Void> disconnectNode(final NodeId nodeId) {
return Futures.immediateFuture(null);
}
}
return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
}
- void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc) {
+ void handleSalInitializationSuccess(final SchemaContext result,
+ final NetconfSessionPreferences remoteSessionCapabilities,
+ final DOMRpcService deviceRpc) {
final BaseSchema baseSchema =
remoteSessionCapabilities.isNotificationsSupported() ?
BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import java.util.List;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
private final RemoteDeviceId id;
private final NetconfDeviceSalProvider salProvider;
-
private final List<AutoCloseable> salRegistrations = Lists.newArrayList();
- public NetconfDeviceSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker) {
+ public NetconfDeviceSalFacade(final RemoteDeviceId id, final DOMMountPointService mountPointService,
+ final DataBroker dataBroker) {
this.id = id;
- this.salProvider = new NetconfDeviceSalProvider(id);
- registerToSal(domBroker, bindingBroker);
+ this.salProvider = new NetconfDeviceSalProvider(id, mountPointService, dataBroker);
}
@VisibleForTesting
- NetconfDeviceSalFacade(final RemoteDeviceId id, NetconfDeviceSalProvider salProvider,
- final Broker domBroker, final BindingAwareBroker bindingBroker) {
+ NetconfDeviceSalFacade(final RemoteDeviceId id, final NetconfDeviceSalProvider salProvider) {
this.id = id;
this.salProvider = salProvider;
- registerToSal(domBroker, bindingBroker);
- }
-
- public void registerToSal(final Broker domRegistryDependency, final BindingAwareBroker bindingBroker) {
- domRegistryDependency.registerProvider(salProvider);
- bindingBroker.registerProvider(salProvider);
}
@Override
package org.opendaylight.netconf.sal.connect.netconf.sal;
import com.google.common.base.Preconditions;
-import java.util.Collection;
-import java.util.Collections;
import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.controller.sal.core.api.Provider;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfDeviceSalProvider implements AutoCloseable, Provider, BindingAwareProvider {
+public class NetconfDeviceSalProvider implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
private final RemoteDeviceId id;
- private MountInstance mountInstance;
+ private final MountInstance mountInstance;
+ private final DataBroker dataBroker;
private volatile NetconfDeviceTopologyAdapter topologyDatastoreAdapter;
- private DataBroker dataBroker;
private BindingTransactionChain txChain;
private final TransactionChainListener transactionChainListener = new TransactionChainListener() {
@Override
- public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction, Throwable cause) {
+ public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
chain.close();
resetTransactionChainForAdapaters();
}
@Override
- public void onTransactionChainSuccessful(TransactionChain<?, ?> chain) {
+ public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
}
};
- public NetconfDeviceSalProvider(final RemoteDeviceId deviceId) {
+ public NetconfDeviceSalProvider(final RemoteDeviceId deviceId, final DOMMountPointService mountService,
+ final DataBroker dataBroker) {
this.id = deviceId;
+ mountInstance = new MountInstance(mountService, id);
+ this.dataBroker = dataBroker;
+ txChain = Preconditions.checkNotNull(dataBroker).createTransactionChain(transactionChainListener);
+
+ topologyDatastoreAdapter = new NetconfDeviceTopologyAdapter(id, txChain);
+ }
+
+ public NetconfDeviceSalProvider(final RemoteDeviceId deviceId, final DOMMountPointService mountService) {
+ this.id = deviceId;
+ mountInstance = new MountInstance(mountService, id);
+ this.dataBroker = null;
}
public MountInstance getMountInstance() {
return topologyDatastoreAdapter;
}
- @Override
- public void onSessionInitiated(final Broker.ProviderSession session) {
- logger.debug("{}: (BI)Session with sal established {}", id, session);
-
- final DOMMountPointService mountService = session.getService(DOMMountPointService.class);
- if (mountService != null) {
- mountInstance = new MountInstance(mountService, id);
- }
- }
-
- @Override
- public Collection<Provider.ProviderFunctionality> getProviderFunctionality() {
- return Collections.emptySet();
- }
-
- @Override
- public void onSessionInitiated(final BindingAwareBroker.ProviderContext session) {
- logger.debug("{}: Session with sal established {}", id, session);
-
- this.dataBroker = session.getSALService(DataBroker.class);
- txChain = Preconditions.checkNotNull(dataBroker).createTransactionChain(transactionChainListener);
-
- topologyDatastoreAdapter = new NetconfDeviceTopologyAdapter(id, txChain);
- }
-
private void resetTransactionChainForAdapaters() {
txChain = Preconditions.checkNotNull(dataBroker).createTransactionChain(transactionChainListener);
public static final class MountInstance implements AutoCloseable {
- private DOMMountPointService mountService;
+ private final DOMMountPointService mountService;
private final RemoteDeviceId id;
private NetconfDeviceNotificationService notificationService;
}
public synchronized void onTopologyDeviceConnected(final SchemaContext initialCtx,
- final DOMDataBroker broker, final DOMRpcService rpc,
- final NetconfDeviceNotificationService notificationService) {
-
+ final DOMDataBroker broker, final DOMRpcService rpc,
+ final NetconfDeviceNotificationService notificationService) {
Preconditions.checkNotNull(mountService, "Closed");
Preconditions.checkState(topologyRegistration == null, "Already initialized");
@Override
public synchronized void close() throws Exception {
onTopologyDeviceDisconnected();
- mountService = null;
}
public synchronized void publish(final DOMNotification domNotification) {
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("test", address);
- final Broker domRegistry = mock(Broker.class);
- final BindingAwareBroker bindingRegistry = mock(BindingAwareBroker.class);
- deviceFacade = new NetconfDeviceSalFacade(remoteDeviceId, salProvider, domRegistry, bindingRegistry);
+ deviceFacade = new NetconfDeviceSalFacade(remoteDeviceId, salProvider);
netconfDeviceTopologyAdapter = PowerMockito.mock(NetconfDeviceTopologyAdapter.class);
mountInstance = PowerMockito.mock(NetconfDeviceSalProvider.MountInstance.class);
package org.opendaylight.netconf.sal.connect.netconf.sal;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.util.concurrent.Futures;
import java.net.InetSocketAddress;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
private DataBroker dataBroker;
@Mock
private BindingTransactionChain chain;
+ @Mock
+ private DOMMountPointService mountPointService;
+ @Mock
+ private WriteTransaction writeTx;
private NetconfDeviceSalProvider provider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- provider = new NetconfDeviceSalProvider(new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)));
+ doReturn(chain).when(dataBroker).createTransactionChain(any(TransactionChainListener.class));
+ doReturn(writeTx).when(chain).newWriteOnlyTransaction();
+ doNothing().when(writeTx).merge(eq(LogicalDatastoreType.OPERATIONAL), any(), any());
+ doReturn("Some object").when(writeTx).getIdentifier();
+ doReturn(Futures.immediateCheckedFuture(null)).when(writeTx).submit();
+ provider = new NetconfDeviceSalProvider(new RemoteDeviceId("device1",
+ InetSocketAddress.createUnresolved("localhost", 17830)), mountPointService, dataBroker);
when(session.getService(DOMMountPointService.class)).thenReturn(mountpointService);
when(context.getSALService(DataBroker.class)).thenReturn(dataBroker);
- when(dataBroker.createTransactionChain(any())).thenReturn(chain);
when(chain.newWriteOnlyTransaction()).thenReturn(tx);
when(tx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
when(tx.getIdentifier()).thenReturn(tx);
}
- @Test
- public void onSessionInitiated() throws Exception {
- provider.onSessionInitiated(session);
- provider.onSessionInitiated(context);
- Assert.assertNotNull(provider.getMountInstance());
- Assert.assertNotNull(provider.getTopologyDatastoreAdapter());
- }
-
- @Test
- public void getProviderFunctionality() throws Exception {
- Assert.assertTrue(provider.getProviderFunctionality().isEmpty());
- }
-
@Test
public void replaceChainIfFailed() throws Exception {
- provider.onSessionInitiated(session);
- provider.onSessionInitiated(context);
- Assert.assertNotNull(provider.getMountInstance());
final ArgumentCaptor<TransactionChainListener> captor = ArgumentCaptor.forClass(TransactionChainListener.class);
verify(dataBroker).createTransactionChain(captor.capture());
try {
@Test
public void close() throws Exception {
- provider.onSessionInitiated(session);
- provider.onSessionInitiated(context);
provider.close();
verify(chain).close();
}
@Test
public void closeWithoutNPE() throws Exception {
- provider.onSessionInitiated(session);
- provider.onSessionInitiated(context);
provider.close();
provider.close();
verify(chain, times(2)).close();