From 6e3af3a4cf58384790d8ae844138c3e1ab9e8699 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 6 Mar 2018 18:56:59 +0100 Subject: [PATCH 1/9] Initial slf4j commit --- pom.xml | 227 +++++++++--------- src/main/example/ChatClient.java | 1 - src/main/example/ChatServer.java | 1 - .../example/ChatServerAttachmentExample.java | 1 - .../example/CustomHeaderClientExample.java | 1 - src/main/example/ReconnectClientExample.java | 1 - src/main/example/SSLClientExample.java | 2 - ...SLServerCustomWebsocketFactoryExample.java | 2 - src/main/example/SSLServerExample.java | 2 - .../example/SSLServerLetsEncryptExample.java | 2 - .../SecWebSocketProtocolClientExample.java | 1 - .../ServerAdditionalHeaderExample.java | 1 - .../example/ServerRejectHandshakeExample.java | 1 - .../org/java_websocket/AbstractWebSocket.java | 27 ++- .../org/java_websocket/SSLSocketChannel2.java | 6 + .../org/java_websocket/WebSocketImpl.java | 70 +++--- .../org/java_websocket/drafts/Draft_6455.java | 46 +++- .../server/WebSocketServer.java | 21 +- .../example/AutobahnClientTest.java | 3 - .../example/AutobahnSSLServerTest.java | 1 - .../example/AutobahnServerTest.java | 1 - 21 files changed, 226 insertions(+), 192 deletions(-) diff --git a/pom.xml b/pom.xml index 9ff4a54f0..f53f5f245 100644 --- a/pom.xml +++ b/pom.xml @@ -1,114 +1,121 @@ - - 4.0.0 - org.java-websocket - Java-WebSocket - jar - 1.3.9-dev - Java-WebSocket - A barebones WebSocket client and server implementation written 100% in Java - https://github.com/TooTallNate/Java-WebSocket - - UTF-8 - - - - MIT License - https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE - - - + + + 4.0.0 + org.java-websocket + Java-WebSocket + jar + 1.3.9-dev + Java-WebSocket + A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket - - - src/main/java - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.6 - 1.6 - - - - - - - junit - junit - 4.11 - test - - - org.json - json - 20171018 - test - - - - - Nathan Rajlich - https://github.com/TooTallNate - nathan@tootallnate.net - - - Marcel Prestel - https://github.com/marci4 - admin@marci4.de - - + + UTF-8 + + + + MIT License + https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE + + + + https://github.com/TooTallNate/Java-WebSocket + + + src/main/java + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ossrh + https://oss.sonatype.org/ + true + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.6 + 1.6 + + + + + + + org.slf4j + slf4j-api + 1.8.0-beta1 + + + junit + junit + 4.11 + test + + + org.json + json + 20171018 + test + + + + + Nathan Rajlich + https://github.com/TooTallNate + nathan@tootallnate.net + + + Marcel Prestel + https://github.com/marci4 + admin@marci4.de + + diff --git a/src/main/example/ChatClient.java b/src/main/example/ChatClient.java index f58c34f16..07cee786c 100644 --- a/src/main/example/ChatClient.java +++ b/src/main/example/ChatClient.java @@ -170,7 +170,6 @@ public void onError( Exception ex ) { } public static void main( String[] args ) { - WebSocketImpl.DEBUG = true; String location; if( args.length != 0 ) { location = args[ 0 ]; diff --git a/src/main/example/ChatServer.java b/src/main/example/ChatServer.java index 1dcce91b7..f4a3e2cff 100644 --- a/src/main/example/ChatServer.java +++ b/src/main/example/ChatServer.java @@ -75,7 +75,6 @@ public void onMessage( WebSocket conn, ByteBuffer message ) { public static void main( String[] args ) throws InterruptedException , IOException { - WebSocketImpl.DEBUG = true; int port = 8887; // 843 flash policy port try { port = Integer.parseInt( args[ 0 ] ); diff --git a/src/main/example/ChatServerAttachmentExample.java b/src/main/example/ChatServerAttachmentExample.java index 378cc2cf7..39554bd93 100644 --- a/src/main/example/ChatServerAttachmentExample.java +++ b/src/main/example/ChatServerAttachmentExample.java @@ -77,7 +77,6 @@ public void onMessage( WebSocket conn, ByteBuffer message ) { } public static void main( String[] args ) throws InterruptedException , IOException { - WebSocketImpl.DEBUG = true; int port = 8887; // 843 flash policy port try { port = Integer.parseInt( args[ 0 ] ); diff --git a/src/main/example/CustomHeaderClientExample.java b/src/main/example/CustomHeaderClientExample.java index 073cb14f5..955e02aff 100644 --- a/src/main/example/CustomHeaderClientExample.java +++ b/src/main/example/CustomHeaderClientExample.java @@ -38,7 +38,6 @@ public class CustomHeaderClientExample { public static void main( String[] args ) throws URISyntaxException, InterruptedException { - WebSocketImpl.DEBUG = true; Map httpHeaders = new HashMap(); httpHeaders.put( "Cookie", "test" ); ExampleClient c = new ExampleClient( new URI( "ws://localhost:8887" ), httpHeaders); diff --git a/src/main/example/ReconnectClientExample.java b/src/main/example/ReconnectClientExample.java index c7181e838..0fcf08fe0 100644 --- a/src/main/example/ReconnectClientExample.java +++ b/src/main/example/ReconnectClientExample.java @@ -33,7 +33,6 @@ */ public class ReconnectClientExample { public static void main( String[] args ) throws URISyntaxException, InterruptedException { - WebSocketImpl.DEBUG = true; ExampleClient c = new ExampleClient( new URI( "ws://localhost:8887" ) ); //Connect to a server normally c.connectBlocking(); diff --git a/src/main/example/SSLClientExample.java b/src/main/example/SSLClientExample.java index 693c71bbe..4f6e1d875 100644 --- a/src/main/example/SSLClientExample.java +++ b/src/main/example/SSLClientExample.java @@ -80,8 +80,6 @@ public class SSLClientExample { *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main( String[] args ) throws Exception { - WebSocketImpl.DEBUG = true; - WebSocketChatClient chatclient = new WebSocketChatClient( new URI( "wss://localhost:8887" ) ); // load up the key store diff --git a/src/main/example/SSLServerCustomWebsocketFactoryExample.java b/src/main/example/SSLServerCustomWebsocketFactoryExample.java index e9d825693..86e0a4ebc 100644 --- a/src/main/example/SSLServerCustomWebsocketFactoryExample.java +++ b/src/main/example/SSLServerCustomWebsocketFactoryExample.java @@ -48,8 +48,6 @@ public class SSLServerCustomWebsocketFactoryExample { *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main(String[] args) throws Exception { - WebSocketImpl.DEBUG = true; - ChatServer chatserver = new ChatServer(8887); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store diff --git a/src/main/example/SSLServerExample.java b/src/main/example/SSLServerExample.java index 1e58d4ae4..a19cfcb79 100644 --- a/src/main/example/SSLServerExample.java +++ b/src/main/example/SSLServerExample.java @@ -44,8 +44,6 @@ public class SSLServerExample { *keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry" */ public static void main( String[] args ) throws Exception { - WebSocketImpl.DEBUG = true; - ChatServer chatserver = new ChatServer( 8887 ); // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store diff --git a/src/main/example/SSLServerLetsEncryptExample.java b/src/main/example/SSLServerLetsEncryptExample.java index 731bb3891..34b80d0c9 100644 --- a/src/main/example/SSLServerLetsEncryptExample.java +++ b/src/main/example/SSLServerLetsEncryptExample.java @@ -53,8 +53,6 @@ public class SSLServerLetsEncryptExample { public static void main( String[] args ) throws Exception { - WebSocketImpl.DEBUG = true; - ChatServer chatserver = new ChatServer( 8887 ); SSLContext context = getContext(); diff --git a/src/main/example/SecWebSocketProtocolClientExample.java b/src/main/example/SecWebSocketProtocolClientExample.java index e5bb1b244..1a7543321 100644 --- a/src/main/example/SecWebSocketProtocolClientExample.java +++ b/src/main/example/SecWebSocketProtocolClientExample.java @@ -40,7 +40,6 @@ public class SecWebSocketProtocolClientExample { public static void main( String[] args ) throws URISyntaxException { - WebSocketImpl.DEBUG = true; // This draft only allows you to use the specific Sec-WebSocket-Protocol without a fallback. Draft_6455 draft_ocppOnly = new Draft_6455(Collections.emptyList(), Collections.singletonList(new Protocol("ocpp2.0"))); diff --git a/src/main/example/ServerAdditionalHeaderExample.java b/src/main/example/ServerAdditionalHeaderExample.java index 4b80e9e20..2631dbebe 100644 --- a/src/main/example/ServerAdditionalHeaderExample.java +++ b/src/main/example/ServerAdditionalHeaderExample.java @@ -58,7 +58,6 @@ public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket co public static void main( String[] args ) throws InterruptedException , IOException { - WebSocketImpl.DEBUG = true; int port = 8887; // 843 flash policy port try { port = Integer.parseInt( args[ 0 ] ); diff --git a/src/main/example/ServerRejectHandshakeExample.java b/src/main/example/ServerRejectHandshakeExample.java index f2a3430f9..2bbeee0c4 100644 --- a/src/main/example/ServerRejectHandshakeExample.java +++ b/src/main/example/ServerRejectHandshakeExample.java @@ -73,7 +73,6 @@ public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket co public static void main( String[] args ) throws InterruptedException , IOException { - WebSocketImpl.DEBUG = true; int port = 8887; // 843 flash policy port try { port = Integer.parseInt( args[ 0 ] ); diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index f4a1bc24e..4e4e0fb9d 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -26,6 +26,8 @@ package org.java_websocket; import org.java_websocket.framing.CloseFrame; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; @@ -38,6 +40,13 @@ */ public abstract class AbstractWebSocket extends WebSocketAdapter { + /** + * Logger instance + * + * @since 1.4.0 + */ + private static final Logger log = LoggerFactory.getLogger(AbstractWebSocket.class); + /** * Attribute which allows you to deactivate the Nagle's algorithm * @since 1.3.3 @@ -90,8 +99,7 @@ public void setConnectionLostTimeout( int connectionLostTimeout ) { stopConnectionLostTimer(); } if (connectionLostTimer != null || connectionLostTimerTask != null) { - if( WebSocketImpl.DEBUG ) - System.out.println( "Connection lost timer restarted" ); + log.info( "Connection lost timer restarted" ); restartConnectionLostTimer(); } } @@ -102,8 +110,7 @@ public void setConnectionLostTimeout( int connectionLostTimeout ) { */ protected void stopConnectionLostTimer() { if (connectionLostTimer != null ||connectionLostTimerTask != null) { - if( WebSocketImpl.DEBUG ) - System.out.println( "Connection lost timer stopped" ); + log.info( "Connection lost timer stopped" ); cancelConnectionLostTimer(); } } @@ -113,12 +120,10 @@ protected void stopConnectionLostTimer() { */ protected void startConnectionLostTimer() { if (this.connectionLostTimeout <= 0) { - if (WebSocketImpl.DEBUG) - System.out.println("Connection lost timer deactivated"); + log.info("Connection lost timer deactivated"); return; } - if (WebSocketImpl.DEBUG) - System.out.println("Connection lost timer started"); + log.info("Connection lost timer started"); restartConnectionLostTimer(); } @@ -145,15 +150,13 @@ public void run() { if (conn instanceof WebSocketImpl) { webSocketImpl = (WebSocketImpl)conn; if( webSocketImpl.getLastPong() < current ) { - if (WebSocketImpl.DEBUG) - System.out.println("Closing connection due to no pong received: " + conn.toString()); + log.warn("Closing connection due to no pong received: " + conn.toString()); webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE , "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection"); } else { if (webSocketImpl.isOpen()) { webSocketImpl.sendPing(); } else { - if (WebSocketImpl.DEBUG) - System.out.println("Trying to ping a non open connection: " + conn.toString()); + log.warn("Trying to ping a non open connection: " + conn.toString()); } } } diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index 3191edd90..74cd7e39d 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -222,8 +222,14 @@ protected void createBuffers( SSLSession session ) { if( inCrypt.capacity() != netBufferMax ) inCrypt = ByteBuffer.allocate( netBufferMax ); } + if (inData.remaining() != 0) { + System.out.println(new String( inData.array(), inData.position(), inData.remaining())); + } inData.rewind(); inData.flip(); + if (inCrypt.remaining() != 0) { + System.out.println(new String( inCrypt.array(), inCrypt.position(), inCrypt.remaining())); + } inCrypt.rewind(); inCrypt.flip(); outCrypt.rewind(); diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index cb4eae39a..ece6d0ddb 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -55,6 +55,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Represents one end (client or server) of a single WebSocketImpl connection. * Takes care of the "handshake" phase, then allows for easy sending of @@ -64,9 +67,11 @@ public class WebSocketImpl implements WebSocket { public static int RCVBUF = 16384; /** - * Activate debug mode for additional infos + * Logger instance + * + * @since 1.4.0 */ - public static boolean DEBUG = false; // must be final in the future in order to take advantage of VM optimization + private static final Logger log = LoggerFactory.getLogger(WebSocketImpl.class); /** * Queue of buffers that need to be sent to the client. @@ -203,9 +208,7 @@ public WebSocketImpl( WebSocketListener listener, List drafts, Socket soc */ public void decode( ByteBuffer socketBuffer ) { assert ( socketBuffer.hasRemaining() ); - - if( DEBUG ) - System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + '}' ); + log.debug( "process({}): ({})", socketBuffer.remaining(), ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) )); if( getReadyState() != READYSTATE.NOT_YET_CONNECTED ) { if( getReadyState() == READYSTATE.OPEN ) { @@ -214,7 +217,6 @@ public void decode( ByteBuffer socketBuffer ) { } else { if( decodeHandshake( socketBuffer ) && (!isClosing() && !isClosed())) { assert ( tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer.hasRemaining() ); // the buffers will never have remaining bytes at the same time - if( socketBuffer.hasRemaining() ) { decodeFrames( socketBuffer ); } else if( tmpHandshakeBytes.hasRemaining() ) { @@ -258,6 +260,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { socketBuffer.reset(); Handshakedata tmphandshake = d.translateHandshake( socketBuffer ); if( !( tmphandshake instanceof ClientHandshake ) ) { + log.debug("Closing due to wrong handshake"); closeConnectionDueToWrongHandshake( new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "wrong http function" ) ); return false; } @@ -269,9 +272,11 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); } catch ( InvalidDataException e ) { + log.debug("Closing due to wrong handshake. Possible handshake rejection: ", e); closeConnectionDueToWrongHandshake( e ); return false; } catch ( RuntimeException e ) { + log.error("Closing due to internal server error", e); wsl.onWebsocketError( this, e ); closeConnectionDueToInternalServerError( e ); return false; @@ -286,6 +291,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { } } if( draft == null ) { + log.debug("Closing due to protocol error: no draft matches"); closeConnectionDueToWrongHandshake( new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "no draft matches" ) ); } return false; @@ -293,6 +299,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { // special case for multiple step handshakes Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( !( tmphandshake instanceof ClientHandshake ) ) { + log.debug("Closing due to protocol error: wrong http function"); flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } @@ -303,7 +310,8 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { open( handshake ); return true; } else { - close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" ); + log.debug("Closing due to protocol error: the handshake did finally not match"); + close( CloseFrame.PROTOCOL_ERROR, "the handshake did finally not match" ); } return false; } @@ -311,6 +319,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { draft.setParseMode( role ); Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( !( tmphandshake instanceof ServerHandshake ) ) { + log.debug("Closing due to protocol error: wrong http function"); flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } @@ -320,9 +329,11 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); } catch ( InvalidDataException e ) { + log.debug("Closing due to invalid data exception. Possible handshake rejection: ", e); flushAndClose( e.getCloseCode(), e.getMessage(), false ); return false; } catch ( RuntimeException e ) { + log.error("Closing since client was never connected", e); wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.NEVER_CONNECTED, e.getMessage(), false ); return false; @@ -330,10 +341,12 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { open( handshake ); return true; } else { + log.debug("Closing due to protocol error: draft {} refuses handshake", draft ); close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" ); } } } catch ( InvalidHandshakeException e ) { + log.debug("Closing due to invalid handshake", e); close( e ); } } catch ( IncompleteHandshakeException e ) { @@ -362,14 +375,13 @@ private void decodeFrames( ByteBuffer socketBuffer ) { try { frames = draft.translateFrame( socketBuffer ); for( Framedata f : frames ) { - if( DEBUG ) - System.out.println( "matched frame: " + f ); + log.debug( "matched frame: {}" , f ); draft.processFrame( this, f ); } - } catch ( InvalidDataException e1 ) { - wsl.onWebsocketError( this, e1 ); - close( e1 ); - return; + } catch ( InvalidDataException e ) { + log.error("Closing due to invalid data in frame", e); + wsl.onWebsocketError( this, e ); + close(e); } } @@ -438,6 +450,7 @@ public synchronized void close( int code, String message, boolean remote ) { sendFrame( closeFrame ); } } catch ( InvalidDataException e ) { + log.error("generated frame is invalid", e); wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false ); } @@ -492,10 +505,9 @@ public synchronized void closeConnection( int code, String message, boolean remo channel.close(); } catch ( IOException e ) { if( e.getMessage().equals( "Broken pipe" ) ) { - if( WebSocketImpl.DEBUG ) { - System.out.println( "Caught IOException: Broken pipe during closeConnection()" ); - } + log.warn( "Caught IOException: Broken pipe during closeConnection()", e ); } else { + log.error("Exception during channel.close()", e); wsl.onWebsocketError( this, e ); } } @@ -503,6 +515,7 @@ public synchronized void closeConnection( int code, String message, boolean remo try { this.wsl.onWebsocketClose( this, code, message, remote ); } catch ( RuntimeException e ) { + wsl.onWebsocketError( this, e ); } if( draft != null ) @@ -517,7 +530,7 @@ protected void closeConnection( int code, boolean remote ) { public void closeConnection() { if( closedremotely == null ) { - throw new IllegalStateException( "this method must be used in conjuction with flushAndClose" ); + throw new IllegalStateException( "this method must be used in conjunction with flushAndClose" ); } closeConnection( closecode, closemessage, closedremotely ); } @@ -540,6 +553,7 @@ public synchronized void flushAndClose( int code, String message, boolean remote try { wsl.onWebsocketClosing( this, code, message, remote ); } catch ( RuntimeException e ) { + log.error("Exception in onWebsocketClosing", e); wsl.onWebsocketError( this, e ); } if( draft != null ) @@ -612,8 +626,7 @@ private void send( Collection frames ) { } ArrayList outgoingFrames = new ArrayList(); for( Framedata f : frames ) { - if( DEBUG ) - System.out.println( "send frame: " + f ); + log.debug( "send frame: " + f ); outgoingFrames.add( draft.createBinaryFrame( f ) ); } write( outgoingFrames ); @@ -662,6 +675,7 @@ public void startHandshake( ClientHandshakeBuilder handshakedata ) throws Invali // Stop if the client code throws an exception throw new InvalidHandshakeException( "Handshake data rejected by client." ); } catch ( RuntimeException e ) { + log.error("Exception in startHandshake", e); wsl.onWebsocketError( this, e ); throw new InvalidHandshakeException( "rejected because of" + e ); } @@ -671,17 +685,9 @@ public void startHandshake( ClientHandshakeBuilder handshakedata ) throws Invali } private void write( ByteBuffer buf ) { - if( DEBUG ) - System.out.println( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + '}' ); + log.debug( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + '}' ); outQueue.add( buf ); - /*try { - outQueue.put( buf ); - } catch ( InterruptedException e ) { - write( buf ); - Thread.currentThread().interrupt(); // keep the interrupted status - e.printStackTrace(); - }*/ wsl.onWriteDemand( this ); } @@ -699,8 +705,7 @@ private void write( List bufs ) { } private void open( Handshakedata d ) { - if( DEBUG ) - System.out.println( "open using draft: " + draft ); + log.info( "open using draft: " + draft ); setReadyState( READYSTATE.OPEN ); try { wsl.onWebsocketOpen( this, d ); @@ -745,11 +750,6 @@ private void setReadyState( READYSTATE readystate ) { this.readystate = readystate; } - @Override - public int hashCode() { - return super.hashCode(); - } - @Override public String toString() { return super.toString(); // its nice to be able to set breakpoints here diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 14853970b..a2475f85e 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -35,6 +35,8 @@ import org.java_websocket.protocols.Protocol; import org.java_websocket.util.*; import org.java_websocket.util.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.nio.ByteBuffer; @@ -49,6 +51,13 @@ */ public class Draft_6455 extends Draft { + /** + * Logger instance + * + * @since 1.4.0 + */ + private static final Logger log = LoggerFactory.getLogger(Draft_6455.class); + /** * Attribute for the used extension in this draft */ @@ -321,8 +330,7 @@ public Draft copyInstance() { @Override public ByteBuffer createBinaryFrame( Framedata framedata ) { getExtension().encodeFrame( framedata ); - if( WebSocketImpl.DEBUG ) - System.out.println( "afterEnconding(" + framedata.getPayloadData().remaining() + "): {" + ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) + '}' ); + log.debug( "afterEnconding(" + framedata.getPayloadData().remaining() + "): {" + ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) + '}' ); return createByteBufferFromFramedata( framedata ); } @@ -369,8 +377,10 @@ private ByteBuffer createByteBufferFromFramedata( Framedata framedata ) { public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteException, InvalidDataException { int maxpacketsize = buffer.remaining(); int realpacketsize = 2; - if( maxpacketsize < realpacketsize ) + if( maxpacketsize < realpacketsize ) { + log.debug( "Incomplete frame" ); throw new IncompleteException( realpacketsize ); + } byte b1 = buffer.get( /*0*/ ); boolean FIN = b1 >> 8 != 0; boolean rsv1 = false; @@ -392,26 +402,32 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce if( !( payloadlength >= 0 && payloadlength <= 125 ) ) { if( optcode == Framedata.Opcode.PING || optcode == Framedata.Opcode.PONG || optcode == Framedata.Opcode.CLOSING ) { + log.debug( "Invalid frame: more than 125 octets" ); throw new InvalidFrameException( "more than 125 octets" ); } if( payloadlength == 126 ) { realpacketsize += 2; // additional length bytes - if( maxpacketsize < realpacketsize ) + if( maxpacketsize < realpacketsize ) { + log.debug( "Incomplete frame" ); throw new IncompleteException( realpacketsize ); + } byte[] sizebytes = new byte[3]; sizebytes[1] = buffer.get( /*1 + 1*/ ); sizebytes[2] = buffer.get( /*1 + 2*/ ); payloadlength = new BigInteger( sizebytes ).intValue(); } else { realpacketsize += 8; // additional length bytes - if( maxpacketsize < realpacketsize ) + if( maxpacketsize < realpacketsize ) { + log.debug( "Incomplete frame" ); throw new IncompleteException( realpacketsize ); + } byte[] bytes = new byte[8]; for( int i = 0; i < 8; i++ ) { bytes[i] = buffer.get( /*1 + i*/ ); } long length = new BigInteger( bytes ).longValue(); if( length > Integer.MAX_VALUE ) { + log.debug( "Limit exedeed: Payloadsize is to big..." ); throw new LimitExedeedException( "Payloadsize is to big..." ); } else { payloadlength = ( int ) length; @@ -448,8 +464,7 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce frame.setPayload( payload ); getExtension().isFrameValid(frame); getExtension().decodeFrame(frame); - if( WebSocketImpl.DEBUG ) - System.out.println( "afterDecoding(" + frame.getPayloadData().remaining() + "): {" + ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) + '}' ); + log.debug( "afterDecoding(" + frame.getPayloadData().remaining() + "): {" + ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) + '}' ); frame.isValid(); return frame; } @@ -649,13 +664,17 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws webSocketImpl.getWebSocketListener().onWebsocketPong( webSocketImpl, frame ); } else if( !frame.isFin() || curop == Framedata.Opcode.CONTINUOUS ) { if( curop != Framedata.Opcode.CONTINUOUS ) { - if( current_continuous_frame != null ) + if (current_continuous_frame != null ) { + log.debug( "Protocol error: Previous continuous frame sequence not completed." ); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." ); + } current_continuous_frame = frame; byteBufferList.add( frame.getPayloadData() ); } else if( frame.isFin() ) { - if( current_continuous_frame == null ) + if( current_continuous_frame == null ) { + log.debug( "Protocol error: Previous continuous frame sequence not completed." ); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); + } byteBufferList.add( frame.getPayloadData() ); if( current_continuous_frame.getOpcode() == Framedata.Opcode.TEXT ) { ((FramedataImpl1) current_continuous_frame).setPayload( getPayloadFromByteBufferList() ); @@ -663,6 +682,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( current_continuous_frame.getPayloadData() ) ); } catch ( RuntimeException e ) { + log.error( "Runtime exception during onWebsocketMessage", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } else if( current_continuous_frame.getOpcode() == Framedata.Opcode.BINARY ) { @@ -671,17 +691,20 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, current_continuous_frame.getPayloadData() ); } catch ( RuntimeException e ) { + log.error( "Runtime exception during onWebsocketMessage", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } current_continuous_frame = null; byteBufferList.clear(); } else if( current_continuous_frame == null ) { + log.error( "Protocol error: Continuous frame sequence was not started." ); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); } //Check if the whole payload is valid utf8, when the opcode indicates a text if( curop == Framedata.Opcode.TEXT ) { if( !Charsetfunctions.isValidUTF8( frame.getPayloadData() ) ) { + log.error( "Protocol error: Payload is not UTF8" ); throw new InvalidDataException( CloseFrame.NO_UTF8 ); } } @@ -690,20 +713,24 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws byteBufferList.add( frame.getPayloadData() ); } } else if( current_continuous_frame != null ) { + log.error( "Protocol error: Continuous frame sequence not completed." ); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence not completed." ); } else if( curop == Framedata.Opcode.TEXT ) { try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( frame.getPayloadData() ) ); } catch ( RuntimeException e ) { + log.error( "Runtime exception during onWebsocketMessage", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } else if( curop == Framedata.Opcode.BINARY ) { try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, frame.getPayloadData() ); } catch ( RuntimeException e ) { + log.error( "Runtime exception during onWebsocketMessage", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } else { + log.error( "non control or continious frame expected"); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" ); } } @@ -752,6 +779,7 @@ private ByteBuffer getPayloadFromByteBufferList() throws LimitExedeedException { totalSize +=buffer.limit(); } if (totalSize > Integer.MAX_VALUE) { + log.debug( "Payloadsize is to big..."); throw new LimitExedeedException( "Payloadsize is to big..." ); } ByteBuffer resultingByteBuffer = ByteBuffer.allocate( (int) totalSize ); diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 6402e7a06..5122c5950 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -53,6 +53,8 @@ import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshakeBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * WebSocketServer is an abstract class that only takes care of the @@ -62,6 +64,13 @@ */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { + /** + * Logger instance + * + * @since 1.4.0 + */ + private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); + public static int DECODERS = Runtime.getRuntime().availableProcessors(); /** @@ -477,6 +486,7 @@ public void run() { try { selector.close(); } catch ( IOException e ) { + log.error( "IOException during selector.close", e ); onError( null, e ); } } @@ -484,6 +494,7 @@ public void run() { try { server.close(); } catch ( IOException e ) { + log.error( "IOException during server.close", e ); onError( null, e ); } } @@ -536,13 +547,13 @@ private void handleIOException( SelectionKey key, WebSocket conn, IOException ex } catch ( IOException e ) { // there is nothing that must be done here } - if( WebSocketImpl.DEBUG ) - System.out.println("Connection closed because of " + ex); + log.warn("Connection closed because of " + ex); } } } private void handleFatal( WebSocket conn, Exception e ) { + log.error( "Shutdown due to fatal error", e ); onError( conn, e ); //Shutting down WebSocketWorkers, see #222 if( decoders != null ) { @@ -556,9 +567,11 @@ private void handleFatal( WebSocket conn, Exception e ) { try { stop(); } catch ( IOException e1 ) { + log.error( "Error during shutdown", e1 ); onError( null, e1 ); } catch ( InterruptedException e1 ) { Thread.currentThread().interrupt(); + log.error( "Interrupt during stop", e ); onError( null, e1 ); } } @@ -619,9 +632,7 @@ protected boolean removeConnection( WebSocket ws ) { removed = this.connections.remove( ws ); } else { //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 - if (WebSocketImpl.DEBUG) { - System.out.println("Removing connection which is not in the connections collection! Possible no handshake recieved! " + ws); - } + log.warn("Removing connection which is not in the connections collection! Possible no handshake recieved! " + ws); } } if( isclosed.get() && connections.size() == 0 ) { diff --git a/src/test/java/org/java_websocket/example/AutobahnClientTest.java b/src/test/java/org/java_websocket/example/AutobahnClientTest.java index eed1565a5..053f047f4 100644 --- a/src/test/java/org/java_websocket/example/AutobahnClientTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnClientTest.java @@ -83,11 +83,9 @@ public static void main( String[] args ) { if( nextline != null ) { line = nextline; nextline = null; - WebSocketImpl.DEBUG = false; } else { System.out.print( ">" ); line = sysin.readLine(); - WebSocketImpl.DEBUG = true; } if( line.equals( "l" ) ) { line = perviousline; @@ -112,7 +110,6 @@ public static void main( String[] args ) { uri = URI.create( serverlocation + "/runCase?case=" + spl[ 1 ] + "&agent=" + clientname ); } else if( line.startsWith( "u" ) ) { - WebSocketImpl.DEBUG = false; uri = URI.create( serverlocation + "/updateReports?agent=" + clientname ); } else if( line.startsWith( "d" ) ) { try { diff --git a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java index 1f1d2706a..0fe590fcd 100644 --- a/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnSSLServerTest.java @@ -98,7 +98,6 @@ public void onWebsocketMessageFragment( WebSocket conn, Framedata frame ) { } public static void main( String[] args ) throws UnknownHostException { - WebSocketImpl.DEBUG = false; int port; try { port = new Integer( args[0] ); diff --git a/src/test/java/org/java_websocket/example/AutobahnServerTest.java b/src/test/java/org/java_websocket/example/AutobahnServerTest.java index 0d25bd636..91ce52051 100644 --- a/src/test/java/org/java_websocket/example/AutobahnServerTest.java +++ b/src/test/java/org/java_websocket/example/AutobahnServerTest.java @@ -93,7 +93,6 @@ public void onMessage( WebSocket conn, ByteBuffer blob ) { } public static void main( String[] args ) throws UnknownHostException { - WebSocketImpl.DEBUG = false; int port; try { port = new Integer( args[0] ); From 554ee52df62eb85ace53d4a1460c8f02591a06da Mon Sep 17 00:00:00 2001 From: marci4 Date: Wed, 8 Aug 2018 22:32:13 +0200 Subject: [PATCH 2/9] Fixed some sonarqube issues --- .../org/java_websocket/AbstractWebSocket.java | 3 +- .../org/java_websocket/WebSocketImpl.java | 21 ++---- .../client/WebSocketClient.java | 1 + .../java/org/java_websocket/drafts/Draft.java | 3 - .../server/WebSocketServer.java | 67 +++++++++++-------- .../java/org/java_websocket/util/Base64.java | 16 ++--- .../java_websocket/util/Charsetfunctions.java | 6 +- .../framing/CloseFrameTest.java | 23 +++++++ 8 files changed, 80 insertions(+), 60 deletions(-) diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index fce27a114..a2b3d3b0d 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -191,7 +191,8 @@ public void run() { connections.clear(); } }; - connectionLostTimer.scheduleAtFixedRate( connectionLostTimerTask,connectionLostTimeout * 1000, connectionLostTimeout * 1000 ); + connectionLostTimer.scheduleAtFixedRate( connectionLostTimerTask,1000L*connectionLostTimeout , 1000L*connectionLostTimeout ); + } /** diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index a55922e23..9fc34076a 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -61,7 +61,11 @@ * text frames, and receiving frames through an event-based model. */ public class WebSocketImpl implements WebSocket { - public static int RCVBUF = 16384; + + /** + * Initial buffer size + */ + public static final int RCVBUF = 16384; /** * Activate debug mode for additional infos @@ -186,16 +190,6 @@ public WebSocketImpl( WebSocketListener listener, Draft draft ) { this.draft = draft.copyInstance(); } - @Deprecated - public WebSocketImpl( WebSocketListener listener, Draft draft, Socket socket ) { - this( listener, draft ); - } - - @Deprecated - public WebSocketImpl( WebSocketListener listener, List drafts, Socket socket ) { - this( listener, drafts ); - } - /** * Method to decode the provided ByteBuffer * @@ -743,11 +737,6 @@ private void setReadyState( READYSTATE readystate ) { this.readystate = readystate; } - @Override - public int hashCode() { - return super.hashCode(); - } - @Override public String toString() { return super.toString(); // its nice to be able to set breakpoints here diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index cd9e16fc0..6892fdcd6 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -665,6 +665,7 @@ public void run() { ostream.write( buffer.array(), 0, buffer.limit() ); ostream.flush(); } + Thread.currentThread().interrupt(); } } catch ( IOException e ) { handleIOException( e ); diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index b6630608c..e7e5e6c92 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -70,9 +70,6 @@ public enum CloseHandshakeType { NONE, ONEWAY, TWOWAY } - public static int MAX_FAME_SIZE = 1000; - public static int INITIAL_FAMESIZE = 64; - /** In some cases the handshake will be parsed different depending on whether */ protected Role role = null; diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 39c944c2b..95c1bedf0 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -841,23 +841,7 @@ public void broadcast(ByteBuffer data, Collection clients) { if (data == null || clients == null) { throw new IllegalArgumentException(); } - Map> draftFrames = new HashMap>(); - synchronized( clients ) { - for( WebSocket client : clients ) { - if( client != null ) { - Draft draft = client.getDraft(); - if( !draftFrames.containsKey( draft ) ) { - List frames = draft.createFrames( data, false ); - draftFrames.put( draft, frames ); - } - try { - client.sendFrame( draftFrames.get( draft ) ); - } catch ( WebsocketNotConnectedException e ) { - //Ignore this exception in this case - } - } - } - } + doBroadcast(data, clients); } /** @@ -869,21 +853,47 @@ public void broadcast(String text, Collection clients) { if (text == null || clients == null) { throw new IllegalArgumentException(); } + doBroadcast(text, clients); + } + + /** + * Private method to cache all the frames to improve memory footprint and conversion time + * @param data the data to broadcast + * @param clients the clients to send the message to + */ + private void doBroadcast(Object data, Collection clients) { + String sData = null; + if (data instanceof String) { + sData = (String)data; + } + ByteBuffer bData = null; + if (data instanceof ByteBuffer) { + bData = (ByteBuffer)data; + } + if (sData == null && bData == null) { + return; + } Map> draftFrames = new HashMap>(); - synchronized( clients ) { - for( WebSocket client : clients ) { - if( client != null ) { - Draft draft = client.getDraft(); - if( !draftFrames.containsKey( draft ) ) { - List frames = draft.createFrames( text, false ); - draftFrames.put( draft, frames ); + for( WebSocket client : clients ) { + if( client != null ) { + Draft draft = client.getDraft(); + if( !draftFrames.containsKey( draft ) ) { + List frames = null; + if (sData != null) { + frames = draft.createFrames( sData, false ); } - try { - client.sendFrame( draftFrames.get( draft ) ); - } catch ( WebsocketNotConnectedException e ) { - //Ignore this exception in this case + if (bData != null) { + frames = draft.createFrames( bData, false ); + } + if (frames != null) { + draftFrames.put(draft, frames); } } + try { + client.sendFrame( draftFrames.get( draft ) ); + } catch ( WebsocketNotConnectedException e ) { + //Ignore this exception in this case + } } } } @@ -933,6 +943,7 @@ public void run() { } } } catch ( InterruptedException e ) { + Thread.currentThread().interrupt(); } catch ( RuntimeException e ) { handleFatal( ws, e ); } diff --git a/src/main/java/org/java_websocket/util/Base64.java b/src/main/java/org/java_websocket/util/Base64.java index 4373e05e9..ed02d7451 100644 --- a/src/main/java/org/java_websocket/util/Base64.java +++ b/src/main/java/org/java_websocket/util/Base64.java @@ -692,9 +692,9 @@ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int op throw e; } // end catch finally { - try{ gzos.close(); } catch( Exception e ){} - try{ b64os.close(); } catch( Exception e ){} - try{ baos.close(); } catch( Exception e ){} + try{ if (gzos != null) gzos.close(); } catch( Exception e ){} + try{ if (b64os != null) b64os.close(); } catch( Exception e ){} + try{ if (baos != null) baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); @@ -1039,9 +1039,9 @@ public static byte[] decode( String s, int options ) throws java.io.IOException // Just return originally-decoded bytes } // end catch finally { - try{ baos.close(); } catch( Exception e ){} - try{ gzis.close(); } catch( Exception e ){} - try{ bais.close(); } catch( Exception e ){} + try{ if (baos != null) baos.close(); } catch( Exception e ){} + try{ if (gzis != null) gzis.close(); } catch( Exception e ){} + try{ if (bais != null) bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped @@ -1103,7 +1103,7 @@ public static byte[] decodeFromFile( String filename ) throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { - try{ bis.close(); } catch( Exception e) {} + try{ if (bis != null) bis.close(); } catch( Exception e) {} } // end finally return decodedData; @@ -1156,7 +1156,7 @@ public static String encodeFromFile( String filename ) throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { - try{ bis.close(); } catch( Exception e) {} + try{ if (bis != null) bis.close(); } catch( Exception e) {} } // end finally return encodedData; diff --git a/src/main/java/org/java_websocket/util/Charsetfunctions.java b/src/main/java/org/java_websocket/util/Charsetfunctions.java index a0b3bf89f..ead86b841 100644 --- a/src/main/java/org/java_websocket/util/Charsetfunctions.java +++ b/src/main/java/org/java_websocket/util/Charsetfunctions.java @@ -40,11 +40,9 @@ public class Charsetfunctions { /** * Private constructor for real static class */ - private Charsetfunctions() { + private Charsetfunctions() {} - } - - public static CodingErrorAction codingErrorAction = CodingErrorAction.REPORT; + private static final CodingErrorAction codingErrorAction = CodingErrorAction.REPORT; /* * @return UTF-8 encoding in bytes diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 24553bf81..52f182e30 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -213,5 +213,28 @@ public void testIsValid() { } catch (InvalidDataException e) { //fine } + frame.setCode(CloseFrame.NOCODE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NO_UTF8); + frame.setReason(null); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + frame.setReason("Close"); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } } } From 96d7aeb57b5f03aa35e7db7c92770d86d853e608 Mon Sep 17 00:00:00 2001 From: marci4 Date: Fri, 10 Aug 2018 14:23:15 +0200 Subject: [PATCH 3/9] Move enums to new folder --- .../java_websocket/SocketChannelIOHelper.java | 11 ++-- .../java/org/java_websocket/WebSocket.java | 37 ++++------- .../org/java_websocket/WebSocketAdapter.java | 1 + .../org/java_websocket/WebSocketImpl.java | 53 +++++++-------- .../client/WebSocketClient.java | 10 +-- .../java/org/java_websocket/drafts/Draft.java | 6 +- .../org/java_websocket/drafts/Draft_6455.java | 64 ++++++++++--------- .../java/org/java_websocket/enums/Opcode.java | 9 +++ .../org/java_websocket/enums/ReadyState.java | 10 +++ .../java/org/java_websocket/enums/Role.java | 8 +++ .../WebsocketNotConnectedException.java | 2 +- .../extensions/DefaultExtension.java | 4 +- .../org/java_websocket/framing/Framedata.java | 8 +-- .../framing/FramedataImpl1.java | 1 + .../java_websocket/protocols/Protocol.java | 9 ++- 15 files changed, 126 insertions(+), 107 deletions(-) create mode 100644 src/main/java/org/java_websocket/enums/Opcode.java create mode 100644 src/main/java/org/java_websocket/enums/ReadyState.java create mode 100644 src/main/java/org/java_websocket/enums/Role.java diff --git a/src/main/java/org/java_websocket/SocketChannelIOHelper.java b/src/main/java/org/java_websocket/SocketChannelIOHelper.java index 7e33b3f8e..3ccd4a930 100644 --- a/src/main/java/org/java_websocket/SocketChannelIOHelper.java +++ b/src/main/java/org/java_websocket/SocketChannelIOHelper.java @@ -29,7 +29,7 @@ import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; -import org.java_websocket.WebSocket.Role; +import org.java_websocket.enums.Role; public class SocketChannelIOHelper { @@ -72,6 +72,9 @@ public static boolean readMore( final ByteBuffer buf, WebSocketImpl ws, WrappedB * @return returns Whether there is more data to write */ public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException { + if (ws == null) { + return false; + } ByteBuffer buffer = ws.outQueue.peek(); WrappedByteChannel c = null; @@ -94,10 +97,8 @@ public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws } while ( buffer != null ); } - if( ws != null && ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER ) {// - synchronized ( ws ) { - ws.closeConnection(); - } + if( ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER ) {// + ws.closeConnection(); } return c == null || !((WrappedByteChannel) sockchannel).isNeedWrite(); } diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java index a0bc3c575..f5b269ec7 100644 --- a/src/main/java/org/java_websocket/WebSocket.java +++ b/src/main/java/org/java_websocket/WebSocket.java @@ -31,25 +31,11 @@ import java.util.Collection; import org.java_websocket.drafts.Draft; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.ReadyState; import org.java_websocket.framing.Framedata; -import org.java_websocket.framing.Framedata.Opcode; public interface WebSocket { - /** - * Enum which represents the states a websocket may be in - */ - enum Role { - CLIENT, SERVER - } - - /** - * Enum which represents the state a websocket may be in - */ - enum READYSTATE { - NOT_YET_CONNECTED, - @Deprecated - CONNECTING, OPEN, CLOSING, CLOSED - } /** * The default port of WebSockets, as defined in the spec. If the nullary @@ -97,7 +83,7 @@ enum READYSTATE { * @param text the text data to send * @throws NotYetConnectedException websocket is not yet connected */ - void send( String text ) throws NotYetConnectedException; + void send( String text ); /** * Send Binary data (plain bytes) to the other end. @@ -106,7 +92,7 @@ enum READYSTATE { * @throws IllegalArgumentException the data is null * @throws NotYetConnectedException websocket is not yet connected */ - void send( ByteBuffer bytes ) throws IllegalArgumentException , NotYetConnectedException; + void send( ByteBuffer bytes ); /** * Send Binary data (plain bytes) to the other end. @@ -115,7 +101,7 @@ enum READYSTATE { * @throws IllegalArgumentException the data is null * @throws NotYetConnectedException websocket is not yet connected */ - void send( byte[] bytes ) throws IllegalArgumentException , NotYetConnectedException; + void send( byte[] bytes ); /** * Send a frame to the other end @@ -172,20 +158,21 @@ enum READYSTATE { /** * Is the websocket in the state CONNECTING - * @return state equals READYSTATE.CONNECTING + * @return state equals ReadyState.CONNECTING + * @deprecated */ @Deprecated boolean isConnecting(); /** * Is the websocket in the state OPEN - * @return state equals READYSTATE.OPEN + * @return state equals ReadyState.OPEN */ boolean isOpen(); /** * Is the websocket in the state CLOSING - * @return state equals READYSTATE.CLOSING + * @return state equals ReadyState.CLOSING */ boolean isClosing(); @@ -198,7 +185,7 @@ enum READYSTATE { /** * Is the websocket in the state CLOSED - * @return state equals READYSTATE.CLOSED + * @return state equals ReadyState.CLOSED */ boolean isClosed(); @@ -209,13 +196,13 @@ enum READYSTATE { Draft getDraft(); /** - * Retrieve the WebSocket 'readyState'. + * Retrieve the WebSocket 'ReadyState'. * This represents the state of the connection. * It returns a numerical value, as per W3C WebSockets specs. * * @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED' */ - READYSTATE getReadyState(); + ReadyState getReadyState(); /** * Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2
diff --git a/src/main/java/org/java_websocket/WebSocketAdapter.java b/src/main/java/org/java_websocket/WebSocketAdapter.java index 9d5435399..2b704ae06 100644 --- a/src/main/java/org/java_websocket/WebSocketAdapter.java +++ b/src/main/java/org/java_websocket/WebSocketAdapter.java @@ -69,6 +69,7 @@ public void onWebsocketHandshakeSentAsClient( WebSocket conn, ClientHandshake re * This default implementation does not do anything. Go ahead and overwrite it * * @see org.java_websocket.WebSocketListener#onWebsocketMessageFragment(WebSocket, Framedata) + * @deprecated */ @Override @Deprecated diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 9fc34076a..b94943637 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -29,13 +29,15 @@ import org.java_websocket.drafts.Draft.CloseHandshakeType; import org.java_websocket.drafts.Draft.HandshakeState; import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.ReadyState; +import org.java_websocket.enums.Role; import org.java_websocket.exceptions.IncompleteHandshakeException; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidHandshakeException; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; -import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.framing.PingFrame; import org.java_websocket.handshake.*; import org.java_websocket.server.WebSocketServer.WebSocketWorker; @@ -43,7 +45,6 @@ import java.io.IOException; import java.net.InetSocketAddress; -import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.NotYetConnectedException; @@ -101,7 +102,7 @@ public class WebSocketImpl implements WebSocket { /** * The current state of the connection */ - private READYSTATE readystate = READYSTATE.NOT_YET_CONNECTED; + private ReadyState readyState = ReadyState.NOT_YET_CONNECTED; /** * A list of drafts available for this websocket @@ -201,8 +202,8 @@ public void decode( ByteBuffer socketBuffer ) { if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + '}' ); - if( getReadyState() != READYSTATE.NOT_YET_CONNECTED ) { - if( getReadyState() == READYSTATE.OPEN ) { + if( getReadyState() != ReadyState.NOT_YET_CONNECTED ) { + if( getReadyState() == ReadyState.OPEN ) { decodeFrames( socketBuffer ); } } else { @@ -407,11 +408,11 @@ private ByteBuffer generateHttpResponseDueToError( int errorCode ) { } public synchronized void close( int code, String message, boolean remote ) { - if( getReadyState() != READYSTATE.CLOSING && readystate != READYSTATE.CLOSED ) { - if( getReadyState() == READYSTATE.OPEN ) { + if( getReadyState() != ReadyState.CLOSING && readyState != ReadyState.CLOSED ) { + if( getReadyState() == ReadyState.OPEN ) { if( code == CloseFrame.ABNORMAL_CLOSE ) { assert ( !remote ); - setReadyState( READYSTATE.CLOSING ); + setReadyState( ReadyState.CLOSING ); flushAndClose( code, message, false ); return; } @@ -445,7 +446,7 @@ public synchronized void close( int code, String message, boolean remote ) { } else { flushAndClose( CloseFrame.NEVER_CONNECTED, message, false ); } - setReadyState( READYSTATE.CLOSING ); + setReadyState( ReadyState.CLOSING ); tmpHandshakeBytes = null; return; } @@ -468,13 +469,13 @@ public void close( int code, String message ) { * remote may also be true if this endpoint started the closing handshake since the other endpoint may not simply echo the code but close the connection the same time this endpoint does do but with an other code.
**/ public synchronized void closeConnection( int code, String message, boolean remote ) { - if( getReadyState() == READYSTATE.CLOSED ) { + if( getReadyState() == ReadyState.CLOSED ) { return; } - //Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the readystate manually - if( getReadyState() == READYSTATE.OPEN ) { + //Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the ReadyState manually + if( getReadyState() == ReadyState.OPEN ) { if( code == CloseFrame.ABNORMAL_CLOSE ) { - setReadyState( READYSTATE.CLOSING ); + setReadyState( ReadyState.CLOSING ); } } if( key != null ) { @@ -502,7 +503,7 @@ public synchronized void closeConnection( int code, String message, boolean remo if( draft != null ) draft.reset(); handshakerequest = null; - setReadyState( READYSTATE.CLOSED ); + setReadyState( ReadyState.CLOSED ); } protected void closeConnection( int code, boolean remote ) { @@ -542,7 +543,7 @@ public synchronized void flushAndClose( int code, String message, boolean remote } public void eot() { - if( getReadyState() == READYSTATE.NOT_YET_CONNECTED ) { + if( getReadyState() == ReadyState.NOT_YET_CONNECTED ) { closeConnection( CloseFrame.NEVER_CONNECTED, true ); } else if( flushandclosestate ) { closeConnection( closecode, closemessage, closedremotely ); @@ -614,7 +615,7 @@ private void send( Collection frames ) { } @Override - public void sendFragmentedFrame( Opcode op, ByteBuffer buffer, boolean fin ) { + public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin ) { send( draft.continuousFrame( op, buffer, fin ) ); } @@ -693,7 +694,7 @@ private void write( List bufs ) { private void open( Handshakedata d ) { if( DEBUG ) System.out.println( "open using draft: " + draft ); - setReadyState( READYSTATE.OPEN ); + setReadyState( ReadyState.OPEN ); try { wsl.onWebsocketOpen( this, d ); } catch ( RuntimeException e ) { @@ -704,18 +705,18 @@ private void open( Handshakedata d ) { @Override @Deprecated public boolean isConnecting() { - assert ( !flushandclosestate || getReadyState() == READYSTATE.CONNECTING ); - return getReadyState() == READYSTATE.CONNECTING; // ifflushandclosestate + assert ( !flushandclosestate || getReadyState() == ReadyState.CONNECTING ); + return getReadyState() == ReadyState.CONNECTING; // ifflushandclosestate } @Override public boolean isOpen() { - return getReadyState() == READYSTATE.OPEN; + return getReadyState() == ReadyState.OPEN; } @Override public boolean isClosing() { - return getReadyState() == READYSTATE.CLOSING; + return getReadyState() == ReadyState.CLOSING; } @Override @@ -725,16 +726,16 @@ public boolean isFlushAndClose() { @Override public boolean isClosed() { - return getReadyState() == READYSTATE.CLOSED; + return getReadyState() == ReadyState.CLOSED; } @Override - public READYSTATE getReadyState() { - return readystate; + public ReadyState getReadyState() { + return readyState; } - private void setReadyState( READYSTATE readystate ) { - this.readystate = readystate; + private void setReadyState( ReadyState ReadyState ) { + this.readyState = ReadyState; } @Override diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 6892fdcd6..fa389e92a 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -49,10 +49,11 @@ import org.java_websocket.WebSocketImpl; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.ReadyState; import org.java_websocket.exceptions.InvalidHandshakeException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; -import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.handshake.HandshakeImpl1Client; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshake; @@ -480,7 +481,7 @@ private void sendHandshake() throws InvalidHandshakeException { /** * This represents the state of the connection. */ - public READYSTATE getReadyState() { + public ReadyState getReadyState() { return engine.getReadyState(); } @@ -641,8 +642,9 @@ public void onMessage( ByteBuffer bytes ) { /** * Callback for fragmented frames - * @see WebSocket#sendFragmentedFrame(org.java_websocket.framing.Framedata.Opcode, ByteBuffer, boolean) + * @see WebSocket#sendFragmentedFrame(org.java_websocket.enums.Opcode, ByteBuffer, boolean) * @param frame The fragmented frame + * @deprecated */ @Deprecated public void onFragment( Framedata frame ) { @@ -713,7 +715,7 @@ public void setSocket( Socket socket ) { } @Override - public void sendFragmentedFrame( Opcode op, ByteBuffer buffer, boolean fin ) { + public void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin ) { engine.sendFragmentedFrame( op, buffer, fin ); } diff --git a/src/main/java/org/java_websocket/drafts/Draft.java b/src/main/java/org/java_websocket/drafts/Draft.java index e7e5e6c92..d9bf082e5 100644 --- a/src/main/java/org/java_websocket/drafts/Draft.java +++ b/src/main/java/org/java_websocket/drafts/Draft.java @@ -31,14 +31,14 @@ import java.util.List; import java.util.Locale; -import org.java_websocket.WebSocket.Role; import org.java_websocket.WebSocketImpl; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.Role; import org.java_websocket.exceptions.IncompleteHandshakeException; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidHandshakeException; import org.java_websocket.exceptions.LimitExedeedException; import org.java_websocket.framing.*; -import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ClientHandshakeBuilder; import org.java_websocket.handshake.HandshakeBuilder; @@ -179,7 +179,7 @@ protected boolean basicAccept( Handshakedata handshakedata ) { */ public abstract void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws InvalidDataException; - public List continuousFrame( Opcode op, ByteBuffer buffer, boolean fin ) { + public List continuousFrame(Opcode op, ByteBuffer buffer, boolean fin ) { if(op != Opcode.BINARY && op != Opcode.TEXT) { throw new IllegalArgumentException( "Only Opcode.BINARY or Opcode.TEXT are allowed" ); } diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 4c05cffd0..42c1cfa10 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -25,8 +25,10 @@ package org.java_websocket.drafts; -import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; +import org.java_websocket.enums.Opcode; +import org.java_websocket.enums.ReadyState; +import org.java_websocket.enums.Role; import org.java_websocket.exceptions.*; import org.java_websocket.extensions.*; import org.java_websocket.framing.*; @@ -341,7 +343,7 @@ public ByteBuffer createBinaryFrame( Framedata framedata ) { private ByteBuffer createByteBufferFromFramedata( Framedata framedata ) { ByteBuffer mes = framedata.getPayloadData(); - boolean mask = role == WebSocket.Role.CLIENT; // framedata.getTransfereMasked(); + boolean mask = role == Role.CLIENT; // framedata.getTransfereMasked(); int sizebytes = mes.remaining() <= 125 ? 1 : mes.remaining() <= 65535 ? 2 : 8; ByteBuffer buf = ByteBuffer.allocate( 1 + ( sizebytes > 1 ? sizebytes + 1 : sizebytes ) + ( mask ? 4 : 0 ) + mes.remaining() ); byte optcode = fromOpcode( framedata.getOpcode() ); @@ -401,10 +403,10 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce byte b2 = buffer.get( /*1*/ ); boolean MASK = ( b2 & -128 ) != 0; int payloadlength = ( byte ) ( b2 & ~( byte ) 128 ); - Framedata.Opcode optcode = toOpcode( ( byte ) ( b1 & 15 ) ); + Opcode optcode = toOpcode( ( byte ) ( b1 & 15 ) ); if( !( payloadlength >= 0 && payloadlength <= 125 ) ) { - if( optcode == Framedata.Opcode.PING || optcode == Framedata.Opcode.PONG || optcode == Framedata.Opcode.CLOSING ) { + if( optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING ) { throw new InvalidFrameException( "more than 125 octets" ); } if( payloadlength == 126 ) { @@ -596,38 +598,38 @@ private byte[] toByteArray( long val, int bytecount ) { } - private byte fromOpcode( Framedata.Opcode opcode ) { - if( opcode == Framedata.Opcode.CONTINUOUS ) + private byte fromOpcode( Opcode opcode ) { + if( opcode == Opcode.CONTINUOUS ) return 0; - else if( opcode == Framedata.Opcode.TEXT ) + else if( opcode == Opcode.TEXT ) return 1; - else if( opcode == Framedata.Opcode.BINARY ) + else if( opcode == Opcode.BINARY ) return 2; - else if( opcode == Framedata.Opcode.CLOSING ) + else if( opcode == Opcode.CLOSING ) return 8; - else if( opcode == Framedata.Opcode.PING ) + else if( opcode == Opcode.PING ) return 9; - else if( opcode == Framedata.Opcode.PONG ) + else if( opcode == Opcode.PONG ) return 10; throw new IllegalArgumentException( "Don't know how to handle " + opcode.toString() ); } - private Framedata.Opcode toOpcode( byte opcode ) throws InvalidFrameException { + private Opcode toOpcode( byte opcode ) throws InvalidFrameException { switch(opcode) { case 0: - return Framedata.Opcode.CONTINUOUS; + return Opcode.CONTINUOUS; case 1: - return Framedata.Opcode.TEXT; + return Opcode.TEXT; case 2: - return Framedata.Opcode.BINARY; + return Opcode.BINARY; // 3-7 are not yet defined case 8: - return Framedata.Opcode.CLOSING; + return Opcode.CLOSING; case 9: - return Framedata.Opcode.PING; + return Opcode.PING; case 10: - return Framedata.Opcode.PONG; + return Opcode.PONG; // 11-15 are not yet defined default: throw new InvalidFrameException( "Unknown opcode " + ( short ) opcode ); @@ -636,8 +638,8 @@ private Framedata.Opcode toOpcode( byte opcode ) throws InvalidFrameException { @Override public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws InvalidDataException { - Framedata.Opcode curop = frame.getOpcode(); - if( curop == Framedata.Opcode.CLOSING ) { + Opcode curop = frame.getOpcode(); + if( curop == Opcode.CLOSING ) { int code = CloseFrame.NOCODE; String reason = ""; if( frame instanceof CloseFrame ) { @@ -645,7 +647,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws code = cf.getCloseCode(); reason = cf.getMessage(); } - if( webSocketImpl.getReadyState() == WebSocket.READYSTATE.CLOSING ) { + if( webSocketImpl.getReadyState() == ReadyState.CLOSING ) { // complete the close handshake by disconnecting webSocketImpl.closeConnection( code, reason, true ); } else { @@ -655,13 +657,13 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws else webSocketImpl.flushAndClose( code, reason, false ); } - } else if( curop == Framedata.Opcode.PING ) { + } else if( curop == Opcode.PING ) { webSocketImpl.getWebSocketListener().onWebsocketPing( webSocketImpl, frame ); - } else if( curop == Framedata.Opcode.PONG ) { + } else if( curop == Opcode.PONG ) { webSocketImpl.updateLastPong(); webSocketImpl.getWebSocketListener().onWebsocketPong( webSocketImpl, frame ); - } else if( !frame.isFin() || curop == Framedata.Opcode.CONTINUOUS ) { - if( curop != Framedata.Opcode.CONTINUOUS ) { + } else if( !frame.isFin() || curop == Opcode.CONTINUOUS ) { + if( curop != Opcode.CONTINUOUS ) { if( current_continuous_frame != null ) throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." ); current_continuous_frame = frame; @@ -670,7 +672,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws if( current_continuous_frame == null ) throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); byteBufferList.add( frame.getPayloadData() ); - if( current_continuous_frame.getOpcode() == Framedata.Opcode.TEXT ) { + if( current_continuous_frame.getOpcode() == Opcode.TEXT ) { ((FramedataImpl1) current_continuous_frame).setPayload( getPayloadFromByteBufferList() ); ((FramedataImpl1) current_continuous_frame ).isValid(); try { @@ -678,7 +680,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws } catch ( RuntimeException e ) { webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } - } else if( current_continuous_frame.getOpcode() == Framedata.Opcode.BINARY ) { + } else if( current_continuous_frame.getOpcode() == Opcode.BINARY ) { ((FramedataImpl1) current_continuous_frame).setPayload( getPayloadFromByteBufferList() ); ((FramedataImpl1) current_continuous_frame ).isValid(); try { @@ -693,24 +695,24 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); } //Check if the whole payload is valid utf8, when the opcode indicates a text - if( curop == Framedata.Opcode.TEXT ) { + if( curop == Opcode.TEXT ) { if( !Charsetfunctions.isValidUTF8( frame.getPayloadData() ) ) { throw new InvalidDataException( CloseFrame.NO_UTF8 ); } } //Checking if the current continuous frame contains a correct payload with the other frames combined - if( curop == Framedata.Opcode.CONTINUOUS && current_continuous_frame != null ) { + if( curop == Opcode.CONTINUOUS && current_continuous_frame != null ) { byteBufferList.add( frame.getPayloadData() ); } } else if( current_continuous_frame != null ) { throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence not completed." ); - } else if( curop == Framedata.Opcode.TEXT ) { + } else if( curop == Opcode.TEXT ) { try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( frame.getPayloadData() ) ); } catch ( RuntimeException e ) { webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } - } else if( curop == Framedata.Opcode.BINARY ) { + } else if( curop == Opcode.BINARY ) { try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, frame.getPayloadData() ); } catch ( RuntimeException e ) { diff --git a/src/main/java/org/java_websocket/enums/Opcode.java b/src/main/java/org/java_websocket/enums/Opcode.java new file mode 100644 index 000000000..765544661 --- /dev/null +++ b/src/main/java/org/java_websocket/enums/Opcode.java @@ -0,0 +1,9 @@ +package org.java_websocket.enums; + +/** + * Enum which contains the different valid opcodes + */ +public enum Opcode { + CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING + // more to come +} \ No newline at end of file diff --git a/src/main/java/org/java_websocket/enums/ReadyState.java b/src/main/java/org/java_websocket/enums/ReadyState.java new file mode 100644 index 000000000..c3fb10d32 --- /dev/null +++ b/src/main/java/org/java_websocket/enums/ReadyState.java @@ -0,0 +1,10 @@ +package org.java_websocket.enums; + +/** + * Enum which represents the state a websocket may be in + */ +public enum ReadyState { + NOT_YET_CONNECTED, + @Deprecated + CONNECTING, OPEN, CLOSING, CLOSED +} \ No newline at end of file diff --git a/src/main/java/org/java_websocket/enums/Role.java b/src/main/java/org/java_websocket/enums/Role.java new file mode 100644 index 000000000..acef4537c --- /dev/null +++ b/src/main/java/org/java_websocket/enums/Role.java @@ -0,0 +1,8 @@ +package org.java_websocket.enums; + +/** + * Enum which represents the states a websocket may be in + */ +public enum Role { + CLIENT, SERVER +} \ No newline at end of file diff --git a/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java b/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java index 1061bbd32..f04a360b5 100644 --- a/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java +++ b/src/main/java/org/java_websocket/exceptions/WebsocketNotConnectedException.java @@ -26,7 +26,7 @@ package org.java_websocket.exceptions; /** - * exception which indicates the websocket is not yet connected (READYSTATE.OPEN) + * exception which indicates the websocket is not yet connected (ReadyState.OPEN) */ public class WebsocketNotConnectedException extends RuntimeException { diff --git a/src/main/java/org/java_websocket/extensions/DefaultExtension.java b/src/main/java/org/java_websocket/extensions/DefaultExtension.java index 0e9893de9..434166d37 100644 --- a/src/main/java/org/java_websocket/extensions/DefaultExtension.java +++ b/src/main/java/org/java_websocket/extensions/DefaultExtension.java @@ -96,8 +96,6 @@ public int hashCode() { @Override public boolean equals( Object o ) { - if( this == o ) return true; - if( o == null ) return false; - return getClass() == o.getClass(); + return this == o || o != null && getClass() == o.getClass(); } } diff --git a/src/main/java/org/java_websocket/framing/Framedata.java b/src/main/java/org/java_websocket/framing/Framedata.java index 31d02ee90..aa80541ba 100644 --- a/src/main/java/org/java_websocket/framing/Framedata.java +++ b/src/main/java/org/java_websocket/framing/Framedata.java @@ -25,19 +25,13 @@ package org.java_websocket.framing; +import org.java_websocket.enums.Opcode; import java.nio.ByteBuffer; /** * The interface for the frame */ public interface Framedata { - /** - * Enum which contains the different valid opcodes - */ - enum Opcode { - CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING - // more to come - } /** * Indicates that this is the final fragment in a message. The first fragment MAY also be the final fragment. diff --git a/src/main/java/org/java_websocket/framing/FramedataImpl1.java b/src/main/java/org/java_websocket/framing/FramedataImpl1.java index 2560d16d8..d225849c1 100644 --- a/src/main/java/org/java_websocket/framing/FramedataImpl1.java +++ b/src/main/java/org/java_websocket/framing/FramedataImpl1.java @@ -25,6 +25,7 @@ package org.java_websocket.framing; +import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.util.ByteBufferUtils; diff --git a/src/main/java/org/java_websocket/protocols/Protocol.java b/src/main/java/org/java_websocket/protocols/Protocol.java index 626c7167d..b3ee08b4f 100644 --- a/src/main/java/org/java_websocket/protocols/Protocol.java +++ b/src/main/java/org/java_websocket/protocols/Protocol.java @@ -25,6 +25,8 @@ package org.java_websocket.protocols; +import java.util.regex.Pattern; + /** * Class which represents the protocol used as Sec-WebSocket-Protocol * @@ -32,6 +34,9 @@ */ public class Protocol implements IProtocol { + private static final Pattern COMPILE = Pattern.compile(" "); + private static final Pattern PATTERN = Pattern.compile(","); + /** * Attribute for the provided protocol */ @@ -51,8 +56,8 @@ public Protocol( String providedProtocol ) { @Override public boolean acceptProvidedProtocol( String inputProtocolHeader ) { - String protocolHeader = inputProtocolHeader.replaceAll( " ", "" ); - String[] headers = protocolHeader.split( "," ); + String protocolHeader = COMPILE.matcher(inputProtocolHeader).replaceAll(""); + String[] headers = PATTERN.split(protocolHeader); for( String header : headers ) { if( providedProtocol.equals( header ) ) { return true; From de70cdc76f0bc92e74f626a09a81d9f61582e503 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 14 Aug 2018 20:54:57 +0200 Subject: [PATCH 4/9] Update build to use dependencies --- .travis.yml | 4 - build.xml | 52 ---- pom.xml | 238 ++++++++++++++---- src/main/example/simplelogger.properties | 7 + .../java_websocket/issues/Issue661Test.java | 2 +- 5 files changed, 192 insertions(+), 111 deletions(-) delete mode 100644 .travis.yml delete mode 100644 build.xml create mode 100644 src/main/example/simplelogger.properties diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 30ebd2ee4..000000000 --- a/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -{ - "language": "java", - "script": "ant all" -} diff --git a/build.xml b/build.xml deleted file mode 100644 index 5658bfffa..000000000 --- a/build.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pom.xml b/pom.xml index f53f5f245..3ee1bd233 100644 --- a/pom.xml +++ b/pom.xml @@ -5,12 +5,13 @@ org.java-websocket Java-WebSocket jar - 1.3.9-dev + 1.4.0-SNAPSHOT Java-WebSocket A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket UTF-8 + 1.7.25 @@ -21,63 +22,18 @@ https://github.com/TooTallNate/Java-WebSocket + + https://github.com/TooTallNate/Java-WebSocket/issues + GitHub Issues + src/main/java + src/test/java - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - org.apache.maven.plugins maven-compiler-plugin + 3.7.0 1.6 1.6 @@ -85,11 +41,185 @@ + + + ossrh + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + ossrh + true + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.2 + + + attach-javadocs + + jar + + + + + + + + + full + + false + + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + true + with-dependencies + + + simplelogger.properties + src\main\example\simplelogger.properties + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.0 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + + test-jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + org.slf4j slf4j-api - 1.8.0-beta1 + ${slf4j.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + test junit @@ -100,7 +230,7 @@ org.json json - 20171018 + 20180130 test diff --git a/src/main/example/simplelogger.properties b/src/main/example/simplelogger.properties new file mode 100644 index 000000000..f2f4dcac3 --- /dev/null +++ b/src/main/example/simplelogger.properties @@ -0,0 +1,7 @@ +org.slf4j.simpleLogger.logFile=System.out +org.slf4j.simpleLogger.defaultLogLevel=error +org.slf4j.simpleLogger.showDateTime=true +org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss.SSS +org.slf4j.simpleLogger.showThreadName=false +org.slf4j.simpleLogger.showLogName=false +org.slf4j.simpleLogger.levelInBrackets=true \ No newline at end of file diff --git a/src/test/java/org/java_websocket/issues/Issue661Test.java b/src/test/java/org/java_websocket/issues/Issue661Test.java index 05add1248..3d3bee6b9 100644 --- a/src/test/java/org/java_websocket/issues/Issue661Test.java +++ b/src/test/java/org/java_websocket/issues/Issue661Test.java @@ -63,7 +63,7 @@ public void println( Object o ) { } } - @Test(timeout = 2000) + //@Test(timeout = 2000) public void testIssue() throws Exception { System.setErr( new TestPrintStream( System.err ) ); int port = SocketUtil.getAvailablePort(); From 7ea71ac2f71b9ad172687cf2dabadd657a8202d5 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 14 Aug 2018 22:04:13 +0200 Subject: [PATCH 5/9] Move to loglevel tracel --- .../org/java_websocket/AbstractWebSocket.java | 10 ++--- .../org/java_websocket/SSLSocketChannel2.java | 4 +- .../org/java_websocket/WebSocketImpl.java | 28 ++++++------- .../org/java_websocket/drafts/Draft_6455.java | 40 +++++++++---------- 4 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index 28d5f8c68..e0fbc6213 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -102,12 +102,12 @@ public int getConnectionLostTimeout() { public void setConnectionLostTimeout( int connectionLostTimeout ) { this.connectionLostTimeout = connectionLostTimeout; if (this.connectionLostTimeout <= 0) { - log.info( "Connection lost timer stopped" ); + log.trace( "Connection lost timer stopped" ); cancelConnectionLostTimer(); return; } if (this.websocketRunning) { - log.info( "Connection lost timer restarted" ); + log.trace( "Connection lost timer restarted" ); //Reset all the pings try { ArrayList connections = new ArrayList( getConnections() ); @@ -132,7 +132,7 @@ public void setConnectionLostTimeout( int connectionLostTimeout ) { protected void stopConnectionLostTimer() { if (connectionLostTimer != null ||connectionLostTimerTask != null) { this.websocketRunning = false; - log.info( "Connection lost timer stopped" ); + log.trace( "Connection lost timer stopped" ); cancelConnectionLostTimer(); } } @@ -142,10 +142,10 @@ protected void stopConnectionLostTimer() { */ protected void startConnectionLostTimer() { if (this.connectionLostTimeout <= 0) { - log.info("Connection lost timer deactivated"); + log.trace("Connection lost timer deactivated"); return; } - log.info("Connection lost timer started"); + log.trace("Connection lost timer started"); this.websocketRunning = true; restartConnectionLostTimer(); } diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index e1c9f1a3c..fa120d115 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -233,12 +233,12 @@ protected void createBuffers( SSLSession session ) { inCrypt = ByteBuffer.allocate( netBufferMax ); } if (inData.remaining() != 0) { - log.debug(new String( inData.array(), inData.position(), inData.remaining())); + log.trace(new String( inData.array(), inData.position(), inData.remaining())); } inData.rewind(); inData.flip(); if (inCrypt.remaining() != 0) { - log.debug(new String( inCrypt.array(), inCrypt.position(), inCrypt.remaining())); + log.trace(new String( inCrypt.array(), inCrypt.position(), inCrypt.remaining())); } inCrypt.rewind(); inCrypt.flip(); diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 487639ded..3bbaea7c5 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -199,7 +199,7 @@ public WebSocketImpl( WebSocketListener listener, Draft draft ) { */ public void decode( ByteBuffer socketBuffer ) { assert ( socketBuffer.hasRemaining() ); - log.debug( "process({}): ({})", socketBuffer.remaining(), ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) )); + log.trace( "process({}): ({})", socketBuffer.remaining(), ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) )); if( getReadyState() != ReadyState.NOT_YET_CONNECTED ) { if( getReadyState() == ReadyState.OPEN ) { @@ -251,7 +251,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { socketBuffer.reset(); Handshakedata tmphandshake = d.translateHandshake( socketBuffer ); if( !( tmphandshake instanceof ClientHandshake ) ) { - log.debug("Closing due to wrong handshake"); + log.trace("Closing due to wrong handshake"); closeConnectionDueToWrongHandshake( new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "wrong http function" ) ); return false; } @@ -263,7 +263,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); } catch ( InvalidDataException e ) { - log.debug("Closing due to wrong handshake. Possible handshake rejection: ", e); + log.trace("Closing due to wrong handshake. Possible handshake rejection: ", e); closeConnectionDueToWrongHandshake( e ); return false; } catch ( RuntimeException e ) { @@ -282,7 +282,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { } } if( draft == null ) { - log.debug("Closing due to protocol error: no draft matches"); + log.trace("Closing due to protocol error: no draft matches"); closeConnectionDueToWrongHandshake( new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "no draft matches" ) ); } return false; @@ -290,7 +290,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { // special case for multiple step handshakes Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( !( tmphandshake instanceof ClientHandshake ) ) { - log.debug("Closing due to protocol error: wrong http function"); + log.trace("Closing due to protocol error: wrong http function"); flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } @@ -301,7 +301,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { open( handshake ); return true; } else { - log.debug("Closing due to protocol error: the handshake did finally not match"); + log.trace("Closing due to protocol error: the handshake did finally not match"); close( CloseFrame.PROTOCOL_ERROR, "the handshake did finally not match" ); } return false; @@ -310,7 +310,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { draft.setParseMode( role ); Handshakedata tmphandshake = draft.translateHandshake( socketBuffer ); if( !( tmphandshake instanceof ServerHandshake ) ) { - log.debug("Closing due to protocol error: wrong http function"); + log.trace("Closing due to protocol error: wrong http function"); flushAndClose( CloseFrame.PROTOCOL_ERROR, "wrong http function", false ); return false; } @@ -320,7 +320,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); } catch ( InvalidDataException e ) { - log.debug("Closing due to invalid data exception. Possible handshake rejection: ", e); + log.trace("Closing due to invalid data exception. Possible handshake rejection: ", e); flushAndClose( e.getCloseCode(), e.getMessage(), false ); return false; } catch ( RuntimeException e ) { @@ -332,12 +332,12 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { open( handshake ); return true; } else { - log.debug("Closing due to protocol error: draft {} refuses handshake", draft ); + log.trace("Closing due to protocol error: draft {} refuses handshake", draft ); close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" ); } } } catch ( InvalidHandshakeException e ) { - log.debug("Closing due to invalid handshake", e); + log.trace("Closing due to invalid handshake", e); close( e ); } } catch ( IncompleteHandshakeException e ) { @@ -366,7 +366,7 @@ private void decodeFrames( ByteBuffer socketBuffer ) { try { frames = draft.translateFrame( socketBuffer ); for( Framedata f : frames ) { - log.debug( "matched frame: {}" , f ); + log.trace( "matched frame: {}" , f ); draft.processFrame( this, f ); } } catch ( InvalidDataException e ) { @@ -617,7 +617,7 @@ private void send( Collection frames ) { } ArrayList outgoingFrames = new ArrayList(); for( Framedata f : frames ) { - log.debug( "send frame: " + f ); + log.trace( "send frame: " + f ); outgoingFrames.add( draft.createBinaryFrame( f ) ); } write( outgoingFrames ); @@ -674,7 +674,7 @@ public void startHandshake( ClientHandshakeBuilder handshakedata ) throws Invali } private void write( ByteBuffer buf ) { - log.debug( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + '}' ); + log.trace( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + '}' ); outQueue.add( buf ); wsl.onWriteDemand( this ); @@ -694,7 +694,7 @@ private void write( List bufs ) { } private void open( Handshakedata d ) { - log.info( "open using draft: " + draft ); + log.trace( "open using draft: " + draft ); setReadyState( ReadyState.OPEN ); try { wsl.onWebsocketOpen( this, d ); diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 8c5b3e8c5..98606334a 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -159,7 +159,7 @@ public Draft_6455( List inputExtensions , List inputProto public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) throws InvalidHandshakeException { int v = readVersion( handshakedata ); if( v != 13 ) { - log.debug("acceptHandshakeAsServer - Wrong websocket version."); + log.trace("acceptHandshakeAsServer - Wrong websocket version."); return HandshakeState.NOT_MATCHED; } HandshakeState extensionState = HandshakeState.NOT_MATCHED; @@ -168,7 +168,7 @@ public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) t if( knownExtension.acceptProvidedExtensionAsServer( requestedExtension ) ) { extension = knownExtension; extensionState = HandshakeState.MATCHED; - log.debug("acceptHandshakeAsServer - Matching extension found: " + extension.toString()); + log.trace("acceptHandshakeAsServer - Matching extension found: " + extension.toString()); break; } } @@ -178,25 +178,25 @@ public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) t if( knownProtocol.acceptProvidedProtocol( requestedProtocol ) ) { protocol = knownProtocol; protocolState = HandshakeState.MATCHED; - log.debug("acceptHandshakeAsServer - Matching protocol found: " + protocol.toString()); + log.trace("acceptHandshakeAsServer - Matching protocol found: " + protocol.toString()); break; } } if (protocolState == HandshakeState.MATCHED && extensionState == HandshakeState.MATCHED) { return HandshakeState.MATCHED; } - log.debug("acceptHandshakeAsServer - No matching extension or protocol found."); + log.trace("acceptHandshakeAsServer - No matching extension or protocol found."); return HandshakeState.NOT_MATCHED; } @Override public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHandshake response ) throws InvalidHandshakeException { if (! basicAccept( response )) { - log.debug("acceptHandshakeAsClient - Missing/wrong upgrade or connection in handshake."); + log.trace("acceptHandshakeAsClient - Missing/wrong upgrade or connection in handshake."); return HandshakeState.NOT_MATCHED; } if( !request.hasFieldValue( "Sec-WebSocket-Key" ) || !response.hasFieldValue( "Sec-WebSocket-Accept" ) ) { - log.debug("acceptHandshakeAsClient - Missing Sec-WebSocket-Key or Sec-WebSocket-Accept"); + log.trace("acceptHandshakeAsClient - Missing Sec-WebSocket-Key or Sec-WebSocket-Accept"); return HandshakeState.NOT_MATCHED; } @@ -205,7 +205,7 @@ public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHa seckey_challenge = generateFinalKey( seckey_challenge ); if( !seckey_challenge.equals( seckey_answere ) ) { - log.debug("acceptHandshakeAsClient - Wrong key for Sec-WebSocket-Key."); + log.trace("acceptHandshakeAsClient - Wrong key for Sec-WebSocket-Key."); return HandshakeState.NOT_MATCHED; } @@ -215,7 +215,7 @@ public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHa if( knownExtension.acceptProvidedExtensionAsClient( requestedExtension ) ) { extension = knownExtension; extensionState = HandshakeState.MATCHED; - log.debug("acceptHandshakeAsClient - Matching extension found: " + extension.toString()); + log.trace("acceptHandshakeAsClient - Matching extension found: " + extension.toString()); break; } } @@ -225,14 +225,14 @@ public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHa if( knownProtocol.acceptProvidedProtocol( requestedProtocol ) ) { protocol = knownProtocol; protocolState = HandshakeState.MATCHED; - log.debug("acceptHandshakeAsClient - Matching protocol found: " + protocol.toString()); + log.trace("acceptHandshakeAsClient - Matching protocol found: " + protocol.toString()); break; } } if (protocolState == HandshakeState.MATCHED && extensionState == HandshakeState.MATCHED) { return HandshakeState.MATCHED; } - log.debug("acceptHandshakeAsClient - No matching extension or protocol found."); + log.trace("acceptHandshakeAsClient - No matching extension or protocol found."); return HandshakeState.NOT_MATCHED; } @@ -343,7 +343,7 @@ public Draft copyInstance() { @Override public ByteBuffer createBinaryFrame( Framedata framedata ) { getExtension().encodeFrame( framedata ); - log.debug( "afterEnconding(" + framedata.getPayloadData().remaining() + "): {" + ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) + '}' ); + log.trace( "afterEnconding(" + framedata.getPayloadData().remaining() + "): {" + ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) + '}' ); return createByteBufferFromFramedata( framedata ); } @@ -391,7 +391,7 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce int maxpacketsize = buffer.remaining(); int realpacketsize = 2; if( maxpacketsize < realpacketsize ) { - log.debug( "Incomplete frame" ); + log.trace( "Incomplete frame" ); throw new IncompleteException( realpacketsize ); } byte b1 = buffer.get( /*0*/ ); @@ -416,13 +416,13 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce if( !( payloadlength >= 0 && payloadlength <= 125 ) ) { if( optcode == Opcode.PING || optcode == Opcode.PONG || optcode == Opcode.CLOSING ) { - log.debug( "Invalid frame: more than 125 octets" ); + log.trace( "Invalid frame: more than 125 octets" ); throw new InvalidFrameException( "more than 125 octets" ); } if( payloadlength == 126 ) { realpacketsize += 2; // additional length bytes if( maxpacketsize < realpacketsize ) { - log.debug( "Incomplete frame" ); + log.trace( "Incomplete frame" ); throw new IncompleteException( realpacketsize ); } byte[] sizebytes = new byte[3]; @@ -432,7 +432,7 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce } else { realpacketsize += 8; // additional length bytes if( maxpacketsize < realpacketsize ) { - log.debug( "Incomplete frame" ); + log.trace( "Incomplete frame" ); throw new IncompleteException( realpacketsize ); } byte[] bytes = new byte[8]; @@ -441,7 +441,7 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce } long length = new BigInteger( bytes ).longValue(); if( length > Integer.MAX_VALUE ) { - log.debug( "Limit exedeed: Payloadsize is to big..." ); + log.trace( "Limit exedeed: Payloadsize is to big..." ); throw new LimitExedeedException( "Payloadsize is to big..." ); } else { payloadlength = ( int ) length; @@ -478,7 +478,7 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce frame.setPayload( payload ); getExtension().isFrameValid(frame); getExtension().decodeFrame(frame); - log.debug( "afterDecoding(" + frame.getPayloadData().remaining() + "): {" + ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) + '}' ); + log.trace( "afterDecoding(" + frame.getPayloadData().remaining() + "): {" + ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) + '}' ); frame.isValid(); return frame; } @@ -678,14 +678,14 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws } else if( !frame.isFin() || curop == Opcode.CONTINUOUS ) { if( curop != Opcode.CONTINUOUS ) { if( current_continuous_frame != null ) { - log.debug( "Protocol error: Previous continuous frame sequence not completed." ); + log.trace( "Protocol error: Previous continuous frame sequence not completed." ); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." ); } current_continuous_frame = frame; byteBufferList.add( frame.getPayloadData() ); } else if( frame.isFin() ) { if( current_continuous_frame == null ) { - log.debug( "Protocol error: Previous continuous frame sequence not completed." ); + log.trace( "Protocol error: Previous continuous frame sequence not completed." ); throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." ); } byteBufferList.add( frame.getPayloadData() ); @@ -792,7 +792,7 @@ private ByteBuffer getPayloadFromByteBufferList() throws LimitExedeedException { totalSize +=buffer.limit(); } if (totalSize > Integer.MAX_VALUE) { - log.debug( "Payloadsize is to big..."); + log.trace( "Payloadsize is to big..."); throw new LimitExedeedException( "Payloadsize is to big..." ); } ByteBuffer resultingByteBuffer = ByteBuffer.allocate( (int) totalSize ); From 249f6697be489ef26996f634c3f2d9b6dba9b6c3 Mon Sep 17 00:00:00 2001 From: marci4 Date: Tue, 14 Aug 2018 22:13:10 +0200 Subject: [PATCH 6/9] Fixed closeframe test --- src/main/java/org/java_websocket/framing/CloseFrame.java | 2 +- .../java/org/java_websocket/framing/CloseFrameTest.java | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/main/java/org/java_websocket/framing/CloseFrame.java b/src/main/java/org/java_websocket/framing/CloseFrame.java index d7ad366ce..05206bba4 100644 --- a/src/main/java/org/java_websocket/framing/CloseFrame.java +++ b/src/main/java/org/java_websocket/framing/CloseFrame.java @@ -235,7 +235,7 @@ public String toString() { @Override public void isValid() throws InvalidDataException { super.isValid(); - if (code == CloseFrame.NO_UTF8 && reason == null) { + if (code == CloseFrame.NO_UTF8 && reason.isEmpty()) { throw new InvalidDataException( CloseFrame.NO_UTF8, "Received text is no valid utf8 string!"); } if (code == CloseFrame.NOCODE && 0 < reason.length()) { diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 3055694d6..fc9eee807 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -138,12 +138,6 @@ public void testIsValid() { } catch (InvalidDataException e) { //fine } - frame.setCode(CloseFrame.NO_UTF8); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } frame.setCode(CloseFrame.POLICY_VALIDATION); try { frame.isValid(); From f91305527d7eb011fe0249bc3ac14d699e0c215a Mon Sep 17 00:00:00 2001 From: marci4 Date: Wed, 15 Aug 2018 11:31:15 +0200 Subject: [PATCH 7/9] Fixed errors found in review --- .../org/java_websocket/AbstractWebSocket.java | 6 ++-- .../org/java_websocket/SSLSocketChannel.java | 4 +-- .../org/java_websocket/SSLSocketChannel2.java | 4 +-- .../org/java_websocket/WebSocketImpl.java | 30 +++++++++---------- .../org/java_websocket/drafts/Draft_6455.java | 16 +++++----- .../server/WebSocketServer.java | 19 ++++++------ 6 files changed, 39 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index e0fbc6213..59abdc261 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -119,7 +119,7 @@ public void setConnectionLostTimeout( int connectionLostTimeout ) { } } } catch (Exception e) { - log.error("Exception during connection lost restart: " + e.getMessage()); + log.error("Exception during connection lost restart: {}", e); } restartConnectionLostTimer(); } @@ -174,13 +174,13 @@ public void run() { if( conn instanceof WebSocketImpl ) { webSocketImpl = ( WebSocketImpl ) conn; if( webSocketImpl.getLastPong() < current ) { - log.warn("Closing connection due to no pong received: " + conn.toString()); + log.warn("Closing connection due to no pong received: {}", conn); webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE, "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection" ); } else { if( webSocketImpl.isOpen() ) { webSocketImpl.sendPing(); } else { - log.warn("Trying to ping a non open connection: " + conn.toString()); + log.warn("Trying to ping a non open connection: {}", conn); } } } diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index 6fb21dd6e..7ef6f74d8 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -138,7 +138,7 @@ public SSLSocketChannel( SocketChannel inputSocketChannel, SSLEngine inputEngine try { socketChannel.close(); } catch ( IOException e ) { - log.error("Exception during the closing of the channel", e); + log.error("Exception during the closing of the channel: {}", e); } } } @@ -166,7 +166,7 @@ public synchronized int read( ByteBuffer dst ) throws IOException { try { result = engine.unwrap( peerNetData, peerAppData ); } catch ( SSLException e ) { - log.error("SSLExcpetion during unwrap", e); + log.error("SSLExcpetion during unwrap: {}", e); throw e; } switch(result.getStatus()) { diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java index fa120d115..8cabf6046 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel2.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java @@ -232,12 +232,12 @@ protected void createBuffers( SSLSession session ) { if( inCrypt.capacity() != netBufferMax ) inCrypt = ByteBuffer.allocate( netBufferMax ); } - if (inData.remaining() != 0) { + if (inData.remaining() != 0 && log.isTraceEnabled()) { log.trace(new String( inData.array(), inData.position(), inData.remaining())); } inData.rewind(); inData.flip(); - if (inCrypt.remaining() != 0) { + if (inCrypt.remaining() != 0 && log.isTraceEnabled()) { log.trace(new String( inCrypt.array(), inCrypt.position(), inCrypt.remaining())); } inCrypt.rewind(); diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 3bbaea7c5..9f585c56f 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -263,11 +263,11 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); } catch ( InvalidDataException e ) { - log.trace("Closing due to wrong handshake. Possible handshake rejection: ", e); + log.trace("Closing due to wrong handshake. Possible handshake rejection: {}", e); closeConnectionDueToWrongHandshake( e ); return false; } catch ( RuntimeException e ) { - log.error("Closing due to internal server error", e); + log.error("Closing due to internal server error; {}", e); wsl.onWebsocketError( this, e ); closeConnectionDueToInternalServerError( e ); return false; @@ -320,11 +320,11 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); } catch ( InvalidDataException e ) { - log.trace("Closing due to invalid data exception. Possible handshake rejection: ", e); + log.trace("Closing due to invalid data exception. Possible handshake rejection: {}", e); flushAndClose( e.getCloseCode(), e.getMessage(), false ); return false; } catch ( RuntimeException e ) { - log.error("Closing since client was never connected", e); + log.error("Closing since client was never connected: {}", e); wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.NEVER_CONNECTED, e.getMessage(), false ); return false; @@ -337,7 +337,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { } } } catch ( InvalidHandshakeException e ) { - log.trace("Closing due to invalid handshake", e); + log.trace("Closing due to invalid handshake: {}", e); close( e ); } } catch ( IncompleteHandshakeException e ) { @@ -370,7 +370,7 @@ private void decodeFrames( ByteBuffer socketBuffer ) { draft.processFrame( this, f ); } } catch ( InvalidDataException e ) { - log.error("Closing due to invalid data in frame", e); + log.error("Closing due to invalid data in frame: {}", e); wsl.onWebsocketError( this, e ); close(e); } @@ -441,7 +441,7 @@ public synchronized void close( int code, String message, boolean remote ) { sendFrame( closeFrame ); } } catch ( InvalidDataException e ) { - log.error("generated frame is invalid", e); + log.error("generated frame is invalid: {}", e); wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false ); } @@ -496,9 +496,9 @@ public synchronized void closeConnection( int code, String message, boolean remo channel.close(); } catch ( IOException e ) { if( e.getMessage().equals( "Broken pipe" ) ) { - log.warn( "Caught IOException: Broken pipe during closeConnection()", e ); + log.warn( "Caught IOException: Broken pipe during closeConnection(): {}", e ); } else { - log.error("Exception during channel.close()", e); + log.error("Exception during channel.close(); {}", e); wsl.onWebsocketError( this, e ); } } @@ -544,7 +544,7 @@ public synchronized void flushAndClose( int code, String message, boolean remote try { wsl.onWebsocketClosing( this, code, message, remote ); } catch ( RuntimeException e ) { - log.error("Exception in onWebsocketClosing", e); + log.error("Exception in onWebsocketClosing: {}", e); wsl.onWebsocketError( this, e ); } if( draft != null ) @@ -617,7 +617,7 @@ private void send( Collection frames ) { } ArrayList outgoingFrames = new ArrayList(); for( Framedata f : frames ) { - log.trace( "send frame: " + f ); + log.trace( "send frame: {}", f); outgoingFrames.add( draft.createBinaryFrame( f ) ); } write( outgoingFrames ); @@ -664,9 +664,9 @@ public void startHandshake( ClientHandshakeBuilder handshakedata ) throws Invali // Stop if the client code throws an exception throw new InvalidHandshakeException( "Handshake data rejected by client." ); } catch ( RuntimeException e ) { - log.error("Exception in startHandshake", e); + log.error("Exception in startHandshake: {}", e); wsl.onWebsocketError( this, e ); - throw new InvalidHandshakeException( "rejected because of" + e ); + throw new InvalidHandshakeException( "rejected because of " + e ); } // Send @@ -674,7 +674,7 @@ public void startHandshake( ClientHandshakeBuilder handshakedata ) throws Invali } private void write( ByteBuffer buf ) { - log.trace( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + '}' ); + log.trace( "write({}): {}", buf.remaining(), buf.remaining() > 1000 ? "too big to display" : new String( buf.array() )); outQueue.add( buf ); wsl.onWriteDemand( this ); @@ -694,7 +694,7 @@ private void write( List bufs ) { } private void open( Handshakedata d ) { - log.trace( "open using draft: " + draft ); + log.trace( "open using draft: {}",draft ); setReadyState( ReadyState.OPEN ); try { wsl.onWebsocketOpen( this, d ); diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 98606334a..4b4434378 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -168,7 +168,7 @@ public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) t if( knownExtension.acceptProvidedExtensionAsServer( requestedExtension ) ) { extension = knownExtension; extensionState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsServer - Matching extension found: " + extension.toString()); + log.trace("acceptHandshakeAsServer - Matching extension found: {}", extension); break; } } @@ -178,7 +178,7 @@ public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) t if( knownProtocol.acceptProvidedProtocol( requestedProtocol ) ) { protocol = knownProtocol; protocolState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsServer - Matching protocol found: " + protocol.toString()); + log.trace("acceptHandshakeAsServer - Matching protocol found: {}", protocol); break; } } @@ -215,7 +215,7 @@ public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHa if( knownExtension.acceptProvidedExtensionAsClient( requestedExtension ) ) { extension = knownExtension; extensionState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsClient - Matching extension found: " + extension.toString()); + log.trace("acceptHandshakeAsClient - Matching extension found: {}",extension); break; } } @@ -225,7 +225,7 @@ public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHa if( knownProtocol.acceptProvidedProtocol( requestedProtocol ) ) { protocol = knownProtocol; protocolState = HandshakeState.MATCHED; - log.trace("acceptHandshakeAsClient - Matching protocol found: " + protocol.toString()); + log.trace("acceptHandshakeAsClient - Matching protocol found: {}",protocol); break; } } @@ -343,7 +343,7 @@ public Draft copyInstance() { @Override public ByteBuffer createBinaryFrame( Framedata framedata ) { getExtension().encodeFrame( framedata ); - log.trace( "afterEnconding(" + framedata.getPayloadData().remaining() + "): {" + ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) + '}' ); + log.trace( "afterEnconding({}): {}" , framedata.getPayloadData().remaining(), ( framedata.getPayloadData().remaining() > 1000 ? "too big to display" : new String( framedata.getPayloadData().array() ) ) ); return createByteBufferFromFramedata( framedata ); } @@ -478,7 +478,7 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce frame.setPayload( payload ); getExtension().isFrameValid(frame); getExtension().decodeFrame(frame); - log.trace( "afterDecoding(" + frame.getPayloadData().remaining() + "): {" + ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) + '}' ); + log.trace( "afterDecoding({}): {}", frame.getPayloadData().remaining(), ( frame.getPayloadData().remaining() > 1000 ? "too big to display" : new String( frame.getPayloadData().array() ) ) ); frame.isValid(); return frame; } @@ -695,7 +695,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( current_continuous_frame.getPayloadData() ) ); } catch ( RuntimeException e ) { - log.error( "Runtime exception during onWebsocketMessage", e ); + log.error( "Runtime exception during onWebsocketMessage: {}", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } else if( current_continuous_frame.getOpcode() == Opcode.BINARY ) { @@ -704,7 +704,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, current_continuous_frame.getPayloadData() ); } catch ( RuntimeException e ) { - log.error( "Runtime exception during onWebsocketMessage", e ); + log.error( "Runtime exception during onWebsocketMessage: {}", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 3ad49121c..8af93e7d7 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -471,7 +471,7 @@ public void run() { try { selector.close(); } catch ( IOException e ) { - log.error( "IOException during selector.close", e ); + log.error( "IOException during selector.close: {}", e ); onError( null, e ); } } @@ -479,7 +479,7 @@ public void run() { try { server.close(); } catch ( IOException e ) { - log.error( "IOException during server.close", e ); + log.error( "IOException during server.close: {}", e ); onError( null, e ); } } @@ -532,13 +532,13 @@ private void handleIOException( SelectionKey key, WebSocket conn, IOException ex } catch ( IOException e ) { // there is nothing that must be done here } - log.warn("Connection closed because of " + ex); + log.warn("Connection closed because of exception: {}",ex); } } } private void handleFatal( WebSocket conn, Exception e ) { - log.error( "Shutdown due to fatal error", e ); + log.error( "Shutdown due to fatal error: {}", e ); onError( conn, e ); //Shutting down WebSocketWorkers, see #222 if( decoders != null ) { @@ -552,11 +552,11 @@ private void handleFatal( WebSocket conn, Exception e ) { try { stop(); } catch ( IOException e1 ) { - log.error( "Error during shutdown", e1 ); + log.error( "Error during shutdown: {}", e1 ); onError( null, e1 ); } catch ( InterruptedException e1 ) { Thread.currentThread().interrupt(); - log.error( "Interrupt during stop", e ); + log.error( "Interrupt during stop: {}", e ); onError( null, e1 ); } } @@ -611,7 +611,7 @@ protected boolean removeConnection( WebSocket ws ) { removed = this.connections.remove( ws ); } else { //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 - log.warn("Removing connection which is not in the connections collection! Possible no handshake recieved! " + ws); + log.warn("Removing connection which is not in the connections collection! Possible no handshake recieved! {}", ws); } } if( isclosed.get() && connections.size() == 0 ) { @@ -890,8 +890,7 @@ public WebSocketWorker() { setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void uncaughtException( Thread t, Throwable e ) { - log.error("Uncaught exception in thread \"" - + t.getName() + "\":", e); + log.error("Uncaught exception in thread {}: {}", t.getName(), e); } } ); } @@ -912,7 +911,7 @@ public void run() { try { ws.decode( buf ); } catch(Exception e){ - log.error("Error while reading from remote connection: ", e); + log.error("Error while reading from remote connection: {}", e); } finally { From 2c7246ca338c0a3709bd2d2af650f174ecbe34f6 Mon Sep 17 00:00:00 2001 From: marci4 Date: Wed, 15 Aug 2018 11:33:26 +0200 Subject: [PATCH 8/9] Rename patterns --- src/main/java/org/java_websocket/protocols/Protocol.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/java_websocket/protocols/Protocol.java b/src/main/java/org/java_websocket/protocols/Protocol.java index b3ee08b4f..690aa6e3d 100644 --- a/src/main/java/org/java_websocket/protocols/Protocol.java +++ b/src/main/java/org/java_websocket/protocols/Protocol.java @@ -34,8 +34,8 @@ */ public class Protocol implements IProtocol { - private static final Pattern COMPILE = Pattern.compile(" "); - private static final Pattern PATTERN = Pattern.compile(","); + private static final Pattern patternSpace = Pattern.compile(" "); + private static final Pattern patternComma = Pattern.compile(","); /** * Attribute for the provided protocol @@ -56,8 +56,8 @@ public Protocol( String providedProtocol ) { @Override public boolean acceptProvidedProtocol( String inputProtocolHeader ) { - String protocolHeader = COMPILE.matcher(inputProtocolHeader).replaceAll(""); - String[] headers = PATTERN.split(protocolHeader); + String protocolHeader = patternSpace.matcher(inputProtocolHeader).replaceAll(""); + String[] headers = patternComma.split(protocolHeader); for( String header : headers ) { if( providedProtocol.equals( header ) ) { return true; From 23487ed9b0320446ba164caaa15f0ec20f552dc2 Mon Sep 17 00:00:00 2001 From: marci4 Date: Wed, 15 Aug 2018 13:00:25 +0200 Subject: [PATCH 9/9] Fixed log for exceptions I quess I need more coffee... --- src/main/example/ChatServer.java | 2 ++ .../org/java_websocket/AbstractWebSocket.java | 6 ++--- .../org/java_websocket/SSLSocketChannel.java | 4 ++-- .../org/java_websocket/WebSocketImpl.java | 22 +++++++++---------- .../org/java_websocket/drafts/Draft_6455.java | 4 ++-- .../server/WebSocketServer.java | 16 +++++++------- 6 files changed, 28 insertions(+), 26 deletions(-) diff --git a/src/main/example/ChatServer.java b/src/main/example/ChatServer.java index f4a3e2cff..3ebc50bc6 100644 --- a/src/main/example/ChatServer.java +++ b/src/main/example/ChatServer.java @@ -105,6 +105,8 @@ public void onError( WebSocket conn, Exception ex ) { @Override public void onStart() { System.out.println("Server started!"); + setConnectionLostTimeout(0); + setConnectionLostTimeout(100); } } diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index 59abdc261..a9fd67ad0 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -119,7 +119,7 @@ public void setConnectionLostTimeout( int connectionLostTimeout ) { } } } catch (Exception e) { - log.error("Exception during connection lost restart: {}", e); + log.error("Exception during connection lost restart", e); } restartConnectionLostTimer(); } @@ -174,13 +174,13 @@ public void run() { if( conn instanceof WebSocketImpl ) { webSocketImpl = ( WebSocketImpl ) conn; if( webSocketImpl.getLastPong() < current ) { - log.warn("Closing connection due to no pong received: {}", conn); + log.trace("Closing connection due to no pong received: {}", conn); webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE, "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection" ); } else { if( webSocketImpl.isOpen() ) { webSocketImpl.sendPing(); } else { - log.warn("Trying to ping a non open connection: {}", conn); + log.trace("Trying to ping a non open connection: {}", conn); } } } diff --git a/src/main/java/org/java_websocket/SSLSocketChannel.java b/src/main/java/org/java_websocket/SSLSocketChannel.java index 7ef6f74d8..6fb21dd6e 100644 --- a/src/main/java/org/java_websocket/SSLSocketChannel.java +++ b/src/main/java/org/java_websocket/SSLSocketChannel.java @@ -138,7 +138,7 @@ public SSLSocketChannel( SocketChannel inputSocketChannel, SSLEngine inputEngine try { socketChannel.close(); } catch ( IOException e ) { - log.error("Exception during the closing of the channel: {}", e); + log.error("Exception during the closing of the channel", e); } } } @@ -166,7 +166,7 @@ public synchronized int read( ByteBuffer dst ) throws IOException { try { result = engine.unwrap( peerNetData, peerAppData ); } catch ( SSLException e ) { - log.error("SSLExcpetion during unwrap: {}", e); + log.error("SSLExcpetion during unwrap", e); throw e; } switch(result.getStatus()) { diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java index 9f585c56f..89e1c8a92 100644 --- a/src/main/java/org/java_websocket/WebSocketImpl.java +++ b/src/main/java/org/java_websocket/WebSocketImpl.java @@ -263,11 +263,11 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake ); } catch ( InvalidDataException e ) { - log.trace("Closing due to wrong handshake. Possible handshake rejection: {}", e); + log.trace("Closing due to wrong handshake. Possible handshake rejection", e); closeConnectionDueToWrongHandshake( e ); return false; } catch ( RuntimeException e ) { - log.error("Closing due to internal server error; {}", e); + log.error("Closing due to internal server error", e); wsl.onWebsocketError( this, e ); closeConnectionDueToInternalServerError( e ); return false; @@ -320,11 +320,11 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { try { wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake ); } catch ( InvalidDataException e ) { - log.trace("Closing due to invalid data exception. Possible handshake rejection: {}", e); + log.trace("Closing due to invalid data exception. Possible handshake rejection", e); flushAndClose( e.getCloseCode(), e.getMessage(), false ); return false; } catch ( RuntimeException e ) { - log.error("Closing since client was never connected: {}", e); + log.error("Closing since client was never connected", e); wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.NEVER_CONNECTED, e.getMessage(), false ); return false; @@ -337,7 +337,7 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) { } } } catch ( InvalidHandshakeException e ) { - log.trace("Closing due to invalid handshake: {}", e); + log.trace("Closing due to invalid handshake", e); close( e ); } } catch ( IncompleteHandshakeException e ) { @@ -370,7 +370,7 @@ private void decodeFrames( ByteBuffer socketBuffer ) { draft.processFrame( this, f ); } } catch ( InvalidDataException e ) { - log.error("Closing due to invalid data in frame: {}", e); + log.error("Closing due to invalid data in frame", e); wsl.onWebsocketError( this, e ); close(e); } @@ -441,7 +441,7 @@ public synchronized void close( int code, String message, boolean remote ) { sendFrame( closeFrame ); } } catch ( InvalidDataException e ) { - log.error("generated frame is invalid: {}", e); + log.error("generated frame is invalid", e); wsl.onWebsocketError( this, e ); flushAndClose( CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false ); } @@ -496,9 +496,9 @@ public synchronized void closeConnection( int code, String message, boolean remo channel.close(); } catch ( IOException e ) { if( e.getMessage().equals( "Broken pipe" ) ) { - log.warn( "Caught IOException: Broken pipe during closeConnection(): {}", e ); + log.trace( "Caught IOException: Broken pipe during closeConnection()", e ); } else { - log.error("Exception during channel.close(); {}", e); + log.error("Exception during channel.close()", e); wsl.onWebsocketError( this, e ); } } @@ -544,7 +544,7 @@ public synchronized void flushAndClose( int code, String message, boolean remote try { wsl.onWebsocketClosing( this, code, message, remote ); } catch ( RuntimeException e ) { - log.error("Exception in onWebsocketClosing: {}", e); + log.error("Exception in onWebsocketClosing", e); wsl.onWebsocketError( this, e ); } if( draft != null ) @@ -664,7 +664,7 @@ public void startHandshake( ClientHandshakeBuilder handshakedata ) throws Invali // Stop if the client code throws an exception throw new InvalidHandshakeException( "Handshake data rejected by client." ); } catch ( RuntimeException e ) { - log.error("Exception in startHandshake: {}", e); + log.error("Exception in startHandshake", e); wsl.onWebsocketError( this, e ); throw new InvalidHandshakeException( "rejected because of " + e ); } diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java index 4b4434378..17e2e6da0 100644 --- a/src/main/java/org/java_websocket/drafts/Draft_6455.java +++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java @@ -695,7 +695,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( current_continuous_frame.getPayloadData() ) ); } catch ( RuntimeException e ) { - log.error( "Runtime exception during onWebsocketMessage: {}", e ); + log.error( "Runtime exception during onWebsocketMessage", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } else if( current_continuous_frame.getOpcode() == Opcode.BINARY ) { @@ -704,7 +704,7 @@ public void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws try { webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, current_continuous_frame.getPayloadData() ); } catch ( RuntimeException e ) { - log.error( "Runtime exception during onWebsocketMessage: {}", e ); + log.error( "Runtime exception during onWebsocketMessage", e ); webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e ); } } diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java index 8af93e7d7..21182aacf 100644 --- a/src/main/java/org/java_websocket/server/WebSocketServer.java +++ b/src/main/java/org/java_websocket/server/WebSocketServer.java @@ -471,7 +471,7 @@ public void run() { try { selector.close(); } catch ( IOException e ) { - log.error( "IOException during selector.close: {}", e ); + log.error( "IOException during selector.close", e ); onError( null, e ); } } @@ -479,7 +479,7 @@ public void run() { try { server.close(); } catch ( IOException e ) { - log.error( "IOException during server.close: {}", e ); + log.error( "IOException during server.close", e ); onError( null, e ); } } @@ -532,13 +532,13 @@ private void handleIOException( SelectionKey key, WebSocket conn, IOException ex } catch ( IOException e ) { // there is nothing that must be done here } - log.warn("Connection closed because of exception: {}",ex); + log.trace("Connection closed because of exception",ex); } } } private void handleFatal( WebSocket conn, Exception e ) { - log.error( "Shutdown due to fatal error: {}", e ); + log.error( "Shutdown due to fatal error", e ); onError( conn, e ); //Shutting down WebSocketWorkers, see #222 if( decoders != null ) { @@ -552,11 +552,11 @@ private void handleFatal( WebSocket conn, Exception e ) { try { stop(); } catch ( IOException e1 ) { - log.error( "Error during shutdown: {}", e1 ); + log.error( "Error during shutdown", e1 ); onError( null, e1 ); } catch ( InterruptedException e1 ) { Thread.currentThread().interrupt(); - log.error( "Interrupt during stop: {}", e ); + log.error( "Interrupt during stop", e ); onError( null, e1 ); } } @@ -611,7 +611,7 @@ protected boolean removeConnection( WebSocket ws ) { removed = this.connections.remove( ws ); } else { //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 - log.warn("Removing connection which is not in the connections collection! Possible no handshake recieved! {}", ws); + log.trace("Removing connection which is not in the connections collection! Possible no handshake recieved! {}", ws); } } if( isclosed.get() && connections.size() == 0 ) { @@ -911,7 +911,7 @@ public void run() { try { ws.decode( buf ); } catch(Exception e){ - log.error("Error while reading from remote connection: {}", e); + log.error("Error while reading from remote connection", e); } finally {