From 4753fa30e1d6127f8b01fef74bea187187fee4d7 Mon Sep 17 00:00:00 2001 From: "matus.kubica" Date: Mon, 24 Apr 2017 15:47:45 +0200 Subject: [PATCH] Bug 8153: Enforce check-style rules for netconf - netconf-netty-util Organize Imports for Checkstyle compliance. Checkstyle compliance: line length. Checkstyle compliance: various types of small changes. Checkstyle compliant Exception handling. Checkstyle final clean up & enforcement. Add the fail on violation flag into the pom.xml . Change-Id: I54aa8b0b3e64c83dff89e54ea4e1281ba839ee98 Signed-off-by: matus.kubica --- netconf/netconf-netty-util/pom.xml | 7 + .../nettyutil/AbstractChannelInitializer.java | 3 +- .../nettyutil/AbstractNetconfSession.java | 6 +- .../AbstractNetconfSessionNegotiator.java | 45 ++-- .../nettyutil/handler/BufferedWriter.java | 48 ++-- .../ChunkedFramingMechanismEncoder.java | 3 +- .../handler/NetconfChunkAggregator.java | 215 +++++++++--------- .../nettyutil/handler/NetconfEXICodec.java | 13 +- .../handler/NetconfEXIToMessageDecoder.java | 9 +- .../NetconfHelloMessageToXMLEncoder.java | 15 +- .../handler/NetconfMessageToEXIEncoder.java | 8 +- .../handler/NetconfMessageToXMLEncoder.java | 6 +- .../NetconfXMLToHelloMessageDecoder.java | 38 ++-- .../handler/NetconfXMLToMessageDecoder.java | 9 +- .../nettyutil/handler/exi/EXIParameters.java | 31 +-- .../handler/exi/NetconfStartExiMessage.java | 42 ++-- .../authentication/AuthenticationHandler.java | 3 +- .../ssh/authentication/LoginPassword.java | 2 +- .../handler/ssh/client/AsyncSshHandler.java | 84 ++++--- .../ssh/client/AsyncSshHandlerReader.java | 17 +- .../ssh/client/AsyncSshHandlerWriter.java | 32 +-- .../AbstractNetconfSessionNegotiatorTest.java | 14 +- .../nettyutil/AbstractNetconfSessionTest.java | 18 +- .../nettyutil/TestingNetconfSession.java | 9 +- .../ChunkedFramingMechanismEncoderTest.java | 6 +- .../handler/NetconfChunkAggregatorTest.java | 28 +-- .../handler/NetconfEXIHandlersTest.java | 3 +- .../NetconfHelloMessageToXMLEncoderTest.java | 9 +- .../NetconfXMLToHelloMessageDecoderTest.java | 24 +- .../NetconfXMLToMessageDecoderTest.java | 10 +- .../handler/exi/EXIParametersTest.java | 26 +-- .../exi/NetconfStartExiMessageTest.java | 36 +-- .../ssh/client/AsyncSshHandlerTest.java | 33 ++- 33 files changed, 476 insertions(+), 376 deletions(-) diff --git a/netconf/netconf-netty-util/pom.xml b/netconf/netconf-netty-util/pom.xml index be792df880..d3689608eb 100644 --- a/netconf/netconf-netty-util/pom.xml +++ b/netconf/netconf-netty-util/pom.xml @@ -124,6 +124,13 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractChannelInitializer.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractChannelInitializer.java index 6bc9d70f1a..c967e8f317 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractChannelInitializer.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractChannelInitializer.java @@ -28,7 +28,8 @@ public abstract class AbstractChannelInitializer { public void initialize(Channel ch, Promise promise) { ch.pipeline().addLast(NETCONF_MESSAGE_AGGREGATOR, new NetconfEOMAggregator()); initializeMessageDecoder(ch); - ch.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER, FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM)); + ch.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER, + FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM)); initializeMessageEncoder(ch); initializeSessionNegotiator(ch, promise); diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSession.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSession.java index e4c03ed50f..b1c1203c4f 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSession.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSession.java @@ -32,7 +32,8 @@ import org.openexi.sax.TransmogrifierException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public abstract class AbstractNetconfSession> extends AbstractProtocolSession implements NetconfSession, NetconfExiSession { +public abstract class AbstractNetconfSession> + extends AbstractProtocolSession implements NetconfSession, NetconfExiSession { private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSession.class); private final L sessionListener; private final long sessionId; @@ -104,7 +105,8 @@ public abstract class AbstractNetconfSession, L extends NetconfSessionListener> +public abstract class AbstractNetconfSessionNegotiator

, L extends NetconfSessionListener> extends AbstractSessionNegotiator { private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class); @@ -54,7 +55,7 @@ public abstract class AbstractNetconfSessionNegotiator

promise, final Channel channel, final Timer timer, - final L sessionListener, final long connectionTimeoutMillis) { + protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise promise, + final Channel channel, final Timer timer, + final L sessionListener, final long connectionTimeoutMillis) { super(promise, channel); this.sessionPreferences = sessionPreferences; this.promise = promise; @@ -95,7 +97,7 @@ public abstract class AbstractNetconfSessionNegotiator

getSslHandler(final Channel channel) { final SslHandler sslHandler = channel.pipeline().get(SslHandler.class); - return sslHandler == null ? Optional. absent() : Optional.of(sslHandler); + return sslHandler == null ? Optional.absent() : Optional.of(sslHandler); } public P getSessionPreferences() { @@ -130,7 +132,7 @@ public abstract class AbstractNetconfSessionNegotiator

() { @Override public void operationComplete(final ChannelFuture future) throws Exception { - if(future.isSuccess()) { + if (future.isSuccess()) { LOG.debug("Channel {} closed: success", future.channel()); } else { LOG.warn("Channel {} closed: fail", future.channel()); @@ -138,7 +140,7 @@ public abstract class AbstractNetconfSessionNegotiator

* Inbound hello message handler should be kept until negotiation is successful * It caches any non-hello messages while negotiation is still in progress */ protected final void replaceHelloMessageInboundHandler(final S session) { - ChannelHandler helloMessageHandler = replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder()); + ChannelHandler helloMessageHandler = replaceChannelHandler(channel, + AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder()); Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder, "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline()); @@ -200,7 +205,8 @@ public abstract class AbstractNetconfSessionNegotiator

* The line separator instance field in java.io.BufferedWriter is * assigned using AccessController and takes considerable amount of time especially * if lots of BufferedWriters are created in the system. + * *

* This implementation should only be used if newLine method is not required * such as netconf message to XML encoders. @@ -31,7 +32,7 @@ public final class BufferedWriter extends Writer { private static final int DEFAULT_CHAR_BUFFER_SIZE = 8192; private final Writer writer; - private final char buffer[]; + private final char[] buffer; private final int bufferSize; private int nextChar = 0; @@ -49,24 +50,27 @@ public final class BufferedWriter extends Writer { } private void flushBuffer() throws IOException { - if (nextChar == 0) + if (nextChar == 0) { return; + } writer.write(buffer, 0, nextChar); nextChar = 0; } @Override - public void write(final int c) throws IOException { - if (nextChar >= bufferSize) + public void write(final int character) throws IOException { + if (nextChar >= bufferSize) { flushBuffer(); - buffer[nextChar++] = (char) c; + } + buffer[nextChar++] = (char) character; } @Override public void write(final char[] buffer, final int offset, final int length) throws IOException { - if ((offset < 0) || (offset > buffer.length) || (length < 0) || - ((offset + length) > buffer.length) || ((offset + length) < 0)) { - throw new IndexOutOfBoundsException(String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length)); + if ((offset < 0) || (offset > buffer.length) + || (length < 0) || ((offset + length) > buffer.length) || ((offset + length) < 0)) { + throw new IndexOutOfBoundsException( + String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length)); } else if (length == 0) { return; } @@ -77,29 +81,31 @@ public final class BufferedWriter extends Writer { return; } - int b = offset; + int bufferOffset = offset; final int t = offset + length; - while (b < t) { - final int d = Math.min(bufferSize - nextChar, t - b); - System.arraycopy(buffer, b, this.buffer, nextChar, d); - b += d; + while (bufferOffset < t) { + final int d = Math.min(bufferSize - nextChar, t - bufferOffset); + System.arraycopy(buffer, bufferOffset, this.buffer, nextChar, d); + bufferOffset += d; nextChar += d; - if (nextChar >= bufferSize) + if (nextChar >= bufferSize) { flushBuffer(); + } } } @Override public void write(final String string, final int offset, final int length) throws IOException { - int b = offset; + int bufferOffset = offset; final int t = offset + length; - while (b < t) { - final int d = Math.min(bufferSize - nextChar, t - b); - string.getChars(b, b + d, buffer, nextChar); - b += d; + while (bufferOffset < t) { + final int d = Math.min(bufferSize - nextChar, t - bufferOffset); + string.getChars(bufferOffset, bufferOffset + d, buffer, nextChar); + bufferOffset += d; nextChar += d; - if (nextChar >= bufferSize) + if (nextChar >= bufferSize) { flushBuffer(); + } } } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java index 8c9a2b35c9..1d7a3cd5ad 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java @@ -27,7 +27,8 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder= MIN_CHUNK_SIZE && chunkSize <= MAX_CHUNK_SIZE, "Unsupported chunk size %s", chunkSize); + Preconditions.checkArgument(chunkSize >= MIN_CHUNK_SIZE && chunkSize <= MAX_CHUNK_SIZE, + "Unsupported chunk size %s", chunkSize); this.chunkSize = chunkSize; } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregator.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregator.java index 08eba8e0f2..144b4f5b4c 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregator.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregator.java @@ -18,12 +18,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NetconfChunkAggregator extends ByteToMessageDecoder { - private final static Logger LOG = LoggerFactory.getLogger(NetconfChunkAggregator.class); + private static final Logger LOG = LoggerFactory.getLogger(NetconfChunkAggregator.class); private static final String GOT_PARAM_WHILE_WAITING_FOR_PARAM = "Got byte {} while waiting for {}"; private static final String GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM = "Got byte {} while waiting for {}-{}"; public static final int DEFAULT_MAXIMUM_CHUNK_SIZE = 16 * 1024 * 1024; - private static enum State { + private enum State { HEADER_ONE, // \n HEADER_TWO, // # HEADER_LENGTH_FIRST, // [1-9] @@ -40,16 +40,16 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder { private long chunkSize; private CompositeByteBuf chunk; - private static void checkNewLine(final byte b,final String errorMessage) { - if (b != '\n') { - LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, b, (byte)'\n'); + private static void checkNewLine(final byte byteToCheck, final String errorMessage) { + if (byteToCheck != '\n') { + LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, byteToCheck, (byte)'\n'); throw new IllegalStateException(errorMessage); } } - private static void checkHash(final byte b,final String errorMessage) { - if (b != '#') { - LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, b, (byte)'#'); + private static void checkHash(final byte byteToCheck, final String errorMessage) { + if (byteToCheck != '#') { + LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, byteToCheck, (byte)'#'); throw new IllegalStateException(errorMessage); } } @@ -62,118 +62,115 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder { } @Override - protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List out) throws IllegalStateException { + protected void decode(final ChannelHandlerContext ctx, + final ByteBuf in, final List out) throws IllegalStateException { while (in.isReadable()) { switch (state) { - case HEADER_ONE: - { - final byte b = in.readByte(); - checkNewLine(b, "Malformed chunk header encountered (byte 0)"); - - state = State.HEADER_TWO; - - initChunk(); - break; - } - case HEADER_TWO: - { - final byte b = in.readByte(); - checkHash(b, "Malformed chunk header encountered (byte 1)"); - - state = State.HEADER_LENGTH_FIRST; - break; - } - case HEADER_LENGTH_FIRST: - { - final byte b = in.readByte(); - chunkSize = processHeaderLengthFirst(b); - state = State.HEADER_LENGTH_OTHER; - break; - } - case HEADER_LENGTH_OTHER: - { - final byte b = in.readByte(); - if (b == '\n') { - state = State.DATA; + case HEADER_ONE: + { + final byte b = in.readByte(); + checkNewLine(b, "Malformed chunk header encountered (byte 0)"); + state = State.HEADER_TWO; + initChunk(); break; } - - if (b < '0' || b > '9') { - LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'0', (byte)'9'); - throw new IllegalStateException("Invalid chunk size encountered"); + case HEADER_TWO: + { + final byte b = in.readByte(); + checkHash(b, "Malformed chunk header encountered (byte 1)"); + state = State.HEADER_LENGTH_FIRST; + break; } - - chunkSize *= 10; - chunkSize += b - '0'; - checkChunkSize(); - break; - } - case DATA: - /* - * FIXME: this gathers all data into one big chunk before passing - * it on. Make sure the pipeline can work with partial data - * and then change this piece to pass the data on as it - * comes through. - */ - if (in.readableBytes() < chunkSize) { - LOG.debug("Buffer has {} bytes, need {} to complete chunk", in.readableBytes(), chunkSize); - in.discardReadBytes(); - return; + case HEADER_LENGTH_FIRST: + { + final byte b = in.readByte(); + chunkSize = processHeaderLengthFirst(b); + state = State.HEADER_LENGTH_OTHER; + break; + } + case HEADER_LENGTH_OTHER: + { + final byte b = in.readByte(); + if (b == '\n') { + state = State.DATA; + break; + } + if (b < '0' || b > '9') { + LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'0', (byte)'9'); + throw new IllegalStateException("Invalid chunk size encountered"); + } + chunkSize *= 10; + chunkSize += b - '0'; + checkChunkSize(); + break; + } + case DATA: + /* + * FIXME: this gathers all data into one big chunk before passing + * it on. Make sure the pipeline can work with partial data + * and then change this piece to pass the data on as it + * comes through. + */ + if (in.readableBytes() < chunkSize) { + LOG.debug("Buffer has {} bytes, need {} to complete chunk", in.readableBytes(), chunkSize); + in.discardReadBytes(); + return; + } + aggregateChunks(in.readBytes((int) chunkSize)); + state = State.FOOTER_ONE; + break; + case FOOTER_ONE: + { + final byte b = in.readByte(); + checkNewLine(b,"Malformed chunk footer encountered (byte 0)"); + state = State.FOOTER_TWO; + chunkSize = 0; + break; + } + case FOOTER_TWO: + { + final byte b = in.readByte(); + checkHash(b,"Malformed chunk footer encountered (byte 1)"); + state = State.FOOTER_THREE; + break; + } + case FOOTER_THREE: + { + final byte b = in.readByte(); + // In this state, either header-of-new-chunk or message-end is expected + // Depends on the next character + extractNewChunkOrMessageEnd(b); + break; + } + case FOOTER_FOUR: + { + final byte b = in.readByte(); + checkNewLine(b,"Malformed chunk footer encountered (byte 3)"); + state = State.HEADER_ONE; + out.add(chunk); + chunk = null; + break; + } + default : + { + LOG.info("Unknown state."); } - aggregateChunks(in.readBytes((int) chunkSize)); - state = State.FOOTER_ONE; - break; - case FOOTER_ONE: - { - final byte b = in.readByte(); - checkNewLine(b,"Malformed chunk footer encountered (byte 0)"); - state = State.FOOTER_TWO; - chunkSize = 0; - break; - } - case FOOTER_TWO: - { - final byte b = in.readByte(); - checkHash(b,"Malformed chunk footer encountered (byte 1)"); - state = State.FOOTER_THREE; - break; - } - case FOOTER_THREE: - { - final byte b = in.readByte(); - - // In this state, either header-of-new-chunk or message-end is expected - // Depends on the next character - - extractNewChunkOrMessageEnd(b); - - break; - } - case FOOTER_FOUR: - { - final byte b = in.readByte(); - checkNewLine(b,"Malformed chunk footer encountered (byte 3)"); - state = State.HEADER_ONE; - out.add(chunk); - chunk = null; - break; - } } } in.discardReadBytes(); } - private void extractNewChunkOrMessageEnd(final byte b) { - if (isHeaderLengthFirst(b)) { + private void extractNewChunkOrMessageEnd(final byte byteToCheck) { + if (isHeaderLengthFirst(byteToCheck)) { // Extract header length#1 from new chunk - chunkSize = processHeaderLengthFirst(b); + chunkSize = processHeaderLengthFirst(byteToCheck); // Proceed with next chunk processing state = State.HEADER_LENGTH_OTHER; - } else if (b == '#') { + } else if (byteToCheck == '#') { state = State.FOOTER_FOUR; } else { - LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte) '#', (byte) '1', (byte) '9'); + LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, byteToCheck, (byte) '#', (byte) '1', (byte) '9'); throw new IllegalStateException("Malformed chunk footer encountered (byte 2)"); } } @@ -189,16 +186,16 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder { chunk.writerIndex(chunk.writerIndex() + newChunk.readableBytes()); } - private static int processHeaderLengthFirst(final byte b) { - if (!isHeaderLengthFirst(b)) { - LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'1', (byte)'9'); + private static int processHeaderLengthFirst(final byte byteToCheck) { + if (!isHeaderLengthFirst(byteToCheck)) { + LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, byteToCheck, (byte)'1', (byte)'9'); throw new IllegalStateException("Invalid chunk size encountered (byte 0)"); } - return b - '0'; + return byteToCheck - '0'; } - private static boolean isHeaderLengthFirst(final byte b) { - return b >= '1' && b <= '9'; + private static boolean isHeaderLengthFirst(final byte byteToCheck) { + return byteToCheck >= '1' && byteToCheck <= '9'; } } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXICodec.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXICodec.java index 1186a5c4d0..235b5378c2 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXICodec.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXICodec.java @@ -45,12 +45,13 @@ public final class NetconfEXICodec { * Since we have a limited number of options we can have, instantiating a weak cache * will allow us to reuse instances where possible. */ - private static final LoadingCache GRAMMAR_CACHES = CacheBuilder.newBuilder().weakValues().build(new CacheLoader() { - @Override - public GrammarCache load(final Short key) { - return new GrammarCache(key); - } - }); + private static final LoadingCache GRAMMAR_CACHES = + CacheBuilder.newBuilder().weakValues().build(new CacheLoader() { + @Override + public GrammarCache load(final Short key) { + return new GrammarCache(key); + } + }); /** * Grammar cache acts as a template and is duplicated by the Transmogrifier and the Reader diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIToMessageDecoder.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIToMessageDecoder.java index 6d2508757a..99d791642a 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIToMessageDecoder.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIToMessageDecoder.java @@ -37,10 +37,12 @@ public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder { private static final Logger LOG = LoggerFactory.getLogger(NetconfEXIToMessageDecoder.class); private static final SAXTransformerFactory FACTORY; + static { final TransformerFactory f = SAXTransformerFactory.newInstance(); if (!f.getFeature(SAXTransformerFactory.FEATURE)) { - throw new TransformerFactoryConfigurationError(String.format("Factory %s is not a SAXTransformerFactory", f)); + throw new TransformerFactoryConfigurationError( + String.format("Factory %s is not a SAXTransformerFactory", f)); } FACTORY = (SAXTransformerFactory)f; @@ -64,7 +66,8 @@ public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder { } @Override - protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List out) throws EXIOptionsException, IOException, SAXException, TransformerConfigurationException { + protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List out) + throws EXIOptionsException, IOException, SAXException, TransformerConfigurationException { /* * Note that we could loop here and process all the messages, but we can't do that. * The reason is operation, which has the contract of immediately stopping @@ -88,7 +91,7 @@ public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder { final DOMResult domResult = new DOMResult(documentBuilder.newDocument()); handler.setResult(domResult); - try (final InputStream is = new ByteBufInputStream(in)) { + try (InputStream is = new ByteBufInputStream(in)) { // Performs internal reset before doing anything reader.parse(new InputSource(is)); } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java index 0d50a2f74b..fac1b2ba4d 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java @@ -25,25 +25,28 @@ import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader * {@link NetconfHelloMessage} * . Used by netconf clients to send information about the user, ip address, * protocol etc. + * *

* Hello message with header example: + * *

* *

  * {@code
  * [tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]
- * 
- * 
- * urn:ietf:params:netconf:base:1.0
- * 
- * 
+ * < hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+ * < capabilities>
+ * < capability>urn:ietf:params:netconf:base:1.0< /capability>
+ * < /capabilities>
+ * < /hello>
  * }
  * 
*/ public final class NetconfHelloMessageToXMLEncoder extends NetconfMessageToXMLEncoder { @Override @VisibleForTesting - public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException { + public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) + throws IOException, TransformerException { Preconditions.checkState(msg instanceof NetconfHelloMessage, "Netconf message of type %s expected, was %s", NetconfHelloMessage.class, msg.getClass()); Optional headerOptional = ((NetconfHelloMessage) msg) diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfMessageToEXIEncoder.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfMessageToEXIEncoder.java index a9500ece28..e874ab3a40 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfMessageToEXIEncoder.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfMessageToEXIEncoder.java @@ -39,15 +39,17 @@ public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder out) throws IOException, SAXException, NetconfDocumentedException { + public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List out) + throws IOException, SAXException, NetconfDocumentedException { if (in.readableBytes() == 0) { LOG.debug("No more content in incoming buffer."); return; @@ -109,9 +108,10 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder } } - private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc) throws NetconfDocumentedException { + private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc) + throws NetconfDocumentedException { NetconfMessage msg = new NetconfMessage(doc); - if(NetconfHelloMessage.isHelloMessage(msg)) { + if (NetconfHelloMessage.isHelloMessage(msg)) { if (additionalHeader != null) { return new NetconfHelloMessage(doc, NetconfHelloMessageAdditionalHeader.fromString(additionalHeader)); } else { @@ -145,15 +145,15 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder return -1; } } - int j = 0; + int index = 0; for (int i = 0; i < bytes.length; i++) { - if (bytes[i] == sequence[j]) { - j++; - if (j == sequence.length) { - return i - j + 1; + if (bytes[i] == sequence[index]) { + index++; + if (index == sequence.length) { + return i - index + 1; } } else { - j = 0; + index = 0; } } return -1; @@ -161,20 +161,20 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder private static void logMessage(final byte[] bytes) { if (LOG.isDebugEnabled()) { - String s = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString(); - LOG.debug("Parsing message \n{}", s); + String string = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString(); + LOG.debug("Parsing message \n{}", string); } } private static boolean startsWithAdditionalHeader(final byte[] bytes) { for (byte[] possibleStart : POSSIBLE_STARTS) { - int i = 0; + int index = 0; for (byte b : possibleStart) { - if(bytes[i++] != b) { + if (bytes[index++] != b) { break; } - if(i == possibleStart.length) { + if (index == possibleStart.length) { return true; } } @@ -188,7 +188,9 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder } /** - * @return Collection of NetconfMessages that were not hello, but were received during negotiation + * Get netconf messages received during negotiation. + * + * @return Collection of NetconfMessages that were not hello, but were received during negotiation. */ public Iterable getPostHelloNetconfMessages() { return nonHelloMessages; diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java index fcb92f0e14..68dba39d63 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java @@ -25,7 +25,8 @@ public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder { private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class); @Override - public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List out) throws IOException, SAXException { + public void decode(final ChannelHandlerContext ctx, final ByteBuf in, + final List out) throws IOException, SAXException { if (in.isReadable()) { if (LOG.isTraceEnabled()) { LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in)); @@ -77,10 +78,10 @@ public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder { * Check whether a byte is whitespace/control character. Considered whitespace characters:
* SPACE, \t, \n, \v, \r, \f * - * @param b byte to check + * @param byteToCheck byte to check * @return true if the byte is a whitespace/control character */ - private static boolean isWhitespace(final byte b) { - return b <= 0x0d && b >= 0x09 || b == 0x20; + private static boolean isWhitespace(final byte byteToCheck) { + return byteToCheck <= 0x0d && byteToCheck >= 0x09 || byteToCheck == 0x20; } } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParameters.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParameters.java index 8ba2873148..f63a1e0ae1 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParameters.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParameters.java @@ -38,7 +38,7 @@ public final class EXIParameters { this.options = Preconditions.checkNotNull(options); } - + @SuppressWarnings("checkstyle:FallThrough") public static EXIParameters fromXmlElement(final XmlElement root) throws EXIOptionsException { final EXIOptions options = new EXIOptions(); final NodeList alignmentElements = root.getElementsByTagName(EXI_PARAMETER_ALIGNMENT); @@ -47,20 +47,21 @@ public final class EXIParameters { final String alignmentTextContent = alignmentElement.getTextContent().trim(); switch (alignmentTextContent) { - case EXI_PARAMETER_BYTE_ALIGNED: - options.setAlignmentType(AlignmentType.byteAligned); - break; - case EXI_PARAMETER_COMPRESSED: - options.setAlignmentType(AlignmentType.compress); - break; - case EXI_PARAMETER_PRE_COMPRESSION: - options.setAlignmentType(AlignmentType.preCompress); - break; - default: - LOG.warn("Unexpected value in alignmentTextContent: {} , using default value", alignmentTextContent); - case EXI_PARAMETER_BIT_PACKED: - options.setAlignmentType(AlignmentType.bitPacked); - break; + case EXI_PARAMETER_BYTE_ALIGNED: + options.setAlignmentType(AlignmentType.byteAligned); + break; + case EXI_PARAMETER_COMPRESSED: + options.setAlignmentType(AlignmentType.compress); + break; + case EXI_PARAMETER_PRE_COMPRESSION: + options.setAlignmentType(AlignmentType.preCompress); + break; + default: + LOG.warn("Unexpected value in alignmentTextContent: {} , using default value", + alignmentTextContent); + case EXI_PARAMETER_BIT_PACKED: + options.setAlignmentType(AlignmentType.bitPacked); + break; } } else { options.setAlignmentType(AlignmentType.bitPacked); diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessage.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessage.java index f3711ae388..3f81a5175e 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessage.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessage.java @@ -33,6 +33,7 @@ public final class NetconfStartExiMessage extends NetconfMessage { public static final String PIS_KEY = "pis"; public static final String PREFIXES_KEY = "prefixes"; private static final Logger LOG = LoggerFactory.getLogger(NetconfStartExiMessage.class); + private NetconfStartExiMessage(final Document doc) { super(doc); } @@ -75,37 +76,40 @@ public final class NetconfStartExiMessage extends NetconfMessage { } } + @SuppressWarnings("checkstyle:FallThrough") private static void addAlignment(final EXIOptions exiOptions, final Document doc, final Element startExiElement) { final Element alignmentElement = doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0, ALIGNMENT_KEY); String alignmentString; switch (exiOptions.getAlignmentType()) { - case byteAligned: { - alignmentString = EXIParameters.EXI_PARAMETER_BYTE_ALIGNED; - break; - } - case compress: { - alignmentString = EXIParameters.EXI_PARAMETER_COMPRESSED; - break; - } - case preCompress: { - alignmentString = EXIParameters.EXI_PARAMETER_PRE_COMPRESSION; - break; - } - default: - LOG.warn("Unexpected value in EXI alignment type: {} , using default value", exiOptions.getAlignmentType()); - case bitPacked: { - alignmentString = EXIParameters.EXI_PARAMETER_BIT_PACKED; - break; - } + case byteAligned: { + alignmentString = EXIParameters.EXI_PARAMETER_BYTE_ALIGNED; + break; + } + case compress: { + alignmentString = EXIParameters.EXI_PARAMETER_COMPRESSED; + break; + } + case preCompress: { + alignmentString = EXIParameters.EXI_PARAMETER_PRE_COMPRESSION; + break; + } + default: + LOG.warn("Unexpected value in EXI alignment type: {} , using default value", + exiOptions.getAlignmentType()); + case bitPacked: { + alignmentString = EXIParameters.EXI_PARAMETER_BIT_PACKED; + break; + } } alignmentElement.setTextContent(alignmentString); startExiElement.appendChild(alignmentElement); } - private static void createFidelityElement(final Document doc, final List fidelityElements, final boolean fidelity, final String fidelityName) { + private static void createFidelityElement(final Document doc, final List fidelityElements, + final boolean fidelity, final String fidelityName) { if (fidelity) { fidelityElements.add(doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0, diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java index c6c417f7d0..aed43347d8 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java @@ -18,5 +18,6 @@ public abstract class AuthenticationHandler { public abstract String getUsername(); - public abstract org.apache.sshd.client.future.AuthFuture authenticate(final ClientSession session) throws IOException; + public abstract org.apache.sshd.client.future.AuthFuture authenticate(ClientSession session) + throws IOException; } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java index 6219f91b2d..46cb2c717b 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java @@ -14,7 +14,7 @@ import org.apache.sshd.client.future.AuthFuture; /** * Class Providing username/password authentication option to - * {@link org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler} + * {@link org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler}. */ public class LoginPassword extends AuthenticationHandler { private final String username; diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java index cb642c1a99..8f6e2baa63 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java @@ -44,6 +44,7 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { private static final long DEFAULT_TIMEOUT = -1L; public static final SshClient DEFAULT_CLIENT; + static { final Map props = new HashMap<>(); props.put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT)); @@ -77,29 +78,31 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { } /** + * Constructor of {@code AsyncSshHandler}. * - * @param authenticationHandler - * @param sshClient started SshClient - * @throws IOException + * @param authenticationHandler authentication handler + * @param sshClient started SshClient + * @throws IOException if the I/O operation fails */ - public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException { + public AsyncSshHandler(final AuthenticationHandler authenticationHandler, + final SshClient sshClient) throws IOException { this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler); this.sshClient = Preconditions.checkNotNull(sshClient); } - public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException { + public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) + throws IOException { return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT); } /** + * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful + * netconf negotiation. * - * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful netconf - * negotiation. - * - * @param authenticationHandler - * @param negotiationFuture - * @return - * @throws IOException + * @param authenticationHandler authentication handler + * @param negotiationFuture negotiation future + * @return {@code AsyncSshHandler} + * @throws IOException if the I/O operation fails */ public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler, final Future negotiationFuture) throws IOException { @@ -135,9 +138,8 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { handleSshAuthenticated(session, ctx); } else { // Exception does not have to be set in the future, add simple exception in such case - final Throwable exception = future.getException() == null ? - new IllegalStateException("Authentication failed") : - future.getException(); + final Throwable exception = future.getException() == null + ? new IllegalStateException("Authentication failed") : future.getException(); handleSshSetupFailure(ctx, exception); } } @@ -149,14 +151,15 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) { try { - LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion()); + LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), + session.getServerVersion()); channel = session.createSubsystemChannel(SUBSYSTEM); channel.setStreaming(ClientChannel.Streaming.Async); channel.open().addListener(new SshFutureListener() { @Override public void operationComplete(final OpenFuture future) { - if(future.isOpened()) { + if (future.isOpened()) { handleSshChanelOpened(ctx); } else { handleSshSetupFailure(ctx, future.getException()); @@ -173,7 +176,7 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) { LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel()); - if(negotiationFuture == null) { + if (negotiationFuture == null) { connectPromise.setSuccess(); } @@ -191,19 +194,20 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { } }, channel.toString(), channel.getAsyncOut()); - // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null - if(channel != null) { + // if readAsyncListener receives immediate close, + // it will close this handler and closing this handler sets channel variable to null + if (channel != null) { sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn()); ctx.fireChannelActive(); } } - private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) { - LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e); + private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) { + LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error); // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure - if(!connectPromise.isDone()) { - connectPromise.setFailure(e); + if (!connectPromise.isDone()) { + connectPromise.setFailure(error); } disconnect(ctx, ctx.newPromise()); @@ -215,11 +219,12 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { } @Override - public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception { + public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, + final SocketAddress localAddress, final ChannelPromise promise) throws Exception { LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise); this.connectPromise = promise; - if(negotiationFuture != null) { + if (negotiationFuture != null) { negotiationFutureListener = new GenericFutureListener>() { @Override @@ -240,36 +245,39 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { disconnect(ctx, promise); } + @SuppressWarnings("checkstyle:IllegalCatch") @Override public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) { - LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise); + LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", + ctx.channel(),connectPromise); - // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic - if(connectPromise.isSuccess()) { + // If we have already succeeded and the session was dropped after, + // we need to fire inactive to notify reconnect logic + if (connectPromise.isSuccess()) { ctx.fireChannelInactive(); } - if(sshWriteAsyncHandler != null) { + if (sshWriteAsyncHandler != null) { sshWriteAsyncHandler.close(); } - if(sshReadAsyncListener != null) { + if (sshReadAsyncListener != null) { sshReadAsyncListener.close(); } //If connection promise is not already set, it means negotiation failed //we must set connection promise to failure - if(!connectPromise.isDone()) { + if (!connectPromise.isDone()) { connectPromise.setFailure(new IllegalStateException("Negotiation failed")); } //Remove listener from negotiation future, we don't want notifications //from negotiation anymore - if(negotiationFuture != null) { + if (negotiationFuture != null) { negotiationFuture.removeListener(negotiationFutureListener); } - if(session!= null && !session.isClosed() && !session.isClosing()) { + if (session != null && !session.isClosed() && !session.isClosing()) { session.close(false).addListener(new SshFutureListener() { @Override public void operationComplete(final CloseFuture future) { @@ -281,9 +289,11 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { }); } - // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources - // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430) - // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation + // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs + // to cleanup its resources e.g. Socket that it tries to open in its constructor + // (https://bugs.opendaylight.org/show_bug.cgi?id=2430) + // TODO better solution would be to implement custom ChannelFactory + Channel + // that will use mina SSH lib internally: port this to custom channel implementation try { // Disconnect has to be closed after inactive channel event was fired, because it interferes with it super.disconnect(ctx, ctx.newPromise()); diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java index b54eb46169..c79b71308a 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java @@ -35,7 +35,8 @@ public final class AsyncSshHandlerReader implements SshFutureListener 0) { final ByteBuf msg = Unpooled.wrappedBuffer(buf.array(), 0, future.getRead()); - if(LOG.isTraceEnabled()) { - LOG.trace("Reading message on channel: {}, message: {}", channelId, AsyncSshHandlerWriter.byteBufToString(msg)); + if (LOG.isTraceEnabled()) { + LOG.trace("Reading message on channel: {}, message: {}", + channelId, AsyncSshHandlerWriter.byteBufToString(msg)); } readHandler.onMessageRead(msg); @@ -77,6 +79,7 @@ public final class AsyncSshHandlerReader implements SshFutureListeneremptySet(), Optional.absent()); + clientHello = NetconfHelloMessage.createClientHello(Collections.emptySet(), + Optional.absent()); } @Test @@ -122,14 +124,17 @@ public class AbstractNetconfSessionTest { doReturn("handler").when(mock).toString(); testingNetconfSession.replaceMessageDecoder(mock); - verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, mock); + verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, + AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, mock); testingNetconfSession.replaceMessageEncoder(mock); - verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock); + verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, + AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock); testingNetconfSession.replaceMessageEncoderAfterNextMessage(mock); verifyNoMoreInteractions(pipeline); testingNetconfSession.sendMessage(clientHello); - verify(pipeline, times(2)).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock); + verify(pipeline, times(2)).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, + AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock); } @Test @@ -154,7 +159,8 @@ public class AbstractNetconfSessionTest { @Test public void testSendMessage() throws Exception { final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L); - final NetconfHelloMessage clientHello = NetconfHelloMessage.createClientHello(Collections.emptySet(), Optional.absent()); + final NetconfHelloMessage clientHello = NetconfHelloMessage.createClientHello(Collections.emptySet(), + Optional.absent()); testingNetconfSession.sendMessage(clientHello); verify(channel).writeAndFlush(clientHello); } diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/TestingNetconfSession.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/TestingNetconfSession.java index b7a1c6c741..cb8733ee05 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/TestingNetconfSession.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/TestingNetconfSession.java @@ -14,9 +14,11 @@ import io.netty.handler.codec.MessageToByteEncoder; import org.opendaylight.netconf.api.NetconfMessage; import org.opendaylight.netconf.api.NetconfSessionListener; -class TestingNetconfSession extends AbstractNetconfSession> { +class TestingNetconfSession + extends AbstractNetconfSession> { - TestingNetconfSession(final NetconfSessionListener sessionListener, final Channel channel, final long sessionId) { + TestingNetconfSession(final NetconfSessionListener sessionListener, + final Channel channel, final long sessionId) { super(sessionListener, channel, sessionId); } @@ -26,7 +28,8 @@ class TestingNetconfSession extends AbstractNetconfSession encoder) { + protected void addExiHandlers(final ByteToMessageDecoder decoder, + final MessageToByteEncoder encoder) { } @Override diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java index c8837dfd95..bb95ff1b02 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java @@ -55,10 +55,10 @@ public class ChunkedFramingMechanismEncoderTest { byte[] buf = new byte[destination.readableBytes()]; destination.readBytes(buf); - String s = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(buf)).toString(); + String string = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(buf)).toString(); - assertTrue(s.startsWith("\n#256\na")); - assertTrue(s.endsWith("\n#20\naaaaaaaaaaaaaaaaaaaa\n##\n")); + assertTrue(string.startsWith("\n#256\na")); + assertTrue(string.endsWith("\n#20\naaaaaaaaaaaaaaaaaaaa\n##\n")); } private static byte[] getByteArray(final int size) { diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java index 321b34ccf7..a9a67f19c4 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java @@ -19,20 +19,20 @@ import org.junit.Test; public class NetconfChunkAggregatorTest { - private static final String CHUNKED_MESSAGE = "\n#4\n" + - "\n" + - " \n" + - "" + - "\n##\n"; - - public static final String EXPECTED_MESSAGE = "\n" + - " \n" + - ""; + private static final String CHUNKED_MESSAGE = "\n#4\n" + + "\n" + + " \n" + + "" + + "\n##\n"; + + public static final String EXPECTED_MESSAGE = "\n" + + " \n" + + ""; private static final String CHUNKED_MESSAGE_ONE = "\n#101\n" + EXPECTED_MESSAGE + "\n##\n"; diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIHandlersTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIHandlersTest.java index f80b4dacf1..b1b6e6d56a 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIHandlersTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIHandlersTest.java @@ -48,7 +48,8 @@ public class NetconfEXIHandlersTest { this.msgAsExi = msgToExi(msgAsString, codec); } - private static byte[] msgToExi(final String msgAsString, final NetconfEXICodec codec) throws EXIOptionsException, TransmogrifierException, IOException { + private static byte[] msgToExi(final String msgAsString,final NetconfEXICodec codec) + throws EXIOptionsException, TransmogrifierException, IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final Transmogrifier transmogrifier = codec.getTransmogrifier(); transmogrifier.setOutputStream(byteArrayOutputStream); diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java index 7eaceff669..794ce8dad2 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java @@ -36,7 +36,8 @@ public class NetconfHelloMessageToXMLEncoderTest { @Test public void testEncode() throws Exception { - final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument(""), + final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument( + ""), NetconfHelloMessageAdditionalHeader.fromString("[tomas;10.0.0.0:10000;tcp;client;]")); final ByteBuf destination = Unpooled.buffer(); new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, destination); @@ -48,7 +49,8 @@ public class NetconfHelloMessageToXMLEncoderTest { @Test public void testEncodeNoHeader() throws Exception { - final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument("")); + final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument( + "")); final ByteBuf destination = Unpooled.buffer(); new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, destination); @@ -59,7 +61,8 @@ public class NetconfHelloMessageToXMLEncoderTest { @Test(expected = IllegalStateException.class) public void testEncodeNotHello() throws Exception { - final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("")); + final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument( + "")); new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, null); } } \ No newline at end of file diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java index 9ee511ace0..fc20f9585d 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java @@ -28,7 +28,8 @@ public class NetconfXMLToHelloMessageDecoderTest { @Test public void testDecodeWithHeader() throws Exception { final ByteBuf src = Unpooled.wrappedBuffer(String.format("%s\n%s", - "[tomas;10.0.0.0:10000;tcp;client;]", "").getBytes()); + "[tomas;10.0.0.0:10000;tcp;client;]", + "").getBytes()); final List out = Lists.newArrayList(); new NetconfXMLToHelloMessageDecoder().decode(null, src, out); @@ -36,13 +37,16 @@ public class NetconfXMLToHelloMessageDecoderTest { assertThat(out.get(0), CoreMatchers.instanceOf(NetconfHelloMessage.class)); final NetconfHelloMessage hello = (NetconfHelloMessage) out.get(0); assertTrue(hello.getAdditionalHeader().isPresent()); - assertEquals("[tomas;10.0.0.0:10000;tcp;client;]" + System.lineSeparator(), hello.getAdditionalHeader().get().toFormattedString()); - assertThat(XmlUtil.toString(hello.getDocument()), CoreMatchers.containsString("".getBytes()); + final ByteBuf src = + Unpooled.wrappedBuffer("".getBytes()); final List out = Lists.newArrayList(); new NetconfXMLToHelloMessageDecoder().decode(null, src, out); @@ -54,9 +58,12 @@ public class NetconfXMLToHelloMessageDecoderTest { @Test public void testDecodeCaching() throws Exception { - final ByteBuf msg1 = Unpooled.wrappedBuffer("".getBytes()); - final ByteBuf msg2 = Unpooled.wrappedBuffer("".getBytes()); - final ByteBuf src = Unpooled.wrappedBuffer("".getBytes()); + final ByteBuf msg1 = + Unpooled.wrappedBuffer("".getBytes()); + final ByteBuf msg2 = + Unpooled.wrappedBuffer("".getBytes()); + final ByteBuf src = + Unpooled.wrappedBuffer("".getBytes()); final List out = Lists.newArrayList(); final NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder(); decoder.decode(null, src, out); @@ -70,7 +77,8 @@ public class NetconfXMLToHelloMessageDecoderTest { @Test(expected = IllegalStateException.class) public void testDecodeNotHelloReceived() throws Exception { - final ByteBuf msg1 = Unpooled.wrappedBuffer("".getBytes()); + final ByteBuf msg1 = + Unpooled.wrappedBuffer("".getBytes()); final List out = Lists.newArrayList(); NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder(); decoder.decode(null, msg1, out); diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java index 37b7b2a9cd..ea5bd62df6 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java @@ -39,7 +39,8 @@ public class NetconfXMLToMessageDecoderTest { * A leading LF is the case reported in BUG-2838. */ final ArrayList out = Lists.newArrayList(); - new NetconfXMLToMessageDecoder().decode(null, Unpooled.wrappedBuffer("\n".getBytes()), out); + new NetconfXMLToMessageDecoder().decode(null, + Unpooled.wrappedBuffer("\n".getBytes()), out); assertEquals(1, out.size()); } @@ -51,11 +52,12 @@ public class NetconfXMLToMessageDecoderTest { * (eg CSR1000V running IOS 15.4(1)S) */ final ArrayList out = Lists.newArrayList(); - new NetconfXMLToMessageDecoder().decode(null, Unpooled.wrappedBuffer("\r\n".getBytes()), out); + new NetconfXMLToMessageDecoder().decode(null, + Unpooled.wrappedBuffer("\r\n".getBytes()), out); assertEquals(1, out.size()); } - @Test(expected=SAXParseException.class) + @Test(expected = SAXParseException.class) public void testDecodeGibberish() throws Exception { /* Test that we reject inputs where we cannot find the xml start '<' character */ final ArrayList out = Lists.newArrayList(); @@ -78,7 +80,7 @@ public class NetconfXMLToMessageDecoderTest { */ final ArrayList out = Lists.newArrayList(); - byte whitespaces[] = {' ', '\t', '\n', '\r', '\f', 0x0b /* vertical tab */}; + byte[] whitespaces = {' ', '\t', '\n', '\r', '\f', 0x0b /* vertical tab */}; new NetconfXMLToMessageDecoder().decode( null, Unpooled.copiedBuffer( diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParametersTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParametersTest.java index 9879d61e6c..f14e0995b0 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParametersTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParametersTest.java @@ -25,22 +25,22 @@ public class EXIParametersTest { @Parameterized.Parameters public static Iterable data() throws Exception { final String noChangeXml = - "\n" + - "bit-packed\n" + - "\n"; + "\n" + + "bit-packed\n" + + "\n"; final String fullOptionsXml = - "\n" + - "byte-aligned\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n"; + "\n" + + "byte-aligned\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n"; final EXIOptions fullOptions = new EXIOptions(); fullOptions.setAlignmentType(AlignmentType.byteAligned); diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessageTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessageTest.java index 24e93d9738..d7ccba6f3b 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessageTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessageTest.java @@ -24,25 +24,27 @@ public class NetconfStartExiMessageTest { @Parameterized.Parameters public static Iterable data() throws Exception { - final String noChangeXml = "\n" + - "\n" + - "bit-packed\n" + - "\n" + - ""; + final String noChangeXml = "\n" + + "\n" + + "bit-packed\n" + + "\n" + + ""; - final String fullOptionsXml = "\n" + - "\n" + - "byte-aligned\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - ""; + final String fullOptionsXml = "\n" + + "\n" + + "byte-aligned\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + ""; final EXIOptions fullOptions = new EXIOptions(); fullOptions.setAlignmentType(AlignmentType.byteAligned); diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java index 4f11465dd2..f1806b43ce 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java @@ -221,7 +221,8 @@ public class AsyncSshHandlerTest { @Override public void onSuccess(final SshFutureListener result) { doReturn(new IllegalStateException()).when(mockedReadFuture).getException(); - doReturn(mockedReadFuture).when(mockedReadFuture).removeListener(Matchers.>any()); + doReturn(mockedReadFuture).when(mockedReadFuture) + .removeListener(Matchers.>any()); doReturn(true).when(asyncOut).isClosing(); doReturn(true).when(asyncOut).isClosed(); result.operationComplete(mockedReadFuture); @@ -251,7 +252,8 @@ public class AsyncSshHandlerTest { @Override public void onSuccess(final SshFutureListener result) { doReturn(new IllegalStateException()).when(mockedReadFuture).getException(); - doReturn(mockedReadFuture).when(mockedReadFuture).removeListener(Matchers.>any()); + doReturn(mockedReadFuture).when(mockedReadFuture) + .removeListener(Matchers.>any()); result.operationComplete(mockedReadFuture); } }); @@ -340,11 +342,14 @@ public class AsyncSshHandlerTest { final ChannelPromise firstWritePromise = getMockedPromise(); - // intercept listener for first write, so we can invoke successful write later thus simulate pending of the first write - final ListenableFuture> firstWriteListenerFuture = stubAddListener(ioWriteFuture); + // intercept listener for first write, + // so we can invoke successful write later thus simulate pending of the first write + final ListenableFuture> firstWriteListenerFuture = + stubAddListener(ioWriteFuture); asyncSshHandler.write(ctx, Unpooled.copiedBuffer(new byte[]{0,1,2,3,4,5}), firstWritePromise); final SshFutureListener firstWriteListener = firstWriteListenerFuture.get(); - // intercept second listener, this is the listener for pending write for the pending write to know when pending state ended + // intercept second listener, + // this is the listener for pending write for the pending write to know when pending state ended final ListenableFuture> pendingListener = stubAddListener(ioWriteFuture); final ChannelPromise secondWritePromise = getMockedPromise(); @@ -386,8 +391,10 @@ public class AsyncSshHandlerTest { final ChannelPromise firstWritePromise = getMockedPromise(); - // intercept listener for first write, so we can invoke successful write later thus simulate pending of the first write - final ListenableFuture> firstWriteListenerFuture = stubAddListener(ioWriteFuture); + // intercept listener for first write, + // so we can invoke successful write later thus simulate pending of the first write + final ListenableFuture> firstWriteListenerFuture = + stubAddListener(ioWriteFuture); asyncSshHandler.write(ctx, Unpooled.copiedBuffer(new byte[]{0,1,2,3,4,5}), firstWritePromise); final ChannelPromise secondWritePromise = getMockedPromise(); @@ -464,7 +471,8 @@ public class AsyncSshHandlerTest { return sshSession; } - private ChannelSubsystem getMockedSubsystemChannel(final IoInputStream asyncOut, final IoOutputStream asyncIn) throws IOException { + private ChannelSubsystem getMockedSubsystemChannel(final IoInputStream asyncOut, + final IoOutputStream asyncIn) throws IOException { final ChannelSubsystem subsystemChannel = mock(ChannelSubsystem.class); doReturn("subsystemChannel").when(subsystemChannel).toString(); @@ -597,14 +605,15 @@ public class AsyncSshHandlerTest { return spy(new DefaultChannelPromise(channel)); } - private static abstract class SuccessFutureListener> implements FutureCallback> { + private abstract static class SuccessFutureListener> + implements FutureCallback> { @Override - public abstract void onSuccess(final SshFutureListener result); + public abstract void onSuccess(SshFutureListener result); @Override - public void onFailure(final Throwable t) { - throw new RuntimeException(t); + public void onFailure(final Throwable throwable) { + throw new RuntimeException(throwable); } } } -- 2.36.6