idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
127,600
public ResourceAddress newResourceAddress ( String location , String nextProtocol ) { if ( nextProtocol != null ) { ResourceOptions options = ResourceOptions . FACTORY . newResourceOptions ( ) ; options . setOption ( NEXT_PROTOCOL , nextProtocol ) ; return newResourceAddress ( location , options ) ; } else { return new...
convenience method only consider removing from API
127,601
private boolean loginMissingToken ( NextFilter nextFilter , IoSession session , HttpRequestMessage httpRequest , AuthenticationToken authToken , TypedCallbackHandlerMap additionalCallbacks , HttpRealmInfo [ ] realms , int realmIndex , LoginContext [ ] loginContexts ) { HttpRealmInfo realm = realms [ realmIndex ] ; Resu...
Handle the initial login attempt where the client has presumably not sent any specific authentication token yet .
127,602
public static void setProperty ( IoSession session , String key , String value ) { if ( key == null ) { throw new NullPointerException ( "key should not be null" ) ; } if ( value == null ) { removeProperty ( session , key ) ; } Map < String , String > context = getContext ( session ) ; context . put ( key , value ) ; M...
Add a property to the context for the given session This property will be added to the MDC for all subsequent events
127,603
public void exceptionCaught ( Throwable cause , IoSession s ) { if ( s == null ) { org . apache . mina . util . ExceptionMonitor . getInstance ( ) . exceptionCaught ( cause ) ; } else { exceptionCaught0 ( cause , s ) ; } }
Invoked when there are any uncaught exceptions .
127,604
public Node removeFirst ( ) { Node node = header . getNextNode ( ) ; firstByte += node . ba . last ( ) ; return removeNode ( node ) ; }
Removes the first node from this list
127,605
public Node removeLast ( ) { Node node = header . getPreviousNode ( ) ; lastByte -= node . ba . last ( ) ; return removeNode ( node ) ; }
Removes the last node in this list
127,606
protected void addNode ( Node nodeToInsert , Node insertBeforeNode ) { nodeToInsert . next = insertBeforeNode ; nodeToInsert . previous = insertBeforeNode . previous ; insertBeforeNode . previous . next = nodeToInsert ; insertBeforeNode . previous = nodeToInsert ; }
Inserts a new node into the list .
127,607
protected Node removeNode ( Node node ) { node . previous . next = node . next ; node . next . previous = node . previous ; node . removed = true ; return node ; }
Removes the specified node from the list .
127,608
public int estimateSize ( Object message ) { if ( message == null ) { return 8 ; } int answer = 8 + estimateSize ( message . getClass ( ) , null ) ; if ( message instanceof IoBuffer ) { answer += ( ( IoBuffer ) message ) . remaining ( ) ; } else if ( message instanceof WriteRequest ) { answer += estimateSize ( ( ( Writ...
Estimate the size of an Objecr in number of bytes
127,609
public static int networkByteOrderToInt ( byte [ ] buf , int start , int count ) { if ( count > 4 ) { throw new IllegalArgumentException ( "Cannot handle more than 4 bytes" ) ; } int result = 0 ; for ( int i = 0 ; i < count ; i ++ ) { result <<= 8 ; result |= ( buf [ start + i ] & 0xff ) ; } return result ; }
Returns the integer represented by up to 4 bytes in network byte order .
127,610
public static byte [ ] intToNetworkByteOrder ( int num , int count ) { byte [ ] buf = new byte [ count ] ; intToNetworkByteOrder ( num , buf , 0 , count ) ; return buf ; }
Encodes an integer into up to 4 bytes in network byte order .
127,611
public static String asHex ( byte [ ] bytes , String separator ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { String code = Integer . toHexString ( bytes [ i ] & 0xFF ) ; if ( ( bytes [ i ] & 0xFF ) < 16 ) { sb . append ( '0' ) ; } sb . append ( code ) ; if ( separator !=...
Returns a hexadecimal representation of the given byte array .
127,612
public static byte [ ] asByteArray ( String hex ) { byte [ ] bts = new byte [ hex . length ( ) / 2 ] ; for ( int i = 0 ; i < bts . length ; i ++ ) { bts [ i ] = ( byte ) Integer . parseInt ( hex . substring ( 2 * i , 2 * i + 2 ) , 16 ) ; } return bts ; }
Converts a hex string representation to a byte array .
127,613
public void updateThroughput ( long currentTime ) { synchronized ( throughputCalculationLock ) { int interval = ( int ) ( currentTime - lastThroughputCalculationTime ) ; long minInterval = getThroughputCalculationIntervalInMillis ( ) ; if ( minInterval == 0 || interval < minInterval ) { return ; } long readBytes = this...
Updates the throughput counters .
127,614
private String nextThreadName ( ) { Class < ? > cls = getClass ( ) ; int newThreadId ; synchronized ( threadIds ) { AtomicInteger threadId = threadIds . get ( cls ) ; if ( threadId == null ) { newThreadId = 1 ; threadIds . put ( cls , new AtomicInteger ( newThreadId ) ) ; } else { newThreadId = threadId . incrementAndG...
Compute the thread ID for this class instance . As we may have different classes we store the last ID number into a Map associating the class name to the last assigned ID .
127,615
private void startupProcessor ( ) { Processor processor = processorRef . get ( ) ; if ( processor == null ) { processor = new Processor ( ) ; if ( processorRef . compareAndSet ( null , processor ) ) { executor . execute ( new NamePreservingRunnable ( processor , threadName ) ) ; } } wakeup ( ) ; }
Starts the inner Processor asking the executor to pick a thread in its pool . The Runnable will be renamed
127,616
private int handleNewSessions ( ) { int addedSessions = 0 ; for ( ; ; ) { T session = newSessions . poll ( ) ; if ( session == null ) { break ; } if ( addNow ( session ) ) { addedSessions ++ ; } } return addedSessions ; }
Loops over the new sessions blocking queue and returns the number of sessions which are effectively created
127,617
private void process ( T session ) { if ( isReadable ( session ) && ! session . isReadSuspended ( ) ) { read ( session ) ; } if ( isWritable ( session ) && ! session . isWriteSuspended ( ) ) { scheduleFlush ( session ) ; } }
Deal with session ready for the read or write operations or both .
127,618
private void updateTrafficMask ( ) { int queueSize = trafficControllingSessions . size ( ) ; while ( queueSize > 0 ) { T session = trafficControllingSessions . poll ( ) ; if ( session == null ) { return ; } SessionState state = getState ( session ) ; switch ( state ) { case OPENED : updateTrafficControl ( session ) ; b...
Update the trafficControl for all the session which has just been opened .
127,619
public boolean sendSummaryData ( ) { if ( clearDirty ( ) ) { String summaryData = getSummaryData ( ) ; for ( SummaryDataListener listener : summaryDataListeners ) { listener . sendSummaryData ( summaryData ) ; } scheduleSummaryData ( ) ; return true ; } else { } return false ; }
Send the summary data returning whether anything actually needed to be sent .
127,620
public void messageReceived ( final NextFilter nextFilter , final IoSession session , final Object message ) throws ProxyAuthException { ProxyLogicHandler handler = getProxyHandler ( session ) ; synchronized ( handler ) { IoBuffer buf = ( IoBuffer ) message ; if ( handler . isHandshakeComplete ( ) ) { nextFilter . mess...
Receives data from the remote host passes to the handler if a handshake is in progress otherwise passes on transparently .
127,621
public void filterWrite ( final NextFilter nextFilter , final IoSession session , final WriteRequest writeRequest ) { writeData ( nextFilter , session , writeRequest , false ) ; }
Filters outgoing writes queueing them up if necessary while a handshake is ongoing .
127,622
public void writeData ( final NextFilter nextFilter , final IoSession session , final WriteRequest writeRequest , final boolean isHandshakeData ) { ProxyLogicHandler handler = getProxyHandler ( session ) ; synchronized ( handler ) { if ( handler . isHandshakeComplete ( ) ) { nextFilter . filterWrite ( session , writeRe...
Actually write data . Queues the data up unless it relates to the handshake or the handshake is done .
127,623
public void messageSent ( final NextFilter nextFilter , final IoSession session , final WriteRequest writeRequest ) throws Exception { if ( writeRequest . getMessage ( ) != null && writeRequest . getMessage ( ) instanceof ProxyHandshakeIoBuffer ) { return ; } nextFilter . messageSent ( session , writeRequest ) ; }
Filter handshake related messages from reaching the messageSent callbacks of downstream filters .
127,624
private static String [ ] decodeAuthAmqPlain ( String response ) { Logger logger = LoggerFactory . getLogger ( SERVICE_AMQP_PROXY_LOGGER ) ; String [ ] credentials = null ; if ( ( response != null ) && ( response . trim ( ) . length ( ) > 0 ) ) { ByteBuffer buffer = ByteBuffer . wrap ( response . getBytes ( ) ) ; @ Sup...
the 1st element is the password .
127,625
private EntryImpl checkOldName ( String baseName ) { EntryImpl e = ( EntryImpl ) name2entry . get ( baseName ) ; if ( e == null ) { throw new IllegalArgumentException ( "Filter not found:" + baseName ) ; } return e ; }
Throws an exception when the specified filter name is not registered in this chain .
127,626
private void internalFlush ( NextFilter nextFilter , IoSession session , IoBuffer buf ) throws Exception { IoBuffer tmp ; synchronized ( buf ) { buf . flip ( ) ; tmp = buf . duplicate ( ) ; buf . clear ( ) ; } logger . debug ( "Flushing buffer: {}" , tmp ) ; nextFilter . filterWrite ( session , new DefaultWriteRequest ...
Internal method that actually flushes the buffered data .
127,627
public void flush ( IoSession session ) { try { internalFlush ( session . getFilterChain ( ) . getNextFilter ( this ) , session , buffersMap . get ( session ) ) ; } catch ( Throwable e ) { session . getFilterChain ( ) . fireExceptionCaught ( e ) ; } }
Flushes the buffered data .
127,628
static WeakReference < Thread > currentThreadRef ( ) { WeakReference < Thread > ref = weakThread . get ( ) ; if ( ref == null ) { ref = new WeakReference < > ( Thread . currentThread ( ) ) ; weakThread . set ( ref ) ; } return ref ; }
Returns a unique object representing the current thread . Although we use a weak - reference to the thread we could use practically anything that does not reference our class - loader .
127,629
private Holder createHolder ( ) { poll ( ) ; Holder holder = new Holder ( queue ) ; WeakReference < Holder > ref = new WeakReference < > ( holder ) ; Holder old ; do { old = strongRefs ; holder . next = old ; } while ( ! strongRefsUpdater . compareAndSet ( this , old , holder ) ) ; local . set ( ref ) ; return holder ;...
Creates a new holder object and registers it appropriately . Also polls for thread - exits .
127,630
public boolean isInitialized ( ) { WeakReference < Holder > ref = local . get ( ) ; if ( ref != null ) { Holder holder = ref . get ( ) ; return holder != null && holder . value != UNINITIALISED ; } else { return false ; } }
Indicates whether thread - local has been initialised for the current thread .
127,631
@ SuppressWarnings ( "unchecked" ) public T swap ( T value ) { final Holder holder ; final T oldValue ; WeakReference < Holder > ref = local . get ( ) ; if ( ref != null ) { holder = ref . get ( ) ; Object holderValue = holder . value ; if ( holderValue != UNINITIALISED ) { oldValue = ( T ) holderValue ; } else { oldVa...
Swaps the current threads value with the supplied value . Thread - local will be initialised if not already done so .
127,632
public void poll ( ) { synchronized ( queue ) { if ( queue . poll ( ) == null ) { return ; } while ( queue . poll ( ) != null ) { } Holder first = strongRefs ; if ( first == null ) { return ; } Holder link = first ; Holder next = link . next ; while ( next != null ) { if ( next . get ( ) == null ) { next = next . next ...
Check if any strong references need should be removed due to thread exit .
127,633
public synchronized final String getHost ( ) { if ( host == null ) { if ( getEndpointAddress ( ) != null && ! getEndpointAddress ( ) . isUnresolved ( ) ) { host = getEndpointAddress ( ) . getHostName ( ) ; } if ( host == null && httpURI != null ) { try { host = ( new URL ( httpURI ) ) . getHost ( ) ; } catch ( Malforme...
Returns the host to which we are connecting .
127,634
public String toHttpString ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( getHttpVerb ( ) ) . append ( ' ' ) . append ( getHttpURI ( ) ) . append ( ' ' ) . append ( getHttpVersion ( ) ) . append ( HttpProxyConstants . CRLF ) ; boolean hostHeaderFound = false ; if ( getHeaders ( ) != null ) { for ( Map ....
Returns the string representation of the HTTP request .
127,635
public void configureGateway ( Gateway gateway ) { Properties properties = new Properties ( ) ; properties . putAll ( System . getProperties ( ) ) ; String gatewayHome = properties . getProperty ( Gateway . GATEWAY_HOME_PROPERTY ) ; if ( ( gatewayHome == null ) || "" . equals ( gatewayHome ) ) { ClassLoader loader = Th...
Bootstrap the Gateway instance with a GATEWAY_HOME if not already set in System properties .
127,636
private void validateOpcodeUsingFin ( Opcode opcode , boolean fin ) throws ProtocolDecoderException { switch ( opcode ) { case CONTINUATION : if ( prevDataFin ) { throw new ProtocolDecoderException ( "Not expecting CONTINUATION frame" ) ; } break ; case TEXT : case BINARY : if ( ! prevDataFin ) { throw new ProtocolDeco...
Validates opcode w . r . t FIN bit
127,637
private void validateRSV ( byte opcodeByte ) throws ProtocolDecoderException { if ( ( opcodeByte & 0x70 ) != 0 ) { if ( ( opcodeByte & 0x40 ) != 0 ) { throw new ProtocolDecoderException ( "RSV1 is set" ) ; } if ( ( opcodeByte & 0x20 ) != 0 ) { throw new ProtocolDecoderException ( "RSV2 is set" ) ; } if ( ( opcodeByte &...
Validates RSV bits
127,638
public synchronized void doHandshake ( final NextFilter nextFilter ) { LOGGER . debug ( " doHandshake()" ) ; writeRequest ( nextFilter , request , ( Integer ) getSession ( ) . getAttribute ( HANDSHAKE_STEP ) ) ; }
Performs the handshake process .
127,639
private IoBuffer encodeInitialGreetingPacket ( final SocksProxyRequest request ) { byte nbMethods = ( byte ) SocksProxyConstants . SUPPORTED_AUTH_METHODS . length ; IoBuffer buf = IoBuffer . allocate ( 2 + nbMethods ) ; buf . put ( request . getProtocolVersion ( ) ) ; buf . put ( nbMethods ) ; buf . put ( SocksProxyCon...
Encodes the initial greeting packet .
127,640
private IoBuffer encodeProxyRequestPacket ( final SocksProxyRequest request ) throws UnsupportedEncodingException { int len = 6 ; InetSocketAddress adr = request . getEndpointAddress ( ) ; byte addressType = 0 ; byte [ ] host = null ; if ( adr != null && ! adr . isUnresolved ( ) ) { if ( adr . getAddress ( ) instanceof...
Encodes the proxy authorization request packet .
127,641
private void writeRequest ( final NextFilter nextFilter , final SocksProxyRequest request , int step ) { try { IoBuffer buf = null ; if ( step == SocksProxyConstants . SOCKS5_GREETING_STEP ) { buf = encodeInitialGreetingPacket ( request ) ; } else if ( step == SocksProxyConstants . SOCKS5_AUTH_STEP ) { buf = encodeAuth...
Encodes a SOCKS5 request and writes it to the next filter so it can be sent to the proxy server .
127,642
public void setSubnetBlacklist ( Iterable < Subnet > subnets ) { if ( subnets == null ) { throw new NullPointerException ( "Subnets must not be null" ) ; } blacklist . clear ( ) ; for ( Subnet subnet : subnets ) { block ( subnet ) ; } }
Sets the subnets to be blacklisted .
127,643
public void addSession ( AbstractIoSession session ) { sessions . add ( session ) ; CloseFuture closeFuture = session . getCloseFuture ( ) ; closeFuture . addListener ( sessionCloseListener ) ; }
Add the session for being checked for idle .
127,644
private void disposeEncoder ( IoSession session ) { ProtocolEncoder encoder = ( ProtocolEncoder ) session . removeAttribute ( ENCODER ) ; if ( encoder == null ) { return ; } try { encoder . dispose ( session ) ; } catch ( Throwable t ) { LOGGER . warn ( "Failed to dispose: " + encoder . getClass ( ) . getName ( ) + " (...
Dispose the encoder removing its instance from the session s attributes and calling the associated dispose method .
127,645
private void disposeDecoder ( IoSession session ) { ProtocolDecoder decoder = ( ProtocolDecoder ) session . removeAttribute ( DECODER ) ; if ( decoder == null ) { return ; } try { decoder . dispose ( session ) ; } catch ( Throwable t ) { LOGGER . warn ( "Failed to dispose: " + decoder . getClass ( ) . getName ( ) + " (...
Dispose the decoder removing its instance from the session s attributes and calling the associated dispose method .
127,646
private ProtocolDecoderOutput getDecoderOut ( IoSession session , NextFilter nextFilter ) { ProtocolDecoderOutput out = ( ProtocolDecoderOutput ) session . getAttribute ( DECODER_OUT ) ; if ( out == null ) { out = new ProtocolDecoderOutputImpl ( ) ; session . setAttribute ( DECODER_OUT , out ) ; } return out ; }
Return a reference to the decoder callback . If it s not already created and stored into the session we create a new instance .
127,647
public boolean validate ( HttpRequestMessage request , boolean isPostMethodAllowed ) { WebSocketWireProtocol wireProtocolVersion = guessWireProtocolVersion ( request ) ; if ( wireProtocolVersion == null ) { return false ; } final WsHandshakeValidator validator = handshakeValidatorsByWireProtocolVersion . get ( wireProt...
Facade method to validate an HttpMessageRequest .
127,648
protected boolean doValidate ( HttpRequestMessage request , final boolean isPostMethodAllowed ) { if ( ! isPostMethodAllowed ) { if ( request . getMethod ( ) != HttpMethod . GET ) { return false ; } } else { if ( request . getMethod ( ) != HttpMethod . GET || request . getMethod ( ) == HttpMethod . POST ) { return fals...
Does the provided request form a valid web socket handshake request?
127,649
private void register ( WebSocketWireProtocol wireProtocolVersion , WsHandshakeValidator validator ) { if ( wireProtocolVersion == null ) { throw new NullPointerException ( "wireProtocolVersion" ) ; } if ( validator == null ) { throw new NullPointerException ( "validator" ) ; } WsHandshakeValidator existingValidator = ...
Allow subclasses to register themselves as validators for specific versions of the wire protocol .
127,650
public IoBuffer fetchAppBuffer ( ) { IoBufferEx appBuffer = this . appBuffer . flip ( ) ; this . appBuffer = null ; return ( IoBuffer ) appBuffer ; }
Get decrypted application data .
127,651
public static boolean hasLiteralIPAddress ( URI resource ) { String host = resource . getHost ( ) ; if ( host == null || host . isEmpty ( ) ) { return false ; } return host . matches ( "([0-9A-Fa-f]|\\.){4,16}" ) ; }
We can make this tighter but IPAddressUtil is in a sun package sadly
127,652
public String getCacheControlHeader ( ) { checkIfMaxAgeIsResolved ( ) ; String maxAge = Directive . MAX_AGE . getName ( ) + "=" + ( maxAgeResolvedValue > 0 ? maxAgeResolvedValue : "0" ) ; return staticDirectives . toString ( ) + maxAge ; }
Returns the Cache - control header string
127,653
private void buildDirectives ( PatternCacheControl patternCacheControl ) { for ( Map . Entry < Directive , String > entry : patternCacheControl . getDirectives ( ) . entrySet ( ) ) { Directive key = entry . getKey ( ) ; String value = entry . getValue ( ) ; switch ( key ) { case MAX_AGE : case MAX_AGE_MPLUS : maxAgeDir...
Builds a string of directives by concatenating all the static directives
127,654
public static String fill ( char c , int size ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < size ; i ++ ) { builder . append ( c ) ; } return builder . toString ( ) ; }
Creates a new String filled with size of a repeating character
127,655
public static String initCaps ( String in ) { return in . length ( ) < 2 ? in . toUpperCase ( ) : in . substring ( 0 , 1 ) . toUpperCase ( ) + in . substring ( 1 ) ; }
Converts the first character of the string to uppercase . Does NOT deal with surrogate pairs .
127,656
public final void sessionOpened ( IoSession session ) throws Exception { ProxyIoSession proxyIoSession = ( ProxyIoSession ) session . getAttribute ( ProxyIoSession . PROXY_SESSION ) ; if ( proxyIoSession . getRequest ( ) instanceof SocksProxyRequest || proxyIoSession . isAuthenticationFailed ( ) || proxyIoSession . get...
Hooked session opened event .
127,657
public void reset ( final Throwable cause ) { if ( cause == null ) { throw new NullPointerException ( "cause must not be null in AbstractBridgeSession.reset" ) ; } if ( ! isIoAligned ( ) || getIoThread ( ) == Thread . currentThread ( ) ) { reset0 ( cause ) ; } else { getIoExecutor ( ) . execute ( new Runnable ( ) { pub...
Behave similarly to connection reset by peer at NIO layer . This method should be called from handlers exceptionCaught method instead of calling fireExceptionCaught and IoProcessor . remove because the latter will fail if we re not on its IO thread .
127,658
private void processToken ( String tokenData ) throws JSONException , LoginException { JSONObject json = new JSONObject ( tokenData ) ; ZonedDateTime expires = ZonedDateTime . parse ( json . getString ( "tokenExpires" ) ) ; ZonedDateTime now = ZonedDateTime . now ( expires . getZone ( ) ) ; if ( expires . isBefore ( no...
Validate the token and extract the username to add to shared state . An exception is thrown if the token is found to be invalid
127,659
public static void xor ( ByteBuffer src , ByteBuffer dst , int mask ) { int remainder = src . remaining ( ) % 4 ; int remaining = src . remaining ( ) - remainder ; int end = remaining + src . position ( ) ; while ( src . position ( ) < end ) { int masked = src . getInt ( ) ^ mask ; dst . putInt ( masked ) ; } byte b ; ...
Masks source buffer into destination buffer .
127,660
private static int countNewLines ( char [ ] ch , int start , int length ) { int newLineCount = 0 ; for ( int i = start ; i < length ; i ++ ) { newLineCount = newLineCount + ( ( ch [ i ] == '\n' ) ? 1 : 0 ) ; } return newLineCount ; }
Count the number of new lines
127,661
private void parseDirectiveWithValue ( String directiveName , String directiveValue ) { Directive directive ; if ( directiveName . equals ( Directive . MAX_AGE . getName ( ) ) ) { if ( directiveValue . startsWith ( M_PLUS_STRING ) ) { directiveValue = directiveValue . replace ( M_PLUS_STRING , EMPTY_STRING_VALUE ) ; di...
Adds a directive with the associated value to the directives map after parsing the value from the configuration file
127,662
private boolean checkDirective ( String directive ) { if ( directives . containsKey ( directive ) ) { throw new IllegalArgumentException ( "Duplicate cache-control directive in configuration file" ) ; } else if ( Directive . get ( directive ) == null ) { throw new IllegalArgumentException ( "Missing or incorrect cache-...
Checks for duplicate directive values and correct syntax
127,663
public Map < String , Object > injectResources ( Map < String , Object > resources ) { Map < String , Object > allResources = new HashMap < > ( resources ) ; for ( Entry < String , Transport > entry : transportsByName . entrySet ( ) ) { allResources . put ( entry . getKey ( ) + ".acceptor" , entry . getValue ( ) . getA...
Inject the given resources plus all available transport acceptors and connectors into every available acceptor and connector .
127,664
private static Collection < String > toWsBalancerURIs ( Collection < String > uris , AcceptOptionsContext acceptOptionsCtx , TransportFactory transportFactory ) throws Exception { List < String > httpURIs = new ArrayList < > ( uris . size ( ) ) ; for ( String uri : uris ) { String schemeFromAcceptURI = uri . substring ...
Converts a collection of WS URIs to their equivalent WSN balancer URIs .
127,665
public void flushPendingSessionEvents ( ) throws Exception { synchronized ( sessionEventsQueue ) { IoSessionEvent evt ; while ( ( evt = sessionEventsQueue . poll ( ) ) != null ) { logger . debug ( " Flushing buffered event: {}" , evt ) ; evt . deliverEvent ( ) ; } } }
Send any session event which were queued while waiting for handshaking to complete .
127,666
private void enqueueSessionEvent ( final IoSessionEvent evt ) { synchronized ( sessionEventsQueue ) { logger . debug ( "Enqueuing event: {}" , evt ) ; sessionEventsQueue . offer ( evt ) ; } }
Enqueue an event to be delivered once handshaking is complete .
127,667
private void startupAcceptor ( ) { if ( ! selectable ) { registerQueue . clear ( ) ; cancelQueue . clear ( ) ; flushingSessions . clear ( ) ; } synchronized ( lock ) { if ( acceptor == null ) { acceptor = new Acceptor ( ) ; executeWorker ( acceptor ) ; } } }
Starts the inner Acceptor thread .
127,668
public static String getReplyCodeAsString ( byte code ) { switch ( code ) { case V4_REPLY_REQUEST_GRANTED : return "Request granted" ; case V4_REPLY_REQUEST_REJECTED_OR_FAILED : return "Request rejected or failed" ; case V4_REPLY_REQUEST_FAILED_NO_IDENTD : return "Request failed because client is not running identd (or...
Return the string associated with the specified reply code .
127,669
public static String [ ] getThrowableStrRep ( Throwable throwable ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; throwable . printStackTrace ( pw ) ; pw . flush ( ) ; LineNumberReader reader = new LineNumberReader ( new StringReader ( sw . toString ( ) ) ) ; ArrayList < String > ...
convert a Throwable into an array of Strings
127,670
private void addCacheControl ( HttpAcceptSession session , File requestFile , String requestPath ) { CacheControlHandler cacheControlHandler = urlCacheControlMap . computeIfAbsent ( requestPath , path -> patterns . stream ( ) . filter ( patternCacheControl -> PatternMatcherUtils . caseInsensitiveMatch ( requestPath , p...
Matches the file URL with the most specific pattern and caches this information in a map Sets cache - control and expires headers
127,671
private String getNTLMHeader ( final HttpProxyResponse response ) { List < String > values = response . getHeaders ( ) . get ( "Proxy-Authenticate" ) ; for ( String s : values ) { if ( s . startsWith ( "NTLM" ) ) { return s ; } } return null ; }
Returns the value of the NTLM Proxy - Authenticate header .
127,672
public void exceptionCaught ( IoSession session , Throwable cause ) throws Exception { ExceptionHandler < Throwable > handler = findExceptionHandler ( cause . getClass ( ) ) ; if ( handler != null ) { handler . exceptionCaught ( session , cause ) ; } else { throw new UnknownMessageTypeException ( "No handler found for ...
Invoked when any exception is thrown by user IoHandler implementation or by MINA . If cause is an instance of IOException MINA will close the connection automatically .
127,673
void start ( ) throws IOException , TooManyListenersException { inputStream = port . getInputStream ( ) ; outputStream = port . getOutputStream ( ) ; ReadWorker w = new ReadWorker ( ) ; w . start ( ) ; port . addEventListener ( this ) ; service . getIdleStatusChecker0 ( ) . addSession ( this ) ; try { getService ( ) . ...
start handling streams
127,674
public void checkForUpdate ( UpdateCheckListener updateCheckListener ) { listeners . add ( updateCheckListener ) ; if ( scheduler != null ) { scheduler . schedule ( new UpdateCheckTask ( this , versionServiceUrl , productName ) , 0 , SECONDS ) ; } else { new UpdateCheckTask ( this , versionServiceUrl , productName ) . ...
Forces a check for an update and registers the listener if it is not already registered
127,675
private void setServicesCount ( ) { servicesCount = MAX_SERVICE_COUNT ; metadataLength = NUMBER_OF_INTS_IN_HEADER * BitUtil . SIZE_OF_INT + SIZEOF_STRING + servicesCount * ( SIZEOF_STRING + NUMBER_OF_INTS_PER_SERVICE * BitUtil . SIZE_OF_INT ) ; endOfMetadata = BitUtil . align ( metadataLength + BitUtil . SIZE_OF_INT , ...
Method setting the number of services and metadata length
127,676
private void fillMetaData ( ) { metaDataBuffer . putInt ( MONITOR_VERSION_OFFSET , MONITOR_VERSION ) ; metaDataBuffer . putInt ( GW_DATA_REFERENCE_OFFSET , GW_DATA_OFFSET ) ; metaDataBuffer . putInt ( SERVICE_DATA_REFERENCE_OFFSET , serviceDataOffset ) ; metaDataBuffer . putStringUtf8 ( GW_ID_OFFSET , gatewayId , ByteO...
Fills the meta data in the specified buffer
127,677
private void fillServiceMetadata ( final String serviceName , final int index ) { final int servAreaOffset = noOfServicesOffset + BitUtil . SIZE_OF_INT ; metaDataBuffer . putInt ( noOfServicesOffset , metaDataBuffer . getInt ( noOfServicesOffset ) + 1 ) ; int serviceNameOffset = getServiceNameOffset ( servAreaOffset ) ...
Method adding services metadata
127,678
private int getServiceNameOffset ( final int servAreaOffset ) { if ( prevServiceOffset != 0 ) { return prevServiceOffset + prevServiceName . length ( ) + BitUtil . SIZE_OF_INT + BitUtil . SIZE_OF_INT ; } return servAreaOffset ; }
Method returning serviceNameOffset
127,679
private void initializeServiceRefMetadata ( int serviceLocationOffset , int serviceOffsetIndex ) { metaDataBuffer . putInt ( serviceLocationOffset , serviceRefSection + serviceOffsetIndex * BitUtil . SIZE_OF_INT ) ; metaDataBuffer . putInt ( serviceRefSection + serviceOffsetIndex * BitUtil . SIZE_OF_INT , 0 ) ; metaDat...
Method initializing service ref metadata section data
127,680
private void setGatewayIdDependentOffsets ( String gatewayId ) { gwCountersLblBuffersReferenceOffset = GW_ID_OFFSET + gatewayId . length ( ) + BitUtil . SIZE_OF_INT ; gwCountersLblBuffersLengthOffset = gwCountersLblBuffersReferenceOffset + BitUtil . SIZE_OF_INT ; gwCountersValueBuffersReferenceOffset = gwCountersLblBuf...
Method setting gatewayId dependent offsets
127,681
public static Gateway createGateway ( ) { Gateway gateway = null ; for ( GatewayCreator factory : loader ) { gateway = factory . createGateway ( gateway ) ; factory . configureGateway ( gateway ) ; } if ( gateway == null ) { throw new RuntimeException ( "Failed to load GatewayCreator implementation class." ) ; } return...
Creates an implementation of an Gateway .
127,682
public void messageReceived ( NextFilter nextFilter , IoSession session , Object message ) throws Exception { LOGGER . debug ( "Processing a MESSAGE_RECEIVED for session {}" , session . getId ( ) ) ; if ( ! ( message instanceof IoBuffer ) ) { nextFilter . messageReceived ( session , message ) ; return ; } IoBuffer in =...
Process the incoming message calling the session decoder . As the incoming buffer might contains more than one messages we have to loop until the decoder throws an exception .
127,683
private void initCodec ( IoSession session ) throws Exception { ProtocolDecoder decoder = factory . getDecoder ( session ) ; session . setAttribute ( DECODER , decoder ) ; ProtocolEncoder encoder = factory . getEncoder ( session ) ; session . setAttribute ( ENCODER , encoder ) ; }
Initialize the encoder and the decoder storing them in the session attributes .
127,684
public static void log ( IoSession session , Throwable t ) { Logger logger = getTransportLogger ( session ) ; log ( session , logger , t ) ; }
Logs an unexpected exception in the same way LoggingFilter would using the transport logger for the transport of the given session .
127,685
public static void log ( IoSession session , Logger logger , Throwable t ) { log ( session , logger , t . toString ( ) , t ) ; }
Logs an unexpected exception in the same way LoggingFilter would .
127,686
static String getUserIdentifier ( IoSession session ) { boolean isAcceptor = isAcceptor ( session ) ; SocketAddress hostPortAddress = isAcceptor ? session . getRemoteAddress ( ) : session . getLocalAddress ( ) ; SocketAddress identityAddress = isAcceptor ? session . getLocalAddress ( ) : session . getRemoteAddress ( ) ...
Get a suitable identification for the user . For now this just consists of the TCP endpoint . the HTTP - layer auth principal etc .
127,687
private static String resolveIdentity ( SocketAddress address , IoSessionEx session ) { if ( address instanceof ResourceAddress ) { Subject subject = session . getSubject ( ) ; if ( subject == null ) { subject = new Subject ( ) ; } return resolveIdentity ( ( ResourceAddress ) address , subject ) ; } return null ; }
Method performing identity resolution - attempts to extract a subject from the current IoSessionEx session
127,688
private static String resolveIdentity ( ResourceAddress address , Subject subject ) { IdentityResolver resolver = address . getOption ( IDENTITY_RESOLVER ) ; ResourceAddress transport = address . getTransport ( ) ; if ( resolver != null ) { return resolver . resolve ( subject ) ; } if ( transport != null ) { return res...
Method attempting to perform identity resolution based on the provided subject parameter and transport It is attempted to perform the resolution from the highest to the lowest layer recursively .
127,689
private static String getHostPort ( SocketAddress address ) { if ( address instanceof ResourceAddress ) { ResourceAddress lowest = getLowestTransportLayer ( ( ResourceAddress ) address ) ; return format ( HOST_PORT_FORMAT , lowest . getResource ( ) . getHost ( ) , lowest . getResource ( ) . getPort ( ) ) ; } if ( addre...
Method attempting to retrieve host port identifier
127,690
static ResourceAddress getLowestTransportLayer ( ResourceAddress transport ) { if ( transport . getTransport ( ) != null ) { return getLowestTransportLayer ( transport . getTransport ( ) ) ; } return transport ; }
Method returning lowest transport layer
127,691
public void handleNotification ( Notification notification , Object handback ) { String notificationType = notification . getType ( ) ; if ( notificationType . equals ( JMXConnectionNotification . OPENED ) ) { managementContext . incrementManagementSessionCount ( ) ; } else if ( notificationType . equals ( JMXConnectio...
NotificationListener support for connection open and closed notifications
127,692
public HttpChallengeFactory lookup ( String authScheme ) { HttpChallengeFactory result ; if ( authScheme == null ) return null ; result = challengeFactoriesByAuthScheme . get ( authScheme ) ; if ( result == null ) { if ( authScheme . startsWith ( AUTH_SCHEME_APPLICATION_PREFIX ) ) { authScheme = authScheme . replaceFir...
public until unit test is moved
127,693
private static ByteBuffer putUnsignedLong ( ByteBuffer buffer , long v ) { buffer . putInt ( 0 ) ; return putUnsignedInt ( buffer , ( int ) v ) ; }
Puts an unsigned long .
127,694
protected void flushQueuedMessages ( IoSession session , AttachedSessionManager attachedSessionManager ) { Queue < Object > messageQueue = getMessageQueue ( session ) ; if ( messageQueue != null ) { flushQueuedMessages ( messageQueue , session , attachedSessionManager ) ; } }
called by connect listener in proxy service handler
127,695
public ChannelFuture joinGroup ( InetAddress multicastAddress , NetworkInterface networkInterface , InetAddress source ) { if ( DetectionUtil . javaVersion ( ) < 7 ) { throw new UnsupportedOperationException ( ) ; } if ( multicastAddress == null ) { throw new NullPointerException ( "multicastAddress" ) ; } if ( network...
Joins the specified multicast group at the specified interface using the specified source .
127,696
public ChannelFuture leaveGroup ( InetAddress multicastAddress , NetworkInterface networkInterface , InetAddress source ) { if ( DetectionUtil . javaVersion ( ) < 7 ) { throw new UnsupportedOperationException ( ) ; } else { if ( multicastAddress == null ) { throw new NullPointerException ( "multicastAddress" ) ; } if (...
Leave the specified multicast group at the specified interface using the specified source .
127,697
public ChannelFuture block ( InetAddress multicastAddress , InetAddress sourceToBlock ) { try { block ( multicastAddress , NetworkInterface . getByInetAddress ( getLocalAddress ( ) . getAddress ( ) ) , sourceToBlock ) ; } catch ( SocketException e ) { return failedFuture ( this , e ) ; } return succeededFuture ( this )...
Block the given sourceToBlock address for the given multicastAddress
127,698
private JSONArray getAlternativeNames ( Collection < List < ? > > alternativeNames ) { if ( alternativeNames == null || alternativeNames . size ( ) == 0 ) { return null ; } JSONArray altNames = new JSONArray ( ) ; for ( List < ? > altName : alternativeNames ) { String altNameValue = altName . get ( 1 ) . toString ( ) ;...
Given an AlternativeNames structure return a JSONArray with the name strings .
127,699
public void startupSessionTimeoutCommand ( ) { if ( initSessionTimeoutCommand . compareAndSet ( false , true ) ) { final Long sessionTimeout = getSessionTimeout ( ) ; if ( sessionTimeout != null && sessionTimeout > 0 ) { if ( scheduledEventslogger . isTraceEnabled ( ) ) { scheduledEventslogger . trace ( "Establishing a...
Start up timer for the session timeout of the WebSocket session