</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) {