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 (...
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_S...
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 . re...
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 ( )...
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 " + conte...
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 ( ( ...
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" ) ; } proxyIoSes...
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 new...
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 ] ; Resu...
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 ) ; M...
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 ( ( ( Writ...
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 !=...
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...
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 . 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 .
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 ) ; b...
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 . mess...
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 , writeRe...
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 ( ) ) ; @ Sup...
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 ...
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 { oldVa...
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 ...
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 ( Malforme...
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 ....
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 = Th...
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 ProtocolDeco...
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 &...
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 ( SocksProxyCon...
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...
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 = encodeAuth...
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 ( ) + " (...
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 ( ) + " (...
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 ( wireProt...
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 fals...
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 = ...
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 : maxAgeDir...
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 . get...
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 ( ) { 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 .
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 ( 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
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 ; ...
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 ) ; di...
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-...
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 ( ) . getA...
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 ...
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...
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 > ...
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 , p...
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 ...
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 ( ) . ...
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 ) . ...
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 , ...
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 , ByteO...
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 ) ...
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 ) ; metaDat...
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 = gwCountersLblBuf...
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...
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 =...
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 ( ) ...
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 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 .
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 ( addre...
Method attempting to retrieve host port identifier