idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
13,800 | public static ByteBuf copyBoolean ( boolean value ) { ByteBuf buf = buffer ( 1 ) ; buf . writeBoolean ( value ) ; return buf ; } | Creates a new single - byte big - endian buffer that holds the specified boolean value . |
13,801 | public static ByteBuf copyBoolean ( boolean ... values ) { if ( values == null || values . length == 0 ) { return EMPTY_BUFFER ; } ByteBuf buffer = buffer ( values . length ) ; for ( boolean v : values ) { buffer . writeBoolean ( v ) ; } return buffer ; } | Create a new big - endian buffer that holds a sequence of the specified boolean values . |
13,802 | public static ByteBuf copyFloat ( float value ) { ByteBuf buf = buffer ( 4 ) ; buf . writeFloat ( value ) ; return buf ; } | Creates a new 4 - byte big - endian buffer that holds the specified 32 - bit floating point number . |
13,803 | public static ByteBuf copyFloat ( float ... values ) { if ( values == null || values . length == 0 ) { return EMPTY_BUFFER ; } ByteBuf buffer = buffer ( values . length * 4 ) ; for ( float v : values ) { buffer . writeFloat ( v ) ; } return buffer ; } | Create a new big - endian buffer that holds a sequence of the specified 32 - bit floating point numbers . |
13,804 | public static ByteBuf copyDouble ( double value ) { ByteBuf buf = buffer ( 8 ) ; buf . writeDouble ( value ) ; return buf ; } | Creates a new 8 - byte big - endian buffer that holds the specified 64 - bit floating point number . |
13,805 | public static ByteBuf copyDouble ( double ... values ) { if ( values == null || values . length == 0 ) { return EMPTY_BUFFER ; } ByteBuf buffer = buffer ( values . length * 8 ) ; for ( double v : values ) { buffer . writeDouble ( v ) ; } return buffer ; } | Create a new big - endian buffer that holds a sequence of the specified 64 - bit floating point numbers . |
13,806 | private static void encodeExtras ( ByteBuf buf , ByteBuf extras ) { if ( extras == null || ! extras . isReadable ( ) ) { return ; } buf . writeBytes ( extras ) ; } | Encode the extras . |
13,807 | public WebSocketServerHandshaker newHandshaker ( HttpRequest req ) { CharSequence version = req . headers ( ) . get ( HttpHeaderNames . SEC_WEBSOCKET_VERSION ) ; if ( version != null ) { if ( version . equals ( WebSocketVersion . V13 . toHttpHeaderValue ( ) ) ) { return new WebSocketServerHandshaker13 ( webSocketURL , subprotocols , allowExtensions , maxFramePayloadLength , allowMaskMismatch ) ; } else if ( version . equals ( WebSocketVersion . V08 . toHttpHeaderValue ( ) ) ) { return new WebSocketServerHandshaker08 ( webSocketURL , subprotocols , allowExtensions , maxFramePayloadLength , allowMaskMismatch ) ; } else if ( version . equals ( WebSocketVersion . V07 . toHttpHeaderValue ( ) ) ) { return new WebSocketServerHandshaker07 ( webSocketURL , subprotocols , allowExtensions , maxFramePayloadLength , allowMaskMismatch ) ; } else { return null ; } } else { return new WebSocketServerHandshaker00 ( webSocketURL , subprotocols , maxFramePayloadLength ) ; } } | Instances a new handshaker |
13,808 | public static ChannelFuture sendUnsupportedVersionResponse ( Channel channel , ChannelPromise promise ) { HttpResponse res = new DefaultFullHttpResponse ( HttpVersion . HTTP_1_1 , HttpResponseStatus . UPGRADE_REQUIRED ) ; res . headers ( ) . set ( HttpHeaderNames . SEC_WEBSOCKET_VERSION , WebSocketVersion . V13 . toHttpHeaderValue ( ) ) ; HttpUtil . setContentLength ( res , 0 ) ; return channel . writeAndFlush ( res , promise ) ; } | Return that we need cannot not support the web socket version |
13,809 | public static ReadOnlyHttp2Headers clientHeaders ( boolean validateHeaders , AsciiString method , AsciiString path , AsciiString scheme , AsciiString authority , AsciiString ... otherHeaders ) { return new ReadOnlyHttp2Headers ( validateHeaders , new AsciiString [ ] { PseudoHeaderName . METHOD . value ( ) , method , PseudoHeaderName . PATH . value ( ) , path , PseudoHeaderName . SCHEME . value ( ) , scheme , PseudoHeaderName . AUTHORITY . value ( ) , authority } , otherHeaders ) ; } | Create a new read only representation of headers used by clients . |
13,810 | public static ReadOnlyHttp2Headers serverHeaders ( boolean validateHeaders , AsciiString status , AsciiString ... otherHeaders ) { return new ReadOnlyHttp2Headers ( validateHeaders , new AsciiString [ ] { PseudoHeaderName . STATUS . value ( ) , status } , otherHeaders ) ; } | Create a new read only representation of headers used by servers . |
13,811 | public int bwt ( ) { final int [ ] SA = this . SA ; final byte [ ] T = this . T ; final int n = this . n ; final int [ ] bucketA = new int [ BUCKET_A_SIZE ] ; final int [ ] bucketB = new int [ BUCKET_B_SIZE ] ; if ( n == 0 ) { return 0 ; } if ( n == 1 ) { SA [ 0 ] = T [ 0 ] ; return 0 ; } int m = sortTypeBstar ( bucketA , bucketB ) ; if ( 0 < m ) { return constructBWT ( bucketA , bucketB ) ; } return 0 ; } | Performs a Burrows Wheeler Transform on the input array . |
13,812 | private CompositeByteBuf addComponents ( boolean increaseIndex , int cIndex , Iterable < ByteBuf > buffers ) { if ( buffers instanceof ByteBuf ) { return addComponent ( increaseIndex , cIndex , ( ByteBuf ) buffers ) ; } checkNotNull ( buffers , "buffers" ) ; Iterator < ByteBuf > it = buffers . iterator ( ) ; try { checkComponentIndex ( cIndex ) ; while ( it . hasNext ( ) ) { ByteBuf b = it . next ( ) ; if ( b == null ) { break ; } cIndex = addComponent0 ( increaseIndex , cIndex , b ) + 1 ; cIndex = Math . min ( cIndex , componentCount ) ; } } finally { while ( it . hasNext ( ) ) { ReferenceCountUtil . safeRelease ( it . next ( ) ) ; } } consolidateIfNeeded ( ) ; return this ; } | but we do in the most common case that the Iterable is a Collection ) |
13,813 | private void consolidateIfNeeded ( ) { int size = componentCount ; if ( size > maxNumComponents ) { final int capacity = components [ size - 1 ] . endOffset ; ByteBuf consolidated = allocBuffer ( capacity ) ; lastAccessed = null ; for ( int i = 0 ; i < size ; i ++ ) { components [ i ] . transferTo ( consolidated ) ; } components [ 0 ] = new Component ( consolidated , 0 , 0 , capacity , consolidated ) ; removeCompRange ( 1 , size ) ; } } | This should only be called as last operation from a method as this may adjust the underlying array of components and so affect the index etc . |
13,814 | public AsciiString decode ( ByteBuf buf , int length ) throws Http2Exception { processor . reset ( ) ; buf . forEachByte ( buf . readerIndex ( ) , length , processor ) ; buf . skipBytes ( length ) ; return processor . end ( ) ; } | Decompresses the given Huffman coded string literal . |
13,815 | public static ClassResolver weakCachingResolver ( ClassLoader classLoader ) { return new CachingClassResolver ( new ClassLoaderClassResolver ( defaultClassLoader ( classLoader ) ) , new WeakReferenceMap < String , Class < ? > > ( new HashMap < String , Reference < Class < ? > > > ( ) ) ) ; } | non - aggressive non - concurrent cache good for non - shared default cache |
13,816 | public static ClassResolver softCachingResolver ( ClassLoader classLoader ) { return new CachingClassResolver ( new ClassLoaderClassResolver ( defaultClassLoader ( classLoader ) ) , new SoftReferenceMap < String , Class < ? > > ( new HashMap < String , Reference < Class < ? > > > ( ) ) ) ; } | aggressive non - concurrent cache good for non - shared cache when we re not worried about class unloading |
13,817 | public static ClassResolver weakCachingConcurrentResolver ( ClassLoader classLoader ) { return new CachingClassResolver ( new ClassLoaderClassResolver ( defaultClassLoader ( classLoader ) ) , new WeakReferenceMap < String , Class < ? > > ( PlatformDependent . < String , Reference < Class < ? > > > newConcurrentHashMap ( ) ) ) ; } | non - aggressive concurrent cache good for shared cache when we re worried about class unloading |
13,818 | public static ClassResolver softCachingConcurrentResolver ( ClassLoader classLoader ) { return new CachingClassResolver ( new ClassLoaderClassResolver ( defaultClassLoader ( classLoader ) ) , new SoftReferenceMap < String , Class < ? > > ( PlatformDependent . < String , Reference < Class < ? > > > newConcurrentHashMap ( ) ) ) ; } | aggressive concurrent cache good for shared cache when we re not worried about class unloading |
13,819 | public static boolean isMultipart ( HttpRequest request ) { if ( request . headers ( ) . contains ( HttpHeaderNames . CONTENT_TYPE ) ) { return getMultipartDataBoundary ( request . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) ) != null ; } else { return false ; } } | Check if the given request is a multipart request |
13,820 | protected static String [ ] getMultipartDataBoundary ( String contentType ) { String [ ] headerContentType = splitHeaderContentType ( contentType ) ; final String multiPartHeader = HttpHeaderValues . MULTIPART_FORM_DATA . toString ( ) ; if ( headerContentType [ 0 ] . regionMatches ( true , 0 , multiPartHeader , 0 , multiPartHeader . length ( ) ) ) { int mrank ; int crank ; final String boundaryHeader = HttpHeaderValues . BOUNDARY . toString ( ) ; if ( headerContentType [ 1 ] . regionMatches ( true , 0 , boundaryHeader , 0 , boundaryHeader . length ( ) ) ) { mrank = 1 ; crank = 2 ; } else if ( headerContentType [ 2 ] . regionMatches ( true , 0 , boundaryHeader , 0 , boundaryHeader . length ( ) ) ) { mrank = 2 ; crank = 1 ; } else { return null ; } String boundary = StringUtil . substringAfter ( headerContentType [ mrank ] , '=' ) ; if ( boundary == null ) { throw new ErrorDataDecoderException ( "Needs a boundary value" ) ; } if ( boundary . charAt ( 0 ) == '"' ) { String bound = boundary . trim ( ) ; int index = bound . length ( ) - 1 ; if ( bound . charAt ( index ) == '"' ) { boundary = bound . substring ( 1 , index ) ; } } final String charsetHeader = HttpHeaderValues . CHARSET . toString ( ) ; if ( headerContentType [ crank ] . regionMatches ( true , 0 , charsetHeader , 0 , charsetHeader . length ( ) ) ) { String charset = StringUtil . substringAfter ( headerContentType [ crank ] , '=' ) ; if ( charset != null ) { return new String [ ] { "--" + boundary , charset } ; } } return new String [ ] { "--" + boundary } ; } return null ; } | Check from the request ContentType if this request is a Multipart request . |
13,821 | protected SslHandler newHandler ( ByteBufAllocator alloc , boolean startTls , Executor executor ) { return new SslHandler ( newEngine ( alloc ) , startTls , executor ) ; } | Create a new SslHandler . |
13,822 | private static String formatSimple ( ChannelHandlerContext ctx , String eventName , Object msg ) { String chStr = ctx . channel ( ) . toString ( ) ; String msgStr = String . valueOf ( msg ) ; StringBuilder buf = new StringBuilder ( chStr . length ( ) + 1 + eventName . length ( ) + 2 + msgStr . length ( ) ) ; return buf . append ( chStr ) . append ( ' ' ) . append ( eventName ) . append ( ": " ) . append ( msgStr ) . toString ( ) ; } | Generates the default log message of the specified event whose argument is an arbitrary object . |
13,823 | final void clear ( ) { while ( ! resolveCache . isEmpty ( ) ) { for ( Iterator < Entry < String , Entries > > i = resolveCache . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < String , Entries > e = i . next ( ) ; i . remove ( ) ; e . getValue ( ) . clearAndCancel ( ) ; } } } | Remove everything from the cache . |
13,824 | final List < ? extends E > get ( String hostname ) { Entries entries = resolveCache . get ( hostname ) ; return entries == null ? null : entries . get ( ) ; } | Returns all caches entries for the given hostname . |
13,825 | final void cache ( String hostname , E value , int ttl , EventLoop loop ) { Entries entries = resolveCache . get ( hostname ) ; if ( entries == null ) { entries = new Entries ( hostname ) ; Entries oldEntries = resolveCache . putIfAbsent ( hostname , entries ) ; if ( oldEntries != null ) { entries = oldEntries ; } } entries . add ( value , ttl , loop ) ; } | Cache a value for the given hostname that will automatically expire once the TTL is reached . |
13,826 | @ SuppressWarnings ( "unchecked" ) public final V get ( ) { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap . get ( ) ; Object v = threadLocalMap . indexedVariable ( index ) ; if ( v != InternalThreadLocalMap . UNSET ) { return ( V ) v ; } return initialize ( threadLocalMap ) ; } | Returns the current value for the current thread |
13,827 | public final void set ( V value ) { if ( value != InternalThreadLocalMap . UNSET ) { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap . get ( ) ; setKnownNotUnset ( threadLocalMap , value ) ; } else { remove ( ) ; } } | Set the value for the current thread . |
13,828 | public void setOcspResponse ( byte [ ] response ) { if ( ! enableOcsp ) { throw new IllegalStateException ( "OCSP stapling is not enabled" ) ; } if ( clientMode ) { throw new IllegalStateException ( "Not a server SSLEngine" ) ; } synchronized ( this ) { SSL . setOcspResponse ( ssl , response ) ; } } | Sets the OCSP response . |
13,829 | public final synchronized void shutdown ( ) { if ( DESTROYED_UPDATER . compareAndSet ( this , 0 , 1 ) ) { engineMap . remove ( ssl ) ; SSL . freeSSL ( ssl ) ; ssl = networkBIO = 0 ; isInboundDone = outboundClosed = true ; } SSL . clearError ( ) ; } | Destroys this engine . |
13,830 | private int writePlaintextData ( final ByteBuffer src , int len ) { final int pos = src . position ( ) ; final int limit = src . limit ( ) ; final int sslWrote ; if ( src . isDirect ( ) ) { sslWrote = SSL . writeToSSL ( ssl , bufferAddress ( src ) + pos , len ) ; if ( sslWrote > 0 ) { src . position ( pos + sslWrote ) ; } } else { ByteBuf buf = alloc . directBuffer ( len ) ; try { src . limit ( pos + len ) ; buf . setBytes ( 0 , src ) ; src . limit ( limit ) ; sslWrote = SSL . writeToSSL ( ssl , memoryAddress ( buf ) , len ) ; if ( sslWrote > 0 ) { src . position ( pos + sslWrote ) ; } else { src . position ( pos ) ; } } finally { buf . release ( ) ; } } return sslWrote ; } | Write plaintext data to the OpenSSL internal BIO |
13,831 | private ByteBuf writeEncryptedData ( final ByteBuffer src , int len ) { final int pos = src . position ( ) ; if ( src . isDirect ( ) ) { SSL . bioSetByteBuffer ( networkBIO , bufferAddress ( src ) + pos , len , false ) ; } else { final ByteBuf buf = alloc . directBuffer ( len ) ; try { final int limit = src . limit ( ) ; src . limit ( pos + len ) ; buf . writeBytes ( src ) ; src . position ( pos ) ; src . limit ( limit ) ; SSL . bioSetByteBuffer ( networkBIO , memoryAddress ( buf ) , len , false ) ; return buf ; } catch ( Throwable cause ) { buf . release ( ) ; PlatformDependent . throwException ( cause ) ; } } return null ; } | Write encrypted data to the OpenSSL network BIO . |
13,832 | private int readPlaintextData ( final ByteBuffer dst ) { final int sslRead ; final int pos = dst . position ( ) ; if ( dst . isDirect ( ) ) { sslRead = SSL . readFromSSL ( ssl , bufferAddress ( dst ) + pos , dst . limit ( ) - pos ) ; if ( sslRead > 0 ) { dst . position ( pos + sslRead ) ; } } else { final int limit = dst . limit ( ) ; final int len = min ( maxEncryptedPacketLength0 ( ) , limit - pos ) ; final ByteBuf buf = alloc . directBuffer ( len ) ; try { sslRead = SSL . readFromSSL ( ssl , memoryAddress ( buf ) , len ) ; if ( sslRead > 0 ) { dst . limit ( pos + sslRead ) ; buf . getBytes ( buf . readerIndex ( ) , dst ) ; dst . limit ( limit ) ; } } finally { buf . release ( ) ; } } return sslRead ; } | Read plaintext data from the OpenSSL internal BIO |
13,833 | private SSLException shutdownWithError ( String operations , int sslError ) { return shutdownWithError ( operations , sslError , SSL . getLastErrorNumber ( ) ) ; } | Log the error shutdown the engine and throw an exception . |
13,834 | private String toJavaCipherSuite ( String openSslCipherSuite ) { if ( openSslCipherSuite == null ) { return null ; } String version = SSL . getVersion ( ssl ) ; String prefix = toJavaCipherSuitePrefix ( version ) ; return CipherSuiteConverter . toJava ( openSslCipherSuite , prefix ) ; } | Converts the specified OpenSSL cipher suite to the Java cipher suite . |
13,835 | static ByteBuf doEncode ( ByteBufAllocator byteBufAllocator , MqttMessage message ) { switch ( message . fixedHeader ( ) . messageType ( ) ) { case CONNECT : return encodeConnectMessage ( byteBufAllocator , ( MqttConnectMessage ) message ) ; case CONNACK : return encodeConnAckMessage ( byteBufAllocator , ( MqttConnAckMessage ) message ) ; case PUBLISH : return encodePublishMessage ( byteBufAllocator , ( MqttPublishMessage ) message ) ; case SUBSCRIBE : return encodeSubscribeMessage ( byteBufAllocator , ( MqttSubscribeMessage ) message ) ; case UNSUBSCRIBE : return encodeUnsubscribeMessage ( byteBufAllocator , ( MqttUnsubscribeMessage ) message ) ; case SUBACK : return encodeSubAckMessage ( byteBufAllocator , ( MqttSubAckMessage ) message ) ; case UNSUBACK : case PUBACK : case PUBREC : case PUBREL : case PUBCOMP : return encodeMessageWithOnlySingleByteFixedHeaderAndMessageId ( byteBufAllocator , message ) ; case PINGREQ : case PINGRESP : case DISCONNECT : return encodeMessageWithOnlySingleByteFixedHeader ( byteBufAllocator , message ) ; default : throw new IllegalArgumentException ( "Unknown message type: " + message . fixedHeader ( ) . messageType ( ) . value ( ) ) ; } } | This is the main encoding method . It s only visible for testing . |
13,836 | private Http2Settings decodeSettings ( ChannelHandlerContext ctx , ByteBuf frame ) throws Http2Exception { try { final Http2Settings decodedSettings = new Http2Settings ( ) ; frameReader . readFrame ( ctx , frame , new Http2FrameAdapter ( ) { public void onSettingsRead ( ChannelHandlerContext ctx , Http2Settings settings ) { decodedSettings . copyFrom ( settings ) ; } } ) ; return decodedSettings ; } finally { frame . release ( ) ; } } | Decodes the settings frame and returns the settings . |
13,837 | private static ByteBuf createSettingsFrame ( ChannelHandlerContext ctx , ByteBuf payload ) { ByteBuf frame = ctx . alloc ( ) . buffer ( FRAME_HEADER_LENGTH + payload . readableBytes ( ) ) ; writeFrameHeader ( frame , payload . readableBytes ( ) , SETTINGS , new Http2Flags ( ) , 0 ) ; frame . writeBytes ( payload ) ; payload . release ( ) ; return frame ; } | Creates an HTTP2 - Settings header with the given payload . The payload buffer is released . |
13,838 | public void closeStreamLocal ( Http2Stream stream , ChannelFuture future ) { switch ( stream . state ( ) ) { case HALF_CLOSED_LOCAL : case OPEN : stream . closeLocalSide ( ) ; break ; default : closeStream ( stream , future ) ; break ; } } | Closes the local side of the given stream . If this causes the stream to be closed adds a hook to close the channel after the given future completes . |
13,839 | public void closeStreamRemote ( Http2Stream stream , ChannelFuture future ) { switch ( stream . state ( ) ) { case HALF_CLOSED_REMOTE : case OPEN : stream . closeRemoteSide ( ) ; break ; default : closeStream ( stream , future ) ; break ; } } | Closes the remote side of the given stream . If this causes the stream to be closed adds a hook to close the channel after the given future completes . |
13,840 | protected void onConnectionError ( ChannelHandlerContext ctx , boolean outbound , Throwable cause , Http2Exception http2Ex ) { if ( http2Ex == null ) { http2Ex = new Http2Exception ( INTERNAL_ERROR , cause . getMessage ( ) , cause ) ; } ChannelPromise promise = ctx . newPromise ( ) ; ChannelFuture future = goAway ( ctx , http2Ex , ctx . newPromise ( ) ) ; if ( http2Ex . shutdownHint ( ) == Http2Exception . ShutdownHint . GRACEFUL_SHUTDOWN ) { doGracefulShutdown ( ctx , future , promise ) ; } else { future . addListener ( new ClosingChannelFutureListener ( ctx , promise ) ) ; } } | Handler for a connection error . Sends a GO_AWAY frame to the remote endpoint . Once all streams are closed the connection is shut down . |
13,841 | protected void handleServerHeaderDecodeSizeError ( ChannelHandlerContext ctx , Http2Stream stream ) { encoder ( ) . writeHeaders ( ctx , stream . id ( ) , HEADERS_TOO_LARGE_HEADERS , 0 , true , ctx . newPromise ( ) ) ; } | Notifies client that this server has received headers that are larger than what it is willing to accept . Override to change behavior . |
13,842 | private void checkCloseConnection ( ChannelFuture future ) { if ( closeListener != null && isGracefulShutdownComplete ( ) ) { ChannelFutureListener closeListener = this . closeListener ; this . closeListener = null ; try { closeListener . operationComplete ( future ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Close listener threw an unexpected exception" , e ) ; } } } | Closes the connection if the graceful shutdown process has completed . |
13,843 | private CharSequence getSettingsHeaderValue ( ChannelHandlerContext ctx ) { ByteBuf buf = null ; ByteBuf encodedBuf = null ; try { Http2Settings settings = connectionHandler . decoder ( ) . localSettings ( ) ; int payloadLength = SETTING_ENTRY_LENGTH * settings . size ( ) ; buf = ctx . alloc ( ) . buffer ( payloadLength ) ; for ( CharObjectMap . PrimitiveEntry < Long > entry : settings . entries ( ) ) { buf . writeChar ( entry . key ( ) ) ; buf . writeInt ( entry . value ( ) . intValue ( ) ) ; } encodedBuf = Base64 . encode ( buf , URL_SAFE ) ; return encodedBuf . toString ( UTF_8 ) ; } finally { release ( buf ) ; release ( encodedBuf ) ; } } | Converts the current settings for the handler to the Base64 - encoded representation used in the HTTP2 - Settings upgrade header . |
13,844 | public static Charset getCharset ( HttpMessage message , Charset defaultCharset ) { CharSequence contentTypeValue = message . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) ; if ( contentTypeValue != null ) { return getCharset ( contentTypeValue , defaultCharset ) ; } else { return defaultCharset ; } } | Fetch charset from message s Content - Type header . |
13,845 | public static CharSequence getCharsetAsSequence ( HttpMessage message ) { CharSequence contentTypeValue = message . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) ; if ( contentTypeValue != null ) { return getCharsetAsSequence ( contentTypeValue ) ; } else { return null ; } } | Fetch charset from message s Content - Type header as a char sequence . |
13,846 | public static CharSequence getCharsetAsSequence ( CharSequence contentTypeValue ) { if ( contentTypeValue == null ) { throw new NullPointerException ( "contentTypeValue" ) ; } int indexOfCharset = AsciiString . indexOfIgnoreCaseAscii ( contentTypeValue , CHARSET_EQUALS , 0 ) ; if ( indexOfCharset == AsciiString . INDEX_NOT_FOUND ) { return null ; } int indexOfEncoding = indexOfCharset + CHARSET_EQUALS . length ( ) ; if ( indexOfEncoding < contentTypeValue . length ( ) ) { CharSequence charsetCandidate = contentTypeValue . subSequence ( indexOfEncoding , contentTypeValue . length ( ) ) ; int indexOfSemicolon = AsciiString . indexOfIgnoreCaseAscii ( charsetCandidate , SEMICOLON , 0 ) ; if ( indexOfSemicolon == AsciiString . INDEX_NOT_FOUND ) { return charsetCandidate ; } return charsetCandidate . subSequence ( 0 , indexOfSemicolon ) ; } return null ; } | Fetch charset from Content - Type header value as a char sequence . |
13,847 | public static CharSequence getMimeType ( CharSequence contentTypeValue ) { if ( contentTypeValue == null ) { throw new NullPointerException ( "contentTypeValue" ) ; } int indexOfSemicolon = AsciiString . indexOfIgnoreCaseAscii ( contentTypeValue , SEMICOLON , 0 ) ; if ( indexOfSemicolon != AsciiString . INDEX_NOT_FOUND ) { return contentTypeValue . subSequence ( 0 , indexOfSemicolon ) ; } else { return contentTypeValue . length ( ) > 0 ? contentTypeValue : null ; } } | Fetch MIME type part from Content - Type header value as a char sequence . |
13,848 | public static String formatHostnameForHttp ( InetSocketAddress addr ) { String hostString = NetUtil . getHostname ( addr ) ; if ( NetUtil . isValidIpV6Address ( hostString ) ) { if ( ! addr . isUnresolved ( ) ) { hostString = NetUtil . toAddressString ( addr . getAddress ( ) ) ; } return '[' + hostString + ']' ; } return hostString ; } | Formats the host string of an address so it can be used for computing an HTTP component such as an URL or a Host header |
13,849 | private static void generateHuffmanCodeLengths ( final int alphabetSize , final int [ ] symbolFrequencies , final int [ ] codeLengths ) { final int [ ] mergedFrequenciesAndIndices = new int [ alphabetSize ] ; final int [ ] sortedFrequencies = new int [ alphabetSize ] ; for ( int i = 0 ; i < alphabetSize ; i ++ ) { mergedFrequenciesAndIndices [ i ] = ( symbolFrequencies [ i ] << 9 ) | i ; } Arrays . sort ( mergedFrequenciesAndIndices ) ; for ( int i = 0 ; i < alphabetSize ; i ++ ) { sortedFrequencies [ i ] = mergedFrequenciesAndIndices [ i ] >>> 9 ; } Bzip2HuffmanAllocator . allocateHuffmanCodeLengths ( sortedFrequencies , HUFFMAN_ENCODE_MAX_CODE_LENGTH ) ; for ( int i = 0 ; i < alphabetSize ; i ++ ) { codeLengths [ mergedFrequenciesAndIndices [ i ] & 0x1ff ] = sortedFrequencies [ i ] ; } } | Generate a Huffman code length table for a given list of symbol frequencies . |
13,850 | private void assignHuffmanCodeSymbols ( ) { final int [ ] [ ] huffmanMergedCodeSymbols = this . huffmanMergedCodeSymbols ; final int [ ] [ ] huffmanCodeLengths = this . huffmanCodeLengths ; final int mtfAlphabetSize = this . mtfAlphabetSize ; final int totalTables = huffmanCodeLengths . length ; for ( int i = 0 ; i < totalTables ; i ++ ) { final int [ ] tableLengths = huffmanCodeLengths [ i ] ; int minimumLength = 32 ; int maximumLength = 0 ; for ( int j = 0 ; j < mtfAlphabetSize ; j ++ ) { final int length = tableLengths [ j ] ; if ( length > maximumLength ) { maximumLength = length ; } if ( length < minimumLength ) { minimumLength = length ; } } int code = 0 ; for ( int j = minimumLength ; j <= maximumLength ; j ++ ) { for ( int k = 0 ; k < mtfAlphabetSize ; k ++ ) { if ( ( huffmanCodeLengths [ i ] [ k ] & 0xff ) == j ) { huffmanMergedCodeSymbols [ i ] [ k ] = ( j << 24 ) | code ; code ++ ; } } code <<= 1 ; } } } | Assigns Canonical Huffman codes based on the calculated lengths . |
13,851 | private void writeSelectorsAndHuffmanTables ( ByteBuf out ) { final Bzip2BitWriter writer = this . writer ; final byte [ ] selectors = this . selectors ; final int totalSelectors = selectors . length ; final int [ ] [ ] huffmanCodeLengths = this . huffmanCodeLengths ; final int totalTables = huffmanCodeLengths . length ; final int mtfAlphabetSize = this . mtfAlphabetSize ; writer . writeBits ( out , 3 , totalTables ) ; writer . writeBits ( out , 15 , totalSelectors ) ; Bzip2MoveToFrontTable selectorMTF = new Bzip2MoveToFrontTable ( ) ; for ( byte selector : selectors ) { writer . writeUnary ( out , selectorMTF . valueToFront ( selector ) ) ; } for ( final int [ ] tableLengths : huffmanCodeLengths ) { int currentLength = tableLengths [ 0 ] ; writer . writeBits ( out , 5 , currentLength ) ; for ( int j = 0 ; j < mtfAlphabetSize ; j ++ ) { final int codeLength = tableLengths [ j ] ; final int value = currentLength < codeLength ? 2 : 3 ; int delta = Math . abs ( codeLength - currentLength ) ; while ( delta -- > 0 ) { writer . writeBits ( out , 2 , value ) ; } writer . writeBoolean ( out , false ) ; currentLength = codeLength ; } } } | Write out the selector list and Huffman tables . |
13,852 | private void writeBlockData ( ByteBuf out ) { final Bzip2BitWriter writer = this . writer ; final int [ ] [ ] huffmanMergedCodeSymbols = this . huffmanMergedCodeSymbols ; final byte [ ] selectors = this . selectors ; final char [ ] mtf = mtfBlock ; final int mtfLength = this . mtfLength ; int selectorIndex = 0 ; for ( int mtfIndex = 0 ; mtfIndex < mtfLength ; ) { final int groupEnd = Math . min ( mtfIndex + HUFFMAN_GROUP_RUN_LENGTH , mtfLength ) - 1 ; final int [ ] tableMergedCodeSymbols = huffmanMergedCodeSymbols [ selectors [ selectorIndex ++ ] ] ; while ( mtfIndex <= groupEnd ) { final int mergedCodeSymbol = tableMergedCodeSymbols [ mtf [ mtfIndex ++ ] ] ; writer . writeBits ( out , mergedCodeSymbol >>> 24 , mergedCodeSymbol ) ; } } } | Writes out the encoded block data . |
13,853 | void encode ( ByteBuf out ) { generateHuffmanOptimisationSeeds ( ) ; for ( int i = 3 ; i >= 0 ; i -- ) { optimiseSelectorsAndHuffmanTables ( i == 0 ) ; } assignHuffmanCodeSymbols ( ) ; writeSelectorsAndHuffmanTables ( out ) ; writeBlockData ( out ) ; } | Encodes and writes the block data . |
13,854 | public void resumeTransfer ( ) { final ChannelHandlerContext ctx = this . ctx ; if ( ctx == null ) { return ; } if ( ctx . executor ( ) . inEventLoop ( ) ) { resumeTransfer0 ( ctx ) ; } else { ctx . executor ( ) . execute ( new Runnable ( ) { public void run ( ) { resumeTransfer0 ( ctx ) ; } } ) ; } } | Continues to fetch the chunks from the input . |
13,855 | boolean decodeHuffmanData ( final Bzip2HuffmanStageDecoder huffmanDecoder ) { final Bzip2BitReader reader = this . reader ; final byte [ ] bwtBlock = this . bwtBlock ; final byte [ ] huffmanSymbolMap = this . huffmanSymbolMap ; final int streamBlockSize = this . bwtBlock . length ; final int huffmanEndOfBlockSymbol = this . huffmanEndOfBlockSymbol ; final int [ ] bwtByteCounts = this . bwtByteCounts ; final Bzip2MoveToFrontTable symbolMTF = this . symbolMTF ; int bwtBlockLength = this . bwtBlockLength ; int repeatCount = this . repeatCount ; int repeatIncrement = this . repeatIncrement ; int mtfValue = this . mtfValue ; for ( ; ; ) { if ( ! reader . hasReadableBits ( HUFFMAN_DECODE_MAX_CODE_LENGTH ) ) { this . bwtBlockLength = bwtBlockLength ; this . repeatCount = repeatCount ; this . repeatIncrement = repeatIncrement ; this . mtfValue = mtfValue ; return false ; } final int nextSymbol = huffmanDecoder . nextSymbol ( ) ; if ( nextSymbol == HUFFMAN_SYMBOL_RUNA ) { repeatCount += repeatIncrement ; repeatIncrement <<= 1 ; } else if ( nextSymbol == HUFFMAN_SYMBOL_RUNB ) { repeatCount += repeatIncrement << 1 ; repeatIncrement <<= 1 ; } else { if ( repeatCount > 0 ) { if ( bwtBlockLength + repeatCount > streamBlockSize ) { throw new DecompressionException ( "block exceeds declared block size" ) ; } final byte nextByte = huffmanSymbolMap [ mtfValue ] ; bwtByteCounts [ nextByte & 0xff ] += repeatCount ; while ( -- repeatCount >= 0 ) { bwtBlock [ bwtBlockLength ++ ] = nextByte ; } repeatCount = 0 ; repeatIncrement = 1 ; } if ( nextSymbol == huffmanEndOfBlockSymbol ) { break ; } if ( bwtBlockLength >= streamBlockSize ) { throw new DecompressionException ( "block exceeds declared block size" ) ; } mtfValue = symbolMTF . indexToFront ( nextSymbol - 1 ) & 0xff ; final byte nextByte = huffmanSymbolMap [ mtfValue ] ; bwtByteCounts [ nextByte & 0xff ] ++ ; bwtBlock [ bwtBlockLength ++ ] = nextByte ; } } this . bwtBlockLength = bwtBlockLength ; initialiseInverseBWT ( ) ; return true ; } | Reads the Huffman encoded data from the input stream performs Run - Length Decoding and applies the Move To Front transform to reconstruct the Burrows - Wheeler Transform array . |
13,856 | private void initialiseInverseBWT ( ) { final int bwtStartPointer = this . bwtStartPointer ; final byte [ ] bwtBlock = this . bwtBlock ; final int [ ] bwtMergedPointers = new int [ bwtBlockLength ] ; final int [ ] characterBase = new int [ 256 ] ; if ( bwtStartPointer < 0 || bwtStartPointer >= bwtBlockLength ) { throw new DecompressionException ( "start pointer invalid" ) ; } System . arraycopy ( bwtByteCounts , 0 , characterBase , 1 , 255 ) ; for ( int i = 2 ; i <= 255 ; i ++ ) { characterBase [ i ] += characterBase [ i - 1 ] ; } for ( int i = 0 ; i < bwtBlockLength ; i ++ ) { int value = bwtBlock [ i ] & 0xff ; bwtMergedPointers [ characterBase [ value ] ++ ] = ( i << 8 ) + value ; } this . bwtMergedPointers = bwtMergedPointers ; bwtCurrentMergedPointer = bwtMergedPointers [ bwtStartPointer ] ; } | Set up the Inverse Burrows - Wheeler Transform merged pointer array . |
13,857 | public int read ( ) { while ( rleRepeat < 1 ) { if ( bwtBytesDecoded == bwtBlockLength ) { return - 1 ; } int nextByte = decodeNextBWTByte ( ) ; if ( nextByte != rleLastDecodedByte ) { rleLastDecodedByte = nextByte ; rleRepeat = 1 ; rleAccumulator = 1 ; crc . updateCRC ( nextByte ) ; } else { if ( ++ rleAccumulator == 4 ) { int rleRepeat = decodeNextBWTByte ( ) + 1 ; this . rleRepeat = rleRepeat ; rleAccumulator = 0 ; crc . updateCRC ( nextByte , rleRepeat ) ; } else { rleRepeat = 1 ; crc . updateCRC ( nextByte ) ; } } } rleRepeat -- ; return rleLastDecodedByte ; } | Decodes a byte from the final Run - Length Encoding stage pulling a new byte from the Burrows - Wheeler Transform stage when required . |
13,858 | private int decodeNextBWTByte ( ) { int mergedPointer = bwtCurrentMergedPointer ; int nextDecodedByte = mergedPointer & 0xff ; bwtCurrentMergedPointer = bwtMergedPointers [ mergedPointer >>> 8 ] ; if ( blockRandomised ) { if ( -- randomCount == 0 ) { nextDecodedByte ^= 1 ; randomIndex = ( randomIndex + 1 ) % 512 ; randomCount = Bzip2Rand . rNums ( randomIndex ) ; } } bwtBytesDecoded ++ ; return nextDecodedByte ; } | Decodes a byte from the Burrows - Wheeler Transform stage . If the block has randomisation applied reverses the randomisation . |
13,859 | public void encode ( ByteBuf out , CharSequence data ) { ObjectUtil . checkNotNull ( out , "out" ) ; if ( data instanceof AsciiString ) { AsciiString string = ( AsciiString ) data ; try { encodeProcessor . out = out ; string . forEachByte ( encodeProcessor ) ; } catch ( Exception e ) { PlatformDependent . throwException ( e ) ; } finally { encodeProcessor . end ( ) ; } } else { encodeSlowPath ( out , data ) ; } } | Compresses the input string literal using the Huffman coding . |
13,860 | int getEncodedLength ( CharSequence data ) { if ( data instanceof AsciiString ) { AsciiString string = ( AsciiString ) data ; try { encodedLengthProcessor . reset ( ) ; string . forEachByte ( encodedLengthProcessor ) ; return encodedLengthProcessor . length ( ) ; } catch ( Exception e ) { PlatformDependent . throwException ( e ) ; return - 1 ; } } else { return getEncodedLengthSlowPath ( data ) ; } } | Returns the number of bytes required to Huffman encode the input string literal . |
13,861 | static boolean patchShadedLibraryId ( InputStream in , OutputStream out , String originalName , String name ) throws IOException { byte [ ] buffer = new byte [ 8192 ] ; int length ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( in . available ( ) ) ; while ( ( length = in . read ( buffer ) ) > 0 ) { byteArrayOutputStream . write ( buffer , 0 , length ) ; } byteArrayOutputStream . flush ( ) ; byte [ ] bytes = byteArrayOutputStream . toByteArray ( ) ; byteArrayOutputStream . close ( ) ; final boolean patched ; if ( ! patchShadedLibraryId ( bytes , originalName , name ) ) { String os = PlatformDependent . normalizedOs ( ) ; String arch = PlatformDependent . normalizedArch ( ) ; String osArch = "_" + os + "_" + arch ; if ( originalName . endsWith ( osArch ) ) { patched = patchShadedLibraryId ( bytes , originalName . substring ( 0 , originalName . length ( ) - osArch . length ( ) ) , name ) ; } else { patched = false ; } } else { patched = true ; } out . write ( bytes , 0 , bytes . length ) ; return patched ; } | Package - private for testing . |
13,862 | private static boolean patchShadedLibraryId ( byte [ ] bytes , String originalName , String name ) { byte [ ] nameBytes = originalName . getBytes ( CharsetUtil . UTF_8 ) ; int idIdx = - 1 ; outerLoop : for ( int i = 0 ; i < bytes . length && bytes . length - i >= nameBytes . length ; i ++ ) { int idx = i ; for ( int j = 0 ; j < nameBytes . length ; ) { if ( bytes [ idx ++ ] != nameBytes [ j ++ ] ) { break ; } else if ( j == nameBytes . length ) { idIdx = i ; break outerLoop ; } } } if ( idIdx == - 1 ) { logger . debug ( "Was not able to find the ID of the shaded native library {}, can't adjust it." , name ) ; return false ; } else { for ( int i = 0 ; i < nameBytes . length ; i ++ ) { bytes [ idIdx + i ] = UNIQUE_ID_BYTES [ PlatformDependent . threadLocalRandom ( ) . nextInt ( UNIQUE_ID_BYTES . length ) ] ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Found the ID of the shaded native library {}. Replacing ID part {} with {}" , name , originalName , new String ( bytes , idIdx , nameBytes . length , CharsetUtil . UTF_8 ) ) ; } return true ; } } | Try to patch shaded library to ensure it uses a unique ID . |
13,863 | private M invalidMessage ( Exception cause ) { state = State . BAD_MESSAGE ; M message = buildInvalidMessage ( ) ; message . setDecoderResult ( DecoderResult . failure ( cause ) ) ; return message ; } | Helper method to create a message indicating a invalid decoding result . |
13,864 | private MemcacheContent invalidChunk ( Exception cause ) { state = State . BAD_MESSAGE ; MemcacheContent chunk = new DefaultLastMemcacheContent ( Unpooled . EMPTY_BUFFER ) ; chunk . setDecoderResult ( DecoderResult . failure ( cause ) ) ; return chunk ; } | Helper method to create a content chunk indicating a invalid decoding result . |
13,865 | private T retain0 ( T instance , final int increment , final int rawIncrement ) { int oldRef = updater ( ) . getAndAdd ( instance , rawIncrement ) ; if ( oldRef != 2 && oldRef != 4 && ( oldRef & 1 ) != 0 ) { throw new IllegalReferenceCountException ( 0 , increment ) ; } if ( ( oldRef <= 0 && oldRef + rawIncrement >= 0 ) || ( oldRef >= 0 && oldRef + rawIncrement < oldRef ) ) { updater ( ) . getAndAdd ( instance , - rawIncrement ) ; throw new IllegalReferenceCountException ( realRefCnt ( oldRef ) , increment ) ; } return instance ; } | rawIncrement == increment << 1 |
13,866 | public final void channelReadComplete ( ChannelHandlerContext ctx ) throws Exception { try { onChannelReadComplete ( ctx ) ; } finally { parentReadInProgress = false ; tail = head = null ; flush0 ( ctx ) ; } channelReadComplete0 ( ctx ) ; } | Notifies any child streams of the read completion . |
13,867 | public static byte [ ] bestAvailableMac ( ) { byte [ ] bestMacAddr = EMPTY_BYTES ; InetAddress bestInetAddr = NetUtil . LOCALHOST4 ; Map < NetworkInterface , InetAddress > ifaces = new LinkedHashMap < NetworkInterface , InetAddress > ( ) ; try { Enumeration < NetworkInterface > interfaces = NetworkInterface . getNetworkInterfaces ( ) ; if ( interfaces != null ) { while ( interfaces . hasMoreElements ( ) ) { NetworkInterface iface = interfaces . nextElement ( ) ; Enumeration < InetAddress > addrs = SocketUtils . addressesFromNetworkInterface ( iface ) ; if ( addrs . hasMoreElements ( ) ) { InetAddress a = addrs . nextElement ( ) ; if ( ! a . isLoopbackAddress ( ) ) { ifaces . put ( iface , a ) ; } } } } } catch ( SocketException e ) { logger . warn ( "Failed to retrieve the list of available network interfaces" , e ) ; } for ( Entry < NetworkInterface , InetAddress > entry : ifaces . entrySet ( ) ) { NetworkInterface iface = entry . getKey ( ) ; InetAddress inetAddr = entry . getValue ( ) ; if ( iface . isVirtual ( ) ) { continue ; } byte [ ] macAddr ; try { macAddr = SocketUtils . hardwareAddressFromNetworkInterface ( iface ) ; } catch ( SocketException e ) { logger . debug ( "Failed to get the hardware address of a network interface: {}" , iface , e ) ; continue ; } boolean replace = false ; int res = compareAddresses ( bestMacAddr , macAddr ) ; if ( res < 0 ) { replace = true ; } else if ( res == 0 ) { res = compareAddresses ( bestInetAddr , inetAddr ) ; if ( res < 0 ) { replace = true ; } else if ( res == 0 ) { if ( bestMacAddr . length < macAddr . length ) { replace = true ; } } } if ( replace ) { bestMacAddr = macAddr ; bestInetAddr = inetAddr ; } } if ( bestMacAddr == EMPTY_BYTES ) { return null ; } switch ( bestMacAddr . length ) { case EUI48_MAC_ADDRESS_LENGTH : byte [ ] newAddr = new byte [ EUI64_MAC_ADDRESS_LENGTH ] ; System . arraycopy ( bestMacAddr , 0 , newAddr , 0 , 3 ) ; newAddr [ 3 ] = ( byte ) 0xFF ; newAddr [ 4 ] = ( byte ) 0xFE ; System . arraycopy ( bestMacAddr , 3 , newAddr , 5 , 3 ) ; bestMacAddr = newAddr ; break ; default : bestMacAddr = Arrays . copyOf ( bestMacAddr , EUI64_MAC_ADDRESS_LENGTH ) ; } return bestMacAddr ; } | Obtains the best MAC address found on local network interfaces . Generally speaking an active network interface used on public networks is better than a local network interface . |
13,868 | protected B maxReservedStreams ( int maxReservedStreams ) { enforceConstraint ( "server" , "connection" , connection ) ; enforceConstraint ( "server" , "codec" , decoder ) ; enforceConstraint ( "server" , "codec" , encoder ) ; this . maxReservedStreams = checkPositiveOrZero ( maxReservedStreams , "maxReservedStreams" ) ; return self ( ) ; } | Set the maximum number of streams which can be in the reserved state at any given time . |
13,869 | private static boolean isUpgradeRequest ( HttpObject msg ) { return msg instanceof HttpRequest && ( ( HttpRequest ) msg ) . headers ( ) . get ( HttpHeaderNames . UPGRADE ) != null ; } | Determines whether or not the message is an HTTP upgrade request . |
13,870 | private static FullHttpResponse createUpgradeResponse ( CharSequence upgradeProtocol ) { DefaultFullHttpResponse res = new DefaultFullHttpResponse ( HTTP_1_1 , SWITCHING_PROTOCOLS , Unpooled . EMPTY_BUFFER , false ) ; res . headers ( ) . add ( HttpHeaderNames . CONNECTION , HttpHeaderValues . UPGRADE ) ; res . headers ( ) . add ( HttpHeaderNames . UPGRADE , upgradeProtocol ) ; return res ; } | Creates the 101 Switching Protocols response message . |
13,871 | private static List < CharSequence > splitHeader ( CharSequence header ) { final StringBuilder builder = new StringBuilder ( header . length ( ) ) ; final List < CharSequence > protocols = new ArrayList < CharSequence > ( 4 ) ; for ( int i = 0 ; i < header . length ( ) ; ++ i ) { char c = header . charAt ( i ) ; if ( Character . isWhitespace ( c ) ) { continue ; } if ( c == ',' ) { protocols . add ( builder . toString ( ) ) ; builder . setLength ( 0 ) ; } else { builder . append ( c ) ; } } if ( builder . length ( ) > 0 ) { protocols . add ( builder . toString ( ) ) ; } return protocols ; } | Splits a comma - separated header value . The returned set is case - insensitive and contains each part with whitespace removed . |
13,872 | void modify ( AbstractEpollChannel ch ) throws IOException { assert inEventLoop ( ) ; Native . epollCtlMod ( epollFd . intValue ( ) , ch . socket . intValue ( ) , ch . flags ) ; } | The flags of the given epoll was modified so update the registration |
13,873 | void handleLoopException ( Throwable t ) { logger . warn ( "Unexpected exception in the selector loop." , t ) ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } | Visible only for testing! |
13,874 | public static String decodeName ( ByteBuf in ) { int position = - 1 ; int checked = 0 ; final int end = in . writerIndex ( ) ; final int readable = in . readableBytes ( ) ; if ( readable == 0 ) { return ROOT ; } final StringBuilder name = new StringBuilder ( readable << 1 ) ; while ( in . isReadable ( ) ) { final int len = in . readUnsignedByte ( ) ; final boolean pointer = ( len & 0xc0 ) == 0xc0 ; if ( pointer ) { if ( position == - 1 ) { position = in . readerIndex ( ) + 1 ; } if ( ! in . isReadable ( ) ) { throw new CorruptedFrameException ( "truncated pointer in a name" ) ; } final int next = ( len & 0x3f ) << 8 | in . readUnsignedByte ( ) ; if ( next >= end ) { throw new CorruptedFrameException ( "name has an out-of-range pointer" ) ; } in . readerIndex ( next ) ; checked += 2 ; if ( checked >= end ) { throw new CorruptedFrameException ( "name contains a loop." ) ; } } else if ( len != 0 ) { if ( ! in . isReadable ( len ) ) { throw new CorruptedFrameException ( "truncated label in a name" ) ; } name . append ( in . toString ( in . readerIndex ( ) , len , CharsetUtil . UTF_8 ) ) . append ( '.' ) ; in . skipBytes ( len ) ; } else { break ; } } if ( position != - 1 ) { in . readerIndex ( position ) ; } if ( name . length ( ) == 0 ) { return ROOT ; } if ( name . charAt ( name . length ( ) - 1 ) != '.' ) { name . append ( '.' ) ; } return name . toString ( ) ; } | Retrieves a domain name given a buffer containing a DNS packet . If the name contains a pointer the position of the buffer will be set to directly after the pointer s index after the name has been read . |
13,875 | void createGlobalTrafficCounter ( ScheduledExecutorService executor ) { if ( executor == null ) { throw new NullPointerException ( "executor" ) ; } TrafficCounter tc = new TrafficCounter ( this , executor , "GlobalTC" , checkInterval ) ; setTrafficCounter ( tc ) ; tc . start ( ) ; } | Create the global TrafficCounter . |
13,876 | public void write ( ChannelHandlerContext ctx , Object msg , ChannelPromise promise ) { String command = ( String ) msg ; if ( command . startsWith ( "get " ) ) { String keyString = command . substring ( "get " . length ( ) ) ; ByteBuf key = Unpooled . wrappedBuffer ( keyString . getBytes ( CharsetUtil . UTF_8 ) ) ; BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest ( key ) ; req . setOpcode ( BinaryMemcacheOpcodes . GET ) ; ctx . write ( req , promise ) ; } else if ( command . startsWith ( "set " ) ) { String [ ] parts = command . split ( " " , 3 ) ; if ( parts . length < 3 ) { throw new IllegalArgumentException ( "Malformed Command: " + command ) ; } String keyString = parts [ 1 ] ; String value = parts [ 2 ] ; ByteBuf key = Unpooled . wrappedBuffer ( keyString . getBytes ( CharsetUtil . UTF_8 ) ) ; ByteBuf content = Unpooled . wrappedBuffer ( value . getBytes ( CharsetUtil . UTF_8 ) ) ; ByteBuf extras = ctx . alloc ( ) . buffer ( 8 ) ; extras . writeZero ( 8 ) ; BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest ( key , extras , content ) ; req . setOpcode ( BinaryMemcacheOpcodes . SET ) ; ctx . write ( req , promise ) ; } else { throw new IllegalStateException ( "Unknown Message: " + msg ) ; } } | Transforms basic string requests to binary memcache requests |
13,877 | public String get ( CharSequence name , String defaultValue ) { String value = get ( name ) ; if ( value == null ) { return defaultValue ; } return value ; } | Returns the value of a header with the specified name . If there are more than one values for the specified name the first value is returned . |
13,878 | public HttpHeaders add ( CharSequence name , Object value ) { return add ( name . toString ( ) , value ) ; } | Adds a new header with the specified name and value . |
13,879 | public HttpHeaders add ( CharSequence name , Iterable < ? > values ) { return add ( name . toString ( ) , values ) ; } | Adds a new header with the specified name and values . |
13,880 | public HttpHeaders set ( CharSequence name , Object value ) { return set ( name . toString ( ) , value ) ; } | Sets a header with the specified name and value . |
13,881 | public HttpHeaders set ( CharSequence name , Iterable < ? > values ) { return set ( name . toString ( ) , values ) ; } | Sets a header with the specified name and values . |
13,882 | public DefaultHeaders < K , V , T > copy ( ) { DefaultHeaders < K , V , T > copy = new DefaultHeaders < K , V , T > ( hashingStrategy , valueConverter , nameValidator , entries . length ) ; copy . addImpl ( this ) ; return copy ; } | Returns a deep copy of this instance . |
13,883 | protected void readTimedOut ( ChannelHandlerContext ctx ) throws Exception { if ( ! closed ) { ctx . fireExceptionCaught ( ReadTimeoutException . INSTANCE ) ; ctx . close ( ) ; closed = true ; } } | Is called when a read timeout was detected . |
13,884 | public String rawQuery ( ) { int start = pathEndIdx ( ) + 1 ; return start < uri . length ( ) ? uri . substring ( start ) : EMPTY_STRING ; } | Returns raw query string of the URI . |
13,885 | static int getUnsignedShort ( ByteBuf buf , int offset ) { return ( buf . getByte ( offset ) & 0xFF ) << 8 | buf . getByte ( offset + 1 ) & 0xFF ; } | Reads a big - endian unsigned short integer from the buffer . |
13,886 | static int getUnsignedMedium ( ByteBuf buf , int offset ) { return ( buf . getByte ( offset ) & 0xFF ) << 16 | ( buf . getByte ( offset + 1 ) & 0xFF ) << 8 | buf . getByte ( offset + 2 ) & 0xFF ; } | Reads a big - endian unsigned medium integer from the buffer . |
13,887 | static int getSignedInt ( ByteBuf buf , int offset ) { return ( buf . getByte ( offset ) & 0xFF ) << 24 | ( buf . getByte ( offset + 1 ) & 0xFF ) << 16 | ( buf . getByte ( offset + 2 ) & 0xFF ) << 8 | buf . getByte ( offset + 3 ) & 0xFF ; } | Reads a big - endian signed integer from the buffer . |
13,888 | static void validateHeaderName ( CharSequence name ) { if ( name == null ) { throw new NullPointerException ( "name" ) ; } if ( name . length ( ) == 0 ) { throw new IllegalArgumentException ( "name cannot be length zero" ) ; } if ( name . length ( ) > SPDY_MAX_NV_LENGTH ) { throw new IllegalArgumentException ( "name exceeds allowable length: " + name ) ; } for ( int i = 0 ; i < name . length ( ) ; i ++ ) { char c = name . charAt ( i ) ; if ( c == 0 ) { throw new IllegalArgumentException ( "name contains null character: " + name ) ; } if ( c >= 'A' && c <= 'Z' ) { throw new IllegalArgumentException ( "name must be all lower case." ) ; } if ( c > 127 ) { throw new IllegalArgumentException ( "name contains non-ascii character: " + name ) ; } } } | Validate a SPDY header name . |
13,889 | static void validateHeaderValue ( CharSequence value ) { if ( value == null ) { throw new NullPointerException ( "value" ) ; } for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; if ( c == 0 ) { throw new IllegalArgumentException ( "value contains null character: " + value ) ; } } } | Validate a SPDY header value . Does not validate max length . |
13,890 | void free ( boolean finalizer ) { if ( freed . compareAndSet ( false , true ) ) { int numFreed = free ( tinySubPageDirectCaches , finalizer ) + free ( smallSubPageDirectCaches , finalizer ) + free ( normalDirectCaches , finalizer ) + free ( tinySubPageHeapCaches , finalizer ) + free ( smallSubPageHeapCaches , finalizer ) + free ( normalHeapCaches , finalizer ) ; if ( numFreed > 0 && logger . isDebugEnabled ( ) ) { logger . debug ( "Freed {} thread-local buffer(s) from thread: {}" , numFreed , Thread . currentThread ( ) . getName ( ) ) ; } if ( directArena != null ) { directArena . numThreadCaches . getAndDecrement ( ) ; } if ( heapArena != null ) { heapArena . numThreadCaches . getAndDecrement ( ) ; } } } | Should be called if the Thread that uses this cache is about to exist to release resources out of the cache |
13,891 | public CorsConfigBuilder allowedRequestHeaders ( final CharSequence ... headers ) { for ( CharSequence header : headers ) { requestHeaders . add ( header . toString ( ) ) ; } return this ; } | Specifies the if headers that should be returned in the CORS Access - Control - Allow - Headers response header . |
13,892 | protected void cancelScheduledTasks ( ) { assert inEventLoop ( ) ; PriorityQueue < ScheduledFutureTask < ? > > scheduledTaskQueue = this . scheduledTaskQueue ; if ( isNullOrEmpty ( scheduledTaskQueue ) ) { return ; } final ScheduledFutureTask < ? > [ ] scheduledTasks = scheduledTaskQueue . toArray ( new ScheduledFutureTask < ? > [ 0 ] ) ; for ( ScheduledFutureTask < ? > task : scheduledTasks ) { task . cancelWithoutRemove ( false ) ; } scheduledTaskQueue . clearIgnoringIndexes ( ) ; } | Cancel all scheduled tasks . |
13,893 | static byte [ ] validIpV4ToBytes ( String ip ) { int i ; return new byte [ ] { ipv4WordToByte ( ip , 0 , i = ip . indexOf ( '.' , 1 ) ) , ipv4WordToByte ( ip , i + 1 , i = ip . indexOf ( '.' , i + 2 ) ) , ipv4WordToByte ( ip , i + 1 , i = ip . indexOf ( '.' , i + 2 ) ) , ipv4WordToByte ( ip , i + 1 , ip . length ( ) ) } ; } | visible for tests |
13,894 | public static String intToIpAddress ( int i ) { StringBuilder buf = new StringBuilder ( 15 ) ; buf . append ( i >> 24 & 0xff ) ; buf . append ( '.' ) ; buf . append ( i >> 16 & 0xff ) ; buf . append ( '.' ) ; buf . append ( i >> 8 & 0xff ) ; buf . append ( '.' ) ; buf . append ( i & 0xff ) ; return buf . toString ( ) ; } | Converts a 32 - bit integer into an IPv4 address . |
13,895 | public static String bytesToIpAddress ( byte [ ] bytes , int offset , int length ) { switch ( length ) { case 4 : { return new StringBuilder ( 15 ) . append ( bytes [ offset ] & 0xff ) . append ( '.' ) . append ( bytes [ offset + 1 ] & 0xff ) . append ( '.' ) . append ( bytes [ offset + 2 ] & 0xff ) . append ( '.' ) . append ( bytes [ offset + 3 ] & 0xff ) . toString ( ) ; } case 16 : return toAddressString ( bytes , offset , false ) ; default : throw new IllegalArgumentException ( "length: " + length + " (expected: 4 or 16)" ) ; } } | Converts 4 - byte or 16 - byte data into an IPv4 or IPv6 string respectively . |
13,896 | private void destroy ( ) { Lock writerLock = ctxLock . writeLock ( ) ; writerLock . lock ( ) ; try { if ( ctx != 0 ) { if ( enableOcsp ) { SSLContext . disableOcsp ( ctx ) ; } SSLContext . free ( ctx ) ; ctx = 0 ; OpenSslSessionContext context = sessionContext ( ) ; if ( context != null ) { context . destroy ( ) ; } } } finally { writerLock . unlock ( ) ; } } | producing a segfault . |
13,897 | public String applicationProtocol ( ) { SSLEngine engine = engine ( ) ; if ( ! ( engine instanceof ApplicationProtocolAccessor ) ) { return null ; } return ( ( ApplicationProtocolAccessor ) engine ) . getNegotiatedApplicationProtocol ( ) ; } | Returns the name of the current application - level protocol . |
13,898 | private void setHandshakeSuccess ( ) { handshakePromise . trySuccess ( ctx . channel ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "{} HANDSHAKEN: {}" , ctx . channel ( ) , engine . getSession ( ) . getCipherSuite ( ) ) ; } ctx . fireUserEventTriggered ( SslHandshakeCompletionEvent . SUCCESS ) ; if ( readDuringHandshake && ! ctx . channel ( ) . config ( ) . isAutoRead ( ) ) { readDuringHandshake = false ; ctx . read ( ) ; } } | Notify all the handshake futures about the successfully handshake |
13,899 | public HttpPostStandardRequestDecoder offer ( HttpContent content ) { checkDestroyed ( ) ; ByteBuf buf = content . content ( ) ; if ( undecodedChunk == null ) { undecodedChunk = buf . copy ( ) ; } else { undecodedChunk . writeBytes ( buf ) ; } if ( content instanceof LastHttpContent ) { isLastChunk = true ; } parseBody ( ) ; if ( undecodedChunk != null && undecodedChunk . writerIndex ( ) > discardThreshold ) { undecodedChunk . discardReadBytes ( ) ; } return this ; } | Initialized the internals from a new chunk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.