From b925756421ea8565637d8575d8143dbf46db5a86 Mon Sep 17 00:00:00 2001 From: Maros Marsalek Date: Mon, 17 Feb 2014 15:03:57 +0100 Subject: [PATCH] Fix warnings in netconf-api and netconf-util Change-Id: Icd7f605796ddb38cc01ac08c4de7e3c62cc8da39 Signed-off-by: Maros Marsalek --- .../ConfigPersisterNotificationHandler.java | 4 +- .../netconf/api/AbstractNetconfSession.java | 4 +- .../api/NetconfSessionPreferences.java | 2 +- .../api/jmx/CommitJMXNotification.java | 4 +- .../api/jmx/DefaultCommitOperationMXBean.java | 4 +- .../DefaultCommitNotificationProducer.java | 2 +- .../impl/NetconfServerSessionNegotiator.java | 2 +- .../netconf/impl/MessageParserTest.java | 6 +- .../it/NetconfConfigPersisterITTest.java | 2 +- .../AbstractNetconfSessionNegotiator.java | 83 ++++++++++--------- .../controller/netconf/util/NetconfUtil.java | 4 +- .../ChunkedFramingMechanismEncoder.java | 2 +- .../FramingMechanismHandlerFactory.java | 4 +- .../NetconfXMLToHelloMessageDecoder.java | 6 +- .../netconf/util/handler/ssh/SshHandler.java | 20 +++-- .../ssh/authentication/LoginPassword.java | 3 +- .../util/handler/ssh/client/Invoker.java | 5 +- .../util/handler/ssh/client/SshClient.java | 10 ++- .../handler/ssh/client/SshClientAdapter.java | 31 +++---- .../util/handler/ssh/client/SshSession.java | 14 +++- .../ssh/virtualsocket/ChannelInputStream.java | 37 ++++----- .../virtualsocket/ChannelOutputStream.java | 31 +++---- .../ssh/virtualsocket/VirtualSocket.java | 30 ++++--- .../NetconfHelloMessageAdditionalHeader.java | 14 ++-- .../messages/NetconfMessageConstants.java | 10 ++- .../util/messages/NetconfMessageUtil.java | 4 +- .../util/messages/SendErrorExceptionUtil.java | 7 +- .../netconf/util/osgi/NetconfConfigUtil.java | 4 +- .../netconf/util/xml/XMLNetconfUtil.java | 4 +- .../netconf/util/xml/XmlElement.java | 30 +++---- .../netconf/util/xml/XmlNetconfConstants.java | 4 +- .../netconf/util/xml/XmlNetconfValidator.java | 11 ++- .../controller/netconf/util/xml/XmlUtil.java | 13 ++- 33 files changed, 222 insertions(+), 189 deletions(-) diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java index e319d2cb67..2d89bbc55c 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java @@ -49,7 +49,7 @@ public class ConfigPersisterNotificationHandler implements Closeable { private static void registerAsJMXListener(MBeanServerConnection mBeanServerConnection, ConfigPersisterNotificationListener listener) { logger.trace("Called registerAsJMXListener"); try { - mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.objectName, listener, null, null); + mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.OBJECT_NAME, listener, null, null); } catch (InstanceNotFoundException | IOException e) { throw new RuntimeException("Cannot register as JMX listener to netconf", e); } @@ -58,7 +58,7 @@ public class ConfigPersisterNotificationHandler implements Closeable { @Override public synchronized void close() { // unregister from JMX - ObjectName on = DefaultCommitOperationMXBean.objectName; + ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME; try { if (mBeanServerConnection.isRegistered(on)) { mBeanServerConnection.removeNotificationListener(on, listener); diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/AbstractNetconfSession.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/AbstractNetconfSession.java index bd75c27dd6..f85d9b9f30 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/AbstractNetconfSession.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/AbstractNetconfSession.java @@ -22,13 +22,13 @@ public abstract class AbstractNetconfSession capabilities; CommitJMXNotification(NotificationBroadcasterSupport source, String message, Element cfgSnapshot, Set capabilities) { - super(TransactionProviderJMXNotificationType.commit, source, String.format(afterCommitMessageTemplate, message)); + super(TransactionProviderJMXNotificationType.commit, source, String.format(AFTER_COMMIT_MESSAGE_TEMPLATE, message)); this.configSnapshot = cfgSnapshot; this.capabilities = capabilities; } diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java index a170d2905f..e45d3c38a2 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java @@ -14,7 +14,7 @@ import javax.management.ObjectName; public interface DefaultCommitOperationMXBean { - static String typeName = "NetconfNotificationProvider"; - public static ObjectName objectName = ObjectNameUtil.createONWithDomainAndType(typeName); + String TYPE_NAME = "NetconfNotificationProvider"; + ObjectName OBJECT_NAME = ObjectNameUtil.createONWithDomainAndType(TYPE_NAME); } diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/DefaultCommitNotificationProducer.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/DefaultCommitNotificationProducer.java index 693fc13783..4461054437 100644 --- a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/DefaultCommitNotificationProducer.java +++ b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/DefaultCommitNotificationProducer.java @@ -31,7 +31,7 @@ public class DefaultCommitNotificationProducer extends NotificationBroadcasterSu private final MBeanServer mbeanServer; - private final ObjectName on = DefaultCommitOperationMXBean.objectName; + private final ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME; public DefaultCommitNotificationProducer(MBeanServer mBeanServer) { this.mbeanServer = mBeanServer; diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiator.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiator.java index 1b4dfff42b..f8024922cf 100644 --- a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiator.java +++ b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiator.java @@ -49,7 +49,7 @@ public class NetconfServerSessionNegotiator extends logger.debug("Additional header from hello parsed as {} from {}", parsedHeader, additionalHeader); - return new NetconfServerSession(sessionListener, channel, sessionPreferences.getSessionId(), parsedHeader); + return new NetconfServerSession(sessionListener, channel, getSessionPreferences().getSessionId(), parsedHeader); } } diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/MessageParserTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/MessageParserTest.java index 8f9d89f1f1..d1c0b066d7 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/MessageParserTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/MessageParserTest.java @@ -69,10 +69,10 @@ public class MessageParserTest { int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE; if (i == chunkCount) { exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1)); - byte[] eom = new byte[NetconfMessageConstants.endOfChunk.length]; - recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.endOfChunk.length, + byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length]; + recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom); - assertArrayEquals(NetconfMessageConstants.endOfChunk, eom); + assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom); } byte[] header = new byte[String.valueOf(exptHeaderLength).length() diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java index ff2efed128..1035c9f9fe 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java @@ -161,7 +161,7 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest { private VerifyingNotificationListener createCommitNotificationListener() throws InstanceNotFoundException { VerifyingNotificationListener listener = new VerifyingNotificationListener(); - platformMBeanServer.addNotificationListener(DefaultCommitNotificationProducer.objectName, listener, null, null); + platformMBeanServer.addNotificationListener(DefaultCommitNotificationProducer.OBJECT_NAME, listener, null, null); return listener; } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/AbstractNetconfSessionNegotiator.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/AbstractNetconfSessionNegotiator.java index ea9fc5dce4..7f2d8c30f0 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/AbstractNetconfSessionNegotiator.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/AbstractNetconfSessionNegotiator.java @@ -21,6 +21,7 @@ import io.netty.util.concurrent.Promise; import java.util.concurrent.TimeUnit; +import io.netty.channel.ChannelInboundHandlerAdapter; import org.opendaylight.controller.netconf.api.AbstractNetconfSession; import org.opendaylight.controller.netconf.api.NetconfMessage; import org.opendaylight.controller.netconf.api.NetconfSessionListener; @@ -47,7 +48,7 @@ extends AbstractSessionNegotiator { private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class); public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler"; - protected final P sessionPreferences; + private final P sessionPreferences; private final L sessionListener; private Timeout timeout; @@ -79,14 +80,15 @@ extends AbstractSessionNegotiator { Future future = sslHandler.get().handshakeFuture(); future.addListener(new GenericFutureListener>() { @Override - public void operationComplete(Future future) throws Exception { + public void operationComplete(Future future) { Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful"); logger.debug("Ssl handshake complete"); start(); } }); - } else + } else { start(); + } } private static Optional getSslHandler(Channel channel) { @@ -94,31 +96,19 @@ extends AbstractSessionNegotiator { return sslHandler == null ? Optional. absent() : Optional.of(sslHandler); } + public P getSessionPreferences() { + return sessionPreferences; + } + private void start() { final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage(); logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument())); - channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() { - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - } - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause); - cancelTimeout(); - negotiationFailed(cause); - changeState(State.FAILED); - } - }); + channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler()); timeout = this.timer.newTimeout(new TimerTask() { @Override - public void run(final Timeout timeout) throws Exception { + public void run(final Timeout timeout) { synchronized (this) { if (state != State.ESTABLISHED) { logger.debug("Connection timeout after {}, session is in state {}", timeout, state); @@ -138,8 +128,9 @@ extends AbstractSessionNegotiator { } private void cancelTimeout() { - if(timeout!=null) + if(timeout!=null) { timeout.cancel(); + } } private void sendMessage(NetconfMessage message) { @@ -148,27 +139,20 @@ extends AbstractSessionNegotiator { @Override protected void handleMessage(NetconfHelloMessage netconfMessage) { - final Document doc = netconfMessage.getDocument(); + Preconditions.checkNotNull(netconfMessage != null, "netconfMessage"); - // Only Hello message should arrive during negotiation - if (netconfMessage instanceof NetconfHelloMessage) { + final Document doc = netconfMessage.getDocument(); - replaceHelloMessageHandlers(); + replaceHelloMessageHandlers(); - if (shouldUseChunkFraming(doc)) { - insertChunkFramingToPipeline(); - } + if (shouldUseChunkFraming(doc)) { + insertChunkFramingToPipeline(); + } - changeState(State.ESTABLISHED); - S session = getSession(sessionListener, channel, netconfMessage); + changeState(State.ESTABLISHED); + S session = getSession(sessionListener, channel, netconfMessage); - negotiationSuccessful(session); - } else { - final IllegalStateException cause = new IllegalStateException( - "Received message was not hello as expected, but was " + XmlUtil.toString(doc)); - logger.warn("Negotiation of netconf session failed", cause); - negotiationFailed(cause); - } + negotiationSuccessful(session); } /** @@ -218,14 +202,31 @@ extends AbstractSessionNegotiator { } private static boolean isStateChangePermitted(State state, State newState) { - if (state == State.IDLE && newState == State.OPEN_WAIT) + if (state == State.IDLE && newState == State.OPEN_WAIT) { return true; - if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) + } + if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) { return true; - if (state == State.OPEN_WAIT && newState == State.FAILED) + } + if (state == State.OPEN_WAIT && newState == State.FAILED) { return true; + } logger.debug("Transition from {} to {} is not allowed", state, newState); return false; } + + /** + * Handler to catch exceptions in pipeline during negotiation + */ + private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter { + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause); + cancelTimeout(); + negotiationFailed(cause); + changeState(State.FAILED); + } + } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/NetconfUtil.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/NetconfUtil.java index aae2f71b86..796ab91a50 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/NetconfUtil.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/NetconfUtil.java @@ -27,10 +27,12 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -public class NetconfUtil { +public final class NetconfUtil { private static final Logger logger = LoggerFactory.getLogger(NetconfUtil.class); + private NetconfUtil() {} + public static NetconfMessage createMessage(final File f) { Preconditions.checkNotNull(f, "File parameter was null"); try { diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ChunkedFramingMechanismEncoder.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ChunkedFramingMechanismEncoder.java index f7d1ba2b7e..ccc80a7b71 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ChunkedFramingMechanismEncoder.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ChunkedFramingMechanismEncoder.java @@ -49,7 +49,7 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder createHandler(FramingMechanism framingMechanism) { logger.debug("{} framing mechanism was selected.", framingMechanism); diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToHelloMessageDecoder.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToHelloMessageDecoder.java index 248871a7aa..c4808e0868 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToHelloMessageDecoder.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToHelloMessageDecoder.java @@ -135,11 +135,13 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder for (byte[] possibleStart : POSSIBLE_STARTS) { int i = 0; for (byte b : possibleStart) { - if(bytes[i++] != b) + if(bytes[i++] != b) { break; + } - if(i == possibleStart.length) + if(i == possibleStart.length) { return true; + } } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/SshHandler.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/SshHandler.java index 0d9096c02a..49d5a05ae2 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/SshHandler.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/SshHandler.java @@ -29,6 +29,8 @@ import org.opendaylight.controller.netconf.util.handler.ssh.virtualsocket.Virtua * stops at instance of this class. All downstream events are handed of to wrapped {@link org.opendaylight.controller.netconf.util.handler.ssh.client.SshClientAdapter}; */ public class SshHandler extends ChannelOutboundHandlerAdapter { + private static final String SOCKET = "socket"; + private final VirtualSocket virtualSocket = new VirtualSocket(); private final SshClientAdapter sshClientAdapter; @@ -39,20 +41,20 @@ public class SshHandler extends ChannelOutboundHandlerAdapter { @Override public void handlerAdded(ChannelHandlerContext ctx){ - if (ctx.channel().pipeline().get("socket") == null) { - ctx.channel().pipeline().addFirst("socket", virtualSocket); + if (ctx.channel().pipeline().get(SOCKET) == null) { + ctx.channel().pipeline().addFirst(SOCKET, virtualSocket); } } @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - if (ctx.channel().pipeline().get("socket") != null) { - ctx.channel().pipeline().remove("socket"); + public void handlerRemoved(ChannelHandlerContext ctx) { + if (ctx.channel().pipeline().get(SOCKET) != null) { + ctx.channel().pipeline().remove(SOCKET); } } @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws IOException { this.sshClientAdapter.write((ByteBuf) msg); } @@ -60,18 +62,18 @@ public class SshHandler extends ChannelOutboundHandlerAdapter { public void connect(final ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, - ChannelPromise promise) throws Exception { + ChannelPromise promise) { ctx.connect(remoteAddress, localAddress, promise); promise.addListener(new ChannelFutureListener() { - public void operationComplete(ChannelFuture channelFuture) throws Exception { + public void operationComplete(ChannelFuture channelFuture) { sshClientAdapter.start(ctx); }} ); } @Override - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { sshClientAdapter.stop(promise); } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/authentication/LoginPassword.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/authentication/LoginPassword.java index 2f1b260bd0..4aa274c6df 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/authentication/LoginPassword.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/authentication/LoginPassword.java @@ -29,7 +29,8 @@ public class LoginPassword extends AuthenticationHandler { public void authenticate(Connection connection) throws IOException { boolean isAuthenticated = connection.authenticateWithPassword(username, password); - if (isAuthenticated == false) + if (isAuthenticated == false) { throw new IOException("Authentication failed."); + } } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/Invoker.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/Invoker.java index 8636e5ecb5..fffb304d26 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/Invoker.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/Invoker.java @@ -19,6 +19,7 @@ public abstract class Invoker { private Invoker(){} protected boolean isInvoked() { + // TODO invoked is always false return invoked; } @@ -34,7 +35,9 @@ public abstract class Invoker { return new Invoker() { @Override void invoke(SshSession session) throws IOException { - if (isInvoked() == true) throw new IllegalStateException("Already invoked."); + if (isInvoked()) { + throw new IllegalStateException("Already invoked."); + } session.startSubSystem(subsystem); } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClient.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClient.java index 3cb608db6a..7beee649ab 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClient.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClient.java @@ -23,7 +23,7 @@ import java.util.Map; */ public class SshClient { private final VirtualSocket socket; - private final Map openSessions = new HashMap(); + private final Map openSessions = new HashMap<>(); private final AuthenticationHandler authenticationHandler; private Connection connection; @@ -33,8 +33,9 @@ public class SshClient { } public SshSession openSession() throws IOException { - if (connection == null) + if (connection == null) { connect(); + } Session session = connection.openSession(); SshSession sshSession = new SshSession(session); @@ -52,7 +53,7 @@ public class SshClient { public void closeSession(SshSession session) { if (session.getState() == Channel.STATE_OPEN || session.getState() == Channel.STATE_OPENING) { - session.session.close(); + session.close(); } } @@ -62,7 +63,8 @@ public class SshClient { openSessions.clear(); - if (connection != null) + if (connection != null) { connection.close(); + } } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClientAdapter.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClientAdapter.java index 4213fe3e06..6350dd1544 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClientAdapter.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClientAdapter.java @@ -27,16 +27,14 @@ import org.opendaylight.controller.netconf.util.handler.ssh.virtualsocket.Virtua * pipeline. */ public class SshClientAdapter implements Runnable { + private static final int BUFFER_SIZE = 1024; + private final SshClient sshClient; private final Invoker invoker; - private SshSession session; - private InputStream stdOut; - private InputStream stdErr; private OutputStream stdIn; - private Queue postponned = new LinkedList<>(); - + private Queue postponed = new LinkedList<>(); private ChannelHandlerContext ctx; private ChannelPromise disconnectPromise; @@ -52,22 +50,22 @@ public class SshClientAdapter implements Runnable { public void run() { try { - session = sshClient.openSession(); + SshSession session = sshClient.openSession(); invoker.invoke(session); - stdOut = session.getStdout(); - stdErr = session.getStderr(); + InputStream stdOut = session.getStdout(); + session.getStderr(); synchronized (lock) { stdIn = session.getStdin(); - ByteBuf message = null; - while ((message = postponned.poll()) != null) { + ByteBuf message; + while ((message = postponed.poll()) != null) { writeImpl(message); } } while (stopRequested.get() == false) { - byte[] readBuff = new byte[1024]; + byte[] readBuff = new byte[BUFFER_SIZE]; int c = stdOut.read(readBuff); if (c == -1) { continue; @@ -89,8 +87,9 @@ public class SshClientAdapter implements Runnable { sshClient.close(); synchronized (lock) { - if (disconnectPromise != null) + if (disconnectPromise != null) { ctx.disconnect(disconnectPromise); + } } } } @@ -99,7 +98,7 @@ public class SshClientAdapter implements Runnable { public void write(ByteBuf message) throws IOException { synchronized (lock) { if (stdIn == null) { - postponned.add(message); + postponed.add(message); return; } writeImpl(message); @@ -119,8 +118,10 @@ public class SshClientAdapter implements Runnable { } public void start(ChannelHandlerContext ctx) { - if (this.ctx != null) - return; // context is already associated. + if (this.ctx != null) { + // context is already associated. + return; + } this.ctx = ctx; new Thread(this).start(); } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshSession.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshSession.java index df400aa141..411036c975 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshSession.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshSession.java @@ -11,6 +11,7 @@ package org.opendaylight.controller.netconf.util.handler.ssh.client; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -18,8 +19,8 @@ import java.io.OutputStream; /** * Wrapper class for proprietary SSH sessions implementations */ -public class SshSession { - final Session session; +public class SshSession implements Closeable { + private final Session session; public SshSession(Session session) { this.session = session; @@ -61,8 +62,8 @@ public class SshSession { return session.waitUntilDataAvailable(timeout); } - public int waitForCondition(int condition_set, long timeout) { - return session.waitForCondition(condition_set, timeout); + public int waitForCondition(int conditionSet, long timeout) { + return session.waitForCondition(conditionSet, timeout); } public Integer getExitStatus() { @@ -72,4 +73,9 @@ public class SshSession { public String getExitSignal() { return session.getExitSignal(); } + + @Override + public void close() { + session.close(); + } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelInputStream.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelInputStream.java index 4b9bfbf5f8..313ea93241 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelInputStream.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelInputStream.java @@ -39,7 +39,9 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan b[off] = (byte)c; - if(this.bb.readableBytes() == 0) return bytesRead; + if(this.bb.readableBytes() == 0) { + return bytesRead; + } int ltr = len-1; ltr = (ltr <= bb.readableBytes()) ? ltr : bb.readableBytes(); @@ -72,28 +74,23 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan } } - public void channelRegistered(ChannelHandlerContext ctx) - throws Exception { + public void channelRegistered(ChannelHandlerContext ctx) { ctx.fireChannelRegistered(); } - public void channelUnregistered(ChannelHandlerContext ctx) - throws Exception { + public void channelUnregistered(ChannelHandlerContext ctx) { ctx.fireChannelUnregistered(); } - public void channelActive(ChannelHandlerContext ctx) - throws Exception { + public void channelActive(ChannelHandlerContext ctx) { ctx.fireChannelActive(); } - public void channelInactive(ChannelHandlerContext ctx) - throws Exception { + public void channelInactive(ChannelHandlerContext ctx) { ctx.fireChannelInactive(); } - public void channelRead(ChannelHandlerContext ctx, Object o) - throws Exception { + public void channelRead(ChannelHandlerContext ctx, Object o) { synchronized(lock) { this.bb.discardReadBytes(); this.bb.writeBytes((ByteBuf) o); @@ -101,31 +98,25 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan } } - public void channelReadComplete(ChannelHandlerContext ctx) - throws Exception { + public void channelReadComplete(ChannelHandlerContext ctx) { ctx.fireChannelReadComplete(); } - public void userEventTriggered(ChannelHandlerContext ctx, Object o) - throws Exception { + public void userEventTriggered(ChannelHandlerContext ctx, Object o) { ctx.fireUserEventTriggered(o); } - public void channelWritabilityChanged(ChannelHandlerContext ctx) - throws Exception { + public void channelWritabilityChanged(ChannelHandlerContext ctx) { ctx.fireChannelWritabilityChanged(); } - public void handlerAdded(ChannelHandlerContext ctx) - throws Exception { + public void handlerAdded(ChannelHandlerContext ctx) { } - public void handlerRemoved(ChannelHandlerContext ctx) - throws Exception { + public void handlerRemoved(ChannelHandlerContext ctx) { } - public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { ctx.fireExceptionCaught(throwable); } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelOutputStream.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelOutputStream.java index b1314a6eed..cd7ec5439b 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelOutputStream.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelOutputStream.java @@ -14,7 +14,6 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.ChannelPromise; -import java.io.IOException; import java.io.OutputStream; import java.net.SocketAddress; @@ -27,7 +26,7 @@ public class ChannelOutputStream extends OutputStream implements ChannelOutbound private ChannelHandlerContext ctx; @Override - public void flush() throws IOException { + public void flush() { synchronized(lock) { ctx.writeAndFlush(buff).awaitUninterruptibly(); buff = Unpooled.buffer(); @@ -35,51 +34,44 @@ public class ChannelOutputStream extends OutputStream implements ChannelOutbound } @Override - public void write(int b) throws IOException { + public void write(int b) { synchronized(lock) { buff.writeByte(b); } } public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, - ChannelPromise promise) throws Exception { + ChannelPromise promise) { ctx.bind(localAddress, promise); } public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, - SocketAddress localAddress, ChannelPromise promise) - throws Exception { + SocketAddress localAddress, ChannelPromise promise) { this.ctx = ctx; ctx.connect(remoteAddress, localAddress, promise); } - public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) - throws Exception { + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { ctx.disconnect(promise); } - public void close(ChannelHandlerContext ctx, ChannelPromise promise) - throws Exception { + public void close(ChannelHandlerContext ctx, ChannelPromise promise) { ctx.close(promise); } - public void deregister(ChannelHandlerContext ctx, ChannelPromise channelPromise) - throws Exception { + public void deregister(ChannelHandlerContext ctx, ChannelPromise channelPromise) { ctx.deregister(channelPromise); } - public void read(ChannelHandlerContext ctx) - throws Exception { + public void read(ChannelHandlerContext ctx) { ctx.read(); } - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) - throws Exception { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { // pass } - public void flush(ChannelHandlerContext ctx) - throws Exception { + public void flush(ChannelHandlerContext ctx) { // pass } @@ -91,8 +83,7 @@ public class ChannelOutputStream extends OutputStream implements ChannelOutbound throws Exception { } - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.fireExceptionCaught(cause); } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/VirtualSocket.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/VirtualSocket.java index 1011ca16be..36c2c1c329 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/VirtualSocket.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/VirtualSocket.java @@ -26,6 +26,9 @@ import java.nio.channels.SocketChannel; * are able to use full potential of NIO environment. */ public class VirtualSocket extends Socket implements ChannelHandler { + private static final String INPUT_STREAM = "inputStream"; + private static final String OUTPUT_STREAM = "outputStream"; + private final ChannelInputStream chis = new ChannelInputStream(); private final ChannelOutputStream chos = new ChannelOutputStream(); private ChannelHandlerContext ctx; @@ -39,29 +42,30 @@ public class VirtualSocket extends Socket implements ChannelHandler { return this.chos; } - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + public void handlerAdded(ChannelHandlerContext ctx) { this.ctx = ctx; - if (ctx.channel().pipeline().get("outputStream") == null) { - ctx.channel().pipeline().addFirst("outputStream", chos); + if (ctx.channel().pipeline().get(OUTPUT_STREAM) == null) { + ctx.channel().pipeline().addFirst(OUTPUT_STREAM, chos); } - if (ctx.channel().pipeline().get("inputStream") == null) { - ctx.channel().pipeline().addFirst("inputStream", chis); + if (ctx.channel().pipeline().get(INPUT_STREAM) == null) { + ctx.channel().pipeline().addFirst(INPUT_STREAM, chis); } } - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - if (ctx.channel().pipeline().get("outputStream") != null) { - ctx.channel().pipeline().remove("outputStream"); + public void handlerRemoved(ChannelHandlerContext ctx) { + if (ctx.channel().pipeline().get(OUTPUT_STREAM) != null) { + ctx.channel().pipeline().remove(OUTPUT_STREAM); } - if (ctx.channel().pipeline().get("inputStream") != null) { - ctx.channel().pipeline().remove("inputStream"); + if (ctx.channel().pipeline().get(INPUT_STREAM) != null) { + ctx.channel().pipeline().remove(INPUT_STREAM); } } - public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { + // TODO exceptionCaught is deprecated transform this handler ctx.fireExceptionCaught(throwable); } @@ -80,7 +84,9 @@ public class VirtualSocket extends Socket implements ChannelHandler { public InetAddress getInetAddress() { InetSocketAddress isa = getInetSocketAddress(); - if (isa == null) throw new VirtualSocketException(); + if (isa == null) { + throw new VirtualSocketException(); + } return getInetSocketAddress().getAddress(); } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageAdditionalHeader.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageAdditionalHeader.java index f3ca30d2c4..d1e064eaeb 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageAdditionalHeader.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageAdditionalHeader.java @@ -18,7 +18,7 @@ import java.util.regex.Pattern; * session's connection. Provided information can be reported via netconf * monitoring. *
- * It has pattern "[username; host-address:port; transport; session-identifier;]"
+ * It has PATTERN "[username; host-address:port; transport; session-identifier;]"
  * username - name of account on a remote
  * host-address - client's IP address
  * port - port number
@@ -92,20 +92,20 @@ public class NetconfHelloMessageAdditionalHeader {
     }
 
     // TODO IPv6
-    private static final Pattern pattern = Pattern
+    private static final Pattern PATTERN = Pattern
             .compile("\\[(?[^;]+);(?
[0-9\\.]+)[:/](?[0-9]+);(?[a-z]+)[^\\]]+\\]"); - private static final Pattern customHeaderPattern = Pattern + private static final Pattern CUSTOM_HEADER_PATTERN = Pattern .compile("\\[(?[^;]+);(?
[0-9\\.]+)[:/](?[0-9]+);(?[a-z]+);(?[a-z]+)[^\\]]+\\]"); /** * Parse additional header from a formatted string */ public static NetconfHelloMessageAdditionalHeader fromString(String additionalHeader) { - additionalHeader = additionalHeader.trim(); - Matcher matcher = pattern.matcher(additionalHeader); - Matcher matcher2 = customHeaderPattern.matcher(additionalHeader); + String additionalHeaderTrimmed = additionalHeader.trim(); + Matcher matcher = PATTERN.matcher(additionalHeaderTrimmed); + Matcher matcher2 = CUSTOM_HEADER_PATTERN.matcher(additionalHeaderTrimmed); Preconditions.checkArgument(matcher.matches(), "Additional header in wrong format %s, expected %s", - additionalHeader, pattern); + additionalHeaderTrimmed, PATTERN); String username = matcher.group("username"); String address = matcher.group("address"); diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageConstants.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageConstants.java index c111998e0a..8bd6b88659 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageConstants.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageConstants.java @@ -17,9 +17,13 @@ public class NetconfMessageConstants { */ public static final byte[] END_OF_MESSAGE = "]]>]]>".getBytes(Charsets.UTF_8); - public static final byte[] endOfChunk = "\n##\n".getBytes(Charsets.UTF_8); + // bytes - public static final int MIN_HEADER_LENGTH = 4; // bytes + public static final int MIN_HEADER_LENGTH = 4; - public static final int MAX_HEADER_LENGTH = 13; // bytes + // bytes + + public static final int MAX_HEADER_LENGTH = 13; + + public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(Charsets.UTF_8); } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageUtil.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageUtil.java index 46053e734e..91eb86908b 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageUtil.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageUtil.java @@ -13,7 +13,9 @@ import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants; import org.w3c.dom.Document; -public class NetconfMessageUtil { +public final class NetconfMessageUtil { + + private NetconfMessageUtil() {} public static boolean isOKMessage(NetconfMessage message) { return isOKMessage(message.getDocument()); diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/SendErrorExceptionUtil.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/SendErrorExceptionUtil.java index 6dc00bb150..de2d6d7e0c 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/SendErrorExceptionUtil.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/SendErrorExceptionUtil.java @@ -29,9 +29,11 @@ import javax.xml.xpath.XPathExpression; import java.io.InputStream; import java.util.Map.Entry; -public class SendErrorExceptionUtil { +public final class SendErrorExceptionUtil { private static final Logger logger = LoggerFactory.getLogger(SendErrorExceptionUtil.class); + private SendErrorExceptionUtil() {} + public static void sendErrorMessage(final NetconfSession session, final NetconfDocumentedException sendErrorException) { logger.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException); @@ -68,8 +70,9 @@ public class SendErrorExceptionUtil { for (int i = 0; i < incomingAttributes.getLength(); i++) { final Attr attr = (Attr) incomingAttributes.item(i); // skip namespace - if (attr.getNodeName().equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) + if (attr.getNodeName().equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) { continue; + } rpcReply.setAttributeNode((Attr) errorDocument.importNode(attr, true)); } } catch (final Exception e) { diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java index 38563cba93..80eaa26de1 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java @@ -17,12 +17,12 @@ import java.net.InetSocketAddress; import static com.google.common.base.Preconditions.checkNotNull; -public class NetconfConfigUtil { +public final class NetconfConfigUtil { private static final Logger logger = LoggerFactory.getLogger(NetconfConfigUtil.class); private static final String PREFIX_PROP = "netconf."; - + private NetconfConfigUtil() {} private enum InfixProp { tcp, ssh diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XMLNetconfUtil.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XMLNetconfUtil.java index d9303228f9..3247e0f7a0 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XMLNetconfUtil.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XMLNetconfUtil.java @@ -13,7 +13,9 @@ import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -public class XMLNetconfUtil { +public final class XMLNetconfUtil { + + private XMLNetconfUtil() {} public static XPathExpression compileXPath(String xPath) { final XPathFactory xPathfactory = XPathFactory.newInstance(); diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java index 18a94c6d07..1fbae1ee2d 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java @@ -31,9 +31,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class XmlElement { +public final class XmlElement { - public final Element element; + private final Element element; private XmlElement(Element element) { this.element = element; @@ -123,9 +123,6 @@ public class XmlElement { public void appendChild(Element element) { this.element.appendChild(element); - // Element newElement = (Element) element.cloneNode(true); - // newElement.appendChild(configElement); - // return XmlElement.fromDomElement(newElement); } public Element getDomElement() { @@ -153,10 +150,12 @@ public class XmlElement { final List result = new ArrayList<>(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); - if (item instanceof Element == false) + if (item instanceof Element == false) { continue; - if (strat.accept((Element) item)) + } + if (strat.accept((Element) item)) { result.add(new XmlElement((Element) item)); + } } return result; @@ -290,12 +289,12 @@ public class XmlElement { public String getNamespace() { String namespaceURI = element.getNamespaceURI(); Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this); - return namespaceURI.toString(); + return namespaceURI; } @Override public String toString() { - final StringBuffer sb = new StringBuffer("XmlElement{"); + final StringBuilder sb = new StringBuilder("XmlElement{"); sb.append("name='").append(getName()).append('\''); if (element.getNamespaceURI() != null) { sb.append(", namespace='").append(getNamespace()).append('\''); @@ -320,7 +319,7 @@ public class XmlElement { public Map.Entry findNamespaceOfTextContent() { Map namespaces = extractNamespaces(element); String textContent = getTextContent(); - int indexOfColon = textContent.indexOf(":"); + int indexOfColon = textContent.indexOf(':'); String prefix; if (indexOfColon > -1) { prefix = textContent.substring(0, indexOfColon); @@ -360,15 +359,18 @@ public class XmlElement { @Override public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } XmlElement that = (XmlElement) o; - if (!element.isEqualNode(that.element)) + if (!element.isEqualNode(that.element)) { return false; + } return true; } @@ -392,7 +394,7 @@ public class XmlElement { return true; } - private static interface ElementFilteringStrategy { + private interface ElementFilteringStrategy { boolean accept(Element e); } } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfConstants.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfConstants.java index c410cf30b0..4a6586cd1d 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfConstants.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfConstants.java @@ -7,7 +7,9 @@ */ package org.opendaylight.controller.netconf.util.xml; -public class XmlNetconfConstants { +public final class XmlNetconfConstants { + + private XmlNetconfConstants() {} public static final String MOUNTPOINTS = "mountpoints"; public static final String MOUNTPOINT = "mountpoint"; diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfValidator.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfValidator.java index de0ebccdca..8108c8e740 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfValidator.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfValidator.java @@ -21,8 +21,11 @@ import org.xml.sax.SAXException; import com.google.common.base.Preconditions; -public class XmlNetconfValidator { - static final Schema schema; +public final class XmlNetconfValidator { + + private static final Schema SCHEMA; + + private XmlNetconfValidator() {} static { final InputStream xmlSchema = XmlNetconfValidator.class.getResourceAsStream("/xml.xsd"); @@ -30,11 +33,11 @@ public class XmlNetconfValidator { final InputStream rfc4714Schema = XmlNetconfValidator.class.getResourceAsStream("/rfc4741.xsd"); Preconditions.checkNotNull(rfc4714Schema, "Cannot find rfc4741.xsd"); - schema = XmlUtil.loadSchema(xmlSchema, rfc4714Schema); + SCHEMA = XmlUtil.loadSchema(xmlSchema, rfc4714Schema); } public static void validate(Document inputDocument) throws SAXException, IOException { - final Validator validator = schema.newValidator(); + final Validator validator = SCHEMA.newValidator(); final Source source = new DOMSource(inputDocument); validator.validate(source); } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java index bb6c35130e..238249dbbd 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java @@ -41,7 +41,8 @@ import org.xml.sax.SAXException; import com.google.common.base.Charsets; -public class XmlUtil { +public final class XmlUtil { + public static final String XMLNS_ATTRIBUTE_KEY = "xmlns"; private static final DocumentBuilderFactory BUILDERFACTORY; @@ -54,6 +55,8 @@ public class XmlUtil { BUILDERFACTORY = factory; } + private XmlUtil() {} + public static Element readXmlToElement(String xmlContent) throws SAXException, IOException { Document doc = readXmlToDocument(xmlContent); return doc.getDocumentElement(); @@ -68,6 +71,9 @@ public class XmlUtil { return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8))); } + // TODO improve exceptions throwing + // along with XmlElement + public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException { DocumentBuilder dBuilder; try { @@ -133,14 +139,13 @@ public class XmlUtil { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes"); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(xml); transformer.transform(source, result); - String xmlString = result.getWriter().toString(); - return xmlString; + return result.getWriter().toString(); } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) { throw new RuntimeException("Unable to serialize xml element " + xml, e); } -- 2.36.6