idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
3,900
public boolean matches ( TagClass tagClass , EncodingType encodingType , int tagNumber ) { return this . tagClass == tagClass && this . encodingType == encodingType && this . tagNumber == tagNumber ; }
Tests whether this DER identifier matches the specified tag class encoding type and tag number .
3,901
protected void setSubject ( Subject subject ) { Subject currentSubject = this . subject ; if ( ! ( currentSubject == null && subject == null ) ) { this . subject = subject ; if ( currentThread ( ) == ioThread ) { notifySubjectChanged ( subject ) ; } else { final Subject changedSubject = subject ; ioExecutor . execute ( new Runnable ( ) { public void run ( ) { notifySubjectChanged ( changedSubject ) ; } } ) ; } } }
Memorizes the Subject representing the current logged on user and fires any currently registered SubjectChangeListeners
3,902
private void initializeSessionCounters ( ) { if ( monitoringEntityFactory == null ) { return ; } numberOfSessionsCounter = monitoringEntityFactory . makeLongMonitoringCounter ( CURRENT_NUMBER_OF_SESSIONS ) ; numberOfNativeSessionsCounter = monitoringEntityFactory . makeLongMonitoringCounter ( CURRENT_NUMBER_OF_NATIVE_SESSIONS ) ; numberOfEmulatedSessionsCounter = monitoringEntityFactory . makeLongMonitoringCounter ( CURRENT_NUMBER_OF_EMULATED_SESSIONS ) ; cumulativeSessionsCounter = monitoringEntityFactory . makeLongMonitoringCounter ( CUMULATIVE_NUMBER_OF_SESSIONS ) ; cumulativeNativeSessionsCounter = monitoringEntityFactory . makeLongMonitoringCounter ( CUMULATIVE_NUMBER_OF_NATIVE_SESSIONS ) ; cumulativeEmulatedSessionsCounter = monitoringEntityFactory . makeLongMonitoringCounter ( CUMULATIVE_NUMBER_OF_EMULATED_SESSIONS ) ; }
Method initializing the service session counters
3,903
public void reset ( IoSession session ) { synchronized ( lock ) { if ( ! ready && this . session != null ) { throw new IllegalStateException ( "Cannot reset a future that has not yet completed" ) ; } this . session = session ; this . firstListener = null ; this . otherListeners = null ; this . result = null ; this . ready = false ; this . waiters = 0 ; } }
Call this method to reuse a future after it has been completed
3,904
public static int decodeLength ( ByteBuffer buf ) { if ( buf == null || buf . remaining ( ) == 0 ) { throw new IllegalArgumentException ( "Null or empty buffer" ) ; } int len = 0 ; byte first = buf . get ( ) ; if ( first >> 7 == 0 ) { len = first & 0x7f ; } else { int numOctets = first & 0x7f ; if ( buf . remaining ( ) < numOctets ) { throw new IllegalArgumentException ( "Insufficient data to decode long-form DER length" ) ; } for ( int i = 0 ; i < numOctets ; i ++ ) { len = ( len << 8 ) + ( 0xff & buf . get ( ) ) ; } } return len ; }
Decode octets and extract the length information from a DER - encoded message .
3,905
public static DerId decodeIdAndLength ( ByteBuffer buf ) { DerId id = DerId . decode ( buf ) ; DerUtils . decodeLength ( buf ) ; return id ; }
Decodes ID and length octets from a DER - encoded message .
3,906
public static int encodeIdAndLength ( DerId . TagClass tagClass , DerId . EncodingType encodingType , int tagNumber , int contentLength , ByteBuffer buf ) { int origPos = buf . position ( ) ; int pos = buf . position ( ) ; if ( contentLength < 0 ) { throw new IllegalArgumentException ( "Invalid content length " + contentLength ) ; } else if ( contentLength <= 0x7f ) { pos -- ; buf . put ( pos , ( byte ) contentLength ) ; } else { int lenOctetCount = 0 ; while ( contentLength != 0 ) { pos -- ; buf . put ( pos , ( byte ) ( contentLength & 0xff ) ) ; contentLength >>>= 8 ; lenOctetCount ++ ; } pos -- ; buf . put ( pos , ( byte ) ( 0x80 | lenOctetCount ) ) ; } if ( tagNumber < 0 ) { throw new IllegalArgumentException ( "Invalid tag number " + tagNumber ) ; } else { byte firstOctet = 0 ; switch ( tagClass ) { case UNIVERSAL : break ; case APPLICATION : firstOctet = 0x40 ; break ; case CONTEXT_SPECIFIC : firstOctet = ( byte ) 0x80 ; break ; case PRIVATE : firstOctet = ( byte ) 0xc0 ; } switch ( encodingType ) { case PRIMITIVE : break ; case CONSTRUCTED : firstOctet |= 0x20 ; } if ( tagNumber <= 30 ) { firstOctet |= tagNumber ; pos -- ; buf . put ( pos , firstOctet ) ; } else { boolean last = true ; while ( tagNumber != 0 ) { byte octet = ( byte ) ( tagNumber & 0x7f ) ; pos -- ; if ( last ) { buf . put ( pos , octet ) ; last = false ; } else { buf . put ( pos , ( byte ) ( octet | 0x80 ) ) ; } tagNumber >>>= 8 ; } firstOctet |= 0x1f ; pos -- ; buf . put ( pos , firstOctet ) ; } } buf . position ( pos ) ; return origPos - pos ; }
DER - encode content into a provided buffer .
3,907
public static int sizeOf ( int tagNumber , int contentLength ) { if ( tagNumber < 0 || contentLength < 0 ) { throw new IllegalArgumentException ( "Invalid tagNumber/contentLength: " + tagNumber + ", " + contentLength ) ; } int len = 0 ; if ( tagNumber <= 30 ) { len ++ ; } else { len = len + 1 + ( int ) Math . ceil ( ( 1 + Integer . numberOfTrailingZeros ( Integer . highestOneBit ( tagNumber ) ) ) / 7.0d ) ; } if ( contentLength <= 0x7f ) { len ++ ; } else { len = len + 1 + ( int ) Math . ceil ( ( 1 + Integer . numberOfTrailingZeros ( Integer . highestOneBit ( contentLength ) ) ) / 8.0d ) ; } len += contentLength ; return len ; }
Computes the DER - encoded size of content with a specified tag number .
3,908
public void run ( ) { Thread currentThread = Thread . currentThread ( ) ; String oldName = currentThread . getName ( ) ; if ( newName != null ) { setName ( currentThread , newName ) ; } try { runnable . run ( ) ; } finally { setName ( currentThread , oldName ) ; } }
Run the runnable after having renamed the current thread s name to the new name . When the runnable has completed set back the current thread name back to its origin .
3,909
public void setProxyIoSession ( ProxyIoSession proxyIoSession ) { if ( proxyIoSession == null ) { throw new NullPointerException ( "proxySession object cannot be null" ) ; } if ( proxyIoSession . getProxyAddress ( ) == null ) { throw new NullPointerException ( "proxySession.proxyAddress cannot be null" ) ; } proxyIoSession . setConnector ( this ) ; setDefaultRemoteAddress ( proxyIoSession . getProxyAddress ( ) ) ; this . proxyIoSession = proxyIoSession ; }
Sets the proxy session object of this connector .
3,910
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 newResourceAddress ( location ) ; } }
convenience method only consider removing from API
3,911
private boolean loginMissingToken ( NextFilter nextFilter , IoSession session , HttpRequestMessage httpRequest , AuthenticationToken authToken , TypedCallbackHandlerMap additionalCallbacks , HttpRealmInfo [ ] realms , int realmIndex , LoginContext [ ] loginContexts ) { HttpRealmInfo realm = realms [ realmIndex ] ; ResultAwareLoginContext loginContext = null ; try { LoginContextFactory loginContextFactory = realm . getLoginContextFactory ( ) ; TypedCallbackHandlerMap callbackHandlerMap = new TypedCallbackHandlerMap ( ) ; registerCallbacks ( session , httpRequest , authToken , callbackHandlerMap ) ; callbackHandlerMap . putAll ( additionalCallbacks ) ; loginContext = ( ResultAwareLoginContext ) loginContextFactory . createLoginContext ( callbackHandlerMap ) ; if ( loginContext == null ) { throw new LoginException ( "Login failed; cannot create a login context for authentication token '" + authToken + "\'." ) ; } if ( loggerEnabled ( ) ) { log ( "Login module login required; [%s]." , authToken ) ; } loginContext . login ( ) ; } catch ( LoginException le ) { if ( loggerEnabled ( ) ) { if ( le . getMessage ( ) != null && ! le . getMessage ( ) . contains ( "all modules ignored" ) ) { log ( "Login failed: " + le . getMessage ( ) , le ) ; } } if ( loginContext == null ) { writeResponse ( HttpStatus . CLIENT_FORBIDDEN , nextFilter , session , httpRequest ) ; return false ; } } catch ( Exception e ) { if ( loggerEnabled ( ) ) { log ( "Login failed." , e ) ; } writeResponse ( HttpStatus . CLIENT_FORBIDDEN , nextFilter , session , httpRequest ) ; return false ; } DefaultLoginResult loginResult = loginContext . getLoginResult ( ) ; String challenge = sendChallengeResponse ( nextFilter , session , httpRequest , loginResult , realms , realmIndex , loginContexts ) ; if ( loggerEnabled ( ) ) { log ( String . format ( "No authentication token was provided. Issuing an authentication challenge '%s'." , challenge ) ) ; } ResourceAddress localAddress = LOCAL_ADDRESS . get ( session ) ; String nextProtocol = localAddress . getOption ( NEXT_PROTOCOL ) ; if ( "http/1.1" . equals ( nextProtocol ) ) { HttpMergeRequestFilter . INITIAL_HTTP_REQUEST_KEY . remove ( session ) ; } return false ; }
Handle the initial login attempt where the client has presumably not sent any specific authentication token yet .
3,912
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 ) ; MDC . put ( key , value ) ; }
Add a property to the context for the given session This property will be added to the MDC for all subsequent events
3,913
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 .
3,914
public Node removeFirst ( ) { Node node = header . getNextNode ( ) ; firstByte += node . ba . last ( ) ; return removeNode ( node ) ; }
Removes the first node from this list
3,915
public Node removeLast ( ) { Node node = header . getPreviousNode ( ) ; lastByte -= node . ba . last ( ) ; return removeNode ( node ) ; }
Removes the last node in this list
3,916
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 .
3,917
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 .
3,918
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 ( ( ( WriteRequest ) message ) . getMessage ( ) ) ; } else if ( message instanceof CharSequence ) { answer += ( ( CharSequence ) message ) . length ( ) << 1 ; } else if ( message instanceof Iterable ) { for ( Object m : ( Iterable < ? > ) message ) { answer += estimateSize ( m ) ; } } return align ( answer ) ; }
Estimate the size of an Objecr in number of bytes
3,919
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 .
3,920
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 .
3,921
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 != null && i < bytes . length - 1 ) { sb . append ( separator ) ; } } return sb . toString ( ) ; }
Returns a hexadecimal representation of the given byte array .
3,922
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 .
3,923
public void updateThroughput ( long currentTime ) { synchronized ( throughputCalculationLock ) { int interval = ( int ) ( currentTime - lastThroughputCalculationTime ) ; long minInterval = getThroughputCalculationIntervalInMillis ( ) ; if ( minInterval == 0 || interval < minInterval ) { return ; } long readBytes = this . readBytes . get ( ) ; long writtenBytes = this . writtenBytes . get ( ) ; long readMessages = this . readMessages . get ( ) ; long writtenMessages = this . writtenMessages . get ( ) ; readBytesThroughput = ( readBytes - lastReadBytes ) * 1000.0 / interval ; writtenBytesThroughput = ( writtenBytes - lastWrittenBytes ) * 1000.0 / interval ; readMessagesThroughput = ( readMessages - lastReadMessages ) * 1000.0 / interval ; writtenMessagesThroughput = ( writtenMessages - lastWrittenMessages ) * 1000.0 / interval ; if ( readBytesThroughput > largestReadBytesThroughput ) { largestReadBytesThroughput = readBytesThroughput ; } if ( writtenBytesThroughput > largestWrittenBytesThroughput ) { largestWrittenBytesThroughput = writtenBytesThroughput ; } if ( readMessagesThroughput > largestReadMessagesThroughput ) { largestReadMessagesThroughput = readMessagesThroughput ; } if ( writtenMessagesThroughput > largestWrittenMessagesThroughput ) { largestWrittenMessagesThroughput = writtenMessagesThroughput ; } lastReadBytes = readBytes ; lastWrittenBytes = writtenBytes ; lastReadMessages = readMessages ; lastWrittenMessages = writtenMessages ; lastThroughputCalculationTime = currentTime ; } }
Updates the throughput counters .
3,924
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 . incrementAndGet ( ) ; } } return cls . getSimpleName ( ) + '-' + newThreadId ; }
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 .
3,925
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
3,926
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
3,927
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 .
3,928
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 ) ; break ; case CLOSING : break ; case OPENING : trafficControllingSessions . add ( session ) ; break ; default : throw new IllegalStateException ( String . valueOf ( state ) ) ; } queueSize -- ; } }
Update the trafficControl for all the session which has just been opened .
3,929
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 .
3,930
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 . messageReceived ( session , buf ) ; } else { LOGGER . debug ( " Data Read: {} ({})" , handler , buf ) ; while ( buf . hasRemaining ( ) && ! handler . isHandshakeComplete ( ) ) { LOGGER . debug ( " Pre-handshake - passing to handler" ) ; int pos = buf . position ( ) ; handler . messageReceived ( nextFilter , buf ) ; if ( buf . position ( ) == pos || session . isClosing ( ) ) { return ; } } if ( buf . hasRemaining ( ) ) { LOGGER . debug ( " Passing remaining data to next filter" ) ; nextFilter . messageReceived ( session , buf ) ; } } } }
Receives data from the remote host passes to the handler if a handshake is in progress otherwise passes on transparently .
3,931
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 .
3,932
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 , writeRequest ) ; } else if ( isHandshakeData ) { LOGGER . debug ( " handshake data: {}" , writeRequest . getMessage ( ) ) ; nextFilter . filterWrite ( session , writeRequest ) ; } else { if ( ! session . isConnected ( ) ) { LOGGER . debug ( " Write request on closed session. Request ignored." ) ; } else { LOGGER . debug ( " Handshaking is not complete yet. Buffering write request." ) ; handler . enqueueWriteRequest ( nextFilter , writeRequest ) ; } } } }
Actually write data . Queues the data up unless it relates to the handshake or the handshake is done .
3,933
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 .
3,934
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 ( ) ) ; @ SuppressWarnings ( "unused" ) String loginKey = getShortString ( buffer ) ; @ SuppressWarnings ( "unused" ) AmqpType ltype = getType ( buffer ) ; String username = getLongString ( buffer ) ; @ SuppressWarnings ( "unused" ) String passwordKey = getShortString ( buffer ) ; @ SuppressWarnings ( "unused" ) AmqpType ptype = getType ( buffer ) ; String password = getLongString ( buffer ) ; if ( logger . isDebugEnabled ( ) ) { String s = ".decodeAuthAmqPlain(): Username = " + username ; logger . debug ( CLASS_NAME + s ) ; } credentials = new String [ ] { username , password } ; } return credentials ; }
the 1st element is the password .
3,935
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 .
3,936
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 ( tmp ) ) ; }
Internal method that actually flushes the buffered data .
3,937
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 .
3,938
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 .
3,939
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 .
3,940
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 .
3,941
@ 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 { oldValue = initialValue ( ) ; } } else { holder = createHolder ( ) ; oldValue = initialValue ( ) ; } holder . value = value ; return oldValue ; }
Swaps the current threads value with the supplied value . Thread - local will be initialised if not already done so .
3,942
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 ; link . next = next ; } else { link = next ; next = next . next ; } } if ( first . get ( ) == null ) { if ( ! strongRefsUpdater . weakCompareAndSet ( this , first , first . next ) ) { first . value = null ; } } } }
Check if any strong references need should be removed due to thread exit .
3,943
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 ( MalformedURLException e ) { logger . debug ( "Malformed URL" , e ) ; } } } return host ; }
Returns the host to which we are connecting .
3,944
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 . Entry < String , List < String > > header : getHeaders ( ) . entrySet ( ) ) { if ( ! hostHeaderFound ) { hostHeaderFound = header . getKey ( ) . equalsIgnoreCase ( "host" ) ; } for ( String value : header . getValue ( ) ) { sb . append ( header . getKey ( ) ) . append ( ": " ) . append ( value ) . append ( HttpProxyConstants . CRLF ) ; } } if ( ! hostHeaderFound && getHttpVersion ( ) == HttpProxyConstants . HTTP_1_1 ) { sb . append ( "Host: " ) . append ( getHost ( ) ) . append ( HttpProxyConstants . CRLF ) ; } } sb . append ( HttpProxyConstants . CRLF ) ; return sb . toString ( ) ; }
Returns the string representation of the HTTP request .
3,945
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 = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL classUrl = loader . getResource ( "org/kaazing/gateway/server/Gateway.class" ) ; String urlStr ; try { urlStr = URLDecoder . decode ( classUrl . toString ( ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( "Failed to configure Gateway" , ex ) ; } int packageSeparatorIndex = urlStr . indexOf ( "!/" ) ; if ( packageSeparatorIndex > 0 ) { urlStr = urlStr . substring ( 0 , urlStr . indexOf ( "!/" ) ) ; urlStr = urlStr . substring ( 4 ) ; } if ( ! urlStr . startsWith ( "file:" ) ) { throw new RuntimeException ( "The Gateway class was not loaded from a file, so we " + "cannot determine the location of GATEWAY_HOME" ) ; } urlStr = urlStr . substring ( 5 ) ; File jarFile = new File ( urlStr ) ; gatewayHome = jarFile . getParentFile ( ) . getParent ( ) ; properties . setProperty ( "GATEWAY_HOME" , gatewayHome ) ; } gateway . setProperties ( properties ) ; }
Bootstrap the Gateway instance with a GATEWAY_HOME if not already set in System properties .
3,946
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 ProtocolDecoderException ( "Expecting CONTINUATION frame, but got " + opcode + " frame" ) ; } break ; case PING : case PONG : case CLOSE : if ( ! fin ) { throw new ProtocolDecoderException ( "Expected FIN for " + opcode + " frame" ) ; } break ; default : break ; } }
Validates opcode w . r . t FIN bit
3,947
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 & 0x10 ) != 0 ) { throw new ProtocolDecoderException ( "RSV3 is set" ) ; } } }
Validates RSV bits
3,948
public synchronized void doHandshake ( final NextFilter nextFilter ) { LOGGER . debug ( " doHandshake()" ) ; writeRequest ( nextFilter , request , ( Integer ) getSession ( ) . getAttribute ( HANDSHAKE_STEP ) ) ; }
Performs the handshake process .
3,949
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 ( SocksProxyConstants . SUPPORTED_AUTH_METHODS ) ; return buf ; }
Encodes the initial greeting packet .
3,950
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 Inet6Address ) { len += 16 ; addressType = SocksProxyConstants . IPV6_ADDRESS_TYPE ; } else if ( adr . getAddress ( ) instanceof Inet4Address ) { len += 4 ; addressType = SocksProxyConstants . IPV4_ADDRESS_TYPE ; } } else { host = request . getHost ( ) != null ? request . getHost ( ) . getBytes ( "ASCII" ) : null ; if ( host != null ) { len += 1 + host . length ; addressType = SocksProxyConstants . DOMAIN_NAME_ADDRESS_TYPE ; } else { throw new IllegalArgumentException ( "SocksProxyRequest object " + "has no suitable endpoint information" ) ; } } IoBuffer buf = IoBuffer . allocate ( len ) ; buf . put ( request . getProtocolVersion ( ) ) ; buf . put ( request . getCommandCode ( ) ) ; buf . put ( ( byte ) 0x00 ) ; buf . put ( addressType ) ; if ( host == null ) { buf . put ( request . getIpAddress ( ) ) ; } else { buf . put ( ( byte ) host . length ) ; buf . put ( host ) ; } buf . put ( request . getPort ( ) ) ; return buf ; }
Encodes the proxy authorization request packet .
3,951
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 = encodeAuthenticationPacket ( request ) ; if ( buf == null ) { step = SocksProxyConstants . SOCKS5_REQUEST_STEP ; } } if ( step == SocksProxyConstants . SOCKS5_REQUEST_STEP ) { buf = encodeProxyRequestPacket ( request ) ; } buf . flip ( ) ; writeData ( nextFilter , buf ) ; } catch ( Exception ex ) { closeSession ( "Unable to send Socks request: " , ex ) ; } }
Encodes a SOCKS5 request and writes it to the next filter so it can be sent to the proxy server .
3,952
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 .
3,953
public void addSession ( AbstractIoSession session ) { sessions . add ( session ) ; CloseFuture closeFuture = session . getCloseFuture ( ) ; closeFuture . addListener ( sessionCloseListener ) ; }
Add the session for being checked for idle .
3,954
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 ( ) + " (" + encoder + ')' ) ; } }
Dispose the encoder removing its instance from the session s attributes and calling the associated dispose method .
3,955
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 ( ) + " (" + decoder + ')' ) ; } }
Dispose the decoder removing its instance from the session s attributes and calling the associated dispose method .
3,956
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 .
3,957
public boolean validate ( HttpRequestMessage request , boolean isPostMethodAllowed ) { WebSocketWireProtocol wireProtocolVersion = guessWireProtocolVersion ( request ) ; if ( wireProtocolVersion == null ) { return false ; } final WsHandshakeValidator validator = handshakeValidatorsByWireProtocolVersion . get ( wireProtocolVersion ) ; return validator != null && validator . doValidate ( request , isPostMethodAllowed ) ; }
Facade method to validate an HttpMessageRequest .
3,958
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 false ; } } if ( request . getVersion ( ) != HttpVersion . HTTP_1_1 ) { return false ; } if ( request . getRequestURI ( ) == null ) { return false ; } boolean ok = requireHeader ( request , "Connection" , "Upgrade" ) ; if ( ! ok ) { return false ; } ok = requireHeader ( request , "Upgrade" , "WebSocket" ) ; if ( ! ok ) { return false ; } ok = requireHeader ( request , "Host" ) ; return ok ; }
Does the provided request form a valid web socket handshake request?
3,959
private void register ( WebSocketWireProtocol wireProtocolVersion , WsHandshakeValidator validator ) { if ( wireProtocolVersion == null ) { throw new NullPointerException ( "wireProtocolVersion" ) ; } if ( validator == null ) { throw new NullPointerException ( "validator" ) ; } WsHandshakeValidator existingValidator = handshakeValidatorsByWireProtocolVersion . put ( wireProtocolVersion , validator ) ; logger . trace ( "Class " + validator . getClass ( ) . getName ( ) + " registered to support websocket handshake for protocol " + wireProtocolVersion ) ; if ( existingValidator != null ) { logger . trace ( "Multiple handshake validators have registered to support wire protocol " + wireProtocolVersion + ". Using class " + this . getClass ( ) . getName ( ) + '.' ) ; } }
Allow subclasses to register themselves as validators for specific versions of the wire protocol .
3,960
public IoBuffer fetchAppBuffer ( ) { IoBufferEx appBuffer = this . appBuffer . flip ( ) ; this . appBuffer = null ; return ( IoBuffer ) appBuffer ; }
Get decrypted application data .
3,961
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
3,962
public String getCacheControlHeader ( ) { checkIfMaxAgeIsResolved ( ) ; String maxAge = Directive . MAX_AGE . getName ( ) + "=" + ( maxAgeResolvedValue > 0 ? maxAgeResolvedValue : "0" ) ; return staticDirectives . toString ( ) + maxAge ; }
Returns the Cache - control header string
3,963
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 : maxAgeDirectives . put ( key , value ) ; break ; default : if ( value . equals ( EMPTY_STRING_VALUE ) ) { staticDirectives . append ( key . getName ( ) + DIRECTIVES_SEPARATOR ) ; break ; } staticDirectives . append ( key . getName ( ) + EQUALS_STRING + value + DIRECTIVES_SEPARATOR ) ; } } }
Builds a string of directives by concatenating all the static directives
3,964
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
3,965
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 .
3,966
public final void sessionOpened ( IoSession session ) throws Exception { ProxyIoSession proxyIoSession = ( ProxyIoSession ) session . getAttribute ( ProxyIoSession . PROXY_SESSION ) ; if ( proxyIoSession . getRequest ( ) instanceof SocksProxyRequest || proxyIoSession . isAuthenticationFailed ( ) || proxyIoSession . getHandler ( ) . isHandshakeComplete ( ) ) { proxySessionOpened ( session ) ; } else { logger . debug ( "Filtered session opened event !" ) ; } }
Hooked session opened event .
3,967
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 ( ) { public void run ( ) { reset0 ( cause ) ; } } ) ; } }
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 .
3,968
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 ( now ) ) { throw new LoginException ( "Token has expired" ) ; } if ( expiringState != null ) { long duration = Duration . between ( now , expires ) . toMillis ( ) ; String nonce = json . getString ( "nonce" ) ; if ( expiringState . putIfAbsent ( nonce , nonce , duration , TimeUnit . MILLISECONDS ) != null ) { throw new LoginException ( String . format ( "Token nonce has already been used: %s" , nonce ) ) ; } } this . username = json . getString ( "username" ) ; logger . fine ( String . format ( "Login: Token is valid for user %s" , username ) ) ; }
Validate the token and extract the username to add to shared state . An exception is thrown if the token is found to be invalid
3,969
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 ; switch ( remainder ) { case 3 : b = ( byte ) ( src . get ( ) ^ ( ( mask >> 24 ) & 0xff ) ) ; dst . put ( b ) ; b = ( byte ) ( src . get ( ) ^ ( ( mask >> 16 ) & 0xff ) ) ; dst . put ( b ) ; b = ( byte ) ( src . get ( ) ^ ( ( mask >> 8 ) & 0xff ) ) ; dst . put ( b ) ; break ; case 2 : b = ( byte ) ( src . get ( ) ^ ( ( mask >> 24 ) & 0xff ) ) ; dst . put ( b ) ; b = ( byte ) ( src . get ( ) ^ ( ( mask >> 16 ) & 0xff ) ) ; dst . put ( b ) ; break ; case 1 : b = ( byte ) ( src . get ( ) ^ ( mask >> 24 ) ) ; dst . put ( b ) ; break ; case 0 : default : break ; } }
Masks source buffer into destination buffer .
3,970
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
3,971
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 ) ; directive = Directive . MAX_AGE_MPLUS ; } else { directive = Directive . MAX_AGE ; } } else { directive = Directive . get ( directiveName ) ; } long value = Utils . parseTimeInterval ( directiveValue , TimeUnit . SECONDS , 0 ) ; directives . put ( directive , Long . toString ( value ) ) ; }
Adds a directive with the associated value to the directives map after parsing the value from the configuration file
3,972
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-control syntax in the configuration file" ) ; } return true ; }
Checks for duplicate directive values and correct syntax
3,973
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 ( ) . getAcceptor ( ) ) ; allResources . put ( entry . getKey ( ) + ".connector" , entry . getValue ( ) . getConnector ( ) ) ; } for ( Transport transport : transportsByName . values ( ) ) { BridgeAcceptor acceptor = transport . getAcceptor ( ) ; if ( acceptor != null ) { injectResources ( acceptor , allResources ) ; } BridgeConnector connector = transport . getConnector ( ) ; if ( connector != null ) { injectResources ( transport . getConnector ( ) , allResources ) ; } for ( Object extension : transport . getExtensions ( ) ) { injectResources ( extension , allResources ) ; } } return allResources ; }
Inject the given resources plus all available transport acceptors and connectors into every available acceptor and connector .
3,974
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 ( 0 , uri . indexOf ( ':' ) ) ; Protocol protocol = transportFactory . getProtocol ( schemeFromAcceptURI ) ; if ( WsProtocol . WS . equals ( protocol ) || WsProtocol . WSS . equals ( protocol ) ) { for ( String scheme : Arrays . asList ( "wsn" , "wsx" ) ) { boolean secure = protocol . isSecure ( ) ; String wsBalancerUriScheme = secure ? scheme + "+ssl" : scheme ; String httpAuthority = getAuthority ( uri ) ; String httpPath = getPath ( uri ) ; String httpQuery = getQuery ( uri ) ; httpURIs . add ( buildURIAsString ( wsBalancerUriScheme , httpAuthority , httpPath , httpQuery , null ) ) ; String internalURI = acceptOptionsCtx . getInternalURI ( uri ) ; if ( ( internalURI != null ) && ! internalURI . equals ( uri ) ) { String authority = getAuthority ( internalURI ) ; acceptOptionsCtx . addBind ( wsBalancerUriScheme , authority ) ; } } } } return httpURIs ; }
Converts a collection of WS URIs to their equivalent WSN balancer URIs .
3,975
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 .
3,976
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 .
3,977
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 .
3,978
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 not reachable from the server)" ; case V4_REPLY_REQUEST_FAILED_ID_NOT_CONFIRMED : return "Request failed because client's identd could not confirm the user ID string in the request" ; case V5_REPLY_SUCCEEDED : return "Request succeeded" ; case V5_REPLY_GENERAL_FAILURE : return "Request failed: general SOCKS server failure" ; case V5_REPLY_NOT_ALLOWED : return "Request failed: connection not allowed by ruleset" ; case V5_REPLY_NETWORK_UNREACHABLE : return "Request failed: network unreachable" ; case V5_REPLY_HOST_UNREACHABLE : return "Request failed: host unreachable" ; case V5_REPLY_CONNECTION_REFUSED : return "Request failed: connection refused" ; case V5_REPLY_TTL_EXPIRED : return "Request failed: TTL expired" ; case V5_REPLY_COMMAND_NOT_SUPPORTED : return "Request failed: command not supported" ; case V5_REPLY_ADDRESS_TYPE_NOT_SUPPORTED : return "Request failed: address type not supported" ; default : return "Unknown reply code" ; } }
Return the string associated with the specified reply code .
3,979
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 > lines = new ArrayList < > ( ) ; try { String line = reader . readLine ( ) ; while ( line != null ) { lines . add ( line ) ; line = reader . readLine ( ) ; } } catch ( IOException ex ) { lines . add ( ex . toString ( ) ) ; } String [ ] rep = new String [ lines . size ( ) ] ; lines . toArray ( rep ) ; return rep ; }
convert a Throwable into an array of Strings
3,980
private void addCacheControl ( HttpAcceptSession session , File requestFile , String requestPath ) { CacheControlHandler cacheControlHandler = urlCacheControlMap . computeIfAbsent ( requestPath , path -> patterns . stream ( ) . filter ( patternCacheControl -> PatternMatcherUtils . caseInsensitiveMatch ( requestPath , patternCacheControl . getPattern ( ) ) ) . findFirst ( ) . map ( patternCacheControl -> new CacheControlHandler ( requestFile , patternCacheControl ) ) . orElse ( null ) ) ; if ( cacheControlHandler != null ) { addCacheControlHeader ( session , requestFile , cacheControlHandler ) ; } }
Matches the file URL with the most specific pattern and caches this information in a map Sets cache - control and expires headers
3,981
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 .
3,982
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 exception type: " + cause . getClass ( ) . getSimpleName ( ) ) ; } }
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 .
3,983
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 ( ) . getFilterChainBuilder ( ) . buildFilterChain ( getFilterChain ( ) ) ; serviceListeners . fireSessionCreated ( this ) ; } catch ( Throwable e ) { getFilterChain ( ) . fireExceptionCaught ( e ) ; processor . remove ( this ) ; } }
start handling streams
3,984
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 ) . run ( ) ; } }
Forces a check for an update and registers the listener if it is not already registered
3,985
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 , BitUtil . CACHE_LINE_LENGTH ) ; serviceRefSection = endOfMetadata - servicesCount * OFFSETS_PER_SERVICE * BitUtil . SIZE_OF_INT ; }
Method setting the number of services and metadata length
3,986
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 , ByteOrder . nativeOrder ( ) ) ; metaDataBuffer . putInt ( gwCountersLblBuffersReferenceOffset , 0 ) ; metaDataBuffer . putInt ( gwCountersLblBuffersLengthOffset , GATEWAY_COUNTER_LABELS_BUFFER_LENGTH ) ; metaDataBuffer . putInt ( gwCountersValueBuffersReferenceOffset , 0 ) ; metaDataBuffer . putInt ( gwCountersValueBuffersLengthOffset , GATEWAY_COUNTER_VALUES_BUFFER_LENGTH ) ; metaDataBuffer . putInt ( noOfServicesOffset , 0 ) ; }
Fills the meta data in the specified buffer
3,987
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 ) ; int serviceLocationOffset = serviceNameOffset + serviceName . length ( ) + BitUtil . SIZE_OF_INT ; metaDataBuffer . putStringUtf8 ( serviceNameOffset , serviceName , ByteOrder . nativeOrder ( ) ) ; initializeServiceRefMetadata ( serviceLocationOffset , index * OFFSETS_PER_SERVICE ) ; prevServiceOffset = serviceNameOffset ; prevServiceName = serviceName ; }
Method adding services metadata
3,988
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
3,989
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 ) ; metaDataBuffer . putInt ( serviceRefSection + ( serviceOffsetIndex + 1 ) * BitUtil . SIZE_OF_INT , SERVICE_COUNTER_LABELS_BUFFER_LENGTH ) ; metaDataBuffer . putInt ( serviceRefSection + ( serviceOffsetIndex + 2 ) * BitUtil . SIZE_OF_INT , 0 ) ; metaDataBuffer . putInt ( serviceRefSection + ( serviceOffsetIndex + 3 ) * BitUtil . SIZE_OF_INT , SERVICE_COUNTER_VALUES_BUFFER_LENGTH ) ; }
Method initializing service ref metadata section data
3,990
private void setGatewayIdDependentOffsets ( String gatewayId ) { gwCountersLblBuffersReferenceOffset = GW_ID_OFFSET + gatewayId . length ( ) + BitUtil . SIZE_OF_INT ; gwCountersLblBuffersLengthOffset = gwCountersLblBuffersReferenceOffset + BitUtil . SIZE_OF_INT ; gwCountersValueBuffersReferenceOffset = gwCountersLblBuffersLengthOffset + BitUtil . SIZE_OF_INT ; gwCountersValueBuffersLengthOffset = gwCountersValueBuffersReferenceOffset + BitUtil . SIZE_OF_INT ; noOfServicesOffset = gwCountersValueBuffersLengthOffset + BitUtil . SIZE_OF_INT ; serviceDataOffset = noOfServicesOffset ; }
Method setting gatewayId dependent offsets
3,991
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 gateway ; }
Creates an implementation of an Gateway .
3,992
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 = ( IoBuffer ) message ; ProtocolDecoder decoder = getDecoder ( session ) ; ProtocolDecoderOutput decoderOut = getDecoderOut ( session , nextFilter ) ; IoSessionEx sessionEx = ( IoSessionEx ) session ; Thread ioThread = sessionEx . getIoThread ( ) ; while ( in . hasRemaining ( ) ) { if ( sessionEx . getIoThread ( ) != ioThread ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( format ( "Decoding for session=%s will be continued by new thread=%s old thread=%s" , session , sessionEx . getIoThread ( ) , ioThread ) ) ; } break ; } int oldPos = in . position ( ) ; try { synchronized ( decoderOut ) { decoder . decode ( session , in , decoderOut ) ; decoderOut . flush ( nextFilter , session ) ; } } catch ( Throwable t ) { ProtocolDecoderException pde ; if ( t instanceof ProtocolDecoderException ) { pde = ( ProtocolDecoderException ) t ; } else { pde = new ProtocolDecoderException ( t ) ; } if ( pde . getHexdump ( ) == null ) { int curPos = in . position ( ) ; in . position ( oldPos ) ; pde . setHexdump ( in . getHexDump ( ) ) ; in . position ( curPos ) ; } synchronized ( decoderOut ) { decoderOut . flush ( nextFilter , session ) ; } nextFilter . exceptionCaught ( session , pde ) ; if ( ! ( t instanceof RecoverableProtocolDecoderException ) || ( in . position ( ) == oldPos ) ) { break ; } } } }
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 .
3,993
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 .
3,994
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 .
3,995
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 .
3,996
static String getUserIdentifier ( IoSession session ) { boolean isAcceptor = isAcceptor ( session ) ; SocketAddress hostPortAddress = isAcceptor ? session . getRemoteAddress ( ) : session . getLocalAddress ( ) ; SocketAddress identityAddress = isAcceptor ? session . getLocalAddress ( ) : session . getRemoteAddress ( ) ; String identity = resolveIdentity ( identityAddress , ( IoSessionEx ) session ) ; String hostPort = getHostPort ( hostPortAddress ) ; return identity == null ? hostPort : format ( "%s %s" , identity , hostPort ) ; }
Get a suitable identification for the user . For now this just consists of the TCP endpoint . the HTTP - layer auth principal etc .
3,997
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
3,998
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 resolveIdentity ( transport , subject ) ; } return null ; }
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 .
3,999
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 ( address instanceof InetSocketAddress ) { InetSocketAddress inet = ( InetSocketAddress ) address ; return format ( HOST_PORT_FORMAT , inet . getHostString ( ) , inet . getPort ( ) ) ; } return null ; }
Method attempting to retrieve host port identifier