<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;
<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
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;
private DOMDataReadOnlyTransaction readTx;
@Mock
private DOMRpcService domRpcService;
+ private YangInstanceIdentifier instanceIdentifier;
+ private LogicalDatastoreType storeType;
@Before
- public void setup() throws UnknownHostException {
+ public void setup() throws Exception {
initMocks(this);
system = ActorSystem.create();
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 {
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;
@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;
+ 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();
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 {