idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
39,900
public static < T > T fromJson ( String json , Class < T > clazz ) { Objects . requireNonNull ( json , Required . JSON . toString ( ) ) ; Objects . requireNonNull ( clazz , Required . CLASS . toString ( ) ) ; T object = null ; try { object = mapper . readValue ( json , clazz ) ; } catch ( IOException e ) { LOG . error ( "Failed to convert json to object class" , e ) ; } return object ; }
Converts a given Json string to given Class
39,901
public String get ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; return this . values . get ( key ) ; }
Retrieves a form value corresponding to the name of the form element
39,902
protected void setSessionCookie ( HttpServerExchange exchange ) { Session session = this . attachment . getSession ( ) ; if ( session . isInvalid ( ) ) { Cookie cookie = new CookieImpl ( this . config . getSessionCookieName ( ) ) . setSecure ( this . config . isSessionCookieSecure ( ) ) . setHttpOnly ( true ) . setPath ( "/" ) . setMaxAge ( 0 ) . setSameSite ( true ) . setSameSiteMode ( SAME_SITE_MODE ) . setDiscard ( true ) ; exchange . setResponseCookie ( cookie ) ; } else if ( session . hasChanges ( ) ) { JwtClaims jwtClaims = new JwtClaims ( ) ; jwtClaims . setClaim ( ClaimKey . AUTHENTICITY . toString ( ) , session . getAuthenticity ( ) ) ; jwtClaims . setClaim ( ClaimKey . DATA . toString ( ) , session . getValues ( ) ) ; if ( session . getExpires ( ) == null ) { jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , "-1" ) ; } else { jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , session . getExpires ( ) . format ( DateUtils . formatter ) ) ; } JsonWebSignature jsonWebSignature = new JsonWebSignature ( ) ; jsonWebSignature . setKey ( new HmacKey ( this . config . getSessionCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; jsonWebSignature . setPayload ( jwtClaims . toJson ( ) ) ; jsonWebSignature . setAlgorithmHeaderValue ( AlgorithmIdentifiers . HMAC_SHA512 ) ; try { String encryptedValue = Application . getInstance ( Crypto . class ) . encrypt ( jsonWebSignature . getCompactSerialization ( ) , this . config . getSessionCookieEncryptionKey ( ) ) ; Cookie cookie = new CookieImpl ( this . config . getSessionCookieName ( ) ) . setValue ( encryptedValue ) . setSameSite ( true ) . setSameSiteMode ( SAME_SITE_MODE ) . setHttpOnly ( true ) . setPath ( "/" ) . setSecure ( this . config . isSessionCookieSecure ( ) ) ; if ( session . getExpires ( ) != null ) { cookie . setExpires ( DateUtils . localDateTimeToDate ( session . getExpires ( ) ) ) ; } exchange . setResponseCookie ( cookie ) ; } catch ( Exception e ) { LOG . error ( "Failed to generate session cookie" , e ) ; } } else { } }
Sets the session cookie to the current HttpServerExchange
39,903
protected void setAuthenticationCookie ( HttpServerExchange exchange ) { Authentication authentication = this . attachment . getAuthentication ( ) ; if ( authentication . isInvalid ( ) || authentication . isLogout ( ) ) { Cookie cookie = new CookieImpl ( this . config . getAuthenticationCookieName ( ) ) . setSecure ( this . config . isAuthenticationCookieSecure ( ) ) . setHttpOnly ( true ) . setPath ( "/" ) . setMaxAge ( 0 ) . setSameSite ( true ) . setSameSiteMode ( SAME_SITE_MODE ) . setDiscard ( true ) ; exchange . setResponseCookie ( cookie ) ; } else if ( authentication . isValid ( ) ) { if ( authentication . isRememberMe ( ) ) { authentication . withExpires ( LocalDateTime . now ( ) . plusHours ( this . config . getAuthenticationCookieRememberExpires ( ) ) ) ; } JwtClaims jwtClaims = new JwtClaims ( ) ; jwtClaims . setSubject ( authentication . getSubject ( ) ) ; jwtClaims . setClaim ( ClaimKey . TWO_FACTOR . toString ( ) , authentication . isTwoFactor ( ) ) ; if ( authentication . getExpires ( ) == null ) { jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , "-1" ) ; } else { jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , authentication . getExpires ( ) . format ( DateUtils . formatter ) ) ; } JsonWebSignature jsonWebSignature = new JsonWebSignature ( ) ; jsonWebSignature . setKey ( new HmacKey ( this . config . getAuthenticationCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; jsonWebSignature . setPayload ( jwtClaims . toJson ( ) ) ; jsonWebSignature . setAlgorithmHeaderValue ( AlgorithmIdentifiers . HMAC_SHA512 ) ; try { String encryptedValue = Application . getInstance ( Crypto . class ) . encrypt ( jsonWebSignature . getCompactSerialization ( ) , this . config . getAuthenticationCookieEncryptionKey ( ) ) ; final Cookie cookie = new CookieImpl ( this . config . getAuthenticationCookieName ( ) ) . setValue ( encryptedValue ) . setSecure ( this . config . isAuthenticationCookieSecure ( ) ) . setHttpOnly ( true ) . setSameSite ( true ) . setPath ( "/" ) . setSameSiteMode ( SAME_SITE_MODE ) ; if ( authentication . getExpires ( ) != null ) { cookie . setExpires ( DateUtils . localDateTimeToDate ( authentication . getExpires ( ) ) ) ; } exchange . setResponseCookie ( cookie ) ; } catch ( JoseException e ) { LOG . error ( "Failed to generate authentication cookie" , e ) ; } } else { } }
Sets the authentication cookie to the current HttpServerExchange
39,904
protected void setFlashCookie ( HttpServerExchange exchange ) { Flash flash = this . attachment . getFlash ( ) ; Form form = this . attachment . getForm ( ) ; if ( flash . isDiscard ( ) || flash . isInvalid ( ) ) { final Cookie cookie = new CookieImpl ( this . config . getFlashCookieName ( ) ) . setHttpOnly ( true ) . setSecure ( this . config . isFlashCookieSecure ( ) ) . setPath ( "/" ) . setSameSite ( true ) . setSameSiteMode ( SAME_SITE_MODE ) . setDiscard ( true ) . setMaxAge ( 0 ) ; exchange . setResponseCookie ( cookie ) ; } else if ( flash . hasContent ( ) || form . flashify ( ) ) { try { JwtClaims jwtClaims = new JwtClaims ( ) ; jwtClaims . setClaim ( ClaimKey . DATA . toString ( ) , flash . getValues ( ) ) ; if ( form . flashify ( ) ) { jwtClaims . setClaim ( ClaimKey . FORM . toString ( ) , CodecUtils . serializeToBase64 ( form ) ) ; } LocalDateTime expires = LocalDateTime . now ( ) . plusSeconds ( SIXTY ) ; jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , expires . format ( DateUtils . formatter ) ) ; JsonWebSignature jsonWebSignature = new JsonWebSignature ( ) ; jsonWebSignature . setKey ( new HmacKey ( this . config . getFlashCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; jsonWebSignature . setPayload ( jwtClaims . toJson ( ) ) ; jsonWebSignature . setAlgorithmHeaderValue ( AlgorithmIdentifiers . HMAC_SHA512 ) ; String encryptedValue = Application . getInstance ( Crypto . class ) . encrypt ( jsonWebSignature . getCompactSerialization ( ) , this . config . getFlashCookieEncryptionKey ( ) ) ; final Cookie cookie = new CookieImpl ( this . config . getFlashCookieName ( ) ) . setValue ( encryptedValue ) . setSecure ( this . config . isFlashCookieSecure ( ) ) . setHttpOnly ( true ) . setSameSite ( true ) . setPath ( "/" ) . setSameSiteMode ( SAME_SITE_MODE ) . setExpires ( DateUtils . localDateTimeToDate ( expires ) ) ; exchange . setResponseCookie ( cookie ) ; } catch ( Exception e ) { LOG . error ( "Failed to generate flash cookie" , e ) ; } } else { } }
Sets the flash cookie to current HttpServerExchange
39,905
protected void handleBinaryResponse ( HttpServerExchange exchange , Response response ) { exchange . dispatch ( exchange . getDispatchExecutor ( ) , Application . getInstance ( BinaryHandler . class ) . withResponse ( response ) ) ; }
Handles a binary response to the client by sending the binary content from the response to the undertow output stream
39,906
protected void handleRedirectResponse ( HttpServerExchange exchange , Response response ) { exchange . setStatusCode ( StatusCodes . FOUND ) ; Server . headers ( ) . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isNotBlank ( entry . getValue ( ) ) ) . forEach ( entry -> exchange . getResponseHeaders ( ) . add ( entry . getKey ( ) . toHttpString ( ) , entry . getValue ( ) ) ) ; exchange . getResponseHeaders ( ) . put ( Header . LOCATION . toHttpString ( ) , response . getRedirectTo ( ) ) ; response . getHeaders ( ) . forEach ( ( key , value ) -> exchange . getResponseHeaders ( ) . add ( key , value ) ) ; exchange . endExchange ( ) ; }
Handles a redirect response to the client by sending a 403 status code to the client
39,907
protected void handleRenderedResponse ( HttpServerExchange exchange , Response response ) { exchange . setStatusCode ( response . getStatusCode ( ) ) ; Server . headers ( ) . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isNotBlank ( entry . getValue ( ) ) ) . forEach ( entry -> exchange . getResponseHeaders ( ) . add ( entry . getKey ( ) . toHttpString ( ) , entry . getValue ( ) ) ) ; exchange . getResponseHeaders ( ) . put ( Header . CONTENT_TYPE . toHttpString ( ) , response . getContentType ( ) + "; charset=" + response . getCharset ( ) ) ; response . getHeaders ( ) . forEach ( ( key , value ) -> exchange . getResponseHeaders ( ) . add ( key , value ) ) ; exchange . getResponseSender ( ) . send ( response . getBody ( ) ) ; }
Handles a rendered response to the client by sending the rendered body from the response object
39,908
private static void prepareMode ( Mode providedMode ) { final String applicationMode = System . getProperty ( Key . APPLICATION_MODE . toString ( ) ) ; if ( StringUtils . isNotBlank ( applicationMode ) ) { switch ( applicationMode . toLowerCase ( Locale . ENGLISH ) ) { case "dev" : mode = Mode . DEV ; break ; case "test" : mode = Mode . TEST ; break ; default : mode = Mode . PROD ; break ; } } else { mode = providedMode ; } }
Sets the mode the application is running in
39,909
private static void prepareConfig ( ) { Config config = getInstance ( Config . class ) ; int bitLength = getBitLength ( config . getApplicationSecret ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Application requires a 512 bit application secret. The current property for application.secret has currently only {} bit." , bitLength ) ; failsafe ( ) ; } bitLength = getBitLength ( config . getAuthenticationCookieEncryptionKey ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Authentication cookie requires a 512 bit encryption key. The current property for authentication.cookie.encryptionkey has only {} bit." , bitLength ) ; failsafe ( ) ; } bitLength = getBitLength ( config . getAuthenticationCookieSignKey ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Authentication cookie requires a 512 bit sign key. The current property for authentication.cookie.signkey has only {} bit." , bitLength ) ; failsafe ( ) ; } bitLength = getBitLength ( config . getSessionCookieEncryptionKey ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Session cookie requires a 512 bit encryption key. The current property for session.cookie.encryptionkey has only {} bit." , bitLength ) ; failsafe ( ) ; } bitLength = getBitLength ( config . getSessionCookieSignKey ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Session cookie requires a 512 bit sign key. The current property for session.cookie.signkey has only {} bit." , bitLength ) ; failsafe ( ) ; } bitLength = getBitLength ( config . getFlashCookieSignKey ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Flash cookie requires a 512 bit sign key. The current property for flash.cookie.signkey has only {} bit." , bitLength ) ; failsafe ( ) ; } bitLength = getBitLength ( config . getFlashCookieEncryptionKey ( ) ) ; if ( bitLength < KEY_MIN_BIT_LENGTH ) { LOG . error ( "Flash cookie requires a 512 bit encryption key. The current property for flash.cookie.encryptionkey has only {} bit." , bitLength ) ; failsafe ( ) ; } if ( ! config . isDecrypted ( ) ) { LOG . error ( "Found encrypted config values in config.props but decryption was not successful!" ) ; failsafe ( ) ; } }
Checks for config failures that prevent the application from starting
39,910
private static void prepareRoutes ( ) { injector . getInstance ( MangooBootstrap . class ) . initializeRoutes ( ) ; Router . getRequestRoutes ( ) . forEach ( ( RequestRoute requestRoute ) -> { if ( ! methodExists ( requestRoute . getControllerMethod ( ) , requestRoute . getControllerClass ( ) ) ) { LOG . error ( "Could not find controller method '{}' in controller class '{}'" , requestRoute . getControllerMethod ( ) , requestRoute . getControllerClass ( ) ) ; failsafe ( ) ; } if ( requestRoute . hasAuthorization ( ) && ( ! MangooUtils . resourceExists ( Default . MODEL_CONF . toString ( ) ) || ! MangooUtils . resourceExists ( Default . POLICY_CSV . toString ( ) ) ) ) { LOG . error ( "Route on method '{}' in controller class '{}' requires authorization, but either model.conf or policy.csv is missing" , requestRoute . getControllerMethod ( ) , requestRoute . getControllerClass ( ) ) ; failsafe ( ) ; } } ) ; }
Validate if the routes that are defined in the router are valid
39,911
private static void createRoutes ( ) { pathHandler = new PathHandler ( getRoutingHandler ( ) ) ; Router . getWebSocketRoutes ( ) . forEach ( ( WebSocketRoute webSocketRoute ) -> pathHandler . addExactPath ( webSocketRoute . getUrl ( ) , Handlers . websocket ( getInstance ( WebSocketHandler . class ) . withControllerClass ( webSocketRoute . getControllerClass ( ) ) . withAuthentication ( webSocketRoute . hasAuthentication ( ) ) ) ) ) ; Router . getServerSentEventRoutes ( ) . forEach ( ( ServerSentEventRoute serverSentEventRoute ) -> pathHandler . addExactPath ( serverSentEventRoute . getUrl ( ) , Handlers . serverSentEvents ( getInstance ( ServerSentEventHandler . class ) . withAuthentication ( serverSentEventRoute . hasAuthentication ( ) ) ) ) ) ; Router . getPathRoutes ( ) . forEach ( ( PathRoute pathRoute ) -> pathHandler . addPrefixPath ( pathRoute . getUrl ( ) , new ResourceHandler ( new ClassPathResourceManager ( Thread . currentThread ( ) . getContextClassLoader ( ) , Default . FILES_FOLDER . toString ( ) + pathRoute . getUrl ( ) ) ) ) ) ; Config config = getInstance ( Config . class ) ; if ( config . isApplicationAdminEnable ( ) ) { pathHandler . addPrefixPath ( "/@admin/assets/" , new ResourceHandler ( new ClassPathResourceManager ( Thread . currentThread ( ) . getContextClassLoader ( ) , "templates/@admin/assets/" ) ) ) ; } }
Create routes for WebSockets ServerSentEvent and Resource files
39,912
public static String getLogo ( ) { String logo = "" ; try ( InputStream inputStream = Resources . getResource ( Default . LOGO_FILE . toString ( ) ) . openStream ( ) ) { logo = IOUtils . toString ( inputStream , Default . ENCODING . toString ( ) ) ; } catch ( final IOException e ) { LOG . error ( "Failed to get application logo" , e ) ; } return logo ; }
Retrieves the logo from the logo file and returns the string
39,913
public boolean validLogin ( String identifier , String password , String hash ) { Objects . requireNonNull ( identifier , Required . USERNAME . toString ( ) ) ; Objects . requireNonNull ( password , Required . PASSWORD . toString ( ) ) ; Objects . requireNonNull ( hash , Required . HASH . toString ( ) ) ; Cache cache = Application . getInstance ( CacheProvider . class ) . getCache ( CacheName . AUTH ) ; boolean authenticated = false ; if ( ! userHasLock ( identifier ) && CodecUtils . checkJBCrypt ( password , hash ) ) { authenticated = true ; } else { cache . increment ( identifier ) ; } return authenticated ; }
Creates a hashed value of a given clear text password and checks if the value matches a given already hashed password
39,914
public boolean userHasLock ( String username ) { Objects . requireNonNull ( username , Required . USERNAME . toString ( ) ) ; boolean lock = false ; Config config = Application . getInstance ( Config . class ) ; Cache cache = Application . getInstance ( CacheProvider . class ) . getCache ( CacheName . AUTH ) ; AtomicInteger counter = cache . getCounter ( username ) ; if ( counter != null && counter . get ( ) > config . getAuthenticationLock ( ) ) { lock = true ; } return lock ; }
Checks if a username is locked because of to many failed login attempts
39,915
public boolean validSecondFactor ( String secret , String number ) { Objects . requireNonNull ( secret , Required . SECRET . toString ( ) ) ; Objects . requireNonNull ( number , Required . TOTP . toString ( ) ) ; return TotpUtils . verifiedTotp ( secret , number ) ; }
Checks if a given number for 2FA is valid for the given secret
39,916
public void withRoutes ( MangooRoute ... routes ) { Objects . requireNonNull ( routes , Required . ROUTE . toString ( ) ) ; for ( MangooRoute route : routes ) { RequestRoute requestRoute = ( RequestRoute ) route ; requestRoute . withControllerClass ( this . controllerClass ) ; if ( hasBasicAuthentication ( ) ) { requestRoute . withBasicAuthentication ( this . username , this . password , this . secret ) ; } if ( hasAuthentication ( ) ) { requestRoute . withAuthentication ( ) ; } if ( hasAuthorization ( ) ) { requestRoute . withAuthorization ( ) ; } if ( hasBlocking ( ) ) { requestRoute . withNonBlocking ( ) ; } if ( requestRoute . getLimit ( ) == 0 ) { requestRoute . withRequestLimit ( this . limit ) ; } if ( requestRoute . hasMultipleMethods ( ) ) { for ( Http method : requestRoute . getMethods ( ) ) { requestRoute . withHttpMethod ( method ) ; Router . addRoute ( requestRoute ) ; } } else { Router . addRoute ( requestRoute ) ; } } }
Sets the given routes to the defined controller class
39,917
public static int bitLength ( byte [ ] bytes ) { Objects . requireNonNull ( bytes , Required . BYTES . toString ( ) ) ; int byteLength = bytes . length ; int length = 0 ; if ( byteLength <= MAX_BYTE_LENGTH && byteLength > 0 ) { length = byteLength * BYTES ; } return length ; }
Calculates the bit length of a given byte array
39,918
public static int bitLength ( String string ) { Objects . requireNonNull ( string , Required . STRING . toString ( ) ) ; int byteLength = string . getBytes ( StandardCharsets . UTF_8 ) . length ; int length = 0 ; if ( byteLength <= MAX_BYTE_LENGTH && byteLength > 0 ) { length = byteLength * BYTES ; } return length ; }
Calculates the bit length of a given string
39,919
private boolean isNotBlank ( String subject , String resource , String operation ) { return StringUtils . isNotBlank ( subject ) && StringUtils . isNotBlank ( resource ) && StringUtils . isNotBlank ( operation ) ; }
Checks if any of the given strings is blank
39,920
private void endRequest ( HttpServerExchange exchange ) { exchange . setStatusCode ( StatusCodes . UNAUTHORIZED ) ; Server . headers ( ) . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isNotBlank ( entry . getValue ( ) ) ) . forEach ( entry -> exchange . getResponseHeaders ( ) . add ( entry . getKey ( ) . toHttpString ( ) , entry . getValue ( ) ) ) ; exchange . endExchange ( ) ; }
Ends the current request by sending a HTTP 401 status code and the default unauthorized template
39,921
public < T > ServiceGraphModule register ( Class < ? extends T > type , ServiceAdapter < T > factory ) { registeredServiceAdapters . put ( type , factory ) ; return this ; }
Puts an instance of class and its factory to the factoryMap
39,922
public < T > ServiceGraphModule registerForSpecificKey ( Key < T > key , ServiceAdapter < T > factory ) { keys . put ( key , factory ) ; return this ; }
Puts the key and its factory to the keys
39,923
public ServiceGraphModule addDependency ( Key < ? > key , Key < ? > keyDependency ) { addedDependencies . computeIfAbsent ( key , key1 -> new HashSet < > ( ) ) . add ( keyDependency ) ; return this ; }
Adds the dependency for key
39,924
public ServiceGraphModule removeDependency ( Key < ? > key , Key < ? > keyDependency ) { removedDependencies . computeIfAbsent ( key , key1 -> new HashSet < > ( ) ) . add ( keyDependency ) ; return this ; }
Removes the dependency
39,925
public ChannelInput < ByteBuf > getInput ( ) { return input -> { this . input = sanitize ( input ) ; if ( this . input != null && this . output != null ) startProcess ( ) ; return getProcessCompletion ( ) ; } ; }
check input for clarity
39,926
public < T > T getCurrentInstance ( Class < T > type ) { return getCurrentInstance ( Key . get ( type ) ) ; }
region getCurrentInstance overloads
39,927
public < T > Provider < T > getCurrentInstanceProvider ( Class < T > type ) { return getCurrentInstanceProvider ( Key . get ( type ) ) ; }
region getCurrentInstanceProvider overloads
39,928
public < T > List < T > getInstances ( Class < T > type ) { return getInstances ( Key . get ( type ) ) ; }
region getInstances overloads
39,929
public static AsyncFile open ( Executor executor , Path path , Set < OpenOption > openOptions ) throws IOException { FileChannel channel = doOpenChannel ( path , openOptions ) ; return new AsyncFile ( executor , channel , path , null ) ; }
Opens file synchronously .
39,930
public static Promise < Void > delete ( Executor executor , Path path ) { return ofBlockingRunnable ( executor , ( ) -> { try { Files . delete ( path ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } ) ; }
Deletes the file concurrently .
39,931
public static Promise < Void > move ( Executor executor , Path source , Path target , CopyOption ... options ) { return ofBlockingRunnable ( executor , ( ) -> { try { Files . move ( source , target , options ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } ) ; }
Moves or renames a file to a target file .
39,932
public static Promise < Void > createDirectories ( Executor executor , Path dir , FileAttribute ... attrs ) { return ofBlockingRunnable ( executor , ( ) -> { try { Files . createDirectories ( dir , attrs ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } ) ; }
Creates a directory by creating all nonexistent parent directories first .
39,933
public Promise < Void > write ( ByteBuf buf ) { return sanitize ( ofBlockingRunnable ( executor , ( ) -> { synchronized ( mutexLock ) { try { int writtenBytes ; do { ByteBuffer byteBuffer = buf . toReadByteBuffer ( ) ; writtenBytes = channel . write ( byteBuffer ) ; buf . ofReadByteBuffer ( byteBuffer ) ; } while ( writtenBytes != - 1 && buf . canRead ( ) ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } finally { buf . recycle ( ) ; } } } ) ) ; }
Writes all bytes of the buffer into this file at its internal position asynchronously .
39,934
public Promise < Void > forceAndClose ( boolean forceMetadata ) { if ( ! isOpen ( ) ) return Promise . ofException ( FILE_CLOSED ) ; return ofBlockingRunnable ( executor , ( ) -> { try { channel . force ( forceMetadata ) ; channel . close ( ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } ) ; }
Forces physical write and then closes the channel if the file is opened .
39,935
public static < T > StreamSorterStorageImpl < T > create ( Executor executor , BinarySerializer < T > serializer , Path path ) { checkArgument ( ! path . getFileName ( ) . toString ( ) . contains ( "%d" ) , "Filename should not contain '%d'" ) ; try { Files . createDirectories ( path ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } return new StreamSorterStorageImpl < > ( executor , serializer , path ) ; }
Creates a new storage
39,936
public Promise < StreamSupplier < T > > read ( int partition ) { Path path = partitionPath ( partition ) ; return AsyncFile . openAsync ( executor , path , set ( READ ) ) . map ( file -> ChannelFileReader . readFile ( file ) . withBufferSize ( readBlockSize ) . transformWith ( ChannelLZ4Decompressor . create ( ) ) . transformWith ( ChannelDeserializer . create ( serializer ) ) . withLateBinding ( ) ) ; }
Returns supplier for reading data from this storage . It read it from external memory decompresses and deserializes it
39,937
public Promise < Void > cleanup ( List < Integer > partitionsToDelete ) { return Promise . ofBlockingCallable ( executor , ( ) -> { for ( Integer partitionToDelete : partitionsToDelete ) { Path path1 = partitionPath ( partitionToDelete ) ; try { Files . delete ( path1 ) ; } catch ( IOException e ) { logger . warn ( "Could not delete {} : {}" , path1 , e . toString ( ) ) ; } } return null ; } ) ; }
Method which removes all creating files
39,938
public void resetStats ( ) { smoothedSum = 0.0 ; smoothedSqr = 0.0 ; smoothedCount = 0.0 ; smoothedMin = 0.0 ; smoothedMax = 0.0 ; lastMaxInteger = Integer . MIN_VALUE ; lastMinInteger = Integer . MAX_VALUE ; lastSumInteger = 0 ; lastSqrInteger = 0 ; lastCountInteger = 0 ; lastValueInteger = 0 ; lastMaxDouble = - Double . MAX_VALUE ; lastMinDouble = Double . MAX_VALUE ; lastSumDouble = 0.0 ; lastSqrDouble = 0.0 ; lastCountDouble = 0 ; lastValueDouble = 0.0 ; lastTimestampMillis = 0L ; smoothedRate = 0 ; smoothedTimeSeconds = 0 ; totalSum = 0.0 ; totalCount = 0 ; if ( histogramLevels != null ) { for ( int i = 0 ; i < histogramValues . length ; i ++ ) { histogramValues [ i ] = 0 ; } } }
Resets stats and sets new parameters
39,939
@ JmxAttribute ( optional = true ) public double getSmoothedStandardDeviation ( ) { if ( totalCount == 0 ) { return 0.0 ; } double avg = smoothedSum / smoothedCount ; double variance = smoothedSqr / smoothedCount - avg * avg ; if ( variance < 0.0 ) variance = 0.0 ; return sqrt ( variance ) ; }
Returns smoothed standard deviation
39,940
public static ServiceAdapter < BlockingService > forBlockingService ( ) { return new SimpleServiceAdapter < BlockingService > ( ) { protected void start ( BlockingService instance ) throws Exception { instance . start ( ) ; } protected void stop ( BlockingService instance ) throws Exception { instance . stop ( ) ; } } ; }
Returns factory which transforms blocking Service to asynchronous non - blocking ConcurrentService . It runs blocking operations from other thread from executor .
39,941
public static ServiceAdapter < Timer > forTimer ( ) { return new SimpleServiceAdapter < Timer > ( false , false ) { protected void start ( Timer instance ) { } protected void stop ( Timer instance ) { instance . cancel ( ) ; } } ; }
Returns factory which transforms Timer to ConcurrentService . On starting it doing nothing on stop it cancel timer .
39,942
public static ServiceAdapter < ExecutorService > forExecutorService ( ) { return new SimpleServiceAdapter < ExecutorService > ( false , true ) { protected void start ( ExecutorService instance ) { } protected void stop ( ExecutorService instance ) throws Exception { List < Runnable > runnables = instance . shutdownNow ( ) ; if ( ! runnables . isEmpty ( ) ) { logger . warn ( "Cancelled tasks: " + runnables ) ; } if ( ! instance . isTerminated ( ) ) { logger . warn ( "Awaiting termination of " + instance + " ..." ) ; instance . awaitTermination ( Long . MAX_VALUE , TimeUnit . MILLISECONDS ) ; } } } ; }
Returns factory which transforms ExecutorService to ConcurrentService . On starting it doing nothing on stopping it shuts down ExecutorService .
39,943
public static ServiceAdapter < Closeable > forCloseable ( ) { return new SimpleServiceAdapter < Closeable > ( false , true ) { protected void start ( Closeable instance ) { } protected void stop ( Closeable instance ) throws Exception { instance . close ( ) ; } } ; }
Returns factory which transforms Closeable object to ConcurrentService . On starting it doing nothing on stopping it close Closeable .
39,944
public static ServiceAdapter < DataSource > forDataSource ( ) { return new SimpleServiceAdapter < DataSource > ( true , false ) { protected void start ( DataSource instance ) throws Exception { Connection connection = instance . getConnection ( ) ; connection . close ( ) ; } protected void stop ( DataSource instance ) { } } ; }
Returns factory which transforms DataSource object to ConcurrentService . On starting it checks connecting on stopping it close DataSource .
39,945
public static String renderQueryString ( Map < String , String > q , String enc ) { StringBuilder sb = new StringBuilder ( ) ; for ( Map . Entry < String , String > e : q . entrySet ( ) ) { String name = urlEncode ( e . getKey ( ) , enc ) ; sb . append ( name ) ; if ( e . getValue ( ) != null ) { sb . append ( '=' ) ; sb . append ( urlEncode ( e . getValue ( ) , enc ) ) ; } sb . append ( '&' ) ; } if ( sb . length ( ) > 0 ) sb . setLength ( sb . length ( ) - 1 ) ; return sb . toString ( ) ; }
Method which creates string with parameters and its value in format URL
39,946
@ Contract ( pure = true ) public ByteBuf peekBuf ( ) { return hasRemaining ( ) ? bufs [ first ] : null ; }
Returns the first ByteBuf of this queue if the queue is not empty . Otherwise returns null .
39,947
@ Contract ( pure = true ) public int remainingBufs ( ) { return last >= first ? last - first : bufs . length + ( last - first ) ; }
Returns the number of ByteBufs in this queue .
39,948
@ Contract ( pure = true ) public int remainingBytes ( ) { int result = 0 ; for ( int i = first ; i != last ; i = next ( i ) ) { result += bufs [ i ] . readRemaining ( ) ; } return result ; }
Returns the number of bytes in this queue .
39,949
@ Contract ( pure = true ) public byte peekByte ( ) { assert hasRemaining ( ) ; ByteBuf buf = bufs [ first ] ; return buf . peek ( ) ; }
Returns the first byte from this queue without any recycling .
39,950
@ SuppressWarnings ( "PointlessArithmeticExpression" ) protected void onStartLine ( byte [ ] line , int limit ) throws ParseException { switchPool ( server . poolReadWrite ) ; HttpMethod method = getHttpMethod ( line ) ; if ( method == null ) { throw new UnknownFormatException ( HttpServerConnection . class , "Unknown HTTP method. First Bytes: " + Arrays . toString ( line ) ) ; } int urlStart = method . size + 1 ; int urlEnd ; for ( urlEnd = urlStart ; urlEnd < limit ; urlEnd ++ ) { if ( line [ urlEnd ] == SP ) { break ; } } int p ; for ( p = urlEnd + 1 ; p < limit ; p ++ ) { if ( line [ p ] != SP ) { break ; } } if ( p + 7 < limit ) { boolean http11 = line [ p + 0 ] == 'H' && line [ p + 1 ] == 'T' && line [ p + 2 ] == 'T' && line [ p + 3 ] == 'P' && line [ p + 4 ] == '/' && line [ p + 5 ] == '1' && line [ p + 6 ] == '.' && line [ p + 7 ] == '1' ; if ( http11 ) { flags |= KEEP_ALIVE ; } } request = new HttpRequest ( method , UrlParser . parse ( decodeAscii ( line , urlStart , urlEnd - urlStart , ThreadLocalCharArray . ensure ( charBuffer , urlEnd - urlStart ) ) ) ) ; if ( method == GET || method == DELETE ) { contentLength = 0 ; } }
This method is called after received line of header .
39,951
protected void onHeader ( HttpHeader header , byte [ ] array , int off , int len ) throws ParseException { if ( header == HttpHeaders . EXPECT ) { if ( equalsLowerCaseAscii ( EXPECT_100_CONTINUE , array , off , len ) ) { socket . write ( ByteBuf . wrapForReading ( EXPECT_RESPONSE_CONTINUE ) ) ; } } if ( request . headers . size ( ) >= MAX_HEADERS ) { throw TOO_MANY_HEADERS ; } request . addParsedHeader ( header , array , off , len ) ; }
This method is called after receiving header . It sets its value to request .
39,952
public static < K , T > StreamMerger < K , T > create ( Function < T , K > keyFunction , Comparator < K > keyComparator , boolean distinct ) { return new StreamMerger < > ( keyFunction , keyComparator , distinct ) ; }
Returns new instance of StreamMerger
39,953
public static < K , I , O , A > StreamReducerSimple < K , I , O , A > create ( Function < I , K > keyFunction , Comparator < K > keyComparator , Reducer < K , I , O , A > reducer ) { return new StreamReducerSimple < > ( keyFunction , keyComparator , reducer ) ; }
Creates a new instance of StreamReducerSimple
39,954
public static Aggregation create ( Eventloop eventloop , Executor executor , DefiningClassLoader classLoader , AggregationChunkStorage aggregationChunkStorage , AggregationStructure structure ) { checkArgument ( structure != null , "Cannot create Aggregation with AggregationStructure that is null" ) ; return new Aggregation ( eventloop , executor , classLoader , aggregationChunkStorage , structure , new AggregationState ( structure ) ) ; }
Instantiates an aggregation with the specified structure that runs in a given event loop uses the specified class loader for creating dynamic classes saves data and metadata to given storages . Maximum size of chunk is 1 000 000 bytes . No more than 1 000 000 records stay in memory while sorting . Maximum duration of consolidation attempt is 30 minutes . Consolidated chunks become available for removal in 10 minutes from consolidation .
39,955
public static < K , O , A > StreamReducer < K , O , A > create ( Comparator < K > keyComparator ) { return new StreamReducer < > ( keyComparator ) ; }
Creates a new instance of StreamReducer
39,956
public < I > StreamConsumer < I > newInput ( Function < I , K > keyFunction , Reducer < K , I , O , A > reducer ) { return super . newInput ( keyFunction , reducer ) ; }
Creates a new input stream for this reducer
39,957
public static < K , L , R , V > StreamJoin < K , L , R , V > create ( Comparator < K > keyComparator , Function < L , K > leftKeyFunction , Function < R , K > rightKeyFunction , Joiner < K , L , R , V > joiner ) { return new StreamJoin < > ( keyComparator , leftKeyFunction , rightKeyFunction , joiner ) ; }
Creates a new instance of StreamJoin
39,958
public static ByteBuf createDnsQueryPayload ( DnsTransaction transaction ) { ByteBuf byteBuf = ByteBufPool . allocate ( MAX_SIZE ) ; byteBuf . writeShort ( transaction . getId ( ) ) ; byteBuf . write ( STANDARD_QUERY_HEADER ) ; byte componentSize = 0 ; DnsQuery query = transaction . getQuery ( ) ; byte [ ] domainBytes = query . getDomainName ( ) . getBytes ( US_ASCII ) ; int pos = - 1 ; while ( ++ pos < domainBytes . length ) { if ( domainBytes [ pos ] != '.' ) { componentSize ++ ; continue ; } byteBuf . writeByte ( componentSize ) ; byteBuf . write ( domainBytes , pos - componentSize , componentSize ) ; componentSize = 0 ; } byteBuf . writeByte ( componentSize ) ; byteBuf . write ( domainBytes , pos - componentSize , componentSize ) ; byteBuf . writeByte ( ( byte ) 0x0 ) ; byteBuf . writeShort ( query . getRecordType ( ) . getCode ( ) ) ; byteBuf . writeShort ( QueryClass . INTERNET . getCode ( ) ) ; return byteBuf ; }
Creates a bytebuf with a DNS query payload
39,959
public int read ( ) throws IOException { if ( pos >= limit ) return - 1 ; try { int c = buf [ pos ] & 0xff ; if ( c < 0x80 ) { pos ++ ; } else if ( c < 0xE0 ) { c = ( char ) ( ( c & 0x1F ) << 6 | buf [ pos + 1 ] & 0x3F ) ; pos += 2 ; } else { c = ( char ) ( ( c & 0x0F ) << 12 | ( buf [ pos + 1 ] & 0x3F ) << 6 | ( buf [ pos + 2 ] & 0x3F ) ) ; pos += 3 ; } if ( pos > limit ) throw new IOException ( ) ; return c ; } catch ( ArrayIndexOutOfBoundsException e ) { throw new IOException ( e ) ; } }
Reads a single character
39,960
private void skipHeaders ( int flag ) { if ( ( flag & FEXTRA ) != 0 ) { skipExtra ( flag ) ; } else if ( ( flag & FNAME ) != 0 ) { skipTerminatorByte ( flag , FNAME ) ; } else if ( ( flag & FCOMMENT ) != 0 ) { skipTerminatorByte ( flag , FCOMMENT ) ; } else if ( ( flag & FHCRC ) != 0 ) { skipCRC16 ( flag ) ; } }
region skip header fields
39,961
public RemoteFsClusterClient withPartition ( Object id , FsClient client ) { clients . put ( id , client ) ; aliveClients . put ( id , client ) ; return this ; }
Adds given client with given partition id to this cluster
39,962
public RemoteFsClusterClient withReplicationCount ( int replicationCount ) { checkArgument ( 1 <= replicationCount && replicationCount <= clients . size ( ) , "Replication count cannot be less than one or more than number of clients" ) ; this . replicationCount = replicationCount ; return this ; }
Sets the replication count that determines how many copies of the file should persist over the cluster .
39,963
private static < T , U > Promise < T > ofFailure ( String message , List < Try < U > > failed ) { StacklessException exception = new StacklessException ( RemoteFsClusterClient . class , message ) ; failed . stream ( ) . map ( Try :: getExceptionOrNull ) . filter ( Objects :: nonNull ) . forEach ( exception :: addSuppressed ) ; return Promise . ofException ( exception ) ; }
shortcut for creating single Exception from list of possibly failed tries
39,964
public static Expression cast ( Expression expression , Class < ? > type ) { return cast ( expression , getType ( type ) ) ; }
Casts expression to the type
39,965
public static PredicateDef cmpEq ( Expression left , Expression right ) { return cmp ( CompareOperation . EQ , left , right ) ; }
Verifies that the arguments are equal
39,966
public static Expression asEquals ( List < String > properties ) { PredicateDefAnd predicate = PredicateDefAnd . create ( ) ; for ( String property : properties ) { predicate . add ( cmpEq ( property ( self ( ) , property ) , property ( cast ( arg ( 0 ) , ExpressionCast . THIS_TYPE ) , property ) ) ) ; } return predicate ; }
Verifies that the properties are equal
39,967
public static Expression asString ( List < String > properties ) { ExpressionToString toString = new ExpressionToString ( ) ; for ( String property : properties ) { toString . withArgument ( property + "=" , property ( self ( ) , property ) ) ; } return toString ; }
Returns the string which was constructed from properties
39,968
public static ExpressionHash hashCodeOfThis ( List < String > properties ) { List < Expression > arguments = new ArrayList < > ( ) ; for ( String property : properties ) { arguments . add ( property ( new VarThis ( ) , property ) ) ; } return new ExpressionHash ( arguments ) ; }
Returns hash of the properties
39,969
public static ExpressionArithmeticOp add ( Expression left , Expression right ) { return new ExpressionArithmeticOp ( ArithmeticOperation . ADD , left , right ) ; }
Returns sum of arguments
39,970
public static ExpressionConstructor constructor ( Class < ? > type , Expression ... fields ) { return new ExpressionConstructor ( type , asList ( fields ) ) ; }
Returns new instance of class
39,971
public static VarLocal newLocal ( Context ctx , Type type ) { int local = ctx . getGeneratorAdapter ( ) . newLocal ( type ) ; return new VarLocal ( local ) ; }
Returns a new local variable from a given context
39,972
public DnsQueryCacheResult tryToResolve ( DnsQuery query ) { CachedDnsQueryResult cachedResult = cache . get ( query ) ; if ( cachedResult == null ) { logger . trace ( "{} cache miss" , query ) ; return null ; } DnsResponse result = cachedResult . response ; assert result != null ; if ( result . isSuccessful ( ) ) { logger . trace ( "{} cache hit" , query ) ; } else { logger . trace ( "{} error cache hit" , query ) ; } if ( isExpired ( cachedResult ) ) { logger . trace ( "{} hard TTL expired" , query ) ; return null ; } else if ( isSoftExpired ( cachedResult ) ) { logger . trace ( "{} soft TTL expired" , query ) ; return new DnsQueryCacheResult ( result , true ) ; } return new DnsQueryCacheResult ( result , false ) ; }
Tries to get status of the entry for some query from the cache .
39,973
public void add ( DnsQuery query , DnsResponse response ) { assert eventloop . inEventloopThread ( ) : "Concurrent cache adds are not allowed" ; long expirationTime = now . currentTimeMillis ( ) ; if ( response . isSuccessful ( ) ) { assert response . getRecord ( ) != null ; long minTtl = response . getRecord ( ) . getMinTtl ( ) * 1000 ; if ( minTtl == 0 ) { return ; } expirationTime += Math . min ( minTtl , maxTtl ) ; } else { expirationTime += response . getErrorCode ( ) == ResponseErrorCode . TIMED_OUT ? timedOutExceptionTtl : errorCacheExpiration ; } CachedDnsQueryResult cachedResult = new CachedDnsQueryResult ( response , expirationTime ) ; CachedDnsQueryResult old = cache . put ( query , cachedResult ) ; expirations . add ( cachedResult ) ; if ( old != null ) { old . response = null ; logger . trace ( "Refreshed cache entry for {}" , query ) ; } else { logger . trace ( "Added cache entry for {}" , query ) ; } }
Adds DnsResponse to this cache
39,974
@ SuppressWarnings ( "unchecked" ) public DatagraphEnvironment with ( Object key , Object value ) { ( ( Map < Object , Object > ) instances ) . put ( key , value ) ; return this ; }
Sets the given value for the specified key .
39,975
public static int encodeUtf8 ( byte [ ] array , int pos , String string ) { int p = pos ; for ( int i = 0 ; i < string . length ( ) ; i ++ ) { p += encodeUtf8 ( array , p , string . charAt ( i ) ) ; } return p - pos ; }
UTF - 8
39,976
public static Object fetchAnnotationElementValue ( Annotation annotation , Method element ) throws ReflectiveOperationException { Object value = element . invoke ( annotation ) ; if ( value == null ) { String errorMsg = "@" + annotation . annotationType ( ) . getName ( ) + "." + element . getName ( ) + "() returned null" ; throw new NullPointerException ( errorMsg ) ; } return value ; }
Returns values if it is not null otherwise throws exception
39,977
public ClassBuilder < T > withField ( String field , Class < ? > fieldClass ) { fields . put ( field , fieldClass ) ; return this ; }
Creates a new field for a dynamic class
39,978
public ClassBuilder < T > withMethod ( String methodName , Expression expression ) { if ( methodName . contains ( "(" ) ) { Method method = Method . getMethod ( methodName ) ; return withMethod ( method , expression ) ; } Method foundMethod = null ; List < List < java . lang . reflect . Method > > listOfMethods = new ArrayList < > ( ) ; listOfMethods . add ( asList ( Object . class . getMethods ( ) ) ) ; listOfMethods . add ( asList ( mainClass . getMethods ( ) ) ) ; listOfMethods . add ( asList ( mainClass . getDeclaredMethods ( ) ) ) ; for ( Class < ? > type : otherClasses ) { listOfMethods . add ( asList ( type . getMethods ( ) ) ) ; listOfMethods . add ( asList ( type . getDeclaredMethods ( ) ) ) ; } for ( List < java . lang . reflect . Method > list : listOfMethods ) { for ( java . lang . reflect . Method m : list ) { if ( m . getName ( ) . equals ( methodName ) ) { Method method = getMethod ( m ) ; if ( foundMethod != null && ! method . equals ( foundMethod ) ) throw new IllegalArgumentException ( "Method " + method + " collides with " + foundMethod ) ; foundMethod = method ; } } } Preconditions . check ( foundMethod != null , "Could not find method '" + methodName + "'" ) ; return withMethod ( foundMethod , expression ) ; }
CCreates a new method for a dynamic class
39,979
public final void setConsumer ( StreamConsumer < T > consumer ) { checkNotNull ( consumer ) ; checkState ( this . consumer == null , "Consumer has already been set" ) ; checkState ( getCapabilities ( ) . contains ( LATE_BINDING ) || eventloop . tick ( ) == createTick , LATE_BINDING_ERROR_MESSAGE , this ) ; this . consumer = consumer ; onWired ( ) ; consumer . getAcknowledgement ( ) . whenException ( this :: close ) . whenComplete ( acknowledgement ) ; }
Sets consumer for this supplier . At the moment of calling this method supplier shouldn t have consumer as well as consumer shouldn t have supplier otherwise there will be error
39,980
public void execute ( ) { Map < Partition , List < Node > > map = getNodesByPartition ( ) ; for ( Partition partition : map . keySet ( ) ) { List < Node > nodes = map . get ( partition ) ; partition . execute ( nodes ) ; } }
Executes the defined operations on all partitions .
39,981
public DynamicMBean createFor ( List < ? > monitorables , MBeanSettings setting , boolean enableRefresh ) { checkNotNull ( monitorables ) ; checkArgument ( monitorables . size ( ) > 0 , "Size of list of monitorables should be greater than 0" ) ; checkArgument ( monitorables . stream ( ) . noneMatch ( Objects :: isNull ) , "Monitorable can not be null" ) ; checkArgument ( CollectionUtils . allItemsHaveSameType ( monitorables ) , "Monitorables should be of the same type" ) ; Object firstMBean = monitorables . get ( 0 ) ; Class < ? > mbeanClass = firstMBean . getClass ( ) ; boolean isRefreshEnabled = enableRefresh ; List < MBeanWrapper > mbeanWrappers = new ArrayList < > ( monitorables . size ( ) ) ; if ( ConcurrentJmxMBean . class . isAssignableFrom ( mbeanClass ) ) { checkArgument ( monitorables . size ( ) == 1 , "ConcurrentJmxMBeans cannot be used in pool. " + "Only EventloopJmxMBeans can be used in pool" ) ; isRefreshEnabled = false ; mbeanWrappers . add ( new ConcurrentJmxMBeanWrapper ( ( ConcurrentJmxMBean ) monitorables . get ( 0 ) ) ) ; } else if ( EventloopJmxMBean . class . isAssignableFrom ( mbeanClass ) ) { for ( Object monitorable : monitorables ) { mbeanWrappers . add ( new EventloopJmxMBeanWrapper ( ( EventloopJmxMBean ) monitorable ) ) ; } } else { throw new IllegalArgumentException ( "MBeans should implement either ConcurrentJmxMBean " + "or EventloopJmxMBean interface" ) ; } AttributeNodeForPojo rootNode = createAttributesTree ( mbeanClass , setting . getCustomTypes ( ) ) ; rootNode . hideNullPojos ( monitorables ) ; for ( String included : setting . getIncludedOptionals ( ) ) { rootNode . setVisible ( included ) ; } for ( String attrName : setting . getModifiers ( ) . keySet ( ) ) { AttributeModifier < ? > modifier = setting . getModifiers ( ) . get ( attrName ) ; try { rootNode . applyModifier ( attrName , modifier , monitorables ) ; } catch ( ClassCastException e ) { throw new IllegalArgumentException ( "Cannot apply modifier \"" + modifier . getClass ( ) . getName ( ) + "\" for attribute \"" + attrName + "\": " + e . toString ( ) ) ; } } MBeanInfo mBeanInfo = createMBeanInfo ( rootNode , mbeanClass ) ; Map < OperationKey , Method > opkeyToMethod = fetchOpkeyToMethod ( mbeanClass ) ; DynamicMBeanAggregator mbean = new DynamicMBeanAggregator ( mBeanInfo , mbeanWrappers , rootNode , opkeyToMethod ) ; if ( isRefreshEnabled ) { handleJmxRefreshables ( mbeanWrappers , rootNode ) ; } return mbean ; }
Creates Jmx MBean for monitorables with operations and attributes .
39,982
private void handleJmxRefreshables ( List < MBeanWrapper > mbeanWrappers , AttributeNodeForPojo rootNode ) { for ( MBeanWrapper mbeanWrapper : mbeanWrappers ) { Eventloop eventloop = mbeanWrapper . getEventloop ( ) ; List < JmxRefreshable > currentRefreshables = rootNode . getAllRefreshables ( mbeanWrapper . getMBean ( ) ) ; if ( ! eventloopToJmxRefreshables . containsKey ( eventloop ) ) { eventloopToJmxRefreshables . put ( eventloop , currentRefreshables ) ; eventloop . execute ( createRefreshTask ( eventloop , null , 0 ) ) ; } else { List < JmxRefreshable > previousRefreshables = eventloopToJmxRefreshables . get ( eventloop ) ; List < JmxRefreshable > allRefreshables = new ArrayList < > ( previousRefreshables ) ; allRefreshables . addAll ( currentRefreshables ) ; eventloopToJmxRefreshables . put ( eventloop , allRefreshables ) ; } refreshableStatsCounts . put ( eventloop , eventloopToJmxRefreshables . get ( eventloop ) . size ( ) ) ; } }
region refreshing jmx
39,983
private AttributeNodeForPojo createAttributesTree ( Class < ? > clazz , Map < Type , JmxCustomTypeAdapter < ? > > customTypes ) { List < AttributeNode > subNodes = createNodesFor ( clazz , clazz , new String [ 0 ] , null , customTypes ) ; return new AttributeNodeForPojo ( "" , null , true , new ValueFetcherDirect ( ) , null , subNodes ) ; }
Creates attribute tree of Jmx attributes for clazz .
39,984
private static MBeanInfo createMBeanInfo ( AttributeNodeForPojo rootNode , Class < ? > monitorableClass ) { String monitorableName = "" ; String monitorableDescription = "" ; MBeanAttributeInfo [ ] attributes = rootNode != null ? fetchAttributesInfo ( rootNode ) : new MBeanAttributeInfo [ 0 ] ; MBeanOperationInfo [ ] operations = fetchOperationsInfo ( monitorableClass ) ; return new MBeanInfo ( monitorableName , monitorableDescription , attributes , null , operations , null ) ; }
region creating jmx metadata - MBeanInfo
39,985
private static Map < OperationKey , Method > fetchOpkeyToMethod ( Class < ? > mbeanClass ) { Map < OperationKey , Method > opkeyToMethod = new HashMap < > ( ) ; Method [ ] methods = mbeanClass . getMethods ( ) ; for ( Method method : methods ) { if ( method . isAnnotationPresent ( JmxOperation . class ) ) { JmxOperation annotation = method . getAnnotation ( JmxOperation . class ) ; String opName = annotation . name ( ) ; if ( opName . equals ( "" ) ) { opName = method . getName ( ) ; } Class < ? > [ ] paramTypes = method . getParameterTypes ( ) ; Annotation [ ] [ ] paramAnnotations = method . getParameterAnnotations ( ) ; assert paramAnnotations . length == paramTypes . length ; String [ ] paramTypesNames = new String [ paramTypes . length ] ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { paramTypesNames [ i ] = paramTypes [ i ] . getName ( ) ; } opkeyToMethod . put ( new OperationKey ( opName , paramTypesNames ) , method ) ; } } return opkeyToMethod ; }
region jmx operations fetching
39,986
public Promise < HttpResponse > send ( HttpRequest request ) { SettablePromise < HttpResponse > promise = new SettablePromise < > ( ) ; this . promise = promise ; assert pool == null ; ( pool = client . poolReadWrite ) . addLastNode ( this ) ; poolTimestamp = eventloop . currentTimeMillis ( ) ; HttpHeaderValue connectionHeader = CONNECTION_KEEP_ALIVE_HEADER ; if ( client . maxKeepAliveRequests != - 1 ) { if ( ++ numberOfKeepAliveRequests >= client . maxKeepAliveRequests ) { connectionHeader = CONNECTION_CLOSE_HEADER ; } } request . addHeader ( CONNECTION , connectionHeader ) ; ByteBuf buf = renderHttpMessage ( request ) ; if ( buf != null ) { writeBuf ( buf ) ; } else { writeHttpMessageAsChunkedStream ( request ) ; } request . recycle ( ) ; if ( ! isClosed ( ) ) { try { readHttpMessage ( ) ; } catch ( ParseException e ) { closeWithError ( e ) ; } } return promise ; }
Sends the request recycles it and closes connection in case of timeout
39,987
protected void onClosed ( ) { assert promise == null ; if ( pool == client . poolKeepAlive ) { AddressLinkedList addresses = client . addresses . get ( remoteAddress ) ; addresses . removeNode ( this ) ; if ( addresses . isEmpty ( ) ) { client . addresses . remove ( remoteAddress ) ; } } pool . removeNode ( this ) ; pool = null ; client . onConnectionClosed ( ) ; if ( response != null ) { response . recycle ( ) ; response = null ; } }
After closing this connection it removes it from its connections cache and recycles Http response .
39,988
public Promise < HttpResponse > request ( HttpRequest request ) { assert eventloop . inEventloopThread ( ) ; if ( inspector != null ) inspector . onRequest ( request ) ; String host = request . getUrl ( ) . getHost ( ) ; assert host != null ; return asyncDnsClient . resolve4 ( host ) . thenEx ( ( dnsResponse , e ) -> { if ( e == null ) { if ( inspector != null ) inspector . onResolve ( request , dnsResponse ) ; if ( dnsResponse . isSuccessful ( ) ) { return doSend ( request , dnsResponse . getRecord ( ) . getIps ( ) ) ; } else { return Promise . ofException ( new DnsQueryException ( AsyncHttpClient . class , dnsResponse ) ) ; } } else { if ( inspector != null ) inspector . onResolveError ( request , e ) ; request . recycle ( ) ; return Promise . ofException ( e ) ; } } ) ; }
Sends the request to server waits the result timeout and handles result with callback
39,989
public static void clear ( ) { for ( int i = 0 ; i < ByteBufPool . NUMBER_OF_SLABS ; i ++ ) { slabs [ i ] . clear ( ) ; created [ i ] . set ( 0 ) ; reused [ i ] . set ( 0 ) ; } synchronized ( registry ) { registry . clear ( ) ; } }
Clears all of the slabs and stats .
39,990
private void ensureCapacity ( ) { if ( size < selectionKeys . length ) { return ; } SelectionKey [ ] newArray = new SelectionKey [ selectionKeys . length * 2 ] ; System . arraycopy ( selectionKeys , 0 , newArray , 0 , size ) ; selectionKeys = newArray ; }
Multiply the size of array twice
39,991
public static < K , T > StreamSorter < K , T > create ( StreamSorterStorage < T > storage , Function < T , K > keyFunction , Comparator < K > keyComparator , boolean distinct , int itemsInMemorySize ) { return new StreamSorter < > ( storage , keyFunction , keyComparator , distinct , itemsInMemorySize ) ; }
Creates a new instance of StreamSorter
39,992
public static void update ( DMatrixRMaj H , DMatrixRMaj s , DMatrixRMaj y , DMatrixRMaj tempV0 , DMatrixRMaj tempV1 ) { double p = VectorVectorMult_DDRM . innerProd ( y , s ) ; if ( p == 0 ) return ; p = 1.0 / p ; double sBs = VectorVectorMult_DDRM . innerProdA ( s , H , s ) ; if ( sBs == 0 ) return ; CommonOps_DDRM . mult ( H , s , tempV0 ) ; CommonOps_DDRM . multTransA ( s , H , tempV1 ) ; VectorVectorMult_DDRM . rank1Update ( - p , H , tempV0 , y ) ; VectorVectorMult_DDRM . rank1Update ( - p , H , y , tempV1 ) ; VectorVectorMult_DDRM . rank1Update ( p * ( p * sBs + 1 ) , H , y , y ) ; }
DFP Hessian update equation . See class description for equations
39,993
public static void inverseUpdate ( DMatrixRMaj H , DMatrixRMaj s , DMatrixRMaj y , DMatrixRMaj tempV0 , DMatrixRMaj tempV1 ) { double alpha = VectorVectorMult_DDRM . innerProdA ( y , H , y ) ; double p = 1.0 / VectorVectorMult_DDRM . innerProd ( s , y ) ; CommonOps_DDRM . mult ( H , y , tempV0 ) ; CommonOps_DDRM . multTransA ( y , H , tempV1 ) ; VectorVectorMult_DDRM . rank1Update ( - p , H , tempV0 , s ) ; VectorVectorMult_DDRM . rank1Update ( - p , H , s , tempV1 ) ; VectorVectorMult_DDRM . rank1Update ( p * alpha * p + p , H , s , s ) ; }
BFGS inverse hessian update equation that orders the multiplications to minimize the number of operations .
39,994
public static boolean process ( IterativeOptimization search , int maxSteps ) { for ( int i = 0 ; i < maxSteps ; i ++ ) { boolean converged = step ( search ) ; if ( converged ) { return search . isConverged ( ) ; } } return true ; }
Iterate until the line search converges or the maximum number of iterations has been exceeded .
39,995
public static boolean step ( IterativeOptimization search ) { for ( int i = 0 ; i < 10000 ; i ++ ) { boolean converged = search . iterate ( ) ; if ( converged || ! search . isUpdated ( ) ) { return converged ; } } throw new RuntimeException ( "After 10,000 iterations it failed to take a step! Probably a bug." ) ; }
Performs a single step by iterating until the parameters are updated .
39,996
public KdTree . Node requestNode ( ) { if ( unusedNodes . isEmpty ( ) ) return new KdTree . Node ( ) ; return unusedNodes . remove ( unusedNodes . size ( ) - 1 ) ; }
Returns a new node . All object references can be assumed to be null .
39,997
public KdTree . Node requestNode ( P point , int index ) { KdTree . Node n = requestNode ( ) ; n . point = point ; n . index = index ; n . split = - 1 ; return n ; }
Request a leaf node be returned . All data parameters will be automatically assigned appropriate values for a leaf .
39,998
public static Polynomial multiply ( Polynomial a , Polynomial b , Polynomial result ) { int N = Math . max ( 0 , a . size ( ) + b . size ( ) - 1 ) ; if ( result == null ) { result = new Polynomial ( N ) ; } else { if ( result . size < N ) throw new IllegalArgumentException ( "Unexpected length of 'result'" ) ; result . zero ( ) ; } for ( int i = 0 ; i < a . size ; i ++ ) { double coef = a . c [ i ] ; int index = i ; for ( int j = 0 ; j < b . size ; j ++ ) { result . c [ index ++ ] += coef * b . c [ j ] ; } } return result ; }
Multiplies the two polynomials together .
39,999
public static Polynomial add ( Polynomial a , Polynomial b , Polynomial results ) { int N = Math . max ( a . size , b . size ) ; if ( results == null ) { results = new Polynomial ( N ) ; } else if ( results . size < N ) { throw new IllegalArgumentException ( "storage for results must be at least as large as the the largest polynomial" ) ; } else { for ( int i = N ; i < results . size ; i ++ ) { results . c [ i ] = 0 ; } } int M = Math . min ( a . size , b . size ) ; for ( int i = 0 ; i < M ; i ++ ) { results . c [ i ] = a . c [ i ] + b . c [ i ] ; } if ( a . size > b . size ) { for ( int i = b . size ; i < N ; i ++ ) results . c [ i ] = a . c [ i ] ; } else { for ( int i = a . size ; i < N ; i ++ ) results . c [ i ] = b . c [ i ] ; } return results ; }
Adds two polynomials together . The lengths of the polynomials do not need to be the zero but the missing coefficients are assumed to be zero .