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 ( )... | 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 ... | 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 passwor... | 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 ... | 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 ( ) =... | 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 .... | 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 < Se... | 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... | 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 , getPubl... | 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... | 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 . onCompl... | 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 instance... | 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 ) ; }... | 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 ( Throw... | 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 ) ;... | 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 ... | 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 ( NoSuchAlgor... | 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 Cl... | 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 ( ) ; ... | 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 . siz... | 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 =... | 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 ( callEr... | 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 . isCircuitTrippingExce... | 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 . clearSuccessiveConn... | 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 : r... | 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... | 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 . getSystemClass... | 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 r... | 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 = n... | 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 . getAnnota... | 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 . c... | 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 ( ) ; } retu... | 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 . newBufferedRea... | 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 . re... | 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 && matche... | 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 Arr... | 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 ... | 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 . ... | 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 ... | 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 ... | 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 . cla... | 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 ( cha... | 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 . e... | 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 . exi... | 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 . handl... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.