signature:
public class RpcServer { /** * Future invocation with a { @ link InvokeContext } , common api notice please see { @ link # invokeWithFuture ( Connection , Object , int ) }
 * @ param conn
 * @ param request
 * @ param invokeContext
 * @ param timeoutMillis
 * @ return
 * @ throws RemotingException */
public RpcResponseFuture invokeWithFuture ( final Connection conn , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException { } }

implementation: return this . rpcRemoting . invokeWithFuture ( conn , request , invokeContext , timeoutMillis ) ;


signature:
public class RpcServer { /** * Callback invocation using a string address , address format example - 127.0.0.1:12200 ? key1 = value1 & key2 = value2 < br >
 * You can specify an implementation of { @ link InvokeCallback } to get the result .
 * Notice : < br >
 * < ol >
 * < li > < b > DO NOT modify the request object concurrently when this method is called . < / b > < / li >
 * < li > When do invocation , use the string address to find a available client connection , if none then throw exception < / li >
 * < li > Unlike rpc client , address arguments takes no effect here , for rpc server will not create connection . < / li >
 * < / ol >
 * @ param addr
 * @ param request
 * @ param invokeCallback
 * @ param timeoutMillis
 * @ throws RemotingException
 * @ throws InterruptedException */
public void invokeWithCallback ( final String addr , final Object request , final InvokeCallback invokeCallback , final int timeoutMillis ) throws RemotingException , InterruptedException { } }

implementation: check ( ) ; this . rpcRemoting . invokeWithCallback ( addr , request , null , invokeCallback , timeoutMillis ) ;


signature:
public class RpcServer { /** * check whether a client address connected
 * @ param remoteAddr
 * @ return */
public boolean isConnected ( String remoteAddr ) { } }

implementation: Url url = this . rpcRemoting . addressParser . parse ( remoteAddr ) ; return this . isConnected ( url ) ;


signature:
public class RpcServer { /** * check whether a { @ link Url } connected
 * @ param url
 * @ return */
public boolean isConnected ( Url url ) { } }

implementation: Connection conn = this . rpcRemoting . connectionManager . get ( url . getUniqueKey ( ) ) ; if ( null != conn ) { return conn . isFine ( ) ; } return false ;


signature:
public class RpcServer { /** * init netty write buffer water mark */
private void initWriteBufferWaterMark ( ) { } }

implementation: int lowWaterMark = this . netty_buffer_low_watermark ( ) ; int highWaterMark = this . netty_buffer_high_watermark ( ) ; if ( lowWaterMark > highWaterMark ) { throw new IllegalArgumentException ( String . format ( "[server side] bolt netty high water mark {%s} should not be smaller than low water mark {%s} bytes)" , highWaterMark , lowWaterMark ) ) ; } else { logger . warn ( "[server side] bolt netty low water mark is {} bytes, high water mark is {} bytes" , lowWaterMark , highWaterMark ) ; } this . bootstrap . childOption ( ChannelOption . WRITE_BUFFER_WATER_MARK , new WriteBufferWaterMark ( lowWaterMark , highWaterMark ) ) ;


signature:
public class Charsetfunctions { /** * Check if the provided BytebBuffer contains a valid utf8 encoded string .
 * Using the algorithm " Flexible and Economical UTF - 8 Decoder " by Björn Höhrmann ( http : / / bjoern . hoehrmann . de / utf - 8 / decoder / dfa / )
 * @ param data the ByteBuffer
 * @ param off offset ( for performance reasons )
 * @ return does the ByteBuffer contain a valid utf8 encoded string */
public static boolean isValidUTF8 ( ByteBuffer data , int off ) { } }

implementation: int len = data . remaining ( ) ; if ( len < off ) { return false ; } int state = 0 ; for ( int i = off ; i < len ; ++ i ) { state = utf8d [ 256 + ( state << 4 ) + utf8d [ ( 0xff & data . get ( i ) ) ] ] ; if ( state == 1 ) { return false ; } } return true ;


signature:
public class FramedataImpl1 { /** * Get a frame with a specific opcode
 * @ param opcode the opcode representing the frame
 * @ return the frame with a specific opcode */
public static FramedataImpl1 get ( Opcode opcode ) { } }

implementation: if ( opcode == null ) { throw new IllegalArgumentException ( "Supplied opcode cannot be null" ) ; } switch ( opcode ) { case PING : return new PingFrame ( ) ; case PONG : return new PongFrame ( ) ; case TEXT : return new TextFrame ( ) ; case BINARY : return new BinaryFrame ( ) ; case CLOSING : return new CloseFrame ( ) ; case CONTINUOUS : return new ContinuousFrame ( ) ; default : throw new IllegalArgumentException ( "Supplied opcode is invalid" ) ; }


signature:
public class SocketChannelIOHelper { /** * Returns whether the whole outQueue has been flushed
 * @ param ws The WebSocketImpl associated with the channels
 * @ param sockchannel The channel to write to
 * @ throws IOException May be thrown by { @ link WrappedByteChannel # writeMore ( ) }
 * @ return returns Whether there is more data to write */
public static boolean batch ( WebSocketImpl ws , ByteChannel sockchannel ) throws IOException { } }

implementation:
if ( ws == null ) { return false ; } ByteBuffer buffer = ws . outQueue . peek ( ) ; WrappedByteChannel c = null ; if ( buffer == null ) { if ( sockchannel instanceof WrappedByteChannel ) { c = ( WrappedByteChannel ) sockchannel ; if ( c . isNeedWrite ( ) ) { c . writeMore ( ) ; } } } else { do { // FIXME writing as much as possible is unfair ! !
/* int written = */
sockchannel . write ( buffer ) ; if ( buffer . remaining ( ) > 0 ) { return false ; } else { ws . outQueue . poll ( ) ; // Buffer finished . Remove it .
buffer = ws . outQueue . peek ( ) ; } } while ( buffer != null ) ; } 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 ( ) ;


signature:
public class CloseFrame { /** * Set the close code for this close frame
 * @ param code the close code */
public void setCode ( int code ) { } }

implementation:
this . code = code ; // CloseFrame . TLS _ ERROR is not allowed to be transfered over the wire
if ( code == CloseFrame . TLS_ERROR ) { this . code = CloseFrame . NOCODE ; this . reason = "" ; } updatePayload ( ) ;


signature:
public class CloseFrame { /** * Validate the payload to valid utf8
 * @ param mark the current mark
 * @ param payload the current payload
 * @ throws InvalidDataException the current payload is not a valid utf8 */
private void validateUtf8 ( ByteBuffer payload , int mark ) throws InvalidDataException { } }

implementation: try { payload . position ( payload . position ( ) + 2 ) ; reason = Charsetfunctions . stringUtf8 ( payload ) ; } catch ( IllegalArgumentException e ) { throw new InvalidDataException ( CloseFrame . NO_UTF8 ) ; } finally { payload . position ( mark ) ; }


signature:
public class CloseFrame { /** * Update the payload to represent the close code and the reason */
private void updatePayload ( ) { } }

implementation: byte [ ] by = Charsetfunctions . utf8Bytes ( reason ) ; ByteBuffer buf = ByteBuffer . allocate ( 4 ) ; buf . putInt ( code ) ; buf . position ( 2 ) ; ByteBuffer pay = ByteBuffer . allocate ( 2 + by . length ) ; pay . put ( buf ) ; pay . put ( by ) ; pay . rewind ( ) ; super . setPayload ( pay ) ;


signature:
public class Draft_6455 { /** * Check if the requested protocol is part of this draft
 * @ param requestedProtocol the requested protocol
 * @ return MATCHED if it is matched , otherwise NOT _ MATCHED */
private HandshakeState containsRequestedProtocol ( String requestedProtocol ) { } }

implementation: for ( IProtocol knownProtocol : knownProtocols ) { if ( knownProtocol . acceptProvidedProtocol ( requestedProtocol ) ) { protocol = knownProtocol ; log . trace ( "acceptHandshake - Matching protocol found: {}" , protocol ) ; return HandshakeState . MATCHED ; } } return HandshakeState . NOT_MATCHED ;


signature:
public class Draft_6455 { /** * Translate the buffer depending when it has an extended payload length ( 126 or 127)
 * @ param buffer the buffer to read from
 * @ param optcode the decoded optcode
 * @ param oldPayloadlength the old payload length
 * @ param maxpacketsize the max packet size allowed
 * @ param oldRealpacketsize the real packet size
 * @ return the new payload data containing new payload length and new packet size
 * @ throws InvalidFrameException thrown if a control frame has an invalid length
 * @ throws IncompleteException if the maxpacketsize is smaller than the realpackagesize
 * @ throws LimitExceededException if the payload length is to big */
private TranslatedPayloadMetaData translateSingleFramePayloadLength ( ByteBuffer buffer , Opcode optcode , int oldPayloadlength , int maxpacketsize , int oldRealpacketsize ) throws InvalidFrameException , IncompleteException , LimitExceededException { } }

implementation:
int payloadlength = oldPayloadlength , realpacketsize = oldRealpacketsize ; if ( optcode == Opcode . PING || optcode == Opcode . PONG || optcode == Opcode . CLOSING ) { log . trace ( "Invalid frame: more than 125 octets" ) ; throw new InvalidFrameException ( "more than 125 octets" ) ; } if ( payloadlength == 126 ) { realpacketsize += 2 ; // additional length bytes
translateSingleFrameCheckPacketSize ( maxpacketsize , 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
translateSingleFrameCheckPacketSize ( maxpacketsize , 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 ( ) ; translateSingleFrameCheckLengthLimit ( length ) ; payloadlength = ( int ) length ; } return new TranslatedPayloadMetaData ( payloadlength , realpacketsize ) ;


signature:
public class Draft_6455 { /** * Check if the frame size exceeds the allowed limit
 * @ param length the current payload length
 * @ throws LimitExceededException if the payload length is to big */
private void translateSingleFrameCheckLengthLimit ( long length ) throws LimitExceededException { } }

implementation: if ( length > Integer . MAX_VALUE ) { log . trace ( "Limit exedeed: Payloadsize is to big..." ) ; throw new LimitExceededException ( "Payloadsize is to big..." ) ; } if ( length > maxFrameSize ) { log . trace ( "Payload limit reached. Allowed: {} Current: {}" , maxFrameSize , length ) ; throw new LimitExceededException ( "Payload limit reached." , maxFrameSize ) ; } if ( length < 0 ) { log . trace ( "Limit underflow: Payloadsize is to little..." ) ; throw new LimitExceededException ( "Payloadsize is to little..." ) ; }


signature:
public class Draft_6455 { /** * Check if the max packet size is smaller than the real packet size
 * @ param maxpacketsize the max packet size
 * @ param realpacketsize the real packet size
 * @ throws IncompleteException if the maxpacketsize is smaller than the realpackagesize */
private void translateSingleFrameCheckPacketSize ( int maxpacketsize , int realpacketsize ) throws IncompleteException { } }

implementation: if ( maxpacketsize < realpacketsize ) { log . trace ( "Incomplete frame: maxpacketsize < realpacketsize" ) ; throw new IncompleteException ( realpacketsize ) ; }


signature:
public class Draft_6455 { /** * Generate a final key from a input string
 * @ param in the input string
 * @ return a final key */
private String generateFinalKey ( String in ) { } }

implementation: String seckey = in . trim ( ) ; String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ; MessageDigest sh1 ; try { sh1 = MessageDigest . getInstance ( "SHA1" ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( e ) ; } return Base64 . encodeBytes ( sh1 . digest ( acc . getBytes ( ) ) ) ;


signature:
public class Draft_6455 { /** * Process the frame if it is a continuous frame or the fin bit is not set
 * @ param webSocketImpl the websocket implementation to use
 * @ param frame the current frame
 * @ param curop the current Opcode
 * @ throws InvalidDataException if there is a protocol error */
private void processFrameContinuousAndNonFin ( WebSocketImpl webSocketImpl , Framedata frame , Opcode curop ) throws InvalidDataException { } }

implementation:
if ( curop != Opcode . CONTINUOUS ) { processFrameIsNotFin ( frame ) ; } else if ( frame . isFin ( ) ) { processFrameIsFin ( webSocketImpl , frame ) ; } else if ( currentContinuousFrame == 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 == Opcode . TEXT && ! Charsetfunctions . isValidUTF8 ( frame . getPayloadData ( ) ) ) { log . error ( "Protocol error: Payload is not UTF8" ) ; throw new InvalidDataException ( CloseFrame . NO_UTF8 ) ; } // Checking if the current continuous frame contains a correct payload with the other frames combined
if ( curop == Opcode . CONTINUOUS && currentContinuousFrame != null ) { addToBufferList ( frame . getPayloadData ( ) ) ; }


signature:
public class Draft_6455 { /** * Process the frame if it is a binary frame
 * @ param webSocketImpl the websocket impl
 * @ param frame the frame */
private void processFrameBinary ( WebSocketImpl webSocketImpl , Framedata frame ) { } }

implementation: try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , frame . getPayloadData ( ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; }


signature:
public class Draft_6455 { /** * Log the runtime exception to the specific WebSocketImpl
 * @ param webSocketImpl the implementation of the websocket
 * @ param e the runtime exception */
private void logRuntimeException ( WebSocketImpl webSocketImpl , RuntimeException e ) { } }

implementation: log . error ( "Runtime exception during onWebsocketMessage" , e ) ; webSocketImpl . getWebSocketListener ( ) . onWebsocketError ( webSocketImpl , e ) ;


signature:
public class Draft_6455 { /** * Process the frame if it is a text frame
 * @ param webSocketImpl the websocket impl
 * @ param frame the frame */
private void processFrameText ( WebSocketImpl webSocketImpl , Framedata frame ) throws InvalidDataException { } }

implementation: try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , Charsetfunctions . stringUtf8 ( frame . getPayloadData ( ) ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; }


signature:
public class Draft_6455 { /** * Process the frame if it is the last frame
 * @ param webSocketImpl the websocket impl
 * @ param frame the frame
 * @ throws InvalidDataException if there is a protocol error */
private void processFrameIsFin ( WebSocketImpl webSocketImpl , Framedata frame ) throws InvalidDataException { } }

implementation: if ( currentContinuousFrame == null ) { log . trace ( "Protocol error: Previous continuous frame sequence not completed." ) ; throw new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , "Continuous frame sequence was not started." ) ; } addToBufferList ( frame . getPayloadData ( ) ) ; checkBufferLimit ( ) ; if ( currentContinuousFrame . getOpcode ( ) == Opcode . TEXT ) { ( ( FramedataImpl1 ) currentContinuousFrame ) . setPayload ( getPayloadFromByteBufferList ( ) ) ; ( ( FramedataImpl1 ) currentContinuousFrame ) . isValid ( ) ; try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , Charsetfunctions . stringUtf8 ( currentContinuousFrame . getPayloadData ( ) ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; } } else if ( currentContinuousFrame . getOpcode ( ) == Opcode . BINARY ) { ( ( FramedataImpl1 ) currentContinuousFrame ) . setPayload ( getPayloadFromByteBufferList ( ) ) ; ( ( FramedataImpl1 ) currentContinuousFrame ) . isValid ( ) ; try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , currentContinuousFrame . getPayloadData ( ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; } } currentContinuousFrame = null ; clearBufferList ( ) ;


signature:
public class Draft_6455 { /** * Process the frame if it is not the last frame
 * @ param frame the frame
 * @ throws InvalidDataException if there is a protocol error */
private void processFrameIsNotFin ( Framedata frame ) throws InvalidDataException { } }

implementation: if ( currentContinuousFrame != null ) { log . trace ( "Protocol error: Previous continuous frame sequence not completed." ) ; throw new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , "Previous continuous frame sequence not completed." ) ; } currentContinuousFrame = frame ; addToBufferList ( frame . getPayloadData ( ) ) ; checkBufferLimit ( ) ;


signature:
public class Draft_6455 { /** * Process the frame if it is a closing frame
 * @ param webSocketImpl the websocket impl
 * @ param frame the frame */
private void processFrameClosing ( WebSocketImpl webSocketImpl , Framedata frame ) { } }

implementation:
int code = CloseFrame . NOCODE ; String reason = "" ; if ( frame instanceof CloseFrame ) { CloseFrame cf = ( CloseFrame ) frame ; code = cf . getCloseCode ( ) ; reason = cf . getMessage ( ) ; } if ( webSocketImpl . getReadyState ( ) == ReadyState . CLOSING ) { // complete the close handshake by disconnecting
webSocketImpl . closeConnection ( code , reason , true ) ; } else { // echo close handshake
if ( getCloseHandshakeType ( ) == CloseHandshakeType . TWOWAY ) webSocketImpl . close ( code , reason , true ) ; else webSocketImpl . flushAndClose ( code , reason , false ) ; }


signature:
public class Draft_6455 { /** * Check the current size of the buffer and throw an exception if the size is bigger than the max allowed frame size
 * @ throws LimitExceededException if the current size is bigger than the allowed size */
private void checkBufferLimit ( ) throws LimitExceededException { } }

implementation: long totalSize = getByteBufferListSize ( ) ; if ( totalSize > maxFrameSize ) { clearBufferList ( ) ; log . trace ( "Payload limit reached. Allowed: {} Current: {}" , maxFrameSize , totalSize ) ; throw new LimitExceededException ( maxFrameSize ) ; }


signature:
public class Draft_6455 { /** * Method to generate a full bytebuffer out of all the fragmented frame payload
 * @ return a bytebuffer containing all the data
 * @ throws LimitExceededException will be thrown when the totalSize is bigger then Integer . MAX _ VALUE due to not being able to allocate more */
private ByteBuffer getPayloadFromByteBufferList ( ) throws LimitExceededException { } }

implementation: long totalSize = 0 ; ByteBuffer resultingByteBuffer ; synchronized ( byteBufferList ) { for ( ByteBuffer buffer : byteBufferList ) { totalSize += buffer . limit ( ) ; } checkBufferLimit ( ) ; resultingByteBuffer = ByteBuffer . allocate ( ( int ) totalSize ) ; for ( ByteBuffer buffer : byteBufferList ) { resultingByteBuffer . put ( buffer ) ; } } resultingByteBuffer . flip ( ) ; return resultingByteBuffer ;


signature:
public class Draft_6455 { /** * Get the current size of the resulting bytebuffer in the bytebuffer list
 * @ return the size as long ( to not get an integer overflow ) */
private long getByteBufferListSize ( ) { } }

implementation: long totalSize = 0 ; synchronized ( byteBufferList ) { for ( ByteBuffer buffer : byteBufferList ) { totalSize += buffer . limit ( ) ; } } return totalSize ;


signature:
public class SSLSocketChannel { /** * Implements the handshake protocol between two peers , required for the establishment of the SSL / TLS connection .
 * During the handshake , encryption configuration information - such as the list of available cipher suites - will be exchanged
 * and if the handshake is successful will lead to an established SSL / TLS session .
 * A typical handshake will usually contain the following steps :
 * < ul >
 * < li > 1 . wrap : ClientHello < / li >
 * < li > 2 . unwrap : ServerHello / Cert / ServerHelloDone < / li >
 * < li > 3 . wrap : ClientKeyExchange < / li >
 * < li > 4 . wrap : ChangeCipherSpec < / li >
 * < li > 5 . wrap : Finished < / li >
 * < li > 6 . unwrap : ChangeCipherSpec < / li >
 * < li > 7 . unwrap : Finished < / li >
 * < / ul >
 * Handshake is also used during the end of the session , in order to properly close the connection between the two peers .
 * A proper connection close will typically include the one peer sending a CLOSE message to another , and then wait for
 * the other ' s CLOSE message to close the transport link . The other peer from his perspective would read a CLOSE message
 * from his peer and then enter the handshake procedure to send his own CLOSE message as well .
 * @ return True if the connection handshake was successful or false if an error occurred .
 * @ throws IOException - if an error occurs during read / write to the socket channel . */
private boolean doHandshake ( ) throws IOException { } }

implementation:
SSLEngineResult result ; HandshakeStatus handshakeStatus ; // NioSslPeer ' s fields myAppData and peerAppData are supposed to be large enough to hold all message data the peer
// will send and expects to receive from the other peer respectively . Since the messages to be exchanged will usually be less
// than 16KB long the capacity of these fields should also be smaller . Here we initialize these two local buffers
// to be used for the handshake , while keeping client ' s buffers at the same size .
int appBufferSize = engine . getSession ( ) . getApplicationBufferSize ( ) ; myAppData = ByteBuffer . allocate ( appBufferSize ) ; peerAppData = ByteBuffer . allocate ( appBufferSize ) ; myNetData . clear ( ) ; peerNetData . clear ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; boolean handshakeComplete = false ; while ( ! handshakeComplete ) { switch ( handshakeStatus ) { case FINISHED : handshakeComplete = ! this . peerNetData . hasRemaining ( ) ; if ( handshakeComplete ) return true ; socketChannel . write ( this . peerNetData ) ; break ; case NEED_UNWRAP : if ( socketChannel . read ( peerNetData ) < 0 ) { if ( engine . isInboundDone ( ) && engine . isOutboundDone ( ) ) { return false ; } try { engine . closeInbound ( ) ; } catch ( SSLException e ) { // Ignore , cant do anything against this exception
} engine . closeOutbound ( ) ; // After closeOutbound the engine will be set to WRAP state , in order to try to send a close message to the client .
handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } peerNetData . flip ( ) ; try { result = engine . unwrap ( peerNetData , peerAppData ) ; peerNetData . compact ( ) ; handshakeStatus = result . getHandshakeStatus ( ) ; } catch ( SSLException sslException ) { engine . closeOutbound ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } switch ( result . getStatus ( ) ) { case OK : break ; case BUFFER_OVERFLOW : // Will occur when peerAppData ' s capacity is smaller than the data derived from peerNetData ' s unwrap .
peerAppData = enlargeApplicationBuffer ( peerAppData ) ; break ; case BUFFER_UNDERFLOW : // Will occur either when no data was read from the peer or when the peerNetData buffer was too small to hold all peer ' s data .
peerNetData = handleBufferUnderflow ( peerNetData ) ; break ; case CLOSED : if ( engine . isOutboundDone ( ) ) { return false ; } else { engine . closeOutbound ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } default : throw new IllegalStateException ( "Invalid SSL status: " + result . getStatus ( ) ) ; } break ; case NEED_WRAP : myNetData . clear ( ) ; try { result = engine . wrap ( myAppData , myNetData ) ; handshakeStatus = result . getHandshakeStatus ( ) ; } catch ( SSLException sslException ) { engine . closeOutbound ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } switch ( result . getStatus ( ) ) { case OK : myNetData . flip ( ) ; while ( myNetData . hasRemaining ( ) ) { socketChannel . write ( myNetData ) ; } break ; case BUFFER_OVERFLOW : // Will occur if there is not enough space in myNetData buffer to write all the data that would be generated by the method wrap .
// Since myNetData is set to session ' s packet size we should not get to this point because SSLEngine is supposed
// to produce messages smaller or equal to that , but a general handling would be the following :
myNetData = enlargePacketBuffer ( myNetData ) ; break ; case BUFFER_UNDERFLOW : throw new SSLException ( "Buffer underflow occured after a wrap. I don't think we should ever get here." ) ; case CLOSED : try { myNetData . flip ( ) ; while ( myNetData . hasRemaining ( ) ) { socketChannel . write ( myNetData ) ; } // At this point the handshake status will probably be NEED _ UNWRAP so we make sure that peerNetData is clear to read .
peerNetData . clear ( ) ; } catch ( Exception e ) { handshakeStatus = engine . getHandshakeStatus ( ) ; } break ; default : throw new IllegalStateException ( "Invalid SSL status: " + result . getStatus ( ) ) ; } break ; case NEED_TASK : Runnable task ; while ( ( task = engine . getDelegatedTask ( ) ) != null ) { executor . execute ( task ) ; } handshakeStatus = engine . getHandshakeStatus ( ) ; break ; case NOT_HANDSHAKING : break ; default : throw new IllegalStateException ( "Invalid SSL status: " + handshakeStatus ) ; } } return true ;


signature:
public class SSLSocketChannel { /** * Compares < code > sessionProposedCapacity < code > with buffer ' s capacity . If buffer ' s capacity is smaller ,
 * returns a buffer with the proposed capacity . If it ' s equal or larger , returns a buffer
 * with capacity twice the size of the initial one .
 * @ param buffer - the buffer to be enlarged .
 * @ param sessionProposedCapacity - the minimum size of the new buffer , proposed by { @ link SSLSession } .
 * @ return A new buffer with a larger capacity . */
private ByteBuffer enlargeBuffer ( ByteBuffer buffer , int sessionProposedCapacity ) { } }

implementation: if ( sessionProposedCapacity > buffer . capacity ( ) ) { buffer = ByteBuffer . allocate ( sessionProposedCapacity ) ; } else { buffer = ByteBuffer . allocate ( buffer . capacity ( ) * 2 ) ; } return buffer ;


signature:
public class SSLSocketChannel { /** * Handles { @ link SSLEngineResult . Status # BUFFER _ UNDERFLOW } . Will check if the buffer is already filled , and if there is no space problem
 * will return the same buffer , so the client tries to read again . If the buffer is already filled will try to enlarge the buffer either to
 * session ' s proposed size or to a larger capacity . A buffer underflow can happen only after an unwrap , so the buffer will always be a
 * peerNetData buffer .
 * @ param buffer - will always be peerNetData buffer .
 * @ return The same buffer if there is no space problem or a new buffer with the same data but more space . */
private ByteBuffer handleBufferUnderflow ( ByteBuffer buffer ) { } }

implementation: if ( engine . getSession ( ) . getPacketBufferSize ( ) < buffer . limit ( ) ) { return buffer ; } else { ByteBuffer replaceBuffer = enlargePacketBuffer ( buffer ) ; buffer . flip ( ) ; replaceBuffer . put ( buffer ) ; return replaceBuffer ; }


signature:
public class Draft { /** * Checking the handshake for the role as server
 * @ return a handshake
 * @ param firstLineTokens the token of the first line split as as an string array
 * @ param line the whole line */
private static HandshakeBuilder translateHandshakeHttpServer ( String [ ] firstLineTokens , String line ) throws InvalidHandshakeException { } }

implementation:
// translating / parsing the request from the CLIENT
if ( ! "GET" . equalsIgnoreCase ( firstLineTokens [ 0 ] ) ) { throw new InvalidHandshakeException ( String . format ( "Invalid request method received: %s Status line: %s" , firstLineTokens [ 0 ] , line ) ) ; } if ( ! "HTTP/1.1" . equalsIgnoreCase ( firstLineTokens [ 2 ] ) ) { throw new InvalidHandshakeException ( String . format ( "Invalid status line received: %s Status line: %s" , firstLineTokens [ 2 ] , line ) ) ; } ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client ( ) ; clienthandshake . setResourceDescriptor ( firstLineTokens [ 1 ] ) ; return clienthandshake ;


signature:
public class Draft { /** * Checking the handshake for the role as client
 * @ return a handshake
 * @ param firstLineTokens the token of the first line split as as an string array
 * @ param line the whole line */
private static HandshakeBuilder translateHandshakeHttpClient ( String [ ] firstLineTokens , String line ) throws InvalidHandshakeException { } }

implementation:
// translating / parsing the response from the SERVER
if ( ! "101" . equals ( firstLineTokens [ 1 ] ) ) { throw new InvalidHandshakeException ( String . format ( "Invalid status code received: %s Status line: %s" , firstLineTokens [ 1 ] , line ) ) ; } if ( ! "HTTP/1.1" . equalsIgnoreCase ( firstLineTokens [ 0 ] ) ) { throw new InvalidHandshakeException ( String . format ( "Invalid status line received: %s Status line: %s" , firstLineTokens [ 0 ] , line ) ) ; } HandshakeBuilder handshake = new HandshakeImpl1Server ( ) ; ServerHandshakeBuilder serverhandshake = ( ServerHandshakeBuilder ) handshake ; serverhandshake . setHttpStatus ( Short . parseShort ( firstLineTokens [ 1 ] ) ) ; serverhandshake . setHttpStatusMessage ( firstLineTokens [ 2 ] ) ; return handshake ;


signature:
public class WebSocketImpl { /** * Method to decode the provided ByteBuffer
 * @ param socketBuffer the ByteBuffer to decode */
public void decode ( ByteBuffer socketBuffer ) { } }

implementation:
assert ( socketBuffer . hasRemaining ( ) ) ; log . trace ( "process({}): ({})" , socketBuffer . remaining ( ) , ( socketBuffer . remaining ( ) > 1000 ? "too big to display" : new String ( socketBuffer . array ( ) , socketBuffer . position ( ) , socketBuffer . remaining ( ) ) ) ) ; if ( readyState != ReadyState . NOT_YET_CONNECTED ) { if ( readyState == ReadyState . OPEN ) { decodeFrames ( 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 ( ) ) { decodeFrames ( tmpHandshakeBytes ) ; } } }


signature:
public class WebSocketImpl { /** * Returns whether the handshake phase has is completed .
 * In case of a broken handshake this will be never the case . */
private boolean decodeHandshake ( ByteBuffer socketBufferNew ) { } }

implementation:
ByteBuffer socketBuffer ; if ( tmpHandshakeBytes . capacity ( ) == 0 ) { socketBuffer = socketBufferNew ; } else { if ( tmpHandshakeBytes . remaining ( ) < socketBufferNew . remaining ( ) ) { ByteBuffer buf = ByteBuffer . allocate ( tmpHandshakeBytes . capacity ( ) + socketBufferNew . remaining ( ) ) ; tmpHandshakeBytes . flip ( ) ; buf . put ( tmpHandshakeBytes ) ; tmpHandshakeBytes = buf ; } tmpHandshakeBytes . put ( socketBufferNew ) ; tmpHandshakeBytes . flip ( ) ; socketBuffer = tmpHandshakeBytes ; } socketBuffer . mark ( ) ; try { HandshakeState handshakestate ; try { if ( role == Role . SERVER ) { if ( draft == null ) { for ( Draft d : knownDrafts ) { d = d . copyInstance ( ) ; try { d . setParseMode ( role ) ; socketBuffer . reset ( ) ; Handshakedata tmphandshake = d . translateHandshake ( socketBuffer ) ; if ( ! ( tmphandshake instanceof ClientHandshake ) ) { log . trace ( "Closing due to wrong handshake" ) ; closeConnectionDueToWrongHandshake ( new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , "wrong http function" ) ) ; return false ; } ClientHandshake handshake = ( ClientHandshake ) tmphandshake ; handshakestate = d . acceptHandshakeAsServer ( handshake ) ; if ( handshakestate == HandshakeState . MATCHED ) { resourceDescriptor = handshake . getResourceDescriptor ( ) ; ServerHandshakeBuilder response ; try { response = wsl . onWebsocketHandshakeReceivedAsServer ( this , d , handshake ) ; } catch ( InvalidDataException 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 ) ; wsl . onWebsocketError ( this , e ) ; closeConnectionDueToInternalServerError ( e ) ; return false ; } write ( d . createHandshake ( d . postProcessHandshakeResponseAsServer ( handshake , response ) ) ) ; draft = d ; open ( handshake ) ; return true ; } } catch ( InvalidHandshakeException e ) { // go on with an other draft
} } if ( draft == null ) { log . trace ( "Closing due to protocol error: no draft matches" ) ; closeConnectionDueToWrongHandshake ( new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , "no draft matches" ) ) ; } return false ; } else { // special case for multiple step handshakes
Handshakedata tmphandshake = draft . translateHandshake ( socketBuffer ) ; if ( ! ( tmphandshake instanceof ClientHandshake ) ) { log . trace ( "Closing due to protocol error: wrong http function" ) ; flushAndClose ( CloseFrame . PROTOCOL_ERROR , "wrong http function" , false ) ; return false ; } ClientHandshake handshake = ( ClientHandshake ) tmphandshake ; handshakestate = draft . acceptHandshakeAsServer ( handshake ) ; if ( handshakestate == HandshakeState . MATCHED ) { open ( handshake ) ; return true ; } else { 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 ; } } else if ( role == Role . CLIENT ) { draft . setParseMode ( role ) ; Handshakedata tmphandshake = draft . translateHandshake ( socketBuffer ) ; if ( ! ( tmphandshake instanceof ServerHandshake ) ) { log . trace ( "Closing due to protocol error: wrong http function" ) ; flushAndClose ( CloseFrame . PROTOCOL_ERROR , "wrong http function" , false ) ; return false ; } ServerHandshake handshake = ( ServerHandshake ) tmphandshake ; handshakestate = draft . acceptHandshakeAsClient ( handshakerequest , handshake ) ; if ( handshakestate == HandshakeState . MATCHED ) { try { wsl . onWebsocketHandshakeReceivedAsClient ( this , handshakerequest , handshake ) ; } catch ( InvalidDataException 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 ) ; wsl . onWebsocketError ( this , e ) ; flushAndClose ( CloseFrame . NEVER_CONNECTED , e . getMessage ( ) , false ) ; return false ; } open ( handshake ) ; return true ; } else { log . trace ( "Closing due to protocol error: draft {} refuses handshake" , draft ) ; close ( CloseFrame . PROTOCOL_ERROR , "draft " + draft + " refuses handshake" ) ; } } } catch ( InvalidHandshakeException e ) { log . trace ( "Closing due to invalid handshake" , e ) ; close ( e ) ; } } catch ( IncompleteHandshakeException e ) { if ( tmpHandshakeBytes . capacity ( ) == 0 ) { socketBuffer . reset ( ) ; int newsize = e . getPreferredSize ( ) ; if ( newsize == 0 ) { newsize = socketBuffer . capacity ( ) + 16 ; } else { assert ( e . getPreferredSize ( ) >= socketBuffer . remaining ( ) ) ; } tmpHandshakeBytes = ByteBuffer . allocate ( newsize ) ; tmpHandshakeBytes . put ( socketBufferNew ) ; // tmpHandshakeBytes . flip ( ) ;
} else { tmpHandshakeBytes . position ( tmpHandshakeBytes . limit ( ) ) ; tmpHandshakeBytes . limit ( tmpHandshakeBytes . capacity ( ) ) ; } } return false ;


signature:
public class WebSocketImpl { /** * Close the connection if the received handshake was not correct
 * @ param exception the InvalidDataException causing this problem */
private void closeConnectionDueToWrongHandshake ( InvalidDataException exception ) { } }

implementation: write ( generateHttpResponseDueToError ( 404 ) ) ; flushAndClose ( exception . getCloseCode ( ) , exception . getMessage ( ) , false ) ;


signature:
public class WebSocketImpl { /** * Close the connection if there was a server error by a RuntimeException
 * @ param exception the RuntimeException causing this problem */
private void closeConnectionDueToInternalServerError ( RuntimeException exception ) { } }

implementation: write ( generateHttpResponseDueToError ( 500 ) ) ; flushAndClose ( CloseFrame . NEVER_CONNECTED , exception . getMessage ( ) , false ) ;


signature:
public class WebSocketImpl { /** * Generate a simple response for the corresponding endpoint to indicate some error
 * @ param errorCode the http error code
 * @ return the complete response as ByteBuffer */
private ByteBuffer generateHttpResponseDueToError ( int errorCode ) { } }

implementation:
String errorCodeDescription ; switch ( errorCode ) { case 404 : errorCodeDescription = "404 WebSocket Upgrade Failure" ; break ; case 500 : default : errorCodeDescription = "500 Internal Server Error" ; } return ByteBuffer . wrap ( Charsetfunctions . asciiBytes ( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription . length ( ) ) + "\r\n\r\n
" + errorCodeDescription + "
" ) ) ;


signature:
public class WebSocketImpl { /** * This will close the connection immediately without a proper close handshake .
 * The code and the message therefore won ' t be transfered over the wire also they will be forwarded to onClose / onWebsocketClose .
 * @ param code the closing code
 * @ param message the closing message
 * @ param remote Indicates who " generated " < code > code < / code > . < br >
 * < code > true < / code > means that this endpoint received the < code > code < / code > from the other endpoint . < br >
 * false means this endpoint decided to send the given code , < br >
 * < code > remote < / code > may also be true if this endpoint started the closing handshake since the other endpoint may not simply echo the < code > code < / code > but close the connection the same time this endpoint does do but with an other < code > code < / code > . < br > */
public synchronized void closeConnection ( int code , String message , boolean remote ) { } }

implementation:
if ( readyState == ReadyState . CLOSED ) { return ; } // Methods like eot ( ) call this method without calling onClose ( ) . Due to that reason we have to adjust the ReadyState manually
if ( readyState == ReadyState . OPEN ) { if ( code == CloseFrame . ABNORMAL_CLOSE ) { readyState = ReadyState . CLOSING ; } } if ( key != null ) { // key . attach ( null ) ; / / see issue # 114
key . cancel ( ) ; } if ( channel != null ) { try { channel . close ( ) ; } catch ( IOException e ) { if ( e . getMessage ( ) . equals ( "Broken pipe" ) ) { log . trace ( "Caught IOException: Broken pipe during closeConnection()" , e ) ; } else { log . error ( "Exception during channel.close()" , e ) ; wsl . onWebsocketError ( this , e ) ; } } } try { this . wsl . onWebsocketClose ( this , code , message , remote ) ; } catch ( RuntimeException e ) { wsl . onWebsocketError ( this , e ) ; } if ( draft != null ) draft . reset ( ) ; handshakerequest = null ; readyState = ReadyState . CLOSED ;


signature:
public class WebSocketImpl { /** * Send Text data to the other end .
 * @ throws WebsocketNotConnectedException websocket is not yet connected */
@ Override public void send ( String text ) { } }

implementation: if ( text == null ) throw new IllegalArgumentException ( "Cannot send 'null' data to a WebSocketImpl." ) ; send ( draft . createFrames ( text , role == Role . CLIENT ) ) ;


signature:
public class WebSocketImpl { /** * Send Binary data ( plain bytes ) to the other end .
 * @ throws IllegalArgumentException the data is null
 * @ throws WebsocketNotConnectedException websocket is not yet connected */
@ Override public void send ( ByteBuffer bytes ) { } }

implementation: if ( bytes == null ) throw new IllegalArgumentException ( "Cannot send 'null' data to a WebSocketImpl." ) ; send ( draft . createFrames ( bytes , role == Role . CLIENT ) ) ;


signature:
public class WebSocketImpl { /** * Write a list of bytebuffer ( frames in binary form ) into the outgoing queue
 * @ param bufs the list of bytebuffer */
private void write ( List < ByteBuffer > bufs ) { } }

implementation: synchronized ( synchronizeWriteObject ) { for ( ByteBuffer b : bufs ) { write ( b ) ; } }


signature:
public class WebSocketClient { /** * Reset everything relevant to allow a reconnect
 * @ since 1.3.8 */
private void reset ( ) { } }

implementation: Thread current = Thread . currentThread ( ) ; if ( current == writeThread || current == connectReadThread ) { throw new IllegalStateException ( "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to insure a successful cleanup." ) ; } try { closeBlocking ( ) ; if ( writeThread != null ) { this . writeThread . interrupt ( ) ; this . writeThread = null ; } if ( connectReadThread != null ) { this . connectReadThread . interrupt ( ) ; this . connectReadThread = null ; } this . draft . reset ( ) ; if ( this . socket != null ) { this . socket . close ( ) ; this . socket = null ; } } catch ( Exception e ) { onError ( e ) ; engine . closeConnection ( CloseFrame . ABNORMAL_CLOSE , e . getMessage ( ) ) ; return ; } connectLatch = new CountDownLatch ( 1 ) ; closeLatch = new CountDownLatch ( 1 ) ; this . engine = new WebSocketImpl ( this , this . draft ) ;


signature:
public class WebSocketClient { /** * Initiates the websocket connection . This method does not block . */
public void connect ( ) { } }

implementation: if ( connectReadThread != null ) throw new IllegalStateException ( "WebSocketClient objects are not reuseable" ) ; connectReadThread = new Thread ( this ) ; connectReadThread . setName ( "WebSocketConnectReadThread-" + connectReadThread . getId ( ) ) ; connectReadThread . start ( ) ;


signature:
public class WebSocketClient { /** * Same as < code > connect < / code > but blocks with a timeout until the websocket connected or failed to do so . < br >
 * @ param timeout
 * The connect timeout
 * @ param timeUnit
 * The timeout time unit
 * @ return Returns whether it succeeded or not .
 * @ throws InterruptedException Thrown when the threads get interrupted */
public boolean connectBlocking ( long timeout , TimeUnit timeUnit ) throws InterruptedException { } }

implementation: connect ( ) ; return connectLatch . await ( timeout , timeUnit ) && engine . isOpen ( ) ;


signature:
public class WebSocketClient { /** * Extract the specified port
 * @ return the specified port or the default port for the specific scheme */
private int getPort ( ) { } }

implementation: int port = uri . getPort ( ) ; if ( port == - 1 ) { String scheme = uri . getScheme ( ) ; if ( "wss" . equals ( scheme ) ) { return WebSocketImpl . DEFAULT_WSS_PORT ; } else if ( "ws" . equals ( scheme ) ) { return WebSocketImpl . DEFAULT_PORT ; } else { throw new IllegalArgumentException ( "unknown scheme: " + scheme ) ; } } return port ;


signature:
public class WebSocketClient { /** * Create and send the handshake to the other endpoint
 * @ throws InvalidHandshakeException a invalid handshake was created */
private void sendHandshake ( ) throws InvalidHandshakeException { } }

implementation: String path ; String part1 = uri . getRawPath ( ) ; String part2 = uri . getRawQuery ( ) ; if ( part1 == null || part1 . length ( ) == 0 ) path = "/" ; else path = part1 ; if ( part2 != null ) path += '?' + part2 ; int port = getPort ( ) ; String host = uri . getHost ( ) + ( ( port != WebSocketImpl . DEFAULT_PORT && port != WebSocketImpl . DEFAULT_WSS_PORT ) ? ":" + port : "" ) ; HandshakeImpl1Client handshake = new HandshakeImpl1Client ( ) ; handshake . setResourceDescriptor ( path ) ; handshake . put ( "Host" , host ) ; if ( headers != null ) { for ( Map . Entry < String , String > kv : headers . entrySet ( ) ) { handshake . put ( kv . getKey ( ) , kv . getValue ( ) ) ; } } engine . startHandshake ( handshake ) ;


signature:
public class WebSocketClient { /** * Calls subclass ' implementation of < var > onOpen < / var > . */
@ Override public final void onWebsocketOpen ( WebSocket conn , Handshakedata handshake ) { } }

implementation: startConnectionLostTimer ( ) ; onOpen ( ( ServerHandshake ) handshake ) ; connectLatch . countDown ( ) ;


signature:
public class WebSocketClient { /** * Calls subclass ' implementation of < var > onClose < / var > . */
@ Override public final void onWebsocketClose ( WebSocket conn , int code , String reason , boolean remote ) { } }

implementation: stopConnectionLostTimer ( ) ; if ( writeThread != null ) writeThread . interrupt ( ) ; onClose ( code , reason , remote ) ; connectLatch . countDown ( ) ; closeLatch . countDown ( ) ;


signature:
public class AbstractWebSocket { /** * Setter for the interval checking for lost connections
 * A value lower or equal 0 results in the check to be deactivated
 * @ param connectionLostTimeout the interval in seconds
 * @ since 1.3.4 */
public void setConnectionLostTimeout ( int connectionLostTimeout ) { } }

implementation:
synchronized ( syncConnectionLost ) { this . connectionLostTimeout = TimeUnit . SECONDS . toNanos ( connectionLostTimeout ) ; if ( this . connectionLostTimeout <= 0 ) { log . trace ( "Connection lost timer stopped" ) ; cancelConnectionLostTimer ( ) ; return ; } if ( this . websocketRunning ) { log . trace ( "Connection lost timer restarted" ) ; // Reset all the pings
try { ArrayList < WebSocket > connections = new ArrayList < WebSocket > ( getConnections ( ) ) ; WebSocketImpl webSocketImpl ; for ( WebSocket conn : connections ) { if ( conn instanceof WebSocketImpl ) { webSocketImpl = ( WebSocketImpl ) conn ; webSocketImpl . updateLastPong ( ) ; } } } catch ( Exception e ) { log . error ( "Exception during connection lost restart" , e ) ; } restartConnectionLostTimer ( ) ; } }


signature:
public class AbstractWebSocket { /** * Stop the connection lost timer
 * @ since 1.3.4 */
protected void stopConnectionLostTimer ( ) { } }

implementation: synchronized ( syncConnectionLost ) { if ( connectionLostCheckerService != null || connectionLostCheckerFuture != null ) { this . websocketRunning = false ; log . trace ( "Connection lost timer stopped" ) ; cancelConnectionLostTimer ( ) ; } }


signature:
public class AbstractWebSocket { /** * Start the connection lost timer
 * @ since 1.3.4 */
protected void startConnectionLostTimer ( ) { } }

implementation: synchronized ( syncConnectionLost ) { if ( this . connectionLostTimeout <= 0 ) { log . trace ( "Connection lost timer deactivated" ) ; return ; } log . trace ( "Connection lost timer started" ) ; this . websocketRunning = true ; restartConnectionLostTimer ( ) ; }


signature:
public class AbstractWebSocket { /** * Send a ping to the endpoint or close the connection since the other endpoint did not respond with a ping
 * @ param webSocket the websocket instance
 * @ param minimumPongTime the lowest / oldest allowable last pong time ( in nanoTime ) before we consider the connection to be lost */
private void executeConnectionLostDetection ( WebSocket webSocket , long minimumPongTime ) { } }

implementation: if ( ! ( webSocket instanceof WebSocketImpl ) ) { return ; } WebSocketImpl webSocketImpl = ( WebSocketImpl ) webSocket ; if ( webSocketImpl . getLastPong ( ) < minimumPongTime ) { log . trace ( "Closing connection due to no pong received: {}" , webSocketImpl ) ; 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 . trace ( "Trying to ping a non open connection: {}" , webSocketImpl ) ; } }


signature:
public class AbstractWebSocket { /** * Cancel any running timer for the connection lost detection
 * @ since 1.3.4 */
private void cancelConnectionLostTimer ( ) { } }

implementation: if ( connectionLostCheckerService != null ) { connectionLostCheckerService . shutdownNow ( ) ; connectionLostCheckerService = null ; } if ( connectionLostCheckerFuture != null ) { connectionLostCheckerFuture . cancel ( false ) ; connectionLostCheckerFuture = null ; }


signature:
public class SSLServerExample { /** * Keystore with certificate created like so ( in JKS format ) :
 * keytool - genkey - keyalg RSA - 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 { } }

implementation:
ChatServer chatserver = new ChatServer ( 8887 ) ; // Firefox does allow multible ssl connection only via port 443 / / tested on FF16
// load up the key store
String STORETYPE = "JKS" ; String KEYSTORE = "keystore.jks" ; String STOREPASSWORD = "storepassword" ; String KEYPASSWORD = "keypassword" ; KeyStore ks = KeyStore . getInstance ( STORETYPE ) ; File kf = new File ( KEYSTORE ) ; ks . load ( new FileInputStream ( kf ) , STOREPASSWORD . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( "SunX509" ) ; kmf . init ( ks , KEYPASSWORD . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( "SunX509" ) ; tmf . init ( ks ) ; SSLContext sslContext = null ; sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; chatserver . setWebSocketFactory ( new DefaultSSLWebSocketServerFactory ( sslContext ) ) ; chatserver . start ( ) ;


signature:
public class WebSocketAdapter { /** * This default implementation does not do anything . Go ahead and overwrite it .
 * @ see org . java _ websocket . WebSocketListener # onWebsocketHandshakeReceivedAsServer ( WebSocket , Draft , ClientHandshake ) */
@ Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer ( WebSocket conn , Draft draft , ClientHandshake request ) throws InvalidDataException { } }

implementation: return new HandshakeImpl1Server ( ) ;


signature:
public class WebSocketAdapter { /** * This default implementation will send a pong in response to the received ping .
 * The pong frame will have the same payload as the ping frame .
 * @ see org . java _ websocket . WebSocketListener # onWebsocketPing ( WebSocket , Framedata ) */
@ Override public void onWebsocketPing ( WebSocket conn , Framedata f ) { } }

implementation: conn . sendFrame ( new PongFrame ( ( PingFrame ) f ) ) ;


signature:
public class SSLServerCustomWebsocketFactoryExample { /** * Keystore with certificate created like so ( in JKS format ) :
 * 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 { } }

implementation:
ChatServer chatserver = new ChatServer ( 8887 ) ; // Firefox does allow multible ssl connection only via port 443 / / tested on FF16
// load up the key store
String STORETYPE = "JKS" ; String KEYSTORE = "keystore.jks" ; String STOREPASSWORD = "storepassword" ; String KEYPASSWORD = "keypassword" ; KeyStore ks = KeyStore . getInstance ( STORETYPE ) ; File kf = new File ( KEYSTORE ) ; ks . load ( new FileInputStream ( kf ) , STOREPASSWORD . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( "SunX509" ) ; kmf . init ( ks , KEYPASSWORD . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( "SunX509" ) ; tmf . init ( ks ) ; SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; // Lets remove some ciphers and protocols
SSLEngine engine = sslContext . createSSLEngine ( ) ; List < String > ciphers = new ArrayList < String > ( Arrays . asList ( engine . getEnabledCipherSuites ( ) ) ) ; ciphers . remove ( "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" ) ; List < String > protocols = new ArrayList < String > ( Arrays . asList ( engine . getEnabledProtocols ( ) ) ) ; protocols . remove ( "SSLv3" ) ; CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory ( sslContext , protocols . toArray ( new String [ ] { } ) , ciphers . toArray ( new String [ ] { } ) ) ; // Different example just using specific ciphers and protocols
/* String [ ] enabledProtocols = { " TLSv1.2 " } ;
 String [ ] enabledCipherSuites = { " TLS _ RSA _ WITH _ AES _ 128 _ CBC _ SHA " , " TLS _ RSA _ WITH _ AES _ 256 _ CBC _ SHA " } ;
 CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory ( sslContext , enabledProtocols , enabledCipherSuites ) ; */
chatserver . setWebSocketFactory ( factory ) ; chatserver . start ( ) ;


signature:
public class SSLSocketChannel2 { /** * This method will do whatever necessary to process the sslengine handshake .
 * Thats why it ' s called both from the { @ link # read ( ByteBuffer ) } and { @ link # write ( ByteBuffer ) } */
private synchronized void processHandshake ( ) throws IOException { } }

implementation:
if ( sslEngine . getHandshakeStatus ( ) == HandshakeStatus . NOT_HANDSHAKING ) return ; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking .
if ( ! tasks . isEmpty ( ) ) { Iterator < Future < ? > > it = tasks . iterator ( ) ; while ( it . hasNext ( ) ) { Future < ? > f = it . next ( ) ; if ( f . isDone ( ) ) { it . remove ( ) ; } else { if ( isBlocking ( ) ) consumeFutureUninterruptible ( f ) ; return ; } } } if ( sslEngine . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_UNWRAP ) { if ( ! isBlocking ( ) || readEngineResult . getStatus ( ) == Status . BUFFER_UNDERFLOW ) { inCrypt . compact ( ) ; int read = socketChannel . read ( inCrypt ) ; if ( read == - 1 ) { throw new IOException ( "connection closed unexpectedly by peer" ) ; } inCrypt . flip ( ) ; } inData . compact ( ) ; unwrap ( ) ; if ( readEngineResult . getHandshakeStatus ( ) == HandshakeStatus . FINISHED ) { createBuffers ( sslEngine . getSession ( ) ) ; return ; } } consumeDelegatedTasks ( ) ; if ( tasks . isEmpty ( ) || sslEngine . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_WRAP ) { socketChannel . write ( wrap ( emptybuffer ) ) ; if ( writeEngineResult . getHandshakeStatus ( ) == HandshakeStatus . FINISHED ) { createBuffers ( sslEngine . getSession ( ) ) ; return ; } } assert ( sslEngine . getHandshakeStatus ( ) != HandshakeStatus . NOT_HANDSHAKING ) ; // this function could only leave NOT _ HANDSHAKING after createBuffers was called unless # 190 occurs which means that nio wrap / unwrap never return HandshakeStatus . FINISHED
bufferallocations = 1 ; // look at variable declaration why this line exists and # 190 . Without this line buffers would not be be recreated when # 190 AND a rehandshake occur .


signature:
public class SSLSocketChannel2 { /** * performs the unwrap operation by unwrapping from { @ link # inCrypt } to { @ link # inData } */
private synchronized ByteBuffer unwrap ( ) throws SSLException { } }

implementation:
int rem ; // There are some ssl test suites , which get around the selector . select ( ) call , which cause an infinite unwrap and 100 % cpu usage ( see # 459 and # 458)
if ( readEngineResult . getStatus ( ) == SSLEngineResult . Status . CLOSED && sslEngine . getHandshakeStatus ( ) == HandshakeStatus . NOT_HANDSHAKING ) { try { close ( ) ; } catch ( IOException e ) { // Not really interesting
} } do { rem = inData . remaining ( ) ; readEngineResult = sslEngine . unwrap ( inCrypt , inData ) ; } while ( readEngineResult . getStatus ( ) == SSLEngineResult . Status . OK && ( rem != inData . remaining ( ) || sslEngine . getHandshakeStatus ( ) == HandshakeStatus . NEED_UNWRAP ) ) ; inData . flip ( ) ; return inData ;


signature:
public class SSLSocketChannel2 { /** * Blocks when in blocking mode until at least one byte has been decoded . < br >
 * When not in blocking mode 0 may be returned .
 * @ return the number of bytes read . */
public int read ( ByteBuffer dst ) throws IOException { } }

implementation:
while ( true ) { if ( ! dst . hasRemaining ( ) ) return 0 ; if ( ! isHandShakeComplete ( ) ) { if ( isBlocking ( ) ) { while ( ! isHandShakeComplete ( ) ) { processHandshake ( ) ; } } else { processHandshake ( ) ; if ( ! isHandShakeComplete ( ) ) { return 0 ; } } } // assert ( bufferallocations > 1 ) ; / / see # 190
// if ( bufferallocations < = 1 ) {
// createBuffers ( sslEngine . getSession ( ) ) ;
/* 1 . When " dst " is smaller than " inData " readRemaining will fill " dst " with data decoded in a previous read call .
 * 2 . When " inCrypt " contains more data than " inData " has remaining space , unwrap has to be called on more time ( readRemaining ) */
int purged = readRemaining ( dst ) ; if ( purged != 0 ) return purged ; /* We only continue when we really need more data from the network .
 * Thats the case if inData is empty or inCrypt holds to less data than necessary for decryption */
assert ( inData . position ( ) == 0 ) ; inData . clear ( ) ; if ( ! inCrypt . hasRemaining ( ) ) inCrypt . clear ( ) ; else inCrypt . compact ( ) ; if ( isBlocking ( ) || readEngineResult . getStatus ( ) == Status . BUFFER_UNDERFLOW ) if ( socketChannel . read ( inCrypt ) == - 1 ) { return - 1 ; } inCrypt . flip ( ) ; unwrap ( ) ; int transfered = transfereTo ( inData , dst ) ; if ( transfered == 0 && isBlocking ( ) ) { continue ; } return transfered ; }


signature:
public class SSLSocketChannel2 { /** * { @ link # read ( ByteBuffer ) } may not be to leave all buffers ( inData , inCrypt ) */
private int readRemaining ( ByteBuffer dst ) throws SSLException { } }

implementation:
if ( inData . hasRemaining ( ) ) { return transfereTo ( inData , dst ) ; } if ( ! inData . hasRemaining ( ) ) inData . clear ( ) ; // test if some bytes left from last read ( e . g . BUFFER _ UNDERFLOW )
if ( inCrypt . hasRemaining ( ) ) { unwrap ( ) ; int amount = transfereTo ( inData , dst ) ; if ( readEngineResult . getStatus ( ) == SSLEngineResult . Status . CLOSED ) { return - 1 ; } if ( amount > 0 ) return amount ; } return 0 ;


signature:
public class WebSocketServer { /** * Closes all connected clients sockets , then closes the underlying
 * ServerSocketChannel , effectively killing the server socket selectorthread ,
 * freeing the port the server was bound to and stops all internal workerthreads .
 * If this method is called before the server is started it will never start .
 * @ param timeout
 * Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking . < br >
 * @ throws InterruptedException Interrupt */
public void stop ( int timeout ) throws InterruptedException { } }

implementation:
if ( ! isclosed . compareAndSet ( false , true ) ) { // this also makes sure that no further connections will be added to this . connections
return ; } List < WebSocket > socketsToClose ; // copy the connections in a list ( prevent callback deadlocks )
synchronized ( connections ) { socketsToClose = new ArrayList < WebSocket > ( connections ) ; } for ( WebSocket ws : socketsToClose ) { ws . close ( CloseFrame . GOING_AWAY ) ; } wsf . close ( ) ; synchronized ( this ) { if ( selectorthread != null && selector != null ) { selector . wakeup ( ) ; selectorthread . join ( timeout ) ; } }


signature:
public class WebSocketServer { /** * Gets the port number that this server listens on .
 * @ return The port number . */
public int getPort ( ) { } }

implementation: int port = getAddress ( ) . getPort ( ) ; if ( port == 0 && server != null ) { port = server . socket ( ) . getLocalPort ( ) ; } return port ;


signature:
public class WebSocketServer { /** * Runnable IMPLEMENTATION / / / / / */
public void run ( ) { } }

implementation:
if ( ! doEnsureSingleThread ( ) ) { return ; } if ( ! doSetupSelectorAndServerThread ( ) ) { return ; } try { int iShutdownCount = 5 ; int selectTimeout = 0 ; while ( ! selectorthread . isInterrupted ( ) && iShutdownCount != 0 ) { SelectionKey key = null ; WebSocketImpl conn = null ; try { if ( isclosed . get ( ) ) { selectTimeout = 5 ; } int keyCount = selector . select ( selectTimeout ) ; if ( keyCount == 0 && isclosed . get ( ) ) { iShutdownCount -- ; } Set < SelectionKey > keys = selector . selectedKeys ( ) ; Iterator < SelectionKey > i = keys . iterator ( ) ; while ( i . hasNext ( ) ) { key = i . next ( ) ; conn = null ; if ( ! key . isValid ( ) ) { continue ; } if ( key . isAcceptable ( ) ) { doAccept ( key , i ) ; continue ; } if ( key . isReadable ( ) && ! doRead ( key , i ) ) { continue ; } if ( key . isWritable ( ) ) { doWrite ( key ) ; } } doAdditionalRead ( ) ; } catch ( CancelledKeyException e ) { // an other thread may cancel the key
} catch ( ClosedByInterruptException e ) { return ; // do the same stuff as when InterruptedException is thrown
} catch ( IOException ex ) { if ( key != null ) key . cancel ( ) ; handleIOException ( key , conn , ex ) ; } catch ( InterruptedException e ) { // FIXME controlled shutdown ( e . g . take care of buffermanagement )
Thread . currentThread ( ) . interrupt ( ) ; } } } catch ( RuntimeException e ) { // should hopefully never occur
handleFatal ( null , e ) ; } finally { doServerShutdown ( ) ; }


signature:
public class WebSocketServer { /** * Do an additional read
 * @ throws InterruptedException thrown by taking a buffer
 * @ throws IOException if an error happened during read */
private void doAdditionalRead ( ) throws InterruptedException , IOException { } }

implementation: WebSocketImpl conn ; while ( ! iqueue . isEmpty ( ) ) { conn = iqueue . remove ( 0 ) ; WrappedByteChannel c = ( ( WrappedByteChannel ) conn . getChannel ( ) ) ; ByteBuffer buf = takeBuffer ( ) ; try { if ( SocketChannelIOHelper . readMore ( buf , conn , c ) ) iqueue . add ( conn ) ; if ( buf . hasRemaining ( ) ) { conn . inQueue . put ( buf ) ; queue ( conn ) ; } else { pushBuffer ( buf ) ; } } catch ( IOException e ) { pushBuffer ( buf ) ; throw e ; } }


signature:
public class WebSocketServer { /** * Execute a accept operation
 * @ param key the selectionkey to read off
 * @ param i the iterator for the selection keys
 * @ throws InterruptedException thrown by taking a buffer
 * @ throws IOException if an error happened during accept */
private void doAccept ( SelectionKey key , Iterator < SelectionKey > i ) throws IOException , InterruptedException { } }

implementation: if ( ! onConnect ( key ) ) { key . cancel ( ) ; return ; } SocketChannel channel = server . accept ( ) ; if ( channel == null ) { return ; } channel . configureBlocking ( false ) ; Socket socket = channel . socket ( ) ; socket . setTcpNoDelay ( isTcpNoDelay ( ) ) ; socket . setKeepAlive ( true ) ; WebSocketImpl w = wsf . createWebSocket ( this , drafts ) ; w . setSelectionKey ( channel . register ( selector , SelectionKey . OP_READ , w ) ) ; try { w . setChannel ( wsf . wrapChannel ( channel , w . getSelectionKey ( ) ) ) ; i . remove ( ) ; allocateBuffers ( w ) ; } catch ( IOException ex ) { if ( w . getSelectionKey ( ) != null ) w . getSelectionKey ( ) . cancel ( ) ; handleIOException ( w . getSelectionKey ( ) , null , ex ) ; }


signature:
public class WebSocketServer { /** * Execute a read operation
 * @ param key the selectionkey to read off
 * @ param i the iterator for the selection keys
 * @ return true , if the read was successful , or false if there was an error
 * @ throws InterruptedException thrown by taking a buffer
 * @ throws IOException if an error happened during read */
private boolean doRead ( SelectionKey key , Iterator < SelectionKey > i ) throws InterruptedException , IOException { } }

implementation: WebSocketImpl conn = ( WebSocketImpl ) key . attachment ( ) ; ByteBuffer buf = takeBuffer ( ) ; if ( conn . getChannel ( ) == null ) { key . cancel ( ) ; handleIOException ( key , conn , new IOException ( ) ) ; return false ; } try { if ( SocketChannelIOHelper . read ( buf , conn , conn . getChannel ( ) ) ) { if ( buf . hasRemaining ( ) ) { conn . inQueue . put ( buf ) ; queue ( conn ) ; i . remove ( ) ; if ( conn . getChannel ( ) instanceof WrappedByteChannel && ( ( WrappedByteChannel ) conn . getChannel ( ) ) . isNeedRead ( ) ) { iqueue . add ( conn ) ; } } else { pushBuffer ( buf ) ; } } else { pushBuffer ( buf ) ; } } catch ( IOException e ) { pushBuffer ( buf ) ; throw e ; } return true ;


signature:
public class WebSocketServer { /** * Execute a write operation
 * @ param key the selectionkey to write on
 * @ throws IOException if an error happened during batch */
private void doWrite ( SelectionKey key ) throws IOException { } }

implementation: WebSocketImpl conn = ( WebSocketImpl ) key . attachment ( ) ; if ( SocketChannelIOHelper . batch ( conn , conn . getChannel ( ) ) ) { if ( key . isValid ( ) ) { key . interestOps ( SelectionKey . OP_READ ) ; } }


signature:
public class WebSocketServer { /** * Setup the selector thread as well as basic server settings
 * @ return true , if everything was successful , false if some error happened */
private boolean doSetupSelectorAndServerThread ( ) { } }

implementation: selectorthread . setName ( "WebSocketSelector-" + selectorthread . getId ( ) ) ; try { server = ServerSocketChannel . open ( ) ; server . configureBlocking ( false ) ; ServerSocket socket = server . socket ( ) ; socket . setReceiveBufferSize ( WebSocketImpl . RCVBUF ) ; socket . setReuseAddress ( isReuseAddr ( ) ) ; socket . bind ( address ) ; selector = Selector . open ( ) ; server . register ( selector , server . validOps ( ) ) ; startConnectionLostTimer ( ) ; for ( WebSocketWorker ex : decoders ) { ex . start ( ) ; } onStart ( ) ; } catch ( IOException ex ) { handleFatal ( null , ex ) ; return false ; } return true ;


signature:
public class WebSocketServer { /** * The websocket server can only be started once
 * @ return true , if the server can be started , false if already a thread is running */
private boolean doEnsureSingleThread ( ) { } }

implementation: synchronized ( this ) { if ( selectorthread != null ) throw new IllegalStateException ( getClass ( ) . getName ( ) + " can only be started once." ) ; selectorthread = Thread . currentThread ( ) ; if ( isclosed . get ( ) ) { return false ; } } return true ;


signature:
public class WebSocketServer { /** * Clean up everything after a shutdown */
private void doServerShutdown ( ) { } }

implementation: stopConnectionLostTimer ( ) ; if ( decoders != null ) { for ( WebSocketWorker w : decoders ) { w . interrupt ( ) ; } } if ( selector != null ) { try { selector . close ( ) ; } catch ( IOException e ) { log . error ( "IOException during selector.close" , e ) ; onError ( null , e ) ; } } if ( server != null ) { try { server . close ( ) ; } catch ( IOException e ) { log . error ( "IOException during server.close" , e ) ; onError ( null , e ) ; } }


signature:
public class WebSocketServer { /** * This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized
 * { @ link # WebSocketServer ( InetSocketAddress , int , List , Collection ) } allows to specify a collection which will be used to store current connections in . < br >
 * Depending on the type on the connection , modifications of that collection may have to be synchronized .
 * @ param ws The Websocket connection which should be removed
 * @ return Removing connection successful */
protected boolean removeConnection ( WebSocket ws ) { } }

implementation:
boolean removed = false ; synchronized ( connections ) { if ( this . connections . contains ( 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 . trace ( "Removing connection which is not in the connections collection! Possible no handshake recieved! {}" , ws ) ; } } if ( isclosed . get ( ) && connections . isEmpty ( ) ) { selectorthread . interrupt ( ) ; } return removed ;


signature:
public class WebSocketServer { /** * Getter to return the socket used by this specific connection
 * @ param conn The specific connection
 * @ return The socket used by this connection */
private Socket getSocket ( WebSocket conn ) { } }

implementation: WebSocketImpl impl = ( WebSocketImpl ) conn ; return ( ( SocketChannel ) impl . getSelectionKey ( ) . channel ( ) ) . socket ( ) ;


signature:
public class WebSocketServer { /** * Send a byte array to a specific collection of websocket connections
 * @ param data the data to send to the endpoints
 * @ param clients a collection of endpoints to whom the text has to be send */
public void broadcast ( byte [ ] data , Collection < WebSocket > clients ) { } }

implementation: if ( data == null || clients == null ) { throw new IllegalArgumentException ( ) ; } broadcast ( ByteBuffer . wrap ( data ) , clients ) ;


signature:
public class WebSocketServer { /** * Send a text to a specific collection of websocket connections
 * @ param text the text to send to the endpoints
 * @ param clients a collection of endpoints to whom the text has to be send */
public void broadcast ( String text , Collection < WebSocket > clients ) { } }

implementation: if ( text == null || clients == null ) { throw new IllegalArgumentException ( ) ; } doBroadcast ( text , clients ) ;


signature:
public class WebSocketServer { /** * 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 < WebSocket > clients ) { } }

implementation:
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 < Draft , List < Framedata > > draftFrames = new HashMap < Draft , List < Framedata > > ( ) ; for ( WebSocket client : clients ) { if ( client != null ) { Draft draft = client . getDraft ( ) ; fillFrames ( draft , draftFrames , sData , bData ) ; try { client . sendFrame ( draftFrames . get ( draft ) ) ; } catch ( WebsocketNotConnectedException e ) { // Ignore this exception in this case
} } }


signature:
public class WebSocketServer { /** * Fills the draftFrames with new data for the broadcast
 * @ param draft The draft to use
 * @ param draftFrames The list of frames per draft to fill
 * @ param sData the string data , can be null
 * @ param bData the bytebuffer data , can be null */
private void fillFrames ( Draft draft , Map < Draft , List < Framedata > > draftFrames , String sData , ByteBuffer bData ) { } }

implementation: if ( ! draftFrames . containsKey ( draft ) ) { List < Framedata > frames = null ; if ( sData != null ) { frames = draft . createFrames ( sData , false ) ; } if ( bData != null ) { frames = draft . createFrames ( bData , false ) ; } if ( frames != null ) { draftFrames . put ( draft , frames ) ; } }


signature:
public class ByteBufferUtils { /** * Transfer from one ByteBuffer to another ByteBuffer
 * @ param source the ByteBuffer to copy from
 * @ param dest the ByteBuffer to copy to
 * @ return the number of transferred bytes */
public static int transferByteBuffer ( ByteBuffer source , ByteBuffer dest ) { } }

implementation: if ( source == null || dest == null ) { throw new IllegalArgumentException ( ) ; } int fremain = source . remaining ( ) ; int toremain = dest . remaining ( ) ; if ( fremain > toremain ) { int limit = Math . min ( fremain , toremain ) ; source . limit ( limit ) ; dest . put ( source ) ; return limit ; } else { dest . put ( source ) ; return fremain ; }


signature:
public class SSLClientExample { /** * Keystore with certificate created like so ( in JKS format ) :
 * keytool - genkey - keyalg RSA - 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 { } }

implementation:
WebSocketChatClient chatclient = new WebSocketChatClient ( new URI ( "wss://localhost:8887" ) ) ; // load up the key store
String STORETYPE = "JKS" ; String KEYSTORE = "keystore.jks" ; String STOREPASSWORD = "storepassword" ; String KEYPASSWORD = "keypassword" ; KeyStore ks = KeyStore . getInstance ( STORETYPE ) ; File kf = new File ( KEYSTORE ) ; ks . load ( new FileInputStream ( kf ) , STOREPASSWORD . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( "SunX509" ) ; kmf . init ( ks , KEYPASSWORD . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( "SunX509" ) ; tmf . init ( ks ) ; SSLContext sslContext = null ; sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; // sslContext . init ( null , null , null ) ; / / will use java ' s default key and trust store which is sufficient unless you deal with self - signed certificates
SSLSocketFactory factory = sslContext . getSocketFactory ( ) ; // ( SSLSocketFactory ) SSLSocketFactory . getDefault ( ) ;
chatclient . setSocketFactory ( factory ) ; chatclient . connectBlocking ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; while ( true ) { String line = reader . readLine ( ) ; if ( line . equals ( "close" ) ) { chatclient . closeBlocking ( ) ; } else if ( line . equals ( "open" ) ) { chatclient . reconnect ( ) ; } else { chatclient . send ( line ) ; } }


signature:
public class DefaultJPAApi { /** * Initialise JPA entity manager factories . */
public JPAApi start ( ) { } }

implementation: jpaConfig . persistenceUnits ( ) . forEach ( persistenceUnit -> emfs . put ( persistenceUnit . name , Persistence . createEntityManagerFactory ( persistenceUnit . unitName ) ) ) ; return this ;


signature:
public class DefaultJPAApi { /** * Get a newly created EntityManager for the specified persistence unit name .
 * @ param name The persistence unit name */
public EntityManager em ( String name ) { } }

implementation: EntityManagerFactory emf = emfs . get ( name ) ; if ( emf == null ) { return null ; } return emf . createEntityManager ( ) ;


signature:
public class DefaultJPAApi { /** * Run a block of code with a newly created EntityManager for the default Persistence Unit .
 * @ param block Block of code to execute */
public void withTransaction ( Consumer < EntityManager > block ) { } }

implementation: withTransaction ( em -> { block . accept ( em ) ; return null ; } ) ;


signature:
public class DefaultJPAApi { /** * Run a block of code with a newly created EntityManager for the named Persistence Unit .
 * @ param name The persistence unit name
 * @ param block Block of code to execute
 * @ param < T > type of result
 * @ return code execution result */
public < T > T withTransaction ( String name , Function < EntityManager , T > block ) { } }

implementation: return withTransaction ( name , false , block ) ;


signature:
public class DefaultJPAApi { /** * Run a block of code with a newly created EntityManager for the named Persistence Unit .
 * @ param name The persistence unit name
 * @ param readOnly Is the transaction read - only ?
 * @ param block Block of code to execute
 * @ param < T > type of result
 * @ return code execution result */
public < T > T withTransaction ( String name , boolean readOnly , Function < EntityManager , T > block ) { } }

implementation: EntityManager entityManager = null ; EntityTransaction tx = null ; try { entityManager = em ( name ) ; if ( entityManager == null ) { throw new RuntimeException ( "Could not create JPA entity manager for '" + name + "'" ) ; } if ( entityManagerContext != null ) { entityManagerContext . push ( entityManager , true ) ; } if ( ! readOnly ) { tx = entityManager . getTransaction ( ) ; tx . begin ( ) ; } T result = block . apply ( entityManager ) ; if ( tx != null ) { if ( tx . getRollbackOnly ( ) ) { tx . rollback ( ) ; } else { tx . commit ( ) ; } } return result ; } catch ( Throwable t ) { if ( tx != null ) { try { if ( tx . isActive ( ) ) { tx . rollback ( ) ; } } catch ( Exception e ) { logger . error ( "Could not rollback transaction" , e ) ; } } throw t ; } finally { if ( entityManager != null ) { if ( entityManagerContext != null ) { entityManagerContext . pop ( true ) ; } entityManager . close ( ) ; } }


signature:
public class DefaultJPAApi { /** * Run a block of code with a newly created EntityManager for the named Persistence Unit .
 * @ param name The persistence unit name
 * @ param readOnly Is the transaction read - only ?
 * @ param block Block of code to execute */
public void withTransaction ( String name , boolean readOnly , Consumer < EntityManager > block ) { } }

implementation: withTransaction ( name , readOnly , em -> { block . accept ( em ) ; return null ; } ) ;


signature:
public class DefaultJPAApi { /** * Run a block of code in a JPA transaction .
 * @ param block Block of code to execute
 * @ deprecated Deprecated as of 2.7.0 . Use { @ link # withTransaction ( Function ) } instead . */
@ Deprecated public < T > T withTransaction ( Supplier < T > block ) { } }

implementation: return withTransaction ( "default" , false , block ) ;


signature:
public class DefaultJPAApi { /** * Run a block of code in a JPA transaction .
 * @ param block Block of code to execute
 * @ deprecated Deprecated as of 2.7.0 . Use { @ link # withTransaction ( Consumer ) } instead . */
@ Deprecated public void withTransaction ( final Runnable block ) { } }

implementation: try { withTransaction ( ( ) -> { block . run ( ) ; return null ; } ) ; } catch ( Throwable t ) { throw new RuntimeException ( "JPA transaction failed" , t ) ; }


signature:
public class DefaultJPAApi { /** * Run a block of code in a JPA transaction .
 * @ param name The persistence unit name
 * @ param readOnly Is the transaction read - only ?
 * @ param block Block of code to execute
 * @ deprecated Deprecated as of 2.7.0 . Use { @ link # withTransaction ( String , boolean , Function ) }
 * instead . */
@ Deprecated public < T > T withTransaction ( String name , boolean readOnly , Supplier < T > block ) { } }

implementation: return withTransaction ( name , readOnly , entityManager -> { return block . get ( ) ; } ) ;


signature:
public class MessagesApi { /** * Converts the varargs to a scala buffer , takes care of wrapping varargs into a intermediate list
 * if necessary
 * @ param args the message arguments
 * @ return scala type for message processing */
private static Seq < Object > convertArgsToScalaBuffer ( final Object ... args ) { } }

implementation: return scala . collection . JavaConverters . asScalaBufferConverter ( wrapArgsToListIfNeeded ( args ) ) . asScala ( ) . toList ( ) ;


signature:
public class MessagesApi { /** * Wraps arguments passed into a list if necessary .
 * < p > Returns the first value as is if it is the only argument and a subtype of ` java . util . List `
 * Otherwise , it calls Arrays . asList on args
 * @ param args arguments as a List */
@ SafeVarargs private static < T > List < T > wrapArgsToListIfNeeded ( final T ... args ) { } }

implementation: List < T > out ; if ( args != null && args . length == 1 && args [ 0 ] instanceof List ) { out = ( List < T > ) args [ 0 ] ; } else { out = Arrays . asList ( args ) ; } return out ;


signature:
public class MessagesApi { /** * Translates a message .
 * < p > Uses ` java . text . MessageFormat ` internally to format the message .
 * @ param lang the message lang
 * @ param key the message key
 * @ param args the message arguments
 * @ return the formatted message or a default rendering if the key wasn ' t defined */
public String get ( play . api . i18n . Lang lang , String key , Object ... args ) { } }

implementation: Seq < Object > scalaArgs = convertArgsToScalaBuffer ( args ) ; return messages . apply ( key , scalaArgs , lang ) ;


signature:
public class MessagesApi { /** * Translates the first defined message .
 * < p > Uses ` java . text . MessageFormat ` internally to format the message .
 * @ param lang the message lang
 * @ param keys the messages keys
 * @ param args the message arguments
 * @ return the formatted message or a default rendering if the key wasn ' t defined */
public String get ( play . api . i18n . Lang lang , List < String > keys , Object ... args ) { } }

implementation: Buffer < String > keyArgs = scala . collection . JavaConverters . asScalaBufferConverter ( keys ) . asScala ( ) ; Seq < Object > scalaArgs = convertArgsToScalaBuffer ( args ) ; return messages . apply ( keyArgs . toSeq ( ) , scalaArgs , lang ) ;


signature:
public class MessagesApi { /** * Check if a message key is defined .
 * @ param lang the message lang
 * @ param key the message key
 * @ return a Boolean */
public Boolean isDefinedAt ( play . api . i18n . Lang lang , String key ) { } }

implementation: return messages . isDefinedAt ( key , lang ) ;


signature:
public class MessagesApi { /** * Get a messages context appropriate for the given candidates .
 * < p > Will select a language from the candidates , based on the languages available , and fallback
 * to the default language if none of the candidates are available .
 * @ param candidates the candidate languages
 * @ return the most appropriate Messages instance given the candidate languages */
public Messages preferred ( Collection < Lang > candidates ) { } }

implementation: Seq < Lang > cs = Scala . asScala ( candidates ) ; play . api . i18n . Messages msgs = messages . preferred ( ( Seq ) cs ) ; return new MessagesImpl ( new Lang ( msgs . lang ( ) ) , this ) ;


signature:
public class MessagesApi { /** * Get a messages context appropriate for the given request .
 * < p > Will select a language from the request , based on the languages available , and fallback to
 * the default language if none of the candidates are available .
 * @ param request the incoming request
 * @ return the preferred messages context for the request */
public Messages preferred ( Http . RequestHeader request ) { } }

implementation: play . api . i18n . Messages msgs = messages . preferred ( request ) ; return new MessagesImpl ( new Lang ( msgs . lang ( ) ) , this ) ;


signature:
public class MessagesApi { /** * Given a Result and a Lang , return a new Result with the lang cookie set to the given Lang .
 * @ param result the result where the lang will be set .
 * @ param lang the lang to set on the result
 * @ return a new result with the lang . */
public Result setLang ( Result result , Lang lang ) { } }

implementation: return messages . setLang ( result . asScala ( ) , lang ) . asJava ( ) ;


signature:
public class GuiceBuilder { /** * Add additional configuration .
 * @ param conf the configuration to add
 * @ return a copy of this builder configured with the supplied configuration */
public final Self configure ( Config conf ) { } }

implementation: return newBuilder ( delegate . configure ( new play . api . Configuration ( conf ) ) ) ;


signature:
public class GuiceBuilder { /** * Add additional configuration .
 * @ param conf the configuration to add
 * @ return a copy of this builder configured with the supplied configuration */
public final Self configure ( Map < String , Object > conf ) { } }

implementation: return configure ( ConfigFactory . parseMap ( conf ) ) ;


signature:
public class GuiceBuilder { /** * Add additional configuration .
 * @ param key a configuration key to set
 * @ param value the associated value for < code > key < / code >
 * @ return a copy of this builder configured with the key = value */
public final Self configure ( String key , Object value ) { } }

implementation: return configure ( ImmutableMap . of ( key , value ) ) ;


signature:
public class GuiceBuilder { /** * Add bindings from guiceable modules .
 * @ param modules the set of modules to bind
 * @ return a copy of this builder configured with those modules */
public final Self bindings ( GuiceableModule ... modules ) { } }

implementation: return newBuilder ( delegate . bindings ( Scala . varargs ( modules ) ) ) ;


signature:
public class GuiceBuilder { /** * Add bindings from Play modules .
 * @ param modules the set of Guice modules whose bindings to apply
 * @ return a copy of this builder configured with the provided bindings */
public final Self bindings ( play . api . inject . Module ... modules ) { } }

implementation: return bindings ( Guiceable . modules ( modules ) ) ;


signature:
public class GuiceBuilder { /** * Add Play bindings .
 * @ param bindings the set of play bindings to apply
 * @ return a copy of this builder configured with the provided bindings */
public final Self bindings ( play . api . inject . Binding < ? > ... bindings ) { } }

implementation: return bindings ( Guiceable . bindings ( bindings ) ) ;


signature:
public class GuiceBuilder { /** * Override bindings using guiceable modules .
 * @ param modules the set of Guice modules whose bindings override some previously configured ones
 * @ return a copy of this builder re - configured with the provided bindings */
public final Self overrides ( GuiceableModule ... modules ) { } }

implementation: return newBuilder ( delegate . overrides ( Scala . varargs ( modules ) ) ) ;


signature:
public class GuiceBuilder { /** * Override bindings using Play modules .
 * @ param modules the set of Play modules whose bindings override some previously configured ones
 * @ return a copy of this builder re - configured with the provided bindings */
public final Self overrides ( play . api . inject . Module ... modules ) { } }

implementation: return overrides ( Guiceable . modules ( modules ) ) ;


signature:
public class GuiceBuilder { /** * Override bindings using Play bindings .
 * @ param bindings a set of Play bindings that override some previously configured ones
 * @ return a copy of this builder re - configured with the provided bindings */
public final Self overrides ( play . api . inject . Binding < ? > ... bindings ) { } }

implementation: return overrides ( Guiceable . bindings ( bindings ) ) ;


signature:
public class GuiceBuilder { /** * Disable modules by class .
 * @ param moduleClasses the module classes whose bindings should be disabled
 * @ return a copy of this builder configured to ignore the provided module classes */
public final Self disable ( Class < ? > ... moduleClasses ) { } }

implementation: return newBuilder ( delegate . disable ( Scala . toSeq ( moduleClasses ) ) ) ;


signature:
public class Action { /** * Executes this action with the given HTTP context and returns the result .
 * @ param ctx the http context in which to execute this action
 * @ return a promise to the action ' s result
 * @ deprecated Since 2.7.0 . Use { @ link # call ( Request ) } instead . Please see < a
 * href = " https : / / www . playframework . com / documentation / latest / JavaHttpContextMigration27 " > the
 * migration guide < / a > for more details . */
@ Deprecated // TODO : When you remove this method make call ( Request ) below abstract
public CompletionStage < Result > call ( Context ctx ) { } }

implementation: return call ( ctx . args != null && ! ctx . args . isEmpty ( ) ? ctx . request ( ) . addAttr ( CTX_ARGS , ctx . args ) : ctx . request ( ) ) ;


signature:
public class Action { /** * Executes this action with the given HTTP request and returns the result .
 * @ param req the http request with which to execute this action
 * @ return a promise to the action ' s result */
public CompletionStage < Result > call ( Request req ) { } }

implementation:
// TODO : Make this method abstract after removing call ( Context )
return Context . safeCurrent ( ) . map ( threadLocalCtx -> { // A previous action did explicitly set a context onto the thread local ( via
// Http . Context . current . set ( . . . ) )
// Let ' s use that context so the user doesn ' t loose data he / she set onto that ctx
// ( args , . . . )
Context newCtx = threadLocalCtx . withRequest ( req . removeAttr ( CTX_ARGS ) ) ; Context . setCurrent ( newCtx ) ; return call ( newCtx ) ; } ) . orElseGet ( ( ) -> { // A previous action did not set a context explicitly , we simply create a new one to
// pass on the request
Context ctx = new Context ( req . removeAttr ( CTX_ARGS ) , contextComponents ) ; ctx . args = req . attrs ( ) . getOptional ( CTX_ARGS ) . orElse ( new HashMap < > ( ) ) ; return call ( ctx ) ; } ) ;


signature:
public class Environment { /** * Retrieves a file relative to the application root path . This method returns an Optional , using
 * empty if the file was not found .
 * @ param relativePath relative path of the file to fetch
 * @ return an existing file */
public Optional < File > getExistingFile ( String relativePath ) { } }

implementation: return OptionConverters . toJava ( env . getExistingFile ( relativePath ) ) ;


signature:
public class Binding { /** * Configure the scope for this binding . */
public < A extends Annotation > Binding < T > in ( final Class < A > scope ) { } }

implementation: return underlying . in ( scope ) . asJava ( ) ;


signature:
public class F { /** * Constructs a tuple of A , B
 * @ param a The a value
 * @ param b The b value
 * @ param < A > a ' s type
 * @ param < B > b ' s type
 * @ return The tuple */
public static < A , B > Tuple < A , B > Tuple ( A a , B b ) { } }

implementation: return new Tuple < A , B > ( a , b ) ;


signature:
public class F { /** * Constructs a tuple of A , B , C , D , E
 * @ param a The a value
 * @ param b The b value
 * @ param c The c value
 * @ param d The d value
 * @ param e The e value
 * @ param < A > a ' s type
 * @ param < B > b ' s type
 * @ param < C > c ' s type
 * @ param < D > d ' s type
 * @ param < E > e ' s type
 * @ return The tuple */
public static < A , B , C , D , E > Tuple5 < A , B , C , D , E > Tuple5 ( A a , B b , C c , D d , E e ) { } }

implementation: return new Tuple5 < A , B , C , D , E > ( a , b , c , d , e ) ;


signature:
public class F { /** * Converts the execution context to an executor , preparing it first .
 * @ param ec the execution context .
 * @ return the Java Executor . */
private static Executor toExecutor ( ExecutionContext ec ) { } }

implementation: ExecutionContext prepared = ec . prepare ( ) ; if ( prepared instanceof Executor ) { return ( Executor ) prepared ; } else { return prepared :: execute ; }


signature:
public class ClientCookieDecoder { /** * Decodes the specified Set - Cookie HTTP header value into a { @ link Cookie } .
 * @ param header the Set - Cookie header .
 * @ return the decoded { @ link Cookie } */
public Cookie decode ( String header ) { } }

implementation:
if ( header == null ) { throw new NullPointerException ( "header" ) ; } final int headerLen = header . length ( ) ; if ( headerLen == 0 ) { return null ; } CookieBuilder cookieBuilder = null ; loop : for ( int i = 0 ; ; ) { // Skip spaces and separators .
for ( ; ; ) { if ( i == headerLen ) { break loop ; } char c = header . charAt ( i ) ; if ( c == ',' ) { // Having multiple cookies in a single Set - Cookie header is
// deprecated , modern browsers only parse the first one
break loop ; } else if ( c == '\t' || c == '\n' || c == 0x0b || c == '\f' || c == '\r' || c == ' ' || c == ';' ) { i ++ ; continue ; } break ; } int nameBegin = i ; int nameEnd = i ; int valueBegin = - 1 ; int valueEnd = - 1 ; if ( i != headerLen ) { keyValLoop : for ( ; ; ) { char curChar = header . charAt ( i ) ; if ( curChar == ';' ) { // NAME ; ( no value till ' ; ' )
nameEnd = i ; valueBegin = valueEnd = - 1 ; break keyValLoop ; } else if ( curChar == '=' ) { // NAME = VALUE
nameEnd = i ; i ++ ; if ( i == headerLen ) { // NAME = ( empty value , i . e . nothing after ' = ' )
valueBegin = valueEnd = 0 ; break keyValLoop ; } valueBegin = i ; // NAME = VALUE ;
int semiPos = header . indexOf ( ';' , i ) ; valueEnd = i = semiPos > 0 ? semiPos : headerLen ; break keyValLoop ; } else { i ++ ; } if ( i == headerLen ) { // NAME ( no value till the end of string )
nameEnd = headerLen ; valueBegin = valueEnd = - 1 ; break ; } } } if ( valueEnd > 0 && header . charAt ( valueEnd - 1 ) == ',' ) { // old multiple cookies separator , skipping it
valueEnd -- ; } if ( cookieBuilder == null ) { // cookie name - value pair
DefaultCookie cookie = initCookie ( header , nameBegin , nameEnd , valueBegin , valueEnd ) ; if ( cookie == null ) { return null ; } cookieBuilder = new CookieBuilder ( cookie ) ; } else { // cookie attribute
String attrValue = valueBegin == - 1 ? null : header . substring ( valueBegin , valueEnd ) ; cookieBuilder . appendAttribute ( header , nameBegin , nameEnd , attrValue ) ; } } return cookieBuilder . cookie ( ) ;


signature:
public class SourceProvider { /** * Returns a new instance that also skips { @ code moreClassesToSkip } .
 * @ param moreClassesToSkip a list of classes to skip in from source provider .
 * @ return the source provider skipping { @ code moreClassesToSkip } . */
public SourceProvider plusSkippedClasses ( Class ... moreClassesToSkip ) { } }

implementation: Set < String > toSkip = new HashSet < String > ( classNamesToSkip ) ; toSkip . addAll ( asStrings ( moreClassesToSkip ) ) ; return new SourceProvider ( toSkip ) ;


signature:
public class SourceProvider { /** * Returns the class names as Strings */
private static List < String > asStrings ( Class ... classes ) { } }

implementation: List < String > strings = new ArrayList < String > ( ) ; for ( Class c : classes ) { strings . add ( c . getName ( ) ) ; } return strings ;


signature:
public class SourceProvider { /** * Returns the calling line of code . The selected line is the nearest to the top of the stack that
 * is not skipped .
 * @ return a stack trace element containing the caller . */
public StackTraceElement get ( ) { } }

implementation: for ( final StackTraceElement element : new Throwable ( ) . getStackTrace ( ) ) { String className = element . getClassName ( ) ; if ( ! classNamesToSkip . contains ( className ) ) { return element ; } } throw new AssertionError ( ) ;


signature:
public class DefaultJPAConfig { /** * Create a default JPA configuration with the given name and unit name .
 * @ param name the name for the entity manager factory
 * @ param unitName the persistence unit name as used in ` persistence . xml `
 * @ return a default JPA configuration */
public static JPAConfig of ( String name , String unitName ) { } }

implementation: return new DefaultJPAConfig ( new JPAConfig . PersistenceUnit ( name , unitName ) ) ;


signature:
public class DefaultJPAConfig { /** * Create a default JPA configuration with the given names and unit names .
 * @ param n1 Name of the first entity manager factory
 * @ param u1 Name of the first unit
 * @ param n2 Name of the second entity manager factory
 * @ param u2 Name of the second unit
 * @ return a default JPA configuration with the provided persistence units . */
public static JPAConfig of ( String n1 , String u1 , String n2 , String u2 ) { } }

implementation: return new DefaultJPAConfig ( new JPAConfig . PersistenceUnit ( n1 , u1 ) , new JPAConfig . PersistenceUnit ( n2 , u2 ) ) ;


signature:
public class DefaultJPAConfig { /** * Create a default JPA configuration from a map of names to unit names .
 * @ param map Map of entity manager factory names to unit names
 * @ return a JPAConfig configured with the provided mapping */
public static JPAConfig from ( Map < String , String > map ) { } }

implementation: ImmutableSet . Builder < JPAConfig . PersistenceUnit > persistenceUnits = new ImmutableSet . Builder < JPAConfig . PersistenceUnit > ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { persistenceUnits . add ( new JPAConfig . PersistenceUnit ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return new DefaultJPAConfig ( persistenceUnits . build ( ) ) ;


signature:
public class Comet { /** * Produces a Flow of escaped ByteString from a series of String elements . Calls out to Comet . flow
 * internally .
 * @ param callbackName the javascript callback method .
 * @ return a flow of ByteString elements . */
public static Flow < String , ByteString , NotUsed > string ( String callbackName ) { } }

implementation: return Flow . of ( String . class ) . map ( str -> { return ByteString . fromString ( "'" + StringEscapeUtils . escapeEcmaScript ( str ) + "'" ) ; } ) . via ( flow ( callbackName ) ) ;


signature:
public class Comet { /** * Produces a flow of ByteString using ` Json . stringify ` from a Flow of JsonNode . Calls out to
 * Comet . flow internally .
 * @ param callbackName the javascript callback method .
 * @ return a flow of ByteString elements . */
public static Flow < JsonNode , ByteString , NotUsed > json ( String callbackName ) { } }

implementation: return Flow . of ( JsonNode . class ) . map ( json -> { return ByteString . fromString ( Json . stringify ( json ) ) ; } ) . via ( flow ( callbackName ) ) ;


signature:
public class Comet { /** * Produces a flow of ByteString with a prepended block and a script wrapper .
 * @ param callbackName the javascript callback method .
 * @ return a flow of ByteString elements . */
public static Flow < ByteString , ByteString , NotUsed > flow ( String callbackName ) { } }

implementation: ByteString cb = ByteString . fromString ( callbackName ) ; return Flow . of ( ByteString . class ) . map ( ( msg ) -> { return formatted ( cb , msg ) ;