idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
22,700
public Optional < Server > chooseRoundRobinAfterFiltering ( List < Server > servers ) { List < Server > eligible = getEligibleServers ( servers ) ; if ( eligible . size ( ) == 0 ) { return Optional . absent ( ) ; } return Optional . of ( eligible . get ( incrementAndGetModulo ( eligible . size ( ) ) ) ) ; }
Choose a server in a round robin fashion after the predicate filters a list of servers . Load balancer key is presumed to be null .
22,701
protected boolean isRetriableException ( Throwable e ) { if ( getRetryHandler ( ) != null ) { return getRetryHandler ( ) . isRetriableException ( e , true ) ; } return false ; }
Determine if operation can be retried if an exception is thrown . For example connect timeout related exceptions are typically retriable .
22,702
protected void updateAllServerList ( List < T > ls ) { if ( serverListUpdateInProgress . compareAndSet ( false , true ) ) { try { for ( T s : ls ) { s . setAlive ( true ) ; } setServersList ( ls ) ; super . forceQuickPing ( ) ; } finally { serverListUpdateInProgress . set ( false ) ; } } }
Update the AllServer list in the LoadBalancer if necessary and enabled
22,703
public int compare ( T server1 , T server2 ) { LoadBalancerStats lbStats = getLoadBalancerStats ( ) ; ServerStats stats1 = lbStats . getSingleServerStat ( server1 ) ; ServerStats stats2 = lbStats . getSingleServerStat ( server2 ) ; int failuresDiff = ( int ) ( stats2 . getFailureCount ( ) - stats1 . getFailureCount ( ) ) ; if ( failuresDiff != 0 ) { return failuresDiff ; } else { return ( stats2 . getActiveRequestsCount ( ) - stats1 . getActiveRequestsCount ( ) ) ; } }
Function to sort the list by server health condition with unhealthy servers before healthy servers . The servers are first sorted by failures count and then concurrent connection count .
22,704
public static synchronized IClient createNamedClient ( String name , Class < ? extends IClientConfig > configClass ) throws ClientException { IClientConfig config = getNamedConfig ( name , configClass ) ; return registerClientFromProperties ( name , config ) ; }
Creates a named client using a IClientConfig instance created off the configClass class object passed in as the parameter .
22,705
public static synchronized ILoadBalancer getNamedLoadBalancer ( String name , Class < ? extends IClientConfig > configClass ) { ILoadBalancer lb = namedLBMap . get ( name ) ; if ( lb != null ) { return lb ; } else { try { lb = registerNamedLoadBalancerFromProperties ( name , configClass ) ; } catch ( ClientException e ) { throw new RuntimeException ( "Unable to create load balancer" , e ) ; } return lb ; } }
Get the load balancer associated with the name or create one with an instance of configClass if does not exist
22,706
private static KeyStore createKeyStore ( final URL storeFile , final String password ) throws ClientSslSocketFactoryException { if ( storeFile == null ) { return null ; } Preconditions . checkArgument ( StringUtils . isNotEmpty ( password ) , "Null keystore should have empty password, defined keystore must have password" ) ; KeyStore keyStore = null ; try { keyStore = KeyStore . getInstance ( "jks" ) ; InputStream is = storeFile . openStream ( ) ; try { keyStore . load ( is , password . toCharArray ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new ClientSslSocketFactoryException ( String . format ( "Failed to create a keystore that supports algorithm %s: %s" , SOCKET_ALGORITHM , e . getMessage ( ) ) , e ) ; } catch ( CertificateException e ) { throw new ClientSslSocketFactoryException ( String . format ( "Failed to create keystore with algorithm %s due to certificate exception: %s" , SOCKET_ALGORITHM , e . getMessage ( ) ) , e ) ; } finally { try { is . close ( ) ; } catch ( IOException ignore ) { } } } catch ( KeyStoreException e ) { throw new ClientSslSocketFactoryException ( String . format ( "KeyStore exception creating keystore: %s" , e . getMessage ( ) ) , e ) ; } catch ( IOException e ) { throw new ClientSslSocketFactoryException ( String . format ( "IO exception creating keystore: %s" , e . getMessage ( ) ) , e ) ; } return keyStore ; }
Opens the specified key or trust store using the given password .
22,707
@ edu . umd . cs . findbugs . annotations . SuppressWarnings ( value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE" ) public Server choose ( ILoadBalancer lb , Object key ) { if ( lb == null ) { return null ; } Server server = null ; while ( server == null ) { if ( Thread . interrupted ( ) ) { return null ; } List < Server > upList = lb . getReachableServers ( ) ; List < Server > allList = lb . getAllServers ( ) ; int serverCount = allList . size ( ) ; if ( serverCount == 0 ) { return null ; } int index = chooseRandomInt ( serverCount ) ; server = upList . get ( index ) ; if ( server == null ) { Thread . yield ( ) ; continue ; } if ( server . isAlive ( ) ) { return ( server ) ; } server = null ; Thread . yield ( ) ; } return server ; }
Randomly choose from all living servers
22,708
public List < Future < Boolean > > primeConnectionsAsync ( final List < Server > servers , final PrimeConnectionListener listener ) { if ( servers == null ) { return Collections . emptyList ( ) ; } List < Server > allServers = new ArrayList < Server > ( ) ; allServers . addAll ( servers ) ; if ( allServers . size ( ) == 0 ) { logger . debug ( "RestClient:" + name + ". No nodes/servers to prime connections" ) ; return Collections . emptyList ( ) ; } logger . info ( "Priming Connections for RestClient:" + name + ", numServers:" + allServers . size ( ) ) ; List < Future < Boolean > > ftList = new ArrayList < Future < Boolean > > ( ) ; for ( Server s : allServers ) { s . setReadyToServe ( false ) ; if ( aSync ) { Future < Boolean > ftC = null ; try { ftC = makeConnectionASync ( s , listener ) ; ftList . add ( ftC ) ; } catch ( RejectedExecutionException ree ) { logger . error ( "executor submit failed" , ree ) ; } catch ( Exception e ) { logger . error ( "general error" , e ) ; } } else { connectToServer ( s , listener ) ; } } return ftList ; }
Prime servers asynchronously .
22,709
public Server choose ( Object key ) { int count = 0 ; Server server = roundRobinRule . choose ( key ) ; while ( count ++ <= 10 ) { if ( server != null && predicate . apply ( new PredicateKey ( server ) ) ) { return server ; } server = roundRobinRule . choose ( key ) ; } return super . choose ( key ) ; }
This method is overridden to provide a more efficient implementation which does not iterate through all servers . This is under the assumption that in most cases there are more available instances than not .
22,710
public HttpRequest replaceUri ( URI newURI ) { return ( new Builder ( ) ) . uri ( newURI ) . headers ( this . httpHeaders ) . overrideConfig ( this . getOverrideConfig ( ) ) . queryParams ( this . queryParams ) . setRetriable ( this . isRetriable ( ) ) . loadBalancerKey ( this . getLoadBalancerKey ( ) ) . verb ( this . getVerb ( ) ) . entity ( this . entity ) . build ( ) ; }
Return a new instance of HttpRequest replacing the URI .
22,711
public void initWithNiwsConfig ( IClientConfig clientConfig ) { if ( clientConfig == null ) { return ; } if ( clientConfig . getOrDefault ( CommonClientConfigKey . TrustStore ) != null ) { throw new IllegalArgumentException ( "Client configured with an AcceptAllSocketFactory cannot utilize a truststore" ) ; } }
In the case of this factory the intent is to ensure that a truststore is not set as this does not make sense in the context of an accept - all policy
22,712
private void addLoadBalancerListener ( ) { if ( ! ( lbContext . getLoadBalancer ( ) instanceof BaseLoadBalancer ) ) { return ; } ( ( BaseLoadBalancer ) lbContext . getLoadBalancer ( ) ) . addServerListChangeListener ( new ServerListChangeListener ( ) { public void serverListChanged ( List < Server > oldList , List < Server > newList ) { Set < Server > removedServers = new HashSet < Server > ( oldList ) ; removedServers . removeAll ( newList ) ; for ( Server server : rxClientCache . keySet ( ) ) { if ( removedServers . contains ( server ) ) { removeClient ( server ) ; } } } } ) ; }
Add a listener that is responsible for removing an HttpClient and shutting down its connection pool if it is no longer available from load balancer .
22,713
protected T getOrCreateRxClient ( Server server ) { T client = rxClientCache . get ( server ) ; if ( client != null ) { return client ; } else { client = createRxClient ( server ) ; client . subscribe ( listener ) ; client . subscribe ( eventSubject ) ; T old = rxClientCache . putIfAbsent ( server , client ) ; if ( old != null ) { return old ; } else { return client ; } } }
Look up the client associated with this Server .
22,714
protected T removeClient ( Server server ) { T client = rxClientCache . remove ( server ) ; if ( client != null ) { client . shutdown ( ) ; } return client ; }
Remove the client for this Server
22,715
public void initialize ( Server server ) { serverFailureCounts = new MeasuredRate ( failureCountSlidingWindowInterval ) ; requestCountInWindow = new MeasuredRate ( 300000L ) ; if ( publisher == null ) { dataDist = new DataDistribution ( getBufferSize ( ) , PERCENTS ) ; publisher = new DataPublisher ( dataDist , getPublishIntervalMillis ( ) ) ; publisher . start ( ) ; } this . server = server ; }
Initializes the object starting data collection and reporting .
22,716
@ Monitor ( name = "ResponseTimePercentileWhen" , type = DataSourceType . INFORMATIONAL , description = "The time the percentile values were computed" ) public String getResponseTimePercentileTime ( ) { return dataDist . getTimestamp ( ) ; }
Gets the time when the varios percentile data was last updated .
22,717
@ Monitor ( name = "ResponseTimeMillis10Percentile" , type = DataSourceType . INFORMATIONAL , description = "10th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime10thPercentile ( ) { return getResponseTimePercentile ( Percent . TEN ) ; }
Gets the 10 - th percentile in the total amount of time spent handling a request in milliseconds .
22,718
@ Monitor ( name = "ResponseTimeMillis25Percentile" , type = DataSourceType . INFORMATIONAL , description = "25th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime25thPercentile ( ) { return getResponseTimePercentile ( Percent . TWENTY_FIVE ) ; }
Gets the 25 - th percentile in the total amount of time spent handling a request in milliseconds .
22,719
@ Monitor ( name = "ResponseTimeMillis50Percentile" , type = DataSourceType . INFORMATIONAL , description = "50th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime50thPercentile ( ) { return getResponseTimePercentile ( Percent . FIFTY ) ; }
Gets the 50 - th percentile in the total amount of time spent handling a request in milliseconds .
22,720
@ Monitor ( name = "ResponseTimeMillis75Percentile" , type = DataSourceType . INFORMATIONAL , description = "75th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime75thPercentile ( ) { return getResponseTimePercentile ( Percent . SEVENTY_FIVE ) ; }
Gets the 75 - th percentile in the total amount of time spent handling a request in milliseconds .
22,721
@ Monitor ( name = "ResponseTimeMillis90Percentile" , type = DataSourceType . INFORMATIONAL , description = "90th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime90thPercentile ( ) { return getResponseTimePercentile ( Percent . NINETY ) ; }
Gets the 90 - th percentile in the total amount of time spent handling a request in milliseconds .
22,722
@ Monitor ( name = "ResponseTimeMillis95Percentile" , type = DataSourceType . GAUGE , description = "95th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime95thPercentile ( ) { return getResponseTimePercentile ( Percent . NINETY_FIVE ) ; }
Gets the 95 - th percentile in the total amount of time spent handling a request in milliseconds .
22,723
@ Monitor ( name = "ResponseTimeMillis98Percentile" , type = DataSourceType . INFORMATIONAL , description = "98th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime98thPercentile ( ) { return getResponseTimePercentile ( Percent . NINETY_EIGHT ) ; }
Gets the 98 - th percentile in the total amount of time spent handling a request in milliseconds .
22,724
@ Monitor ( name = "ResponseTimeMillis99Percentile" , type = DataSourceType . GAUGE , description = "99th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime99thPercentile ( ) { return getResponseTimePercentile ( Percent . NINETY_NINE ) ; }
Gets the 99 - th percentile in the total amount of time spent handling a request in milliseconds .
22,725
@ Monitor ( name = "ResponseTimeMillis99_5Percentile" , type = DataSourceType . GAUGE , description = "99.5th percentile in total time to handle a request, in milliseconds" ) public double getResponseTime99point5thPercentile ( ) { return getResponseTimePercentile ( Percent . NINETY_NINE_POINT_FIVE ) ; }
Gets the 99 . 5 - th percentile in the total amount of time spent handling a request in milliseconds .
22,726
private static HttpHost determineTarget ( HttpUriRequest request ) throws ClientProtocolException { HttpHost target = null ; URI requestURI = request . getURI ( ) ; if ( requestURI . isAbsolute ( ) ) { target = URIUtils . extractHost ( requestURI ) ; if ( target == null ) { throw new ClientProtocolException ( "URI does not specify a valid host name: " + requestURI ) ; } } return target ; }
copied from httpclient source code
22,727
private Observable < Server > selectServer ( ) { return Observable . create ( new OnSubscribe < Server > ( ) { public void call ( Subscriber < ? super Server > next ) { try { Server server = loadBalancerContext . getServerFromLoadBalancer ( loadBalancerURI , loadBalancerKey ) ; next . onNext ( server ) ; next . onCompleted ( ) ; } catch ( Exception e ) { next . onError ( e ) ; } } } ) ; }
Return an Observable that either emits only the single requested server or queries the load balancer for the next server on each subscription
22,728
public String resolve ( String vipAddressMacro , IClientConfig niwsClientConfig ) { if ( vipAddressMacro == null || vipAddressMacro . length ( ) == 0 ) { return vipAddressMacro ; } return replaceMacrosFromConfig ( vipAddressMacro ) ; }
Resolve the vip address by replacing macros with actual values in configuration . If there is no macro the passed in string will be returned . If a macro is found but there is no property defined in configuration the same macro is returned as part of the result .
22,729
public void onStartWithServer ( ExecutionContext < I > context , ExecutionInfo info ) { for ( ExecutionListener < I , O > listener : listeners ) { try { if ( ! isListenerDisabled ( listener ) ) { listener . onStartWithServer ( context . getChildContext ( listener ) , info ) ; } } catch ( Throwable e ) { if ( e instanceof AbortExecutionException ) { throw ( AbortExecutionException ) e ; } logger . error ( "Error invoking listener " + listener , e ) ; } } }
Called when a server is chosen and the request is going to be executed on the server .
22,730
public void onExceptionWithServer ( ExecutionContext < I > context , Throwable exception , ExecutionInfo info ) { for ( ExecutionListener < I , O > listener : listeners ) { try { if ( ! isListenerDisabled ( listener ) ) { listener . onExceptionWithServer ( context . getChildContext ( listener ) , exception , info ) ; } } catch ( Throwable e ) { logger . error ( "Error invoking listener " + listener , e ) ; } } }
Called when an exception is received from executing the request on a server .
22,731
public void onExecutionSuccess ( ExecutionContext < I > context , O response , ExecutionInfo info ) { for ( ExecutionListener < I , O > listener : listeners ) { try { if ( ! isListenerDisabled ( listener ) ) { listener . onExecutionSuccess ( context . getChildContext ( listener ) , response , info ) ; } } catch ( Throwable e ) { logger . error ( "Error invoking listener " + listener , e ) ; } } }
Called when the request is executed successfully on the server
22,732
public void onExecutionFailed ( ExecutionContext < I > context , Throwable finalException , ExecutionInfo info ) { for ( ExecutionListener < I , O > listener : listeners ) { try { if ( ! isListenerDisabled ( listener ) ) { listener . onExecutionFailed ( context . getChildContext ( listener ) , finalException , info ) ; } } catch ( Throwable e ) { logger . error ( "Error invoking listener " + listener , e ) ; } } }
Called when the request is considered failed after all retries .
22,733
private SSLContext createSSLContext ( ) throws ClientSslSocketFactoryException { final KeyManager [ ] keyManagers = this . keyStore != null ? createKeyManagers ( ) : null ; final TrustManager [ ] trustManagers = this . trustStore != null ? createTrustManagers ( ) : null ; try { final SSLContext sslcontext = SSLContext . getInstance ( SOCKET_ALGORITHM ) ; sslcontext . init ( keyManagers , trustManagers , null ) ; return sslcontext ; } catch ( NoSuchAlgorithmException e ) { throw new ClientSslSocketFactoryException ( String . format ( "Failed to create an SSL context that supports algorithm %s: %s" , SOCKET_ALGORITHM , e . getMessage ( ) ) , e ) ; } catch ( KeyManagementException e ) { throw new ClientSslSocketFactoryException ( String . format ( "Failed to initialize an SSL context: %s" , e . getMessage ( ) ) , e ) ; } }
Creates the SSL context needed to create the socket factory used by this factory . The key and trust store parameters are optional . If they are null then the JRE defaults will be used .
22,734
private KeyManager [ ] createKeyManagers ( ) throws ClientSslSocketFactoryException { final KeyManagerFactory factory ; try { factory = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; factory . init ( this . keyStore , this . keyStorePassword . toCharArray ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new ClientSslSocketFactoryException ( String . format ( "Failed to create the key store because the algorithm %s is not supported. " , KeyManagerFactory . getDefaultAlgorithm ( ) ) , e ) ; } catch ( UnrecoverableKeyException e ) { throw new ClientSslSocketFactoryException ( "Unrecoverable Key Exception initializing key manager factory; this is probably fatal" , e ) ; } catch ( KeyStoreException e ) { throw new ClientSslSocketFactoryException ( "KeyStore exception initializing key manager factory; this is probably fatal" , e ) ; } KeyManager [ ] managers = factory . getKeyManagers ( ) ; LOGGER . debug ( "Key managers are initialized. Total {} managers. " , managers . length ) ; return managers ; }
Creates the key managers to be used by the factory from the associated key store and password .
22,735
private TrustManager [ ] createTrustManagers ( ) throws ClientSslSocketFactoryException { final TrustManagerFactory factory ; try { factory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; factory . init ( this . trustStore ) ; } catch ( NoSuchAlgorithmException e ) { throw new ClientSslSocketFactoryException ( String . format ( "Failed to create the trust store because the algorithm %s is not supported. " , KeyManagerFactory . getDefaultAlgorithm ( ) ) , e ) ; } catch ( KeyStoreException e ) { throw new ClientSslSocketFactoryException ( "KeyStore exception initializing trust manager factory; this is probably fatal" , e ) ; } final TrustManager [ ] managers = factory . getTrustManagers ( ) ; LOGGER . debug ( "TrustManagers are initialized. Total {} managers: " , managers . length ) ; return managers ; }
Creates the trust managers to be used by the factory from the specified trust store file and password .
22,736
protected void putDefaultIntegerProperty ( IClientConfigKey propName , Integer defaultValue ) { Integer value = ConfigurationManager . getConfigInstance ( ) . getInteger ( getDefaultPropName ( propName ) , defaultValue ) ; setPropertyInternal ( propName , value ) ; }
passed as argument is used to put into the properties member variable
22,737
public void loadProperties ( String restClientName ) { enableDynamicProperties = true ; setClientName ( restClientName ) ; loadDefaultValues ( ) ; Configuration props = ConfigurationManager . getConfigInstance ( ) . subset ( restClientName ) ; for ( Iterator < String > keys = props . getKeys ( ) ; keys . hasNext ( ) ; ) { String key = keys . next ( ) ; String prop = key ; try { if ( prop . startsWith ( getNameSpace ( ) ) ) { prop = prop . substring ( getNameSpace ( ) . length ( ) + 1 ) ; } setPropertyInternal ( prop , getStringValue ( props , key ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( String . format ( "Property %s is invalid" , prop ) ) ; } } }
Load properties for a given client . It first loads the default values for all properties and any properties already defined with Archaius ConfigurationManager .
22,738
public List < Server > getEligibleServers ( List < Server > servers , Object loadBalancerKey ) { List < Server > result = super . getEligibleServers ( servers , loadBalancerKey ) ; Iterator < AbstractServerPredicate > i = fallbacks . iterator ( ) ; while ( ! ( result . size ( ) >= minimalFilteredServers && result . size ( ) > ( int ) ( servers . size ( ) * minimalFilteredPercentage ) ) && i . hasNext ( ) ) { AbstractServerPredicate predicate = i . next ( ) ; result = predicate . getEligibleServers ( servers , loadBalancerKey ) ; } return result ; }
Get the filtered servers from primary predicate and if the number of the filtered servers are not enough trying the fallback predicates
22,739
public void initWithNiwsConfig ( IClientConfig clientConfig ) { if ( clientConfig == null ) { return ; } clientName = clientConfig . getClientName ( ) ; if ( StringUtils . isEmpty ( clientName ) ) { clientName = "default" ; } vipAddresses = clientConfig . resolveDeploymentContextbasedVipAddresses ( ) ; maxAutoRetries = clientConfig . getOrDefault ( CommonClientConfigKey . MaxAutoRetries ) ; maxAutoRetriesNextServer = clientConfig . getOrDefault ( CommonClientConfigKey . MaxAutoRetriesNextServer ) ; okToRetryOnAllOperations = clientConfig . getOrDefault ( CommonClientConfigKey . OkToRetryOnAllOperations ) ; defaultRetryHandler = new DefaultLoadBalancerRetryHandler ( clientConfig ) ; tracer = getExecuteTracer ( ) ; Monitors . registerObject ( "Client_" + clientName , this ) ; }
Set necessary parameters from client configuration and register with Servo monitors .
22,740
public void noteRequestCompletion ( ServerStats stats , Object response , Throwable e , long responseTime , RetryHandler errorHandler ) { if ( stats == null ) { return ; } try { recordStats ( stats , responseTime ) ; RetryHandler callErrorHandler = errorHandler == null ? getRetryHandler ( ) : errorHandler ; if ( callErrorHandler != null && response != null ) { stats . clearSuccessiveConnectionFailureCount ( ) ; } else if ( callErrorHandler != null && e != null ) { if ( callErrorHandler . isCircuitTrippingException ( e ) ) { stats . incrementSuccessiveConnectionFailureCount ( ) ; stats . addToFailureCount ( ) ; } else { stats . clearSuccessiveConnectionFailureCount ( ) ; } } } catch ( Exception ex ) { logger . error ( "Error noting stats for client {}" , clientName , ex ) ; } }
This is called after a response is received or an exception is thrown from the client to update related stats .
22,741
protected void noteError ( ServerStats stats , ClientRequest request , Throwable e , long responseTime ) { if ( stats == null ) { return ; } try { recordStats ( stats , responseTime ) ; RetryHandler errorHandler = getRetryHandler ( ) ; if ( errorHandler != null && e != null ) { if ( errorHandler . isCircuitTrippingException ( e ) ) { stats . incrementSuccessiveConnectionFailureCount ( ) ; stats . addToFailureCount ( ) ; } else { stats . clearSuccessiveConnectionFailureCount ( ) ; } } } catch ( Exception ex ) { logger . error ( "Error noting stats for client {}" , clientName , ex ) ; } }
This is called after an error is thrown from the client to update related stats .
22,742
protected void noteResponse ( ServerStats stats , ClientRequest request , Object response , long responseTime ) { if ( stats == null ) { return ; } try { recordStats ( stats , responseTime ) ; RetryHandler errorHandler = getRetryHandler ( ) ; if ( errorHandler != null && response != null ) { stats . clearSuccessiveConnectionFailureCount ( ) ; } } catch ( Exception ex ) { logger . error ( "Error noting stats for client {}" , clientName , ex ) ; } }
This is called after a response is received from the client to update related stats .
22,743
public void noteOpenConnection ( ServerStats serverStats ) { if ( serverStats == null ) { return ; } try { serverStats . incrementActiveRequestsCount ( ) ; } catch ( Exception ex ) { logger . error ( "Error noting stats for client {}" , clientName , ex ) ; } }
This is usually called just before client execute a request .
22,744
private State nextState ( State currentState , int i ) { switch ( currentState ) { case FREE_TEXT : return jumpFromFreeText ( str , i ) ; case PARAM_START : return jumpFromParamStart ( str , i ) ; case PARAM : return jumpFromParam ( str , i ) ; case PARAM_END : return jumpFromParamEnd ( str , i ) ; case ESCAPE_CHAR : return State . FREE_TEXT ; default : throw UncheckedTemplateException . invalidStateException ( currentState ) ; } }
in the string and the current value of the character
22,745
private void appendParamValue ( StringBuilder param , StringBuilder result ) { if ( param == null ) throw UncheckedTemplateException . invalidArgumentName ( param ) ; final String objectName = takeUntilDotOrEnd ( param ) ; final Object objectValue = arguments . get ( objectName ) ; Object toAppend ; if ( param . length ( ) != 0 ) { toAppend = valueInChain ( objectValue , param ) ; } else { toAppend = evaluateIfArray ( objectValue ) ; } if ( null != toAppend ) { result . append ( toAppend ) ; } }
in this case it is obtained by calling recursively the methods on the last obtained object
22,746
public static ClassLoader getDefault ( ) { ClassLoader loader = null ; try { loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } catch ( Exception ignored ) { } if ( loader == null ) { loader = Environment . class . getClassLoader ( ) ; if ( loader == null ) { try { loader = ClassLoader . getSystemClassLoader ( ) ; } catch ( Exception e ) { } } } return loader ; }
Get current thread context ClassLoader
22,747
public static < T > Validation < T > notNull ( String msg ) { return SimpleValidation . from ( Objects :: nonNull , msg ) ; }
The input object is not null . if yes the check passes
22,748
public static Validation < String > notEmpty ( String msg ) { return SimpleValidation . from ( s -> null != s && ! s . isEmpty ( ) , msg ) ; }
The input string is not empty . if yes the check passes
22,749
public static Validation < String > length ( int minSize , int maxSize ) { return moreThan ( minSize ) . and ( lessThan ( maxSize ) ) ; }
The length of the input string must be between minSize and maxSize . if yes the check passes
22,750
public static Validation < Integer > lowerThan ( int max , String msg ) { return SimpleValidation . from ( ( i ) -> i < max , format ( msg , max ) ) ; }
Determine if the input int parameter is lower than max . if yes the check passes
22,751
public static Validation < Integer > greaterThan ( int min , String msg ) { return SimpleValidation . from ( ( i ) -> i > min , format ( msg , min ) ) ; }
Determine if the input int parameter is greater than min . if yes the check passes
22,752
public static Validation < Integer > range ( int min , int max ) { return greaterThan ( min ) . and ( lowerThan ( max ) ) ; }
Determine if the input int parameter is it in a range . if yes the check passes
22,753
public static Validation < String > isEmail ( String msg ) { return notEmpty ( ) . and ( SimpleValidation . from ( PatternKit :: isEmail , msg ) ) ; }
Determine if the input parameter is a Email . if yes the check passes .
22,754
public static int toUnix ( String time , String pattern ) { LocalDateTime formatted = LocalDateTime . parse ( time , DateTimeFormatter . ofPattern ( pattern ) ) ; return ( int ) formatted . atZone ( ZoneId . systemDefault ( ) ) . toInstant ( ) . getEpochSecond ( ) ; }
format string time to unix time
22,755
private void routeHandle ( RouteContext context ) { Object target = context . routeTarget ( ) ; if ( null == target ) { Class < ? > clazz = context . routeAction ( ) . getDeclaringClass ( ) ; target = WebContext . blade ( ) . getBean ( clazz ) ; } if ( context . targetType ( ) == RouteHandler . class ) { RouteHandler routeHandler = ( RouteHandler ) target ; routeHandler . handle ( context ) ; } else if ( context . targetType ( ) == RouteHandler0 . class ) { RouteHandler0 routeHandler = ( RouteHandler0 ) target ; routeHandler . handle ( context . request ( ) , context . response ( ) ) ; } else { Method actionMethod = context . routeAction ( ) ; Class < ? > returnType = actionMethod . getReturnType ( ) ; Path path = target . getClass ( ) . getAnnotation ( Path . class ) ; JSON JSON = actionMethod . getAnnotation ( JSON . class ) ; boolean isRestful = ( null != JSON ) || ( null != path && path . restful ( ) ) ; if ( isRestful ) { if ( ! context . isIE ( ) ) { context . contentType ( Const . CONTENT_TYPE_JSON ) ; } else { context . contentType ( Const . CONTENT_TYPE_HTML ) ; } } int len = actionMethod . getParameterTypes ( ) . length ; MethodAccess methodAccess = BladeCache . getMethodAccess ( target . getClass ( ) ) ; Object returnParam = methodAccess . invoke ( target , actionMethod . getName ( ) , len > 0 ? context . routeParameters ( ) : null ) ; if ( null == returnParam ) { return ; } if ( isRestful ) { context . json ( returnParam ) ; return ; } if ( returnType == String . class ) { context . body ( ViewBody . of ( new ModelAndView ( returnParam . toString ( ) ) ) ) ; return ; } if ( returnType == ModelAndView . class ) { context . body ( ViewBody . of ( ( ModelAndView ) returnParam ) ) ; } } }
Actual routing method execution
22,756
public static boolean isImage ( String suffix ) { if ( null != suffix && ! "" . equals ( suffix ) && suffix . contains ( "." ) ) { String regex = "(.*?)(?i)(jpg|jpeg|png|gif|bmp|webp)" ; return isMatch ( regex , suffix ) ; } return false ; }
Verify that the suffix is a picture format .
22,757
public static boolean isMatch ( final String regex , final CharSequence input ) { return input != null && input . length ( ) > 0 && Pattern . matches ( regex , input ) ; }
Determines whether the regular is matched .
22,758
private static boolean sameType ( Type [ ] types , Class < ? > [ ] classes ) { if ( types . length != classes . length ) return false ; for ( int i = 0 ; i < types . length ; i ++ ) { if ( ! Type . getType ( classes [ i ] ) . equals ( types [ i ] ) ) return false ; } return true ; }
Compare whether the parameter type is consistent
22,759
public static String [ ] getMethodParamNames ( final Method m ) { if ( METHOD_NAMES_POOL . containsKey ( m ) ) return METHOD_NAMES_POOL . get ( m ) ; final String [ ] paramNames = new String [ m . getParameterTypes ( ) . length ] ; final String n = m . getDeclaringClass ( ) . getName ( ) ; ClassReader cr ; try { cr = new ClassReader ( n ) ; } catch ( IOException e ) { return null ; } cr . accept ( new ClassVisitor ( Opcodes . ASM5 ) { public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { final Type [ ] args = Type . getArgumentTypes ( desc ) ; if ( ! name . equals ( m . getName ( ) ) || ! sameType ( args , m . getParameterTypes ( ) ) ) { return super . visitMethod ( access , name , desc , signature , exceptions ) ; } MethodVisitor v = super . visitMethod ( access , name , desc , signature , exceptions ) ; return new MethodVisitor ( Opcodes . ASM5 , v ) { public void visitLocalVariable ( String name , String desc , String signature , Label start , Label end , int index ) { int i = index - 1 ; if ( Modifier . isStatic ( m . getModifiers ( ) ) ) { i = index ; } if ( i >= 0 && i < paramNames . length ) { paramNames [ i ] = name ; } super . visitLocalVariable ( name , desc , signature , start , end , index ) ; } } ; } } , 0 ) ; METHOD_NAMES_POOL . put ( m , paramNames ) ; return paramNames ; }
get method param names
22,760
public void addRouter ( final Class < ? > routeType , Object controller ) { Method [ ] methods = routeType . getDeclaredMethods ( ) ; if ( BladeKit . isEmpty ( methods ) ) { return ; } String nameSpace = null , suffix = null ; if ( null != routeType . getAnnotation ( Path . class ) ) { nameSpace = routeType . getAnnotation ( Path . class ) . value ( ) ; suffix = routeType . getAnnotation ( Path . class ) . suffix ( ) ; } if ( null == nameSpace ) { log . warn ( "Route [{}] not path annotation" , routeType . getName ( ) ) ; return ; } for ( Method method : methods ) { com . blade . mvc . annotation . Route mapping = method . getAnnotation ( com . blade . mvc . annotation . Route . class ) ; GetRoute getRoute = method . getAnnotation ( GetRoute . class ) ; PostRoute postRoute = method . getAnnotation ( PostRoute . class ) ; PutRoute putRoute = method . getAnnotation ( PutRoute . class ) ; DeleteRoute deleteRoute = method . getAnnotation ( DeleteRoute . class ) ; this . parseRoute ( RouteStruct . builder ( ) . mapping ( mapping ) . getRoute ( getRoute ) . postRoute ( postRoute ) . putRoute ( putRoute ) . deleteRoute ( deleteRoute ) . nameSpace ( nameSpace ) . suffix ( suffix ) . routeType ( routeType ) . controller ( controller ) . method ( method ) . build ( ) ) ; } }
Parse all routing in a controller
22,761
public Blade enableCors ( boolean enableCors , CorsConfiger corsConfig ) { this . environment . set ( ENV_KEY_CORS_ENABLE , enableCors ) ; if ( enableCors ) { this . corsMiddleware = new CorsMiddleware ( corsConfig ) ; } return this ; }
Set whether to config cors
22,762
public Blade listen ( int port ) { Assert . greaterThan ( port , 0 , "server port not is negative number." ) ; this . environment . set ( ENV_KEY_SERVER_PORT , port ) ; return this ; }
Set to start the web server to monitor port the default is 9000
22,763
public Blade start ( Class < ? > mainCls , String ... args ) { try { this . loadConfig ( args ) ; this . bootClass = mainCls ; eventManager . fireEvent ( EventType . SERVER_STARTING , new Event ( ) . attribute ( "blade" , this ) ) ; Thread thread = new Thread ( ( ) -> { try { server . start ( Blade . this ) ; latch . countDown ( ) ; server . join ( ) ; } catch ( BindException e ) { log . error ( "Bind address error\n" , e ) ; System . exit ( 0 ) ; } catch ( Exception e ) { startupExceptionHandler . accept ( e ) ; } } ) ; String threadName = null != this . threadName ? this . threadName : environment . get ( ENV_KEY_APP_THREAD_NAME , null ) ; threadName = null != threadName ? threadName : DEFAULT_THREAD_NAME ; thread . setName ( threadName ) ; thread . start ( ) ; this . started = true ; Thread resourceFilesRefreshThread = new Thread ( ( ) -> { try { FileChangeDetector fileChangeDetector = new FileChangeDetector ( environment . get ( ENV_KEY_AUTO_REFRESH_DIR ) . get ( ) ) ; fileChangeDetector . processEvent ( ( event , filePath ) -> { try { if ( event . equals ( StandardWatchEventKinds . ENTRY_MODIFY ) ) { Path destPath = FileChangeDetector . getDestPath ( filePath , environment ) ; Files . copy ( filePath , destPath , StandardCopyOption . REPLACE_EXISTING ) ; } } catch ( IOException e ) { log . error ( "Exception when trying to copy updated file" ) ; startupExceptionHandler . accept ( e ) ; } } ) ; } catch ( IOException e ) { startupExceptionHandler . accept ( e ) ; } } ) ; if ( devMode ( ) && isAutoRefreshDir ( ) ) { log . info ( "auto refresh is enabled" ) ; resourceFilesRefreshThread . start ( ) ; } } catch ( Exception e ) { startupExceptionHandler . accept ( e ) ; } return this ; }
Start blade application
22,764
public Blade await ( ) { if ( ! this . started ) { throw new IllegalStateException ( "Server hasn't been started. Call start() before calling this method." ) ; } try { this . latch . await ( ) ; } catch ( Exception e ) { log . error ( "Blade start await error" , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } return this ; }
Await web server started
22,765
public String bannerText ( ) { if ( null != bannerText ) return bannerText ; String bannerPath = environment . get ( ENV_KEY_BANNER_PATH , null ) ; if ( StringKit . isEmpty ( bannerPath ) || Files . notExists ( Paths . get ( bannerPath ) ) ) { return null ; } try { BufferedReader bufferedReader = Files . newBufferedReader ( Paths . get ( bannerPath ) ) ; bannerText = bufferedReader . lines ( ) . collect ( Collectors . joining ( "\r\n" ) ) ; } catch ( Exception e ) { log . error ( "Load Start Banner file error" , e ) ; } return bannerText ; }
Get banner text
22,766
private void loadConfig ( String [ ] args ) { String bootConf = environment ( ) . get ( ENV_KEY_BOOT_CONF , PROP_NAME ) ; Environment bootEnv = Environment . of ( bootConf ) ; String envName = "default" ; if ( null == bootEnv || bootEnv . isEmpty ( ) ) { bootEnv = Environment . of ( PROP_NAME0 ) ; } if ( ! Objects . requireNonNull ( bootEnv ) . isEmpty ( ) ) { Map < String , String > bootEnvMap = bootEnv . toMap ( ) ; Set < Map . Entry < String , String > > entrySet = bootEnvMap . entrySet ( ) ; entrySet . forEach ( entry -> environment . set ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } Map < String , String > argsMap = BladeKit . parseArgs ( args ) ; if ( null != argsMap && ! argsMap . isEmpty ( ) ) { log . info ( " command line args: {}" , JsonKit . toString ( argsMap ) ) ; } if ( StringKit . isNotEmpty ( argsMap . get ( ENV_KEY_APP_ENV ) ) ) { envName = argsMap . get ( ENV_KEY_APP_ENV ) ; String evnFileName = "application-" + envName + ".properties" ; Environment customEnv = Environment . of ( evnFileName ) ; if ( customEnv != null && ! customEnv . isEmpty ( ) ) { customEnv . props ( ) . forEach ( ( key , value ) -> this . environment . set ( key . toString ( ) , value ) ) ; } else { evnFileName = "app-" + envName + ".properties" ; customEnv = Environment . of ( evnFileName ) ; if ( customEnv != null && ! customEnv . isEmpty ( ) ) { Iterator < Map . Entry < Object , Object > > iterator = customEnv . props ( ) . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < Object , Object > next = iterator . next ( ) ; this . environment . set ( next . getKey ( ) . toString ( ) , next . getValue ( ) ) ; } } } argsMap . remove ( ENV_KEY_APP_ENV ) ; } this . environment . set ( ENV_KEY_APP_ENV , envName ) ; this . register ( this . environment ) ; if ( BladeKit . isEmpty ( args ) ) { return ; } Iterator < Map . Entry < String , String > > iterator = argsMap . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < String , String > next = iterator . next ( ) ; this . environment . set ( next . getKey ( ) , next . getValue ( ) ) ; } }
Load application environment configuration
22,767
public List < Route > getBefore ( String path ) { String cleanPath = parsePath ( path ) ; List < Route > collect = hooks . values ( ) . stream ( ) . flatMap ( Collection :: stream ) . sorted ( Comparator . comparingInt ( Route :: getSort ) ) . filter ( route -> route . getHttpMethod ( ) == HttpMethod . BEFORE && matchesPath ( route . getPath ( ) , cleanPath ) ) . collect ( Collectors . toList ( ) ) ; this . giveMatch ( path , collect ) ; return collect ; }
Find all in before of the hook
22,768
private void giveMatch ( final String uri , List < Route > routes ) { routes . stream ( ) . sorted ( ( o1 , o2 ) -> { if ( o2 . getPath ( ) . equals ( uri ) ) { return o2 . getPath ( ) . indexOf ( uri ) ; } return - 1 ; } ) ; }
Sort of path
22,769
public void register ( ) { routes . values ( ) . forEach ( route -> logAddRoute ( log , route ) ) ; hooks . values ( ) . stream ( ) . flatMap ( Collection :: stream ) . forEach ( route -> logAddRoute ( log , route ) ) ; Stream . of ( routes . values ( ) , hooks . values ( ) . stream ( ) . findAny ( ) . orElse ( new ArrayList < > ( ) ) ) . flatMap ( Collection :: stream ) . forEach ( this :: registerRoute ) ; regexMapping . register ( ) ; webSockets . keySet ( ) . forEach ( path -> logWebSocket ( log , path ) ) ; }
register route to container
22,770
public void createSession ( Session session ) { sessionMap . put ( session . id ( ) , session ) ; Event event = new Event ( ) ; event . attribute ( "session" , session ) ; eventManager . fireEvent ( EventType . SESSION_CREATED , event ) ; }
Add a session instance to sessionMap
22,771
public void destorySession ( Session session ) { session . attributes ( ) . clear ( ) ; sessionMap . remove ( session . id ( ) ) ; Event event = new Event ( ) ; event . attribute ( "session" , session ) ; eventManager . fireEvent ( EventType . SESSION_DESTROY , event ) ; }
Remove a session
22,772
private void invoke ( WebSocketContext ctx , Class < ? extends Annotation > event ) { Map < Class < ? extends Annotation > , Method > methodCache = this . methodCache . get ( path . get ( ) ) ; if ( methodCache != null ) { Method method = methodCache . get ( event ) ; if ( method != null ) { Class < ? > [ ] paramTypes = method . getParameterTypes ( ) ; Object [ ] param = new Object [ paramTypes . length ] ; try { for ( int i = 0 ; i < paramTypes . length ; i ++ ) { Class < ? > paramType = paramTypes [ i ] ; if ( paramType == WebSocketContext . class ) { param [ i ] = ctx ; } else { Object bean = this . blade . getBean ( paramType ) ; if ( bean != null ) { param [ i ] = bean ; } else { param [ i ] = ReflectKit . newInstance ( paramType ) ; } } } method . invoke ( blade . getBean ( handlers . get ( path . get ( ) ) ) , param ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } } }
invoke target handler methods
22,773
private void printBanner ( ) { if ( null != blade . bannerText ( ) ) { System . out . println ( blade . bannerText ( ) ) ; } else { String text = Const . BANNER_TEXT + NEW_LINE + StringKit . padLeft ( " :: Blade :: (v" , Const . BANNER_PADDING - 9 ) + Const . VERSION + ") " + NEW_LINE ; System . out . println ( Ansi . Magenta . format ( text ) ) ; } }
print blade start banner text
22,774
public static < T > T newInstance ( Type type ) { try { Class < T > clazz = ( Class < T > ) getClass ( type ) ; if ( clazz == null ) { return null ; } return clazz . newInstance ( ) ; } catch ( Exception e ) { log . warn ( "new instance fail :{}" , e . getCause ( ) . toString ( ) ) ; throw new NewInstanceException ( e . getCause ( ) . toString ( ) ) ; } }
Create an instance of the none constructor .
22,775
public static Object convert ( Type type , String value ) { if ( null == value ) { return value ; } if ( "" . equals ( value ) ) { if ( type . equals ( String . class ) ) { return value ; } if ( type . equals ( int . class ) || type . equals ( double . class ) || type . equals ( short . class ) || type . equals ( long . class ) || type . equals ( byte . class ) || type . equals ( float . class ) ) { return 0 ; } if ( type . equals ( boolean . class ) ) { return false ; } return null ; } if ( type . equals ( int . class ) || type . equals ( Integer . class ) ) { return Integer . parseInt ( value ) ; } else if ( type . equals ( String . class ) ) { return value ; } else if ( type . equals ( Double . class ) || type . equals ( double . class ) ) { return Double . parseDouble ( value ) ; } else if ( type . equals ( Float . class ) || type . equals ( float . class ) ) { return Float . parseFloat ( value ) ; } else if ( type . equals ( Long . class ) || type . equals ( long . class ) ) { return Long . parseLong ( value ) ; } else if ( type . equals ( Boolean . class ) || type . equals ( boolean . class ) ) { return Boolean . parseBoolean ( value ) ; } else if ( type . equals ( Short . class ) || type . equals ( short . class ) ) { return Short . parseShort ( value ) ; } else if ( type . equals ( Byte . class ) || type . equals ( byte . class ) ) { return Byte . parseByte ( value ) ; } else if ( type . equals ( BigDecimal . class ) ) { return new BigDecimal ( value ) ; } else if ( type . equals ( Date . class ) ) { if ( value . length ( ) == 10 ) return DateKit . toDate ( value , "yyyy-MM-dd" ) ; return DateKit . toDateTime ( value , "yyyy-MM-dd HH:mm:ss" ) ; } else if ( type . equals ( LocalDate . class ) ) { return DateKit . toLocalDate ( value , "yyyy-MM-dd" ) ; } else if ( type . equals ( LocalDateTime . class ) ) { return DateKit . toLocalDateTime ( value , "yyyy-MM-dd HH:mm:ss" ) ; } return value ; }
Converts a string type to a target type
22,776
public static < T > T cast ( Object value , Class < T > type ) { if ( null == value ) { return null ; } if ( ! type . isAssignableFrom ( value . getClass ( ) ) ) { if ( is ( type , int . class , Integer . class ) ) { value = Integer . parseInt ( value . toString ( ) ) ; } else if ( is ( type , long . class , Long . class ) ) { value = Long . parseLong ( value . toString ( ) ) ; } else if ( is ( type , float . class , Float . class ) ) { value = Float . parseFloat ( value . toString ( ) ) ; } else if ( is ( type , double . class , Double . class ) ) { value = Double . parseDouble ( value . toString ( ) ) ; } else if ( is ( type , boolean . class , Boolean . class ) ) { value = Boolean . parseBoolean ( value . toString ( ) ) ; } else if ( is ( type , String . class ) ) { value = value . toString ( ) ; } } return ( T ) value ; }
Converts value to a specified type
22,777
public static boolean is ( Object instance , Object ... maybeValues ) { if ( instance != null && maybeValues != null ) { for ( Object mb : maybeValues ) if ( instance . equals ( mb ) ) return true ; } return false ; }
Whether the object is one of them .
22,778
public static boolean hasInterface ( Class < ? > cls , Class < ? > inter ) { return Stream . of ( cls . getInterfaces ( ) ) . anyMatch ( c -> c . equals ( inter ) ) ; }
Determine whether CLS is an implementation of an inteface Type .
22,779
public static Method getMethod ( Class < ? > cls , String methodName , Class < ? > ... types ) { try { return cls . getMethod ( methodName , types ) ; } catch ( Exception e ) { return null ; } }
Get cls method name by name and parameter types
22,780
public static boolean isPrimitive ( Type type ) { return type . equals ( boolean . class ) || type . equals ( double . class ) || type . equals ( float . class ) || type . equals ( short . class ) || type . equals ( int . class ) || type . equals ( long . class ) || type . equals ( byte . class ) || type . equals ( char . class ) ; }
Is cls a basic type
22,781
public static Class < ? > form ( String typeName ) { try { return Class . forName ( typeName ) ; } catch ( Exception e ) { log . warn ( "Class.forName fail" , e . getMessage ( ) ) ; return null ; } }
Load a class according to the class name .
22,782
public static String rand ( int size ) { StringBuilder num = new StringBuilder ( ) ; for ( int i = 0 ; i < size ; i ++ ) { double a = Math . random ( ) * 9 ; a = Math . ceil ( a ) ; int randomNum = new Double ( a ) . intValue ( ) ; num . append ( randomNum ) ; } return num . toString ( ) ; }
Generate a number of numeric strings randomly
22,783
public static boolean isNotBlank ( String ... str ) { if ( str == null ) return false ; for ( String s : str ) { if ( isBlank ( s ) ) { return false ; } } return true ; }
Determine whether a list of string is not blank
22,784
public static void isNotBlankThen ( String str , Consumer < String > consumer ) { notBankAccept ( str , Function . identity ( ) , consumer ) ; }
Execute consumer when the string is not empty
22,785
public static void isBlankThen ( String str , Consumer < String > consumer ) { if ( isBlank ( str ) ) { consumer . accept ( str ) ; } }
Execute consumer when the string is empty
22,786
public static boolean isAnyBlank ( String ... values ) { if ( CollectionKit . isEmpty ( values ) ) { return true ; } return Stream . of ( values ) . filter ( StringKit :: isBlank ) . count ( ) == values . length ; }
There is at least one null in the array of strings
22,787
public static boolean isNumber ( String value ) { try { Double . parseDouble ( value ) ; } catch ( NumberFormatException nfe ) { return false ; } return true ; }
determines whether the string is a numeric format
22,788
public static String alignLeft ( Object o , int width , char c ) { if ( null == o ) return null ; String s = o . toString ( ) ; int length = s . length ( ) ; if ( length >= width ) return s ; return s + dup ( c , width - length ) ; }
Fill a certain number of special characters on the right side of the string
22,789
public RouteContext attribute ( String key , Object value ) { this . request . attribute ( key , value ) ; return this ; }
Setting Request Attribute
22,790
public String query ( String paramName , String defaultValue ) { return this . request . query ( paramName , defaultValue ) ; }
Get a request parameter if NULL is returned to defaultValue
22,791
public Integer queryInt ( String paramName , Integer defaultValue ) { return this . request . queryInt ( paramName , defaultValue ) ; }
Returns a request parameter for a Int type
22,792
public Long queryLong ( String paramName , Long defaultValue ) { return this . request . queryLong ( paramName , defaultValue ) ; }
Returns a request parameter for a Long type
22,793
public RouteContext header ( String name , String value ) { this . response . header ( name , value ) ; return this ; }
Set current response header
22,794
public static String ipAddress ( Request request ) { String ipAddress = request . header ( "x-forwarded-for" ) ; if ( StringKit . isBlank ( ipAddress ) || UNKNOWN_MAGIC . equalsIgnoreCase ( ipAddress ) ) { ipAddress = request . header ( "Proxy-Client-IP" ) ; } if ( StringKit . isBlank ( ipAddress ) || UNKNOWN_MAGIC . equalsIgnoreCase ( ipAddress ) ) { ipAddress = request . header ( "WL-Proxy-Client-IP" ) ; } if ( StringKit . isBlank ( ipAddress ) || UNKNOWN_MAGIC . equalsIgnoreCase ( ipAddress ) ) { ipAddress = request . header ( "X-Real-IP" ) ; } if ( StringKit . isBlank ( ipAddress ) || UNKNOWN_MAGIC . equalsIgnoreCase ( ipAddress ) ) { ipAddress = request . header ( "HTTP_CLIENT_IP" ) ; } if ( StringKit . isBlank ( ipAddress ) || UNKNOWN_MAGIC . equalsIgnoreCase ( ipAddress ) ) { ipAddress = request . header ( "HTTP_X_FORWARDED_FOR" ) ; } return ipAddress ; }
Get the client IP address by request
22,795
public static void init ( Blade blade , String contextPath ) { WebContext . blade = blade ; WebContext . contextPath = contextPath ; WebContext . sessionKey = blade . environment ( ) . get ( ENV_KEY_SESSION_KEY , DEFAULT_SESSION_KEY ) ; }
Initializes the project when it starts
22,796
private Set < ClassInfo > findClassByPackage ( final String packageName , final String packagePath , final Class < ? > parent , final Class < ? extends Annotation > annotation , final boolean recursive , Set < ClassInfo > classes ) throws ClassNotFoundException { File dir = new File ( packagePath ) ; if ( ( ! dir . exists ( ) ) || ( ! dir . isDirectory ( ) ) ) { log . warn ( "The package [{}] not found." , packageName ) ; } File [ ] dirFiles = accept ( dir , recursive ) ; if ( null != dirFiles && dirFiles . length > 0 ) { for ( File file : dirFiles ) { if ( file . isDirectory ( ) ) { findClassByPackage ( packageName + '.' + file . getName ( ) , file . getAbsolutePath ( ) , parent , annotation , recursive , classes ) ; } else { String className = file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - 6 ) ; Class < ? > clazz = Class . forName ( packageName + '.' + className ) ; if ( null != parent && null != annotation ) { if ( null != clazz . getSuperclass ( ) && clazz . getSuperclass ( ) . equals ( parent ) && null != clazz . getAnnotation ( annotation ) ) { classes . add ( new ClassInfo ( clazz ) ) ; } continue ; } if ( null != parent ) { if ( null != clazz . getSuperclass ( ) && clazz . getSuperclass ( ) . equals ( parent ) ) { classes . add ( new ClassInfo ( clazz ) ) ; } else { if ( null != clazz . getInterfaces ( ) && clazz . getInterfaces ( ) . length > 0 && clazz . getInterfaces ( ) [ 0 ] . equals ( parent ) ) { classes . add ( new ClassInfo ( clazz ) ) ; } } continue ; } if ( null != annotation ) { if ( null != clazz . getAnnotation ( annotation ) ) { classes . add ( new ClassInfo ( clazz ) ) ; } continue ; } classes . add ( new ClassInfo ( clazz ) ) ; } } } return classes ; }
Get class by condition
22,797
private File [ ] accept ( File file , final boolean recursive ) { return file . listFiles ( file1 -> ( recursive && file1 . isDirectory ( ) ) || ( file1 . getName ( ) . endsWith ( ".class" ) ) ) ; }
Filter the file rules
22,798
private void handleWebSocketFrame ( ChannelHandlerContext ctx , WebSocketFrame frame ) { if ( frame instanceof CloseWebSocketFrame ) { this . handshaker . close ( ctx . channel ( ) , ( CloseWebSocketFrame ) frame . retain ( ) ) ; CompletableFuture . completedFuture ( new WebSocketContext ( this . session , this . handler ) ) . thenAcceptAsync ( this . handler :: onDisConnect ) ; return ; } if ( frame instanceof PingWebSocketFrame ) { ctx . channel ( ) . write ( new PongWebSocketFrame ( frame . content ( ) . retain ( ) ) ) ; return ; } if ( ! ( frame instanceof TextWebSocketFrame ) ) { throw new UnsupportedOperationException ( "unsupported frame type: " + frame . getClass ( ) . getName ( ) ) ; } CompletableFuture . completedFuture ( new WebSocketContext ( this . session , this . handler , ( ( TextWebSocketFrame ) frame ) . text ( ) ) ) . thenAcceptAsync ( this . handler :: onText , ctx . executor ( ) ) ; }
Only supported TextWebSocketFrame
22,799
public static < T > List < T > newLists ( T ... values ) { if ( null == values || values . length == 0 ) { Assert . notNull ( values , "values not is null." ) ; } return Arrays . asList ( values ) ; }
New List and add values