idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
10,600
static void copyState ( Object object , Object context , FieldMatchingStrategy strategy ) { if ( object == null ) { throw new IllegalArgumentException ( "object to set state cannot be null" ) ; } else if ( context == null ) { throw new IllegalArgumentException ( "context cannot be null" ) ; } else if ( strategy == null ) { throw new IllegalArgumentException ( "strategy cannot be null" ) ; } Set < Field > allFields = isClass ( context ) ? getAllStaticFields ( getType ( context ) ) : getAllInstanceFields ( context ) ; for ( Field field : allFields ) { try { final boolean isStaticField = Modifier . isStatic ( field . getModifiers ( ) ) ; setInternalState ( isStaticField ? getType ( object ) : object , field . getType ( ) , field . get ( context ) ) ; } catch ( FieldNotFoundException e ) { if ( strategy == FieldMatchingStrategy . STRICT ) { throw e ; } } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Internal Error: Failed to get the field value in method setInternalStateFromContext." , e ) ; } } }
Copy state .
10,601
private static Class < ? > [ ] convertParameterTypesToPrimitive ( Class < ? > [ ] parameterTypes ) { Class < ? > [ ] converted = new Class < ? > [ parameterTypes . length ] ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { Class < ? > primitiveWrapperType = PrimitiveWrapper . getPrimitiveFromWrapperType ( parameterTypes [ i ] ) ; if ( primitiveWrapperType == null ) { converted [ i ] = parameterTypes [ i ] ; } else { converted [ i ] = primitiveWrapperType ; } } return converted ; }
Convert parameter types to primitive .
10,602
public static < T > T createMock ( Class < T > type , ConstructorArgs constructorArgs , Method ... methods ) { return doMock ( type , false , new DefaultMockStrategy ( ) , constructorArgs , methods ) ; }
Creates a mock object that supports mocking of final and native methods and invokes a specific constructor .
10,603
public static < T > T createMock ( Class < T > type , Object ... constructorArguments ) { Constructor < ? > constructor = WhiteboxImpl . findUniqueConstructorOrThrowException ( type , constructorArguments ) ; ConstructorArgs constructorArgs = new ConstructorArgs ( constructor , constructorArguments ) ; return doMock ( type , false , new DefaultMockStrategy ( ) , constructorArgs , ( Method [ ] ) null ) ; }
Creates a mock object that supports mocking of final and native methods and invokes a specific constructor based on the supplied argument values .
10,604
public static synchronized < T > T createStrictMock ( Class < T > type , Method ... methods ) { return doMock ( type , false , new StrictMockStrategy ( ) , null , methods ) ; }
Creates a strict mock object that supports mocking of final and native methods .
10,605
public static synchronized < T > T createNiceMock ( Class < T > type ) { return doMock ( type , false , new NiceMockStrategy ( ) , null , ( Method [ ] ) null ) ; }
Creates a nice mock object that supports mocking of final and native methods .
10,606
public static < T > T createStrictMock ( Class < T > type , ConstructorArgs constructorArgs , Method ... methods ) { return doMock ( type , false , new StrictMockStrategy ( ) , constructorArgs , methods ) ; }
Creates a strict mock object that supports mocking of final and native methods and invokes a specific constructor .
10,607
public static < T > T createNiceMock ( Class < T > type , ConstructorArgs constructorArgs , Method ... methods ) { return doMock ( type , false , new NiceMockStrategy ( ) , constructorArgs , methods ) ; }
Creates a nice mock object that supports mocking of final and native methods and invokes a specific constructor .
10,608
public static < T > T createStrictMock ( Class < T > type , Object ... constructorArguments ) { Constructor < ? > constructor = WhiteboxImpl . findUniqueConstructorOrThrowException ( type , constructorArguments ) ; ConstructorArgs constructorArgs = new ConstructorArgs ( constructor , constructorArguments ) ; return doMock ( type , false , new StrictMockStrategy ( ) , constructorArgs , ( Method [ ] ) null ) ; }
Creates a strict mock object that supports mocking of final and native methods and invokes a specific constructor based on the supplied argument values .
10,609
public static < T > T createNiceMock ( Class < T > type , Object ... constructorArguments ) { Constructor < ? > constructor = WhiteboxImpl . findUniqueConstructorOrThrowException ( type , constructorArguments ) ; ConstructorArgs constructorArgs = new ConstructorArgs ( constructor , constructorArguments ) ; return doMock ( type , false , new NiceMockStrategy ( ) , constructorArgs , ( Method [ ] ) null ) ; }
Creates a nice mock object that supports mocking of final and native methods and invokes a specific constructor based on the supplied argument values .
10,610
public static synchronized void mockStatic ( Class < ? > type , Method ... methods ) { doMock ( type , true , new DefaultMockStrategy ( ) , null , methods ) ; }
Enable static mocking for a class .
10,611
public static synchronized void mockStaticStrict ( Class < ? > type ) { doMock ( type , true , new StrictMockStrategy ( ) , null , ( Method [ ] ) null ) ; }
Enable strict static mocking for a class .
10,612
public static synchronized void mockStaticNice ( Class < ? > type , Method ... methods ) { doMock ( type , true , new NiceMockStrategy ( ) , null , methods ) ; }
Enable nice static mocking for a class .
10,613
public static synchronized < T > T createPartialMockForAllMethodsExcept ( Class < T > type , String methodNameToExclude , Class < ? > firstArgumentType , Class < ? > ... moreTypes ) { final Class < ? > [ ] argumentTypes = mergeArgumentTypes ( firstArgumentType , moreTypes ) ; return createMock ( type , WhiteboxImpl . getAllMethodsExcept ( type , methodNameToExclude , argumentTypes ) ) ; }
Mock all methods of a class except for a specific one . Use this method only if you have several overloaded methods .
10,614
public static synchronized < T > T createNicePartialMockForAllMethodsExcept ( Class < T > type , String methodNameToExclude , Class < ? > firstArgumentType , Class < ? > ... moreTypes ) { final Class < ? > [ ] argumentTypes = mergeArgumentTypes ( firstArgumentType , moreTypes ) ; return createNiceMock ( type , WhiteboxImpl . getAllMethodsExcept ( type , methodNameToExclude , argumentTypes ) ) ; }
Mock all methods of a class except for a specific one nicely . Use this method only if you have several overloaded methods .
10,615
public static synchronized < T > T createStrictPartialMockForAllMethodsExcept ( Class < T > type , String methodNameToExclude , Class < ? > firstArgumentType , Class < ? > ... moreTypes ) { final Class < ? > [ ] argumentTypes = mergeArgumentTypes ( firstArgumentType , moreTypes ) ; return createStrictMock ( type , WhiteboxImpl . getAllMethodsExcept ( type , methodNameToExclude , argumentTypes ) ) ; }
Mock all methods of a class except for a specific one strictly . Use this method only if you have several overloaded methods .
10,616
public static synchronized < T > T createPartialMock ( Class < T > type , String methodNameToMock , Class < ? > firstArgumentType , Class < ? > ... additionalArgumentTypes ) { return doMockSpecific ( type , new DefaultMockStrategy ( ) , new String [ ] { methodNameToMock } , null , mergeArgumentTypes ( firstArgumentType , additionalArgumentTypes ) ) ; }
Mock a single specific method . Use this to handle overloaded methods .
10,617
public static synchronized < T > T createStrictPartialMock ( Class < T > type , String methodNameToMock , Class < ? > firstArgumentType , Class < ? > ... additionalArgumentTypes ) { return doMockSpecific ( type , new StrictMockStrategy ( ) , new String [ ] { methodNameToMock } , null , mergeArgumentTypes ( firstArgumentType , additionalArgumentTypes ) ) ; }
Strictly mock a single specific method . Use this to handle overloaded methods .
10,618
public static synchronized < T > T createNicePartialMock ( Class < T > type , String methodNameToMock , Class < ? > firstArgumentType , Class < ? > ... additionalArgumentTypes ) { return doMockSpecific ( type , new NiceMockStrategy ( ) , new String [ ] { methodNameToMock } , null , mergeArgumentTypes ( firstArgumentType , additionalArgumentTypes ) ) ; }
Nicely mock a single specific method . Use this to handle overloaded methods .
10,619
public static synchronized void mockStaticPartial ( Class < ? > clazz , String methodNameToMock , Class < ? > firstArgumentType , Class < ? > ... additionalArgumentTypes ) { doMockSpecific ( clazz , new DefaultMockStrategy ( ) , new String [ ] { methodNameToMock } , null , mergeArgumentTypes ( firstArgumentType , additionalArgumentTypes ) ) ; }
Mock a single static method .
10,620
public static synchronized < T > IExpectationSetters < T > expectPrivate ( Class < ? > clazz , Method method , Object ... arguments ) throws Exception { return doExpectPrivate ( clazz , method , arguments ) ; }
Used to specify expectations on private static methods . If possible use variant with only method name .
10,621
public static synchronized < T > IExpectationSetters < T > expectPrivate ( Object instance , Method method , Object ... arguments ) throws Exception { return doExpectPrivate ( instance , method , arguments ) ; }
Used to specify expectations on private methods . If possible use variant with only method name .
10,622
@ SuppressWarnings ( "all" ) public static synchronized < T > IExpectationSetters < T > expectPrivate ( Object instance , String methodName , Class < ? > [ ] parameterTypes , Object ... arguments ) throws Exception { if ( arguments == null ) { arguments = new Object [ 0 ] ; } if ( instance == null ) { throw new IllegalArgumentException ( "instance cannot be null." ) ; } else if ( arguments . length != parameterTypes . length ) { throw new IllegalArgumentException ( "The length of the arguments must be equal to the number of parameter types." ) ; } Method foundMethod = Whitebox . getMethod ( instance . getClass ( ) , methodName , parameterTypes ) ; WhiteboxImpl . throwExceptionIfMethodWasNotFound ( instance . getClass ( ) , methodName , foundMethod , parameterTypes ) ; return doExpectPrivate ( instance , foundMethod , arguments ) ; }
Used to specify expectations on private methods . Use this method to handle overloaded methods .
10,623
public static synchronized < T > IExpectationSetters < T > expectPrivate ( Object instance , String methodName , Object ... arguments ) throws Exception { if ( instance == null ) { throw new IllegalArgumentException ( "Instance or class cannot be null." ) ; } return expectPrivate ( instance , methodName , Whitebox . getType ( instance ) , arguments ) ; }
Used to specify expectations on methods using the method name . Works on for example private or package private methods .
10,624
private static boolean isEasyMocked ( Object mock ) { return Enhancer . isEnhanced ( mock . getClass ( ) ) || Proxy . isProxyClass ( mock . getClass ( ) ) ; }
Test if a object is a mock created by EasyMock or not .
10,625
public static synchronized void reset ( Class < ? > ... classMocks ) { for ( Class < ? > type : classMocks ) { final MethodInvocationControl invocationHandler = MockRepository . getStaticMethodInvocationControl ( type ) ; if ( invocationHandler != null ) { invocationHandler . reset ( ) ; } NewInvocationControl < ? > newInvocationControl = MockRepository . getNewInstanceControl ( type ) ; if ( newInvocationControl != null ) { try { newInvocationControl . reset ( ) ; } catch ( AssertionError e ) { NewInvocationControlAssertionError . throwAssertionErrorForNewSubstitutionFailure ( e , type ) ; } } } }
Reset a list of class mocks .
10,626
public static synchronized void reset ( Object ... mocks ) { try { for ( Object mock : mocks ) { if ( mock instanceof Class < ? > ) { reset ( ( Class < ? > ) mock ) ; } else { MethodInvocationControl invocationControl = MockRepository . getInstanceMethodInvocationControl ( mock ) ; if ( invocationControl != null ) { invocationControl . reset ( ) ; } else { if ( isNiceReplayAndVerifyMode ( ) && ! isEasyMocked ( mock ) ) { } else { try { org . easymock . EasyMock . reset ( mock ) ; } catch ( RuntimeException e ) { throw new RuntimeException ( mock + " is not a mock object" , e ) ; } } } } } } catch ( Throwable t ) { MockRepository . putAdditionalState ( NICE_REPLAY_AND_VERIFY_KEY , false ) ; if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } throw new RuntimeException ( t ) ; } }
Reset a list of mock objects or classes .
10,627
public static synchronized void verify ( Object ... objects ) { for ( Object mock : objects ) { if ( mock instanceof Class < ? > ) { verifyClass ( ( Class < ? > ) mock ) ; } else { EasyMockMethodInvocationControl invocationControl = ( EasyMockMethodInvocationControl ) MockRepository . getInstanceMethodInvocationControl ( mock ) ; if ( invocationControl != null ) { invocationControl . verify ( ) ; } else { if ( isNiceReplayAndVerifyMode ( ) && ! isEasyMocked ( mock ) ) { } else { try { org . easymock . EasyMock . verify ( mock ) ; } catch ( RuntimeException e ) { throw new RuntimeException ( mock + " is not a mock object" , e ) ; } } } } } }
Switches the mocks or classes to verify mode . Note that you must use this method when using PowerMock!
10,628
public static synchronized < T > T createMockAndExpectNew ( Class < T > type , Object ... arguments ) throws Exception { T mock = createMock ( type ) ; expectNew ( type , arguments ) . andReturn ( mock ) ; return mock ; }
Convenience method for createMock followed by expectNew .
10,629
public static synchronized < T > T createNiceMockAndExpectNew ( Class < T > type , Object ... arguments ) throws Exception { T mock = createNiceMock ( type ) ; IExpectationSetters < T > expectationSetters = expectNiceNew ( type , arguments ) ; if ( expectationSetters != null ) { expectationSetters . andReturn ( mock ) ; } return mock ; }
Convenience method for createNiceMock followed by expectNew .
10,630
public static synchronized < T > T createStrictMockAndExpectNew ( Class < T > type , Object ... arguments ) throws Exception { T mock = createStrictMock ( type ) ; expectStrictNew ( type , arguments ) . andReturn ( mock ) ; return mock ; }
Convenience method for createStrictMock followed by expectNew .
10,631
public static boolean matches ( String text , String pattern ) { if ( text == null ) { throw new IllegalArgumentException ( "text cannot be null" ) ; } text += '\0' ; pattern += '\0' ; int N = pattern . length ( ) ; boolean [ ] states = new boolean [ N + 1 ] ; boolean [ ] old = new boolean [ N + 1 ] ; old [ 0 ] = true ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; states = new boolean [ N + 1 ] ; for ( int j = 0 ; j < N ; j ++ ) { char p = pattern . charAt ( j ) ; if ( old [ j ] && ( p == WILDCARD ) ) old [ j + 1 ] = true ; if ( old [ j ] && ( p == c ) ) states [ j + 1 ] = true ; if ( old [ j ] && ( p == WILDCARD ) ) states [ j ] = true ; if ( old [ j ] && ( p == WILDCARD ) ) states [ j + 1 ] = true ; } old = states ; } return states [ N ] ; }
Performs a wildcard matching for the text and pattern provided .
10,632
public Method [ ] getLoggerMethods ( String fullyQualifiedClassName , String methodName , String logFramework ) { try { return Whitebox . getMethods ( getType ( fullyQualifiedClassName , logFramework ) , methodName ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Get the methods that should be mocked .
10,633
public Class < ? > getType ( String name , String logFramework ) throws Exception { final Class < ? > loggerType ; try { loggerType = Class . forName ( name ) ; } catch ( ClassNotFoundException e ) { final String message = String . format ( "Cannot find %s in the classpath which the %s policy requires." , logFramework , getClass ( ) . getSimpleName ( ) ) ; throw new RuntimeException ( message , e ) ; } return loggerType ; }
Get the class type representing the fully - qualified name .
10,634
@ SuppressWarnings ( "unchecked" ) public static < T > Class < T > loadClass ( String className ) { return loadClass ( className , ClassLoaderUtil . class . getClassLoader ( ) ) ; }
Loads a class from the current classloader
10,635
@ SuppressWarnings ( "unchecked" ) public static < T > boolean hasClass ( Class < T > type , ClassLoader classloader ) { try { loadClass ( type . getName ( ) , classloader ) ; return true ; } catch ( RuntimeException e ) { if ( e . getCause ( ) instanceof ClassNotFoundException ) { return false ; } throw e ; } }
Check whether a classloader can load the given class .
10,636
public static < T > Class < T > loadClass ( String className , ClassLoader classloader ) { if ( className == null ) { throw new IllegalArgumentException ( "className cannot be null" ) ; } if ( classloader == null ) { throw new IllegalArgumentException ( "classloader cannot be null" ) ; } try { return ( Class < T > ) Class . forName ( className , false , classloader ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
Load a class from a specific classloader
10,637
public static void proxy ( Method method , InvocationHandler invocationHandler ) { assertInvocationHandlerNotNull ( invocationHandler ) ; MockRepository . putMethodProxy ( method , invocationHandler ) ; }
Add a proxy for this method . Each call to the method will be routed to the invocationHandler instead .
10,638
public static synchronized void suppressConstructor ( Constructor < ? > ... constructors ) { if ( constructors == null ) { throw new IllegalArgumentException ( "constructors cannot be null." ) ; } for ( Constructor < ? > constructor : constructors ) { MockRepository . addConstructorToSuppress ( constructor ) ; Class < ? > declaringClass = constructor . getDeclaringClass ( ) ; if ( declaringClass != null ) { suppressConstructor ( ( Class < ? > ) declaringClass . getSuperclass ( ) ) ; } } }
Suppress constructor calls on specific constructors only .
10,639
public static synchronized void suppressConstructor ( Class < ? > ... classes ) { for ( Class < ? > clazz : classes ) { Class < ? > tempClass = clazz ; while ( tempClass != Object . class ) { suppressConstructor ( tempClass , false ) ; tempClass = tempClass . getSuperclass ( ) ; } } }
Suppress all constructors in the given class and it s super classes .
10,640
public static synchronized void suppressConstructor ( Class < ? > clazz , boolean excludePrivateConstructors ) { Constructor < ? > [ ] ctors = null ; if ( excludePrivateConstructors ) { ctors = clazz . getConstructors ( ) ; } else { ctors = clazz . getDeclaredConstructors ( ) ; } for ( Constructor < ? > ctor : ctors ) { MockRepository . addConstructorToSuppress ( ctor ) ; } }
Suppress all constructors in the given class .
10,641
public static synchronized void suppressField ( Class < ? > [ ] classes ) { if ( classes == null || classes . length == 0 ) { throw new IllegalArgumentException ( "You must supply at least one class." ) ; } for ( Class < ? > clazz : classes ) { suppressField ( clazz . getDeclaredFields ( ) ) ; } }
Suppress all fields for these classes .
10,642
public static synchronized void suppressMethod ( Class < ? > clazz , boolean excludePrivateMethods ) { Method [ ] methods = null ; if ( excludePrivateMethods ) { methods = clazz . getMethods ( ) ; } else { methods = clazz . getDeclaredMethods ( ) ; } for ( Method method : methods ) { MockRepository . addMethodToSuppress ( method ) ; } }
suSuppress all methods for this class .
10,643
@ SuppressWarnings ( "UnusedDeclaration" ) public static Object methodCall ( Class < ? > type , String methodName , Object [ ] args , Class < ? > [ ] sig , String returnTypeAsString ) throws Throwable { return doMethodCall ( type , methodName , args , sig , returnTypeAsString ) ; }
used for static methods
10,644
public static void suppress ( AccessibleObject [ ] accessibleObjects ) { if ( accessibleObjects == null ) { throw new IllegalArgumentException ( "accessibleObjects cannot be null" ) ; } for ( AccessibleObject accessibleObject : accessibleObjects ) { if ( accessibleObject instanceof Constructor < ? > ) { SuppressCode . suppressConstructor ( ( Constructor < ? > ) accessibleObject ) ; } else if ( accessibleObject instanceof Field ) { SuppressCode . suppressField ( ( Field ) accessibleObject ) ; } else if ( accessibleObject instanceof Method ) { SuppressCode . suppressMethod ( ( Method ) accessibleObject ) ; } } }
Suppress an array of accessible objects .
10,645
@ SuppressWarnings ( "unchecked" ) public static < T > Constructor < T > constructor ( Class < T > declaringClass , Class < ? > ... parameterTypes ) { return ( Constructor < T > ) WhiteboxImpl . findUniqueConstructorOrThrowException ( declaringClass , ( Object [ ] ) parameterTypes ) ; }
Returns a constructor specified in declaringClass .
10,646
public static synchronized void mockStatic ( Class < ? > type , Class < ? > ... types ) { DefaultMockCreator . mock ( type , true , false , null , null , ( Method [ ] ) null ) ; if ( types != null && types . length > 0 ) { for ( Class < ? > aClass : types ) { DefaultMockCreator . mock ( aClass , true , false , null , null , ( Method [ ] ) null ) ; } } }
Enable static mocking for all methods of a class .
10,647
public static PrivateMethodVerification verifyPrivate ( Object object , VerificationMode verificationMode ) { Mockito . verify ( object , verificationMode ) ; return new DefaultPrivateMethodVerification ( object ) ; }
Verify a private method invocation with a given verification mode .
10,648
public static PrivateMethodVerification verifyPrivate ( Class < ? > clazz , VerificationMode verificationMode ) { return verifyPrivate ( ( Object ) clazz , verificationMode ) ; }
Verify a private method invocation for a class with a given verification mode .
10,649
public static < T > WithOrWithoutExpectedArguments < T > when ( Class < ? > cls , Method method ) { return new DefaultMethodExpectationSetup < T > ( cls , method ) ; }
Expect calls to private static methods .
10,650
public static < T > OngoingStubbing < T > when ( Class < ? > clazz , String methodToExpect , Object ... arguments ) throws Exception { return Mockito . when ( Whitebox . < T > invokeMethod ( clazz , methodToExpect , arguments ) ) ; }
Expect a static private or inner class method call .
10,651
public static < T > OngoingStubbing < T > when ( Class < ? > klass , Object ... arguments ) throws Exception { return Mockito . when ( Whitebox . < T > invokeMethod ( klass , arguments ) ) ; }
Expect calls to private static methods without having to specify the method name . The method will be looked up using the parameter types if possible
10,652
@ SuppressWarnings ( "unchecked" ) public static Iterator < Class < ? > > getClassIterator ( ClassLoader classLoader ) throws NoSuchFieldException , IllegalAccessException { Class < ? > classLoaderClass = classLoader . getClass ( ) ; while ( classLoaderClass != ClassLoader . class ) { classLoaderClass = classLoaderClass . getSuperclass ( ) ; } Field classesField = classLoaderClass . getDeclaredField ( "classes" ) ; classesField . setAccessible ( true ) ; Vector < Class < ? > > classes = ( Vector < Class < ? > > ) classesField . get ( classLoader ) ; return classes . iterator ( ) ; }
Get an iterator of all classes loaded by the specific classloader .
10,653
public void cache ( Class < ? > cls ) { if ( cls != null ) { classes . put ( cls . getName ( ) , new SoftReference < Class < ? > > ( cls ) ) ; } }
Register a class to the cache of this classloader
10,654
protected URL findResource ( String name ) { try { return Whitebox . invokeMethod ( deferTo , "findResource" , name ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Finds the resource with the specified name on the search path .
10,655
public InputStream setFlag ( String name , String value ) throws IOException { return executeCommand ( "setflag" , name , value ) ; }
set JVM command line flag
10,656
public static void setInternalState ( Object object , String fieldName , Object value , Class < ? > where ) { WhiteboxImpl . setInternalState ( object , fieldName , value , where ) ; }
Set the value of a field using reflection . Use this method when you need to specify in which class the field is declared . This might be useful when you have mocked the instance you are trying to modify .
10,657
public static < T > T getInternalState ( Object object , String fieldName , Class < ? > where ) { return WhiteboxImpl . getInternalState ( object , fieldName , where ) ; }
Get the value of a field using reflection . Use this method when you need to specify in which class the field is declared . This might be useful when you have mocked the instance you are trying to access .
10,658
public static synchronized < T > T invokeMethod ( Class < ? > clazz , String methodToExecute , Object ... arguments ) throws Exception { return WhiteboxImpl . invokeMethod ( clazz , methodToExecute , arguments ) ; }
Invoke a static private or inner class method . This may be useful to test private methods .
10,659
public static Class < Object > getInnerClassType ( Class < ? > declaringClass , String name ) throws ClassNotFoundException { return WhiteboxImpl . getInnerClassType ( declaringClass , name ) ; }
Get an inner class type
10,660
public void onApplicationEvent ( ContextRefreshedEvent event ) { ApplicationContext context = event . getApplicationContext ( ) ; if ( isSpringBoot ) { CrawlerProperties crawlerProperties = context . getBean ( CrawlerProperties . class ) ; if ( ! crawlerProperties . isEnabled ( ) ) { logger . warn ( "{} is not enabled" , Constants . SEIMI_CRAWLER_BOOTSTRAP_ENABLED ) ; return ; } } if ( context != null ) { if ( CollectionUtils . isEmpty ( CrawlerCache . getCrawlers ( ) ) ) { logger . info ( "Not find any crawler,may be you need to check." ) ; return ; } workersPool = Executors . newFixedThreadPool ( Constants . BASE_THREAD_NUM * Runtime . getRuntime ( ) . availableProcessors ( ) * CrawlerCache . getCrawlers ( ) . size ( ) ) ; for ( Class < ? extends BaseSeimiCrawler > a : CrawlerCache . getCrawlers ( ) ) { CrawlerModel crawlerModel = new CrawlerModel ( a , context ) ; if ( CrawlerCache . isExist ( crawlerModel . getCrawlerName ( ) ) ) { logger . error ( "Crawler:{} is repeated,please check" , crawlerModel . getCrawlerName ( ) ) ; throw new SeimiInitExcepiton ( StrFormatUtil . info ( "Crawler:{} is repeated,please check" , crawlerModel . getCrawlerName ( ) ) ) ; } CrawlerCache . putCrawlerModel ( crawlerModel . getCrawlerName ( ) , crawlerModel ) ; } for ( Map . Entry < String , CrawlerModel > crawlerEntry : CrawlerCache . getCrawlerModelContext ( ) . entrySet ( ) ) { for ( int i = 0 ; i < Constants . BASE_THREAD_NUM * Runtime . getRuntime ( ) . availableProcessors ( ) ; i ++ ) { workersPool . execute ( new SeimiProcessor ( CrawlerCache . getInterceptors ( ) , crawlerEntry . getValue ( ) ) ) ; } } if ( isSpringBoot ) { CrawlerProperties crawlerProperties = context . getBean ( CrawlerProperties . class ) ; String crawlerNames = crawlerProperties . getNames ( ) ; if ( StringUtils . isBlank ( crawlerNames ) ) { logger . info ( "Spring boot start [{}] as worker." , StringUtils . join ( CrawlerCache . getCrawlerModelContext ( ) . keySet ( ) , "," ) ) ; } else { String [ ] crawlers = crawlerNames . split ( "," ) ; for ( String cn : crawlers ) { CrawlerModel crawlerModel = CrawlerCache . getCrawlerModel ( cn ) ; if ( crawlerModel == null ) { logger . warn ( "Crawler name = {} is not existent." , cn ) ; continue ; } crawlerModel . startRequest ( ) ; } } SeimiConfig config = new SeimiConfig ( ) ; config . setBloomFilterExpectedInsertions ( crawlerProperties . getBloomFilterExpectedInsertions ( ) ) ; config . setBloomFilterFalseProbability ( crawlerProperties . getBloomFilterFalseProbability ( ) ) ; config . setSeimiAgentHost ( crawlerProperties . getSeimiAgentHost ( ) ) ; config . setSeimiAgentPort ( crawlerProperties . getSeimiAgentPort ( ) ) ; CrawlerCache . setConfig ( config ) ; } } }
Handle an application event .
10,661
public long notJmhEventLoop ( StreamObjects streamObjects ) throws Exception { ANOTHER_EVENT_LOOP . execute ( ( ) -> { final StreamMessage < Integer > stream = newStream ( streamObjects ) ; stream . subscribe ( streamObjects . subscriber , ANOTHER_EVENT_LOOP ) ; streamObjects . writeAllValues ( stream ) ; } ) ; streamObjects . completedLatch . await ( 10 , TimeUnit . SECONDS ) ; return streamObjects . computedSum ( ) ; }
to compare approaches .
10,662
protected final InetSocketAddress remoteAddress ( ) { if ( remoteAddress == null ) { if ( server ) { remoteAddress = new InetSocketAddress ( NetUtil . LOCALHOST , randomClientPort ( ) ) ; } else { remoteAddress = new InetSocketAddress ( NetUtil . LOCALHOST , guessServerPort ( sessionProtocol , authority ) ) ; } } return remoteAddress ; }
Returns the remote socket address of the connection .
10,663
protected final InetSocketAddress localAddress ( ) { if ( localAddress == null ) { if ( server ) { localAddress = new InetSocketAddress ( NetUtil . LOCALHOST , guessServerPort ( sessionProtocol , authority ) ) ; } else { localAddress = new InetSocketAddress ( NetUtil . LOCALHOST , randomClientPort ( ) ) ; } } return localAddress ; }
Returns the local socket address of the connection .
10,664
public final B requestStartTime ( long requestStartTimeNanos , long requestStartTimeMicros ) { this . requestStartTimeNanos = requestStartTimeNanos ; this . requestStartTimeMicros = requestStartTimeMicros ; requestStartTimeSet = true ; return self ( ) ; }
Sets the request start time of the request .
10,665
private Map < String , TField > computeFieldNameMap ( Class < ? > clazz ) { final Map < String , TField > map = new HashMap < > ( ) ; if ( isTBase ( clazz ) ) { @ SuppressWarnings ( "unchecked" ) final Map < ? extends TFieldIdEnum , FieldMetaData > metaDataMap = FieldMetaData . getStructMetaDataMap ( ( Class < ? extends TBase < ? , ? > > ) clazz ) ; for ( Entry < ? extends TFieldIdEnum , FieldMetaData > e : metaDataMap . entrySet ( ) ) { final String fieldName = e . getKey ( ) . getFieldName ( ) ; final FieldMetaData metaData = e . getValue ( ) ; final FieldValueMetaData elementMetaData ; if ( metaData . valueMetaData . isContainer ( ) ) { if ( metaData . valueMetaData instanceof SetMetaData ) { elementMetaData = ( ( SetMetaData ) metaData . valueMetaData ) . elemMetaData ; } else if ( metaData . valueMetaData instanceof ListMetaData ) { elementMetaData = ( ( ListMetaData ) metaData . valueMetaData ) . elemMetaData ; } else if ( metaData . valueMetaData instanceof MapMetaData ) { elementMetaData = ( ( MapMetaData ) metaData . valueMetaData ) . valueMetaData ; } else { elementMetaData = metaData . valueMetaData ; } } else { elementMetaData = metaData . valueMetaData ; } if ( elementMetaData instanceof EnumMetaData ) { classMap . put ( fieldName , ( ( EnumMetaData ) elementMetaData ) . enumClass ) ; } else if ( elementMetaData instanceof StructMetaData ) { classMap . put ( fieldName , ( ( StructMetaData ) elementMetaData ) . structClass ) ; } final byte type = TType . ENUM == metaData . valueMetaData . type ? TType . I32 : metaData . valueMetaData . type ; map . put ( fieldName , new TField ( fieldName , type , e . getKey ( ) . getThriftFieldId ( ) ) ) ; } } else { map . put ( "message" , new TField ( "message" , ( byte ) 11 , ( short ) 1 ) ) ; map . put ( "type" , new TField ( "type" , ( byte ) 8 , ( short ) 2 ) ) ; } return map ; }
Compute a new field name map for the current thrift message we are parsing .
10,666
private void cleanup ( ) { if ( ( ++ counter & 0xFF ) != 0 ) { return ; } final long currentTimeNanos = System . nanoTime ( ) ; if ( currentTimeNanos - lastCleanupTimeNanos < CLEANUP_INTERVAL_NANOS ) { return ; } for ( final Iterator < State > i = map . values ( ) . iterator ( ) ; i . hasNext ( ) ; ) { final State state = i . next ( ) ; final boolean remove ; synchronized ( state ) { remove = state . allActiveRequests == 0 && currentTimeNanos - state . lastActivityTimeNanos >= CLEANUP_INTERVAL_NANOS ; } if ( remove ) { i . remove ( ) ; } } lastCleanupTimeNanos = System . nanoTime ( ) ; }
Cleans up empty entries with no activity for more than 1 minute . For reduced overhead we perform this only when 1 ) the last clean - up was more than 1 minute ago and 2 ) the number of acquisitions % 256 is 0 .
10,667
public final B serverAddresses ( Iterable < InetSocketAddress > serverAddresses ) { requireNonNull ( serverAddresses , "serverAddresses" ) ; final DnsServerAddresses addrs = DnsServerAddresses . sequential ( serverAddresses ) ; serverAddressStreamProvider = hostname -> addrs . stream ( ) ; return self ( ) ; }
Sets the DNS server addresses to send queries to . Operating system default is used by default .
10,668
private static void streamResource ( ServiceRequestContext ctx , HttpResponseWriter res , ReadableByteChannel in , long remainingBytes ) { final int chunkSize = ( int ) Math . min ( 8192 , remainingBytes ) ; final ByteBuf buf = ctx . alloc ( ) . buffer ( chunkSize ) ; final int readBytes ; boolean success = false ; try { readBytes = read ( in , buf ) ; if ( readBytes < 0 ) { throw new EOFException ( ) ; } success = true ; } catch ( Exception e ) { close ( res , in , e ) ; return ; } finally { if ( ! success ) { buf . release ( ) ; } } final long nextRemainingBytes = remainingBytes - readBytes ; final boolean endOfStream = nextRemainingBytes == 0 ; if ( readBytes > 0 ) { if ( ! res . tryWrite ( new ByteBufHttpData ( buf , endOfStream ) ) ) { close ( in ) ; return ; } } else { buf . release ( ) ; } if ( endOfStream ) { close ( res , in ) ; return ; } res . onDemand ( ( ) -> { try { ctx . blockingTaskExecutor ( ) . execute ( ( ) -> streamResource ( ctx , res , in , nextRemainingBytes ) ) ; } catch ( Exception e ) { close ( res , in , e ) ; } } ) ; }
streaming a ReadableByteChannel and an InputStream .
10,669
public HttpHeaders generatePreflightResponseHeaders ( ) { final HttpHeaders headers = new DefaultHttpHeaders ( ) ; preflightResponseHeaders . forEach ( ( key , value ) -> { final Object val = getValue ( value ) ; if ( val instanceof Iterable ) { headers . addObject ( key , ( Iterable < ? > ) val ) ; } else { headers . addObject ( key , val ) ; } } ) ; return headers . asImmutable ( ) ; }
Generates immutable HTTP response headers that should be added to a CORS preflight response .
10,670
public static < T > T toUnpooled ( T o ) { if ( o instanceof ByteBufHolder ) { o = copyAndRelease ( ( ByteBufHolder ) o ) ; } else if ( o instanceof ByteBuf ) { o = copyAndRelease ( ( ByteBuf ) o ) ; } return o ; }
Converts the given object to an unpooled copy and releases the given object .
10,671
private static String doEscape ( byte [ ] valueBytes , int ri ) { final byte [ ] escapedBytes = new byte [ ri + ( valueBytes . length - ri ) * 3 ] ; if ( ri != 0 ) { System . arraycopy ( valueBytes , 0 , escapedBytes , 0 , ri ) ; } int wi = ri ; for ( ; ri < valueBytes . length ; ri ++ ) { final byte b = valueBytes [ ri ] ; if ( isEscapingChar ( b ) ) { escapedBytes [ wi ] = '%' ; escapedBytes [ wi + 1 ] = HEX [ ( b >> 4 ) & 0xF ] ; escapedBytes [ wi + 2 ] = HEX [ b & 0xF ] ; wi += 3 ; continue ; } escapedBytes [ wi ++ ] = b ; } final byte [ ] dest = new byte [ wi ] ; System . arraycopy ( escapedBytes , 0 , dest , 0 , wi ) ; return new String ( dest , StandardCharsets . US_ASCII ) ; }
Escapes the given byte array .
10,672
private static void encodeHeader ( CharSequence name , CharSequence value , ByteBuf buf ) { final int nameLen = name . length ( ) ; final int valueLen = value . length ( ) ; final int entryLen = nameLen + valueLen + 4 ; buf . ensureWritable ( entryLen ) ; int offset = buf . writerIndex ( ) ; writeAscii ( buf , offset , name , nameLen ) ; offset += nameLen ; buf . setByte ( offset ++ , ':' ) ; buf . setByte ( offset ++ , ' ' ) ; writeAscii ( buf , offset , value , valueLen ) ; offset += valueLen ; buf . setByte ( offset ++ , '\r' ) ; buf . setByte ( offset ++ , '\n' ) ; buf . writerIndex ( offset ) ; }
Copied from io . netty . handler . codec . http . HttpHeadersEncoder
10,673
public ArmeriaServerConfigurator armeriaTomcat ( ) { WebServer webServer = ( ( WebServerApplicationContext ) applicationContext ) . getWebServer ( ) ; if ( webServer instanceof TomcatWebServer ) { Tomcat tomcat = ( ( TomcatWebServer ) webServer ) . getTomcat ( ) ; return serverBuilder -> serverBuilder . service ( "prefix:/tomcat/api/rest/v1" , TomcatService . forTomcat ( tomcat ) ) ; } return serverBuilder -> { } ; }
Bean to configure Armeria Tomcat service .
10,674
public Endpoint withDefaultPort ( int defaultPort ) { ensureSingle ( ) ; validatePort ( "defaultPort" , defaultPort ) ; if ( port != 0 ) { return this ; } return new Endpoint ( host ( ) , ipAddr ( ) , defaultPort , weight ( ) , hostType ) ; }
Returns a new host endpoint with the specified default port number .
10,675
public Endpoint withWeight ( int weight ) { ensureSingle ( ) ; validateWeight ( weight ) ; if ( this . weight == weight ) { return this ; } return new Endpoint ( host ( ) , ipAddr ( ) , port , weight , hostType ) ; }
Returns a new host endpoint with the specified weight .
10,676
public String authority ( ) { String authority = this . authority ; if ( authority != null ) { return authority ; } if ( isGroup ( ) ) { authority = "group:" + groupName ; } else if ( port != 0 ) { if ( hostType == HostType . IPv6_ONLY ) { authority = '[' + host ( ) + "]:" + port ; } else { authority = host ( ) + ':' + port ; } } else if ( hostType == HostType . IPv6_ONLY ) { authority = '[' + host ( ) + ']' ; } else { authority = host ( ) ; } return this . authority = authority ; }
Converts this endpoint into the authority part of a URI .
10,677
public final void close ( ) { stopped = true ; super . close ( ) ; final ScheduledFuture < ? > scheduledFuture = this . scheduledFuture ; if ( scheduledFuture != null ) { scheduledFuture . cancel ( true ) ; } }
Stops polling DNS servers for service updates .
10,678
final void warnInvalidRecord ( DnsRecordType type , ByteBuf content ) { if ( logger ( ) . isWarnEnabled ( ) ) { final String dump = ByteBufUtil . hexDump ( content ) ; logger ( ) . warn ( "{} Skipping invalid {} record: {}" , logPrefix ( ) , type . name ( ) , dump . isEmpty ( ) ? "<empty>" : dump ) ; } }
Logs a warning message about an invalid record .
10,679
public final List < Function < Service < HttpRequest , HttpResponse > , ? extends Service < HttpRequest , HttpResponse > > > getDecorators ( ) { return decorators ; }
Returns the decorators of the annotated service object .
10,680
public TomcatServiceBuilder baseDir ( Path baseDir ) { baseDir = requireNonNull ( baseDir , "baseDir" ) . toAbsolutePath ( ) ; if ( ! Files . isDirectory ( baseDir ) ) { throw new IllegalArgumentException ( "baseDir: " + baseDir + " (expected: a directory)" ) ; } this . baseDir = baseDir ; return this ; }
Sets the base directory of an embedded Tomcat .
10,681
public static TypeSignature ofBase ( String baseTypeName ) { checkBaseTypeName ( baseTypeName , "baseTypeName" ) ; return new TypeSignature ( baseTypeName , ImmutableList . of ( ) ) ; }
Creates a new type signature for a base type .
10,682
public static TypeSignature ofNamed ( String name , Object namedTypeDescriptor ) { return new TypeSignature ( requireNonNull ( name , "name" ) , requireNonNull ( namedTypeDescriptor , "namedTypeDescriptor" ) ) ; }
Creates a new named type signature for the provided name and arbitrary descriptor .
10,683
public static TypeSignature ofUnresolved ( String unresolvedTypeName ) { requireNonNull ( unresolvedTypeName , "unresolvedTypeName" ) ; return new TypeSignature ( '?' + unresolvedTypeName , ImmutableList . of ( ) ) ; }
Creates a new unresolved type signature with the specified type name .
10,684
@ SuppressWarnings ( "FloatingPointEquality" ) private static HttpEncodingType determineEncoding ( String acceptEncoding ) { float starQ = - 1.0f ; float gzipQ = - 1.0f ; float deflateQ = - 1.0f ; for ( String encoding : acceptEncoding . split ( "," ) ) { float q = 1.0f ; final int equalsPos = encoding . indexOf ( '=' ) ; if ( equalsPos != - 1 ) { try { q = Float . parseFloat ( encoding . substring ( equalsPos + 1 ) ) ; } catch ( NumberFormatException e ) { q = 0.0f ; } } if ( encoding . contains ( "*" ) ) { starQ = q ; } else if ( encoding . contains ( "gzip" ) && q > gzipQ ) { gzipQ = q ; } else if ( encoding . contains ( "deflate" ) && q > deflateQ ) { deflateQ = q ; } } if ( gzipQ > 0.0f || deflateQ > 0.0f ) { if ( gzipQ >= deflateQ ) { return HttpEncodingType . GZIP ; } else { return HttpEncodingType . DEFLATE ; } } if ( starQ > 0.0f ) { if ( gzipQ == - 1.0f ) { return HttpEncodingType . GZIP ; } if ( deflateQ == - 1.0f ) { return HttpEncodingType . DEFLATE ; } } return null ; }
Copied from netty s HttpContentCompressor .
10,685
public ResponseEntity < Greeting > greetingSync ( @ RequestParam ( value = "name" , defaultValue = "World" ) String name ) { return ResponseEntity . ok ( new Greeting ( String . format ( template , name ) ) ) ; }
Greeting endpoint .
10,686
void cleanupQueue ( SubscriptionImpl subscription , Queue < Object > queue ) { final Throwable cause = ClosedPublisherException . get ( ) ; for ( ; ; ) { final Object e = queue . poll ( ) ; if ( e == null ) { break ; } try { if ( e instanceof CloseEvent ) { notifySubscriberOfCloseEvent ( subscription , ( CloseEvent ) e ) ; continue ; } if ( e instanceof CompletableFuture ) { ( ( CompletableFuture < ? > ) e ) . completeExceptionally ( cause ) ; } @ SuppressWarnings ( "unchecked" ) final T obj = ( T ) e ; onRemoval ( obj ) ; } finally { ReferenceCountUtil . safeRelease ( e ) ; } } }
Helper method for the common case of cleaning up all elements in a queue when shutting down the stream .
10,687
private byte [ ] fetchDecoderOutput ( ) { final CompositeByteBuf decoded = Unpooled . compositeBuffer ( ) ; for ( ; ; ) { final ByteBuf buf = decoder . readInbound ( ) ; if ( buf == null ) { break ; } if ( ! buf . isReadable ( ) ) { buf . release ( ) ; continue ; } decoded . addComponent ( true , buf ) ; } final byte [ ] ret = ByteBufUtil . getBytes ( decoded ) ; decoded . release ( ) ; return ret ; }
Mostly copied from netty s HttpContentDecoder .
10,688
public HttpHealthCheckedEndpointGroupBuilder retryInterval ( Duration retryInterval ) { requireNonNull ( retryInterval , "retryInterval" ) ; checkArgument ( ! retryInterval . isNegative ( ) && ! retryInterval . isZero ( ) , "retryInterval: %s (expected > 0)" , retryInterval ) ; this . retryInterval = retryInterval ; return this ; }
Sets the interval between health check requests . Must be positive .
10,689
public void close ( Throwable cause ) { requireNonNull ( cause , "cause" ) ; final DefaultStreamMessage < T > m = new DefaultStreamMessage < > ( ) ; m . close ( cause ) ; delegate ( m ) ; }
Closes the deferred stream without setting a delegate .
10,690
protected static void scheduleNextRetry ( ClientRequestContext ctx , Consumer < ? super Throwable > actionOnException , Runnable retryTask , long nextDelayMillis ) { try { if ( nextDelayMillis == 0 ) { ctx . contextAwareEventLoop ( ) . execute ( retryTask ) ; } else { @ SuppressWarnings ( "unchecked" ) final ScheduledFuture < Void > scheduledFuture = ( ScheduledFuture < Void > ) ctx . contextAwareEventLoop ( ) . schedule ( retryTask , nextDelayMillis , TimeUnit . MILLISECONDS ) ; scheduledFuture . addListener ( future -> { if ( future . isCancelled ( ) ) { actionOnException . accept ( new IllegalStateException ( ClientFactory . class . getSimpleName ( ) + " has been closed." ) ) ; } } ) ; } } catch ( Throwable t ) { actionOnException . accept ( t ) ; } }
Schedules next retry .
10,691
private static String [ ] guessAndSerializeExampleRequest ( Object exampleRequest ) { checkArgument ( ! ( exampleRequest instanceof CharSequence ) , "can't guess service or method name from a string: " , exampleRequest ) ; boolean guessed = false ; for ( DocServicePlugin plugin : DocService . plugins ) { if ( plugin . supportedExampleRequestTypes ( ) . stream ( ) . noneMatch ( type -> type . isInstance ( exampleRequest ) ) ) { continue ; } final Optional < String > serviceName = plugin . guessServiceName ( exampleRequest ) ; final Optional < String > methodName = plugin . guessServiceMethodName ( exampleRequest ) ; if ( ! serviceName . isPresent ( ) || ! methodName . isPresent ( ) ) { continue ; } guessed = true ; final String s = serviceName . get ( ) ; final String f = methodName . get ( ) ; final Optional < String > serialized = plugin . serializeExampleRequest ( s , f , exampleRequest ) ; if ( serialized . isPresent ( ) ) { return new String [ ] { s , f , serialized . get ( ) } ; } } if ( guessed ) { throw new IllegalArgumentException ( "could not find a plugin that can serialize: " + exampleRequest ) ; } else { throw new IllegalArgumentException ( "could not find a plugin that can guess the service and method name from: " + exampleRequest ) ; } }
Returns a tuple of a service name a method name and a serialized example request .
10,692
private static int appendLong ( byte [ ] data , int offset , long value ) { offset = appendByte ( data , offset , value >>> 56 ) ; offset = appendByte ( data , offset , value >>> 48 ) ; offset = appendByte ( data , offset , value >>> 40 ) ; offset = appendByte ( data , offset , value >>> 32 ) ; offset = appendInt ( data , offset , value ) ; return offset ; }
Appends a 64 - bit integer without its leading zero bytes .
10,693
private static int appendByte ( byte [ ] dst , int offset , long value ) { if ( value == 0 ) { return offset ; } dst [ offset ] = ( byte ) value ; return offset + 1 ; }
Appends a byte if it s not a leading zero .
10,694
public ClientFactoryBuilder connectTimeoutMillis ( long connectTimeoutMillis ) { checkArgument ( connectTimeoutMillis > 0 , "connectTimeoutMillis: %s (expected: > 0)" , connectTimeoutMillis ) ; return channelOption ( ChannelOption . CONNECT_TIMEOUT_MILLIS , ConvertUtils . safeLongToInt ( connectTimeoutMillis ) ) ; }
Sets the timeout of a socket connection attempt in milliseconds .
10,695
public ClientFactoryBuilder idleTimeout ( Duration idleTimeout ) { requireNonNull ( idleTimeout , "idleTimeout" ) ; checkArgument ( ! idleTimeout . isNegative ( ) , "idleTimeout: %s (expected: >= 0)" , idleTimeout ) ; return idleTimeoutMillis ( idleTimeout . toMillis ( ) ) ; }
Sets the idle timeout of a socket connection . The connection is closed if there is no request in progress for this amount of time .
10,696
private EventCount trimAndSum ( long tickerNanos ) { final long oldLimit = tickerNanos - slidingWindowNanos ; final Iterator < Bucket > iterator = reservoir . iterator ( ) ; long success = 0 ; long failure = 0 ; while ( iterator . hasNext ( ) ) { final Bucket bucket = iterator . next ( ) ; if ( bucket . timestamp < oldLimit ) { iterator . remove ( ) ; } else { success += bucket . success ( ) ; failure += bucket . failure ( ) ; } } return new EventCount ( success , failure ) ; }
Sums up buckets within the time window and removes all the others .
10,697
public ClientConnectionTimingsBuilder socketConnectEnd ( ) { checkState ( socketConnectStartTimeMicros >= 0 , "socketConnectStart() is not called yet." ) ; checkState ( ! socketConnectEndSet , "socketConnectEnd() is already called." ) ; socketConnectEndNanos = System . nanoTime ( ) ; socketConnectEndSet = true ; return this ; }
Sets the time when the client ended to connect to a remote peer .
10,698
private static boolean firstPathComponentContainsColon ( Bytes path ) { final int length = path . length ; for ( int i = 1 ; i < length ; i ++ ) { final byte b = path . data [ i ] ; if ( b == '/' ) { break ; } if ( b == ':' ) { return true ; } } return false ; }
According to RFC 3986 section 3 . 3 path can contain a colon except the first segment .
10,699
static int mod ( int dividend , int divisor ) { int result = dividend % divisor ; return result >= 0 ? result : divisor + result ; }
Returns a non - negative mod .