Input: Transitively resolves aliases . Given aliases ( X to Y ) and ( Y to Z ) it will return mappings ( X to Z ) and ( Y to Z ) . [CODESPLIT] private Map < NodeId , NodeId > resolveAliases ( Iterable < Alias > aliases ) { Map < NodeId , NodeId > resolved = Maps . newHashMap ( ) ; SetMultimap < NodeId , NodeId > inverse = HashMultimap . create ( ) ; for ( Alias alias : aliases ) { NodeId from = alias . getFromId ( ) ; NodeId to = alias . getToId ( ) ; if ( resolved . containsKey ( to ) ) { to = resolved . get ( to ) ; } resolved . put ( from , to ) ; inverse . put ( to , from ) ; Set < NodeId > prev = inverse . get ( from ) ; if ( prev != null ) { for ( NodeId id : prev ) { resolved . remove ( id ) ; inverse . remove ( from , id ) ; resolved . put ( id , to ) ; inverse . put ( to , id ) ; } } } return resolved ; }


Input: Returns true if this scope is a singleton that should be loaded eagerly in { [CODESPLIT] public boolean isEagerSingleton ( Stage stage ) { if ( this == EAGER_SINGLETON ) { return true ; } if ( stage == Stage . PRODUCTION ) { return this == SINGLETON_ANNOTATION || this == SINGLETON_INSTANCE ; } return false ; }


Input: Scopes an internal factory . [CODESPLIT] static < T > InternalFactory < ? extends T > scope ( Key < T > key , InjectorImpl injector , InternalFactory < ? extends T > creator , Object source , Scoping scoping ) { if ( scoping . isNoScope ( ) ) { return creator ; } Scope scope = scoping . getScopeInstance ( ) ; // NOTE: SingletonScope relies on the fact that we are passing a // ProviderToInternalFactoryAdapter here.  If you change the type make sure to update // SingletonScope as well. Provider < T > scoped = scope . scope ( key , new ProviderToInternalFactoryAdapter < T > ( injector , creator ) ) ; return new InternalFactoryToProviderAdapter < T > ( scoped , source ) ; }


Input: Replaces annotation scopes with instance scopes using the Injector s annotation - to - instance map . If the scope annotation has no corresponding instance an error will be added and unscoped will be retuned . [CODESPLIT] static Scoping makeInjectable ( Scoping scoping , InjectorImpl injector , Errors errors ) { Class < ? extends Annotation > scopeAnnotation = scoping . getScopeAnnotation ( ) ; if ( scopeAnnotation == null ) { return scoping ; } ScopeBinding scope = injector . state . getScopeBinding ( scopeAnnotation ) ; if ( scope != null ) { return forInstance ( scope . getScope ( ) ) ; } errors . scopeNotFound ( scopeAnnotation ) ; return UNSCOPED ; }


Input: Normalizes a path by unescaping all safe percent encoded characters . [CODESPLIT] static String normalizePath ( String path ) { StringBuilder sb = new StringBuilder ( path . length ( ) ) ; int queryStart = path . indexOf ( ' ' ) ; String query = null ; if ( queryStart != - 1 ) { query = path . substring ( queryStart ) ; path = path . substring ( 0 , queryStart ) ; } // Normalize the path.  we need to decode path segments, normalize and rejoin in order to // 1. decode and normalize safe percent escaped characters.  e.g. %70 -> 'p' // 2. decode and interpret dangerous character sequences. e.g. /%2E/ -> '/./' -> '/' // 3. preserve dangerous encoded characters. e.g. '/%2F/' -> '///' -> '/%2F' List < String > segments = new ArrayList <> ( ) ; for ( String segment : SLASH_SPLITTER . split ( path ) ) { // This decodes all non-special characters from the path segment.  so if someone passes // /%2E/foo we will normalize it to /./foo and then /foo String normalized = UrlEscapers . urlPathSegmentEscaper ( ) . escape ( lenientDecode ( segment , UTF_8 , false ) ) ; if ( "." . equals ( normalized ) ) { // skip } else if ( ".." . equals ( normalized ) ) { if ( segments . size ( ) > 1 ) { segments . remove ( segments . size ( ) - 1 ) ; } } else { segments . add ( normalized ) ; } } SLASH_JOINER . appendTo ( sb , segments ) ; if ( query != null ) { sb . append ( query ) ; } return sb . toString ( ) ; }


Input: Percent - decodes a US - ASCII string into a Unicode string . The specified encoding is used to determine what characters are represented by any consecutive sequences of the form %<i > XX< / i > . This is the lenient kind of decoding that will simply ignore and copy as - is any %XX sequence that is invalid ( for example %HH ) . [CODESPLIT] private static String lenientDecode ( String string , Charset encoding , boolean decodePlus ) { checkNotNull ( string ) ; checkNotNull ( encoding ) ; if ( decodePlus ) { string = string . replace ( ' ' , ' ' ) ; } int firstPercentPos = string . indexOf ( ' ' ) ; if ( firstPercentPos < 0 ) { return string ; } ByteAccumulator accumulator = new ByteAccumulator ( string . length ( ) , encoding ) ; StringBuilder builder = new StringBuilder ( string . length ( ) ) ; if ( firstPercentPos > 0 ) { builder . append ( string , 0 , firstPercentPos ) ; } for ( int srcPos = firstPercentPos ; srcPos < string . length ( ) ; srcPos ++ ) { char c = string . charAt ( srcPos ) ; if ( c < 0x80 ) { // ASCII boolean processed = false ; if ( c == ' ' && string . length ( ) >= srcPos + 3 ) { String hex = string . substring ( srcPos + 1 , srcPos + 3 ) ; try { int encoded = Integer . parseInt ( hex , 16 ) ; if ( encoded >= 0 ) { accumulator . append ( ( byte ) encoded ) ; srcPos += 2 ; processed = true ; } } catch ( NumberFormatException ignore ) { // Expected case (badly formatted % group) } } if ( ! processed ) { if ( accumulator . isEmpty ( ) ) { // We're not accumulating elements of a multibyte encoded // char, so just toss it right into the result string. builder . append ( c ) ; } else { accumulator . append ( ( byte ) c ) ; } } } else { // Non-ASCII // A non-ASCII char marks the end of a multi-char encoding sequence, // if one is in progress. accumulator . dumpTo ( builder ) ; builder . append ( c ) ; } } accumulator . dumpTo ( builder ) ; return builder . toString ( ) ; }


Input: We tolerate duplicate bindings if one exposes the other or if the two bindings are considered duplicates ( see { @link Bindings#areDuplicates ( BindingImpl BindingImpl ) } . [CODESPLIT] private boolean isOkayDuplicate ( BindingImpl < ? > original , BindingImpl < ? > binding , State state ) { if ( original instanceof ExposedBindingImpl ) { ExposedBindingImpl exposed = ( ExposedBindingImpl ) original ; InjectorImpl exposedFrom = ( InjectorImpl ) exposed . getPrivateElements ( ) . getInjector ( ) ; return ( exposedFrom == binding . getInjector ( ) ) ; } else { original = ( BindingImpl < ? > ) state . getExplicitBindingsThisLevel ( ) . get ( binding . getKey ( ) ) ; // If no original at this level, the original was on a parent, and we don't // allow deduplication between parents & children. if ( original == null ) { return false ; } else { return original . equals ( binding ) ; } } }


Input: Generates an Annotation for the annotation class . Requires that the annotation is all optionals . [CODESPLIT] public static < T extends Annotation > T generateAnnotation ( Class < T > annotationType ) { Preconditions . checkState ( isAllDefaultMethods ( annotationType ) , "%s is not all default methods" , annotationType ) ; return ( T ) cache . getUnchecked ( annotationType ) ; }


Input: Implements { [CODESPLIT] private static boolean annotationEquals ( Class < ? extends Annotation > type , Map < String , Object > members , Object other ) throws Exception { if ( ! type . isInstance ( other ) ) { return false ; } for ( Method method : type . getDeclaredMethods ( ) ) { String name = method . getName ( ) ; if ( ! Arrays . deepEquals ( new Object [ ] { method . invoke ( other ) } , new Object [ ] { members . get ( name ) } ) ) { return false ; } } return true ; }


Input: Implements { [CODESPLIT] private static int annotationHashCode ( Class < ? extends Annotation > type , Map < String , Object > members ) throws Exception { int result = 0 ; for ( Method method : type . getDeclaredMethods ( ) ) { String name = method . getName ( ) ; Object value = members . get ( name ) ; result += ( 127 * name . hashCode ( ) ) ^ ( Arrays . deepHashCode ( new Object [ ] { value } ) - 31 ) ; } return result ; }


Input: Implements { [CODESPLIT] private static String annotationToString ( Class < ? extends Annotation > type , Map < String , Object > members ) throws Exception { StringBuilder sb = new StringBuilder ( ) . append ( "@" ) . append ( type . getName ( ) ) . append ( "(" ) ; JOINER . appendTo ( sb , Maps . transformValues ( members , arg -> { String s = Arrays . deepToString ( new Object [ ] { arg } ) ; return s . substring ( 1 , s . length ( ) - 1 ) ; // cut off brackets } ) ) ; return sb . append ( ")" ) . toString ( ) ; }


Input: Returns true if the given annotation is retained at runtime . [CODESPLIT] public static boolean isRetainedAtRuntime ( Class < ? extends Annotation > annotationType ) { Retention retention = annotationType . getAnnotation ( Retention . class ) ; return retention != null && retention . value ( ) == RetentionPolicy . RUNTIME ; }


Input: Returns the scope annotation on { [CODESPLIT] public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Class < ? > implementation ) { return findScopeAnnotation ( errors , implementation . getAnnotations ( ) ) ; }


Input: Returns the scoping annotation or null if there isn t one . [CODESPLIT] public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Annotation [ ] annotations ) { Class < ? extends Annotation > found = null ; for ( Annotation annotation : annotations ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; if ( isScopeAnnotation ( annotationType ) ) { if ( found != null ) { errors . duplicateScopeAnnotations ( found , annotationType ) ; } else { found = annotationType ; } } } return found ; }


Input: Adds an error if there is a misplaced annotations on { [CODESPLIT] public static void checkForMisplacedScopeAnnotations ( Class < ? > type , Object source , Errors errors ) { if ( Classes . isConcrete ( type ) ) { return ; } Class < ? extends Annotation > scopeAnnotation = findScopeAnnotation ( errors , type ) ; if ( scopeAnnotation != null // We let Dagger Components through to aid migrations. && ! containsComponentAnnotation ( type . getAnnotations ( ) ) ) { errors . withSource ( type ) . scopeAnnotationOnAbstractType ( scopeAnnotation , type , source ) ; } }


Input: Gets a key for the given type member and annotations . [CODESPLIT] public static Key < ? > getKey ( TypeLiteral < ? > type , Member member , Annotation [ ] annotations , Errors errors ) throws ErrorsException { int numErrorsBefore = errors . size ( ) ; Annotation found = findBindingAnnotation ( errors , member , annotations ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; return found == null ? Key . get ( type ) : Key . get ( type , found ) ; }


Input: Returns the binding annotation on { [CODESPLIT] public static Annotation findBindingAnnotation ( Errors errors , Member member , Annotation [ ] annotations ) { Annotation found = null ; for ( Annotation annotation : annotations ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; if ( isBindingAnnotation ( annotationType ) ) { if ( found != null ) { errors . duplicateBindingAnnotations ( member , found . annotationType ( ) , annotationType ) ; } else { found = annotation ; } } } return found ; }


Input: If the annotation is an instance of { [CODESPLIT] public static Annotation canonicalizeIfNamed ( Annotation annotation ) { if ( annotation instanceof javax . inject . Named ) { return Names . named ( ( ( javax . inject . Named ) annotation ) . value ( ) ) ; } else { return annotation ; } }


Input: If the annotation is the class { [CODESPLIT] public static Class < ? extends Annotation > canonicalizeIfNamed ( Class < ? extends Annotation > annotationType ) { if ( annotationType == javax . inject . Named . class ) { return Named . class ; } else { return annotationType ; } }


Input: Returns the name the binding should use . This is based on the annotation . If the annotation has an instance and is not a marker annotation we ask the annotation for its toString . If it was a marker annotation or just an annotation type we use the annotation s name . Otherwise the name is the empty string . [CODESPLIT] public static String nameOf ( Key < ? > key ) { Annotation annotation = key . getAnnotation ( ) ; Class < ? extends Annotation > annotationType = key . getAnnotationType ( ) ; if ( annotation != null && ! isMarker ( annotationType ) ) { return key . getAnnotation ( ) . toString ( ) ; } else if ( key . getAnnotationType ( ) != null ) { return "@" + key . getAnnotationType ( ) . getName ( ) ; } else { return "" ; } }


Input: Sets the actual provider . [CODESPLIT] public void initializeDelegate ( Provider < T > delegate ) { checkState ( this . delegate == null , "delegate already initialized" ) ; this . delegate = checkNotNull ( delegate , "delegate" ) ; }


Input: Returns the looked up provider . The result is not valid until this lookup has been initialized which usually happens when the injector is created . The provider will throw an { [CODESPLIT] public Provider < T > getProvider ( ) { return new ProviderWithDependencies < T > ( ) { @ Override public T get ( ) { Provider < T > local = delegate ; if ( local == null ) { throw new IllegalStateException ( "This Provider cannot be used until the Injector has been created." ) ; } return local . get ( ) ; } @ Override public Set < Dependency < ? > > getDependencies ( ) { // We depend on Provider<T>, not T directly.  This is an important distinction // for dependency analysis tools that short-circuit on providers. Key < ? > providerKey = getKey ( ) . ofType ( Types . providerOf ( getKey ( ) . getTypeLiteral ( ) . getType ( ) ) ) ; return ImmutableSet . < Dependency < ? > > of ( Dependency . get ( providerKey ) ) ; } @ Override public String toString ( ) { return "Provider<" + getKey ( ) . getTypeLiteral ( ) + ">" ; } } ; }


Input: Returns { [CODESPLIT] public static Class < ? extends Member > memberType ( Member member ) { checkNotNull ( member , "member" ) ; if ( member instanceof Field ) { return Field . class ; } else if ( member instanceof Method ) { return Method . class ; } else if ( member instanceof Constructor ) { return Constructor . class ; } else { throw new IllegalArgumentException ( "Unsupported implementation class for Member, " + member . getClass ( ) ) ; } }


Input: Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType ) { return new MapBinder < K , V > ( newMapRealBinder ( binder . skipSources ( MapBinder . class ) , keyType , valueType ) ) ; }


Input: Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , Class < K > keyType , Class < V > valueType ) { return newMapBinder ( binder , TypeLiteral . get ( keyType ) , TypeLiteral . get ( valueType ) ) ; }


Input: Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType , Annotation annotation ) { return new MapBinder < K , V > ( newRealMapBinder ( binder . skipSources ( MapBinder . class ) , keyType , valueType , annotation ) ) ; }


Input: Adds a binding for T . Multiple calls to this are safe and will be collapsed as duplicate bindings . [CODESPLIT] private void addDirectTypeBinding ( Binder binder ) { binder . bind ( bindingSelection . getDirectKey ( ) ) . toProvider ( new RealDirectTypeProvider < T > ( bindingSelection ) ) ; }


Input: Returns a new complete constructor injector with injection listeners registered . [CODESPLIT] public ConstructorInjector < ? > get ( InjectionPoint constructorInjector , Errors errors ) throws ErrorsException { return cache . get ( constructorInjector , errors ) ; }


Input: Returns true if the given class has a scope annotation . [CODESPLIT] private static boolean hasScope ( Class < ? extends Interceptor > interceptorClass ) { for ( Annotation annotation : interceptorClass . getAnnotations ( ) ) { if ( Annotations . isScopeAnnotation ( annotation . annotationType ( ) ) ) { return true ; } } return false ; }


Input: Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType , Annotation annotation ) { binder = binder . skipSources ( RealMapBinder . class ) ; return newRealMapBinder ( binder , keyType , valueType , Key . get ( mapOf ( keyType , valueType ) , annotation ) , RealMultibinder . newRealSetBinder ( binder , Key . get ( entryOfProviderOf ( keyType , valueType ) , annotation ) ) ) ; }


Input: provider map <K V > is safely a Map<K javax . inject . Provider<V >>> [CODESPLIT] @ SuppressWarnings ( "unchecked" ) static < K , V > TypeLiteral < Map < K , javax . inject . Provider < V > > > mapOfJavaxProviderOf ( TypeLiteral < K > keyType , TypeLiteral < V > valueType ) { return ( TypeLiteral < Map < K , javax . inject . Provider < V > > > ) TypeLiteral . get ( Types . mapOf ( keyType . getType ( ) , newParameterizedType ( javax . inject . Provider . class , valueType . getType ( ) ) ) ) ; }


Input: Given a Key<T > will return a Key<Provider<T >> [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private static < T > Key < Provider < T > > getKeyOfProvider ( Key < T > valueKey ) { return ( Key < Provider < T > > ) valueKey . ofType ( Types . providerOf ( valueKey . getTypeLiteral ( ) . getType ( ) ) ) ; }


Input: since it s an easy way to group a type and an optional annotation type or instance . [CODESPLIT] static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , Key < V > valueTypeAndAnnotation ) { binder = binder . skipSources ( RealMapBinder . class ) ; TypeLiteral < V > valueType = valueTypeAndAnnotation . getTypeLiteral ( ) ; return newRealMapBinder ( binder , keyType , valueType , valueTypeAndAnnotation . ofType ( mapOf ( keyType , valueType ) ) , RealMultibinder . newRealSetBinder ( binder , valueTypeAndAnnotation . ofType ( entryOfProviderOf ( keyType , valueType ) ) ) ) ; }


Input: Adds a binding to the map for the given key . [CODESPLIT] Key < V > getKeyForNewValue ( K key ) { checkNotNull ( key , "key" ) ; checkConfiguration ( ! bindingSelection . isInitialized ( ) , "MapBinder was already initialized" ) ; RealMultibinder < Map . Entry < K , Provider < V > > > entrySetBinder = bindingSelection . getEntrySetBinder ( ) ; Key < V > valueKey = Key . get ( bindingSelection . getValueType ( ) , new RealElement ( entrySetBinder . getSetName ( ) , MAPBINDER , bindingSelection . getKeyType ( ) . toString ( ) ) ) ; entrySetBinder . addBinding ( ) . toProvider ( new ProviderMapEntry < K , V > ( key , valueKey ) ) ; return valueKey ; }


Input: Returns some metadata if the method is annotated { @code @Finder } or null . [CODESPLIT] public static DynamicFinder from ( Method method ) { return method . isAnnotationPresent ( Finder . class ) ? new DynamicFinder ( method ) : null ; }


Input: Returns { [CODESPLIT] static void onNullInjectedIntoNonNullableDependency ( Object source , Dependency < ? > dependency ) throws InternalProvisionException { // Hack to allow null parameters to @Provides methods, for backwards compatibility. if ( dependency . getInjectionPoint ( ) . getMember ( ) instanceof Method ) { Method annotated = ( Method ) dependency . getInjectionPoint ( ) . getMember ( ) ; if ( annotated . isAnnotationPresent ( Provides . class ) ) { switch ( InternalFlags . getNullableProvidesOption ( ) ) { case ERROR : break ; // break out & let the below exception happen case IGNORE : return ; // user doesn't care about injecting nulls to non-@Nullables. case WARN : // Warn only once, otherwise we spam logs too much. if ( warnedDependencies . add ( dependency ) ) { logger . log ( Level . WARNING , "Guice injected null into {0} (a {1}), please mark it @Nullable." + " Use -Dguice_check_nullable_provides_params=ERROR to turn this into an" + " error." , new Object [ ] { Messages . formatParameter ( dependency ) , Messages . convert ( dependency . getKey ( ) ) } ) ; } return ; } } } Object formattedDependency = ( dependency . getParameterIndex ( ) != - 1 ) ? Messages . formatParameter ( dependency ) : StackTraceElements . forMember ( dependency . getInjectionPoint ( ) . getMember ( ) ) ; throw InternalProvisionException . create ( "null returned by binding at %s%n but %s is not @Nullable" , source , formattedDependency ) . addSource ( source ) ; }


Input: Prepends the given { @code source } to the stack of binding sources for the errors reported in this exception . [CODESPLIT] InternalProvisionException addSource ( Object source ) { if ( source == SourceProvider . UNKNOWN_SOURCE ) { return this ; } int sz = sourcesToPrepend . size ( ) ; if ( sz > 0 && sourcesToPrepend . get ( sz - 1 ) == source ) { // This is for when there are two identical sources added in a row.  This behavior is copied // from Errors.withSource where it can happen when an constructor/provider method throws an // exception return this ; } sourcesToPrepend . add ( source ) ; return this ; }


Input: Construct an instance . Returns { [CODESPLIT] Object construct ( final InternalContext context , Dependency < ? > dependency , /* @Nullable */ ProvisionListenerStackCallback < T > provisionCallback ) throws InternalProvisionException { final ConstructionContext < T > constructionContext = context . getConstructionContext ( this ) ; // We have a circular reference between constructors. Return a proxy. if ( constructionContext . isConstructing ( ) ) { // TODO (crazybob): if we can't proxy this object, can we proxy the other object? return constructionContext . createProxy ( context . getInjectorOptions ( ) , dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) ) ; } // If we're re-entering this factory while injecting fields or methods, // return the same instance. This prevents infinite loops. T t = constructionContext . getCurrentReference ( ) ; if ( t != null ) { if ( context . getInjectorOptions ( ) . disableCircularProxies ) { throw InternalProvisionException . circularDependenciesDisabled ( dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) ) ; } else { return t ; } } constructionContext . startConstruction ( ) ; try { // Optimization: Don't go through the callback stack if we have no listeners. if ( provisionCallback == null ) { return provision ( context , constructionContext ) ; } else { return provisionCallback . provision ( context , new ProvisionCallback < T > ( ) { @ Override public T call ( ) throws InternalProvisionException { return provision ( context , constructionContext ) ; } } ) ; } } finally { constructionContext . finishConstruction ( ) ; } }


Input: Provisions a new T . [CODESPLIT] private T provision ( InternalContext context , ConstructionContext < T > constructionContext ) throws InternalProvisionException { try { T t ; try { Object [ ] parameters = SingleParameterInjector . getAll ( context , parameterInjectors ) ; t = constructionProxy . newInstance ( parameters ) ; constructionContext . setProxyDelegates ( t ) ; } finally { constructionContext . finishConstruction ( ) ; } // Store reference. If an injector re-enters this factory, they'll get the same reference. constructionContext . setCurrentReference ( t ) ; MembersInjectorImpl < T > localMembersInjector = membersInjector ; localMembersInjector . injectMembers ( t , context , false ) ; localMembersInjector . notifyListeners ( t ) ; return t ; } catch ( InvocationTargetException userException ) { Throwable cause = userException . getCause ( ) != null ? userException . getCause ( ) : userException ; throw InternalProvisionException . errorInjectingConstructor ( cause ) . addSource ( constructionProxy . getInjectionPoint ( ) ) ; } finally { constructionContext . removeCurrentReference ( ) ; } }


Input: Sets the binding to a copy with the specified annotation on the bound key [CODESPLIT] protected BindingImpl < T > annotatedWithInternal ( Class < ? extends Annotation > annotationType ) { checkNotNull ( annotationType , "annotationType" ) ; checkNotAnnotated ( ) ; return setBinding ( binding . withKey ( Key . get ( this . binding . getKey ( ) . getTypeLiteral ( ) , annotationType ) ) ) ; }


Input: Sets the binding to a copy with the specified annotation on the bound key [CODESPLIT] protected BindingImpl < T > annotatedWithInternal ( Annotation annotation ) { checkNotNull ( annotation , "annotation" ) ; checkNotAnnotated ( ) ; return setBinding ( binding . withKey ( Key . get ( this . binding . getKey ( ) . getTypeLiteral ( ) , annotation ) ) ) ; }


Input: When serialized we eagerly convert sources to strings . This hurts our formatting but it guarantees that the receiving end will be able to read the message . [CODESPLIT] private Object writeReplace ( ) throws ObjectStreamException { Object [ ] sourcesAsStrings = sources . toArray ( ) ; for ( int i = 0 ; i < sourcesAsStrings . length ; i ++ ) { sourcesAsStrings [ i ] = Errors . convert ( sourcesAsStrings [ i ] ) . toString ( ) ; } return new Message ( ImmutableList . copyOf ( sourcesAsStrings ) , message , cause ) ; }


Input: Returns a module which creates bindings for provider methods from the given module . [CODESPLIT] static Module forModule ( Module module ) { // avoid infinite recursion, since installing a module always installs itself if ( module instanceof CheckedProviderMethodsModule ) { return Modules . EMPTY_MODULE ; } return new CheckedProviderMethodsModule ( module ) ; }


Input: the collection is immutable . [CODESPLIT] @ Override @ SuppressWarnings ( "unchecked" ) public Collection < AssistedMethod > getAssistedMethods ( ) { return ( Collection < AssistedMethod > ) ( Collection < ? > ) assistDataByMethod . values ( ) ; }


Input: Returns true if the ConfigurationException is due to an error of TypeLiteral not being fully specified . [CODESPLIT] private boolean isTypeNotSpecified ( TypeLiteral < ? > typeLiteral , ConfigurationException ce ) { Collection < Message > messages = ce . getErrorMessages ( ) ; if ( messages . size ( ) == 1 ) { Message msg = Iterables . getOnlyElement ( new Errors ( ) . keyNotFullySpecified ( typeLiteral ) . getMessages ( ) ) ; return msg . getMessage ( ) . equals ( Iterables . getOnlyElement ( messages ) . getMessage ( ) ) ; } else { return false ; } }


Input: Finds a constructor suitable for the method . If the implementation contained any constructors marked with { [CODESPLIT] private < T > InjectionPoint findMatchingConstructorInjectionPoint ( Method method , Key < ? > returnType , TypeLiteral < T > implementation , List < Key < ? > > paramList ) throws ErrorsException { Errors errors = new Errors ( method ) ; if ( returnType . getTypeLiteral ( ) . equals ( implementation ) ) { errors = errors . withSource ( implementation ) ; } else { errors = errors . withSource ( returnType ) . withSource ( implementation ) ; } Class < ? > rawType = implementation . getRawType ( ) ; if ( Modifier . isInterface ( rawType . getModifiers ( ) ) ) { errors . addMessage ( "%s is an interface, not a concrete class.  Unable to create AssistedInject factory." , implementation ) ; throw errors . toException ( ) ; } else if ( Modifier . isAbstract ( rawType . getModifiers ( ) ) ) { errors . addMessage ( "%s is abstract, not a concrete class.  Unable to create AssistedInject factory." , implementation ) ; throw errors . toException ( ) ; } else if ( Classes . isInnerClass ( rawType ) ) { errors . cannotInjectInnerClass ( rawType ) ; throw errors . toException ( ) ; } Constructor < ? > matchingConstructor = null ; boolean anyAssistedInjectConstructors = false ; // Look for AssistedInject constructors... for ( Constructor < ? > constructor : rawType . getDeclaredConstructors ( ) ) { if ( constructor . isAnnotationPresent ( AssistedInject . class ) ) { anyAssistedInjectConstructors = true ; if ( constructorHasMatchingParams ( implementation , constructor , paramList , errors ) ) { if ( matchingConstructor != null ) { errors . addMessage ( "%s has more than one constructor annotated with @AssistedInject" + " that matches the parameters in method %s.  Unable to create " + "AssistedInject factory." , implementation , method ) ; throw errors . toException ( ) ; } else { matchingConstructor = constructor ; } } } } if ( ! anyAssistedInjectConstructors ) { // If none existed, use @Inject. try { return InjectionPoint . forConstructorOf ( implementation ) ; } catch ( ConfigurationException e ) { errors . merge ( e . getErrorMessages ( ) ) ; throw errors . toException ( ) ; } } else { // Otherwise, use it or fail with a good error message. if ( matchingConstructor != null ) { // safe because we got the constructor from this implementation. @ SuppressWarnings ( "unchecked" ) InjectionPoint ip = InjectionPoint . forConstructor ( ( Constructor < ? super T > ) matchingConstructor , implementation ) ; return ip ; } else { errors . addMessage ( "%s has @AssistedInject constructors, but none of them match the" + " parameters in method %s.  Unable to create AssistedInject factory." , implementation , method ) ; throw errors . toException ( ) ; } } }


Input: Matching logic for constructors annotated with AssistedInject . This returns true if and only if all [CODESPLIT] private boolean constructorHasMatchingParams ( TypeLiteral < ? > type , Constructor < ? > constructor , List < Key < ? > > paramList , Errors errors ) throws ErrorsException { List < TypeLiteral < ? > > params = type . getParameterTypes ( constructor ) ; Annotation [ ] [ ] paramAnnotations = constructor . getParameterAnnotations ( ) ; int p = 0 ; List < Key < ? > > constructorKeys = Lists . newArrayList ( ) ; for ( TypeLiteral < ? > param : params ) { Key < ? > paramKey = Annotations . getKey ( param , constructor , paramAnnotations [ p ++ ] , errors ) ; constructorKeys . add ( paramKey ) ; } // Require that every key exist in the constructor to match up exactly. for ( Key < ? > key : paramList ) { // If it didn't exist in the constructor set, we can't use it. if ( ! constructorKeys . remove ( key ) ) { return false ; } } // If any keys remain and their annotation is Assisted, we can't use it. for ( Key < ? > key : constructorKeys ) { if ( key . getAnnotationType ( ) == Assisted . class ) { return false ; } } // All @Assisted params match up to the method's parameters. return true ; }


Input: Calculates all dependencies required by the implementation and constructor . [CODESPLIT] private Set < Dependency < ? > > getDependencies ( InjectionPoint ctorPoint , TypeLiteral < ? > implementation ) { ImmutableSet . Builder < Dependency < ? > > builder = ImmutableSet . builder ( ) ; builder . addAll ( ctorPoint . getDependencies ( ) ) ; if ( ! implementation . getRawType ( ) . isInterface ( ) ) { for ( InjectionPoint ip : InjectionPoint . forInstanceMethodsAndFields ( implementation ) ) { builder . addAll ( ip . getDependencies ( ) ) ; } } return builder . build ( ) ; }


Input: Return all non - assisted dependencies . [CODESPLIT] private Set < Dependency < ? > > removeAssistedDeps ( Set < Dependency < ? > > deps ) { ImmutableSet . Builder < Dependency < ? > > builder = ImmutableSet . builder ( ) ; for ( Dependency < ? > dep : deps ) { Class < ? > annotationType = dep . getKey ( ) . getAnnotationType ( ) ; if ( annotationType == null || ! annotationType . equals ( Assisted . class ) ) { builder . add ( dep ) ; } } return builder . build ( ) ; }


Input: Returns true if all dependencies are suitable for the optimized version of AssistedInject . The optimized version caches the binding & uses a ThreadLocal Provider so can only be applied if the assisted bindings are immediately provided . This looks for hints that the values may be lazily retrieved by looking for injections of Injector or a Provider for the assisted values . [CODESPLIT] private boolean isValidForOptimizedAssistedInject ( Set < Dependency < ? > > dependencies , Class < ? > implementation , TypeLiteral < ? > factoryType ) { Set < Dependency < ? > > badDeps = null ; // optimization: create lazily for ( Dependency < ? > dep : dependencies ) { if ( isInjectorOrAssistedProvider ( dep ) ) { if ( badDeps == null ) { badDeps = Sets . newHashSet ( ) ; } badDeps . add ( dep ) ; } } if ( badDeps != null && ! badDeps . isEmpty ( ) ) { logger . log ( Level . WARNING , "AssistedInject factory {0} will be slow " + "because {1} has assisted Provider dependencies or injects the Injector. " + "Stop injecting @Assisted Provider<T> (instead use @Assisted T) " + "or Injector to speed things up. (It will be a ~6500% speed bump!)  " + "The exact offending deps are: {2}" , new Object [ ] { factoryType , implementation , badDeps } ) ; return false ; } return true ; }


Input: Returns true if the dependency is for { [CODESPLIT] private boolean isInjectorOrAssistedProvider ( Dependency < ? > dependency ) { Class < ? > annotationType = dependency . getKey ( ) . getAnnotationType ( ) ; if ( annotationType != null && annotationType . equals ( Assisted . class ) ) { // If it's assisted.. if ( dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) . equals ( Provider . class ) ) { // And a Provider... return true ; } } else if ( dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) . equals ( Injector . class ) ) { // If it's the Injector... return true ; } return false ; }


Input: At injector - creation time we initialize the invocation handler . At this time we make sure all factory methods will be able to build the target types . [CODESPLIT] @ Inject @ Toolable void initialize ( Injector injector ) { if ( this . injector != null ) { throw new ConfigurationException ( ImmutableList . of ( new Message ( FactoryProvider2 . class , "Factories.create() factories may only be used in one Injector!" ) ) ) ; } this . injector = injector ; for ( Map . Entry < Method , AssistData > entry : assistDataByMethod . entrySet ( ) ) { Method method = entry . getKey ( ) ; AssistData data = entry . getValue ( ) ; Object [ ] args ; if ( ! data . optimized ) { args = new Object [ method . getParameterTypes ( ) . length ] ; Arrays . fill ( args , "dummy object for validating Factories" ) ; } else { args = null ; // won't be used -- instead will bind to data.providers. } getBindingFromNewInjector ( method , args , data ) ; // throws if the binding isn't properly configured } }


Input: Creates a child injector that binds the args and returns the binding for the method s result . [CODESPLIT] public Binding < ? > getBindingFromNewInjector ( final Method method , final Object [ ] args , final AssistData data ) { checkState ( injector != null , "Factories.create() factories cannot be used until they're initialized by Guice." ) ; final Key < ? > returnType = data . returnType ; // We ignore any pre-existing binding annotation. final Key < ? > returnKey = Key . get ( returnType . getTypeLiteral ( ) , RETURN_ANNOTATION ) ; Module assistedModule = new AbstractModule ( ) { @ Override @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) // raw keys are necessary for the args array and return value protected void configure ( ) { Binder binder = binder ( ) . withSource ( method ) ; int p = 0 ; if ( ! data . optimized ) { for ( Key < ? > paramKey : data . paramTypes ) { // Wrap in a Provider to cover null, and to prevent Guice from injecting the // parameter binder . bind ( ( Key ) paramKey ) . toProvider ( Providers . of ( args [ p ++ ] ) ) ; } } else { for ( Key < ? > paramKey : data . paramTypes ) { // Bind to our ThreadLocalProviders. binder . bind ( ( Key ) paramKey ) . toProvider ( data . providers . get ( p ++ ) ) ; } } Constructor constructor = data . constructor ; // Constructor *should* always be non-null here, // but if it isn't, we'll end up throwing a fairly good error // message for the user. if ( constructor != null ) { binder . bind ( returnKey ) . toConstructor ( constructor , ( TypeLiteral ) data . implementationType ) . in ( Scopes . NO_SCOPE ) ; // make sure we erase any scope on the implementation type } } } ; Injector forCreate = injector . createChildInjector ( assistedModule ) ; Binding < ? > binding = forCreate . getBinding ( returnKey ) ; // If we have providers cached in data, cache the binding for future optimizations. if ( data . optimized ) { data . cachedBinding = binding ; } return binding ; }


Input: When a factory method is invoked we create a child injector that binds all parameters then use that to get an instance of the return type . [CODESPLIT] @ Override public Object invoke ( Object proxy , final Method method , final Object [ ] args ) throws Throwable { // If we setup a method handle earlier for this method, call it. // This is necessary for default methods that java8 creates, so we // can call the default method implementation (and not our proxied version of it). if ( methodHandleByMethod . containsKey ( method ) ) { return methodHandleByMethod . get ( method ) . invokeWithArguments ( args ) ; } if ( method . getDeclaringClass ( ) . equals ( Object . class ) ) { if ( "equals" . equals ( method . getName ( ) ) ) { return proxy == args [ 0 ] ; } else if ( "hashCode" . equals ( method . getName ( ) ) ) { return System . identityHashCode ( proxy ) ; } else { return method . invoke ( this , args ) ; } } AssistData data = assistDataByMethod . get ( method ) ; checkState ( data != null , "No data for method: %s" , method ) ; Provider < ? > provider ; if ( data . cachedBinding != null ) { // Try to get optimized form... provider = data . cachedBinding . getProvider ( ) ; } else { provider = getBindingFromNewInjector ( method , args , data ) . getProvider ( ) ; } try { int p = 0 ; for ( ThreadLocalProvider tlp : data . providers ) { tlp . set ( args [ p ++ ] ) ; } return provider . get ( ) ; } catch ( ProvisionException e ) { // if this is an exception declared by the factory method, throw it as-is if ( e . getErrorMessages ( ) . size ( ) == 1 ) { Message onlyError = getOnlyElement ( e . getErrorMessages ( ) ) ; Throwable cause = onlyError . getCause ( ) ; if ( cause != null && canRethrow ( method , cause ) ) { throw cause ; } } throw e ; } finally { for ( ThreadLocalProvider tlp : data . providers ) { tlp . remove ( ) ; } } }


Input: Returns true if { [CODESPLIT] static boolean canRethrow ( Method invoked , Throwable thrown ) { if ( thrown instanceof Error || thrown instanceof RuntimeException ) { return true ; } for ( Class < ? > declared : invoked . getExceptionTypes ( ) ) { if ( declared . isInstance ( thrown ) ) { return true ; } } return false ; }


Input: Throws a ConfigurationException with an NullPointerExceptions as the cause if the given reference is { [CODESPLIT] static < T > T checkNotNull ( T reference , String name ) { if ( reference != null ) { return reference ; } NullPointerException npe = new NullPointerException ( name ) ; throw new ConfigurationException ( ImmutableSet . of ( new Message ( npe . toString ( ) , npe ) ) ) ; }


Input: Throws a ConfigurationException with a formatted { [CODESPLIT] static void checkConfiguration ( boolean condition , String format , Object ... args ) { if ( condition ) { return ; } throw new ConfigurationException ( ImmutableSet . of ( new Message ( Errors . format ( format , args ) ) ) ) ; }


Input: Returns an instance that uses { [CODESPLIT] public Errors withSource ( Object source ) { return source == this . source || source == SourceProvider . UNKNOWN_SOURCE ? this : new Errors ( this , source ) ; }


Input: Within guice s core allow for better missing binding messages [CODESPLIT] < T > Errors missingImplementationWithHint ( Key < T > key , Injector injector ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( format ( "No implementation for %s was bound." , key ) ) ; // Keys which have similar strings as the desired key List < String > possibleMatches = new ArrayList <> ( ) ; // Check for other keys that may have the same type, // but not the same annotation TypeLiteral < T > type = key . getTypeLiteral ( ) ; List < Binding < T > > sameTypes = injector . findBindingsByType ( type ) ; if ( ! sameTypes . isEmpty ( ) ) { sb . append ( format ( "%n  Did you mean?" ) ) ; int howMany = Math . min ( sameTypes . size ( ) , MAX_MATCHING_TYPES_REPORTED ) ; for ( int i = 0 ; i < howMany ; ++ i ) { // TODO: Look into a better way to prioritize suggestions. For example, possbily // use levenshtein distance of the given annotation vs actual annotation. sb . append ( format ( "%n    * %s" , sameTypes . get ( i ) . getKey ( ) ) ) ; } int remaining = sameTypes . size ( ) - MAX_MATCHING_TYPES_REPORTED ; if ( remaining > 0 ) { String plural = ( remaining == 1 ) ? "" : "s" ; sb . append ( format ( "%n    %d more binding%s with other annotations." , remaining , plural ) ) ; } } else { // For now, do a simple substring search for possibilities. This can help spot // issues when there are generics being used (such as a wrapper class) and the // user has forgotten they need to bind based on the wrapper, not the underlying // class. In the future, consider doing a strict in-depth type search. // TODO: Look into a better way to prioritize suggestions. For example, possbily // use levenshtein distance of the type literal strings. String want = type . toString ( ) ; Map < Key < ? > , Binding < ? > > bindingMap = injector . getAllBindings ( ) ; for ( Key < ? > bindingKey : bindingMap . keySet ( ) ) { String have = bindingKey . getTypeLiteral ( ) . toString ( ) ; if ( have . contains ( want ) || want . contains ( have ) ) { Formatter fmt = new Formatter ( ) ; Messages . formatSource ( fmt , bindingMap . get ( bindingKey ) . getSource ( ) ) ; String match = String . format ( "%s bound%s" , convert ( bindingKey ) , fmt . toString ( ) ) ; possibleMatches . add ( match ) ; // TODO: Consider a check that if there are more than some number of results, // don't suggest any. if ( possibleMatches . size ( ) > MAX_RELATED_TYPES_REPORTED ) { // Early exit if we have found more than we need. break ; } } } if ( ( possibleMatches . size ( ) > 0 ) && ( possibleMatches . size ( ) <= MAX_RELATED_TYPES_REPORTED ) ) { sb . append ( format ( "%n  Did you mean?" ) ) ; for ( String possibleMatch : possibleMatches ) { sb . append ( format ( "%n    %s" , possibleMatch ) ) ; } } } // If where are no possibilities to suggest, then handle the case of missing // annotations on simple types. This is usually a bad idea. if ( sameTypes . isEmpty ( ) && possibleMatches . isEmpty ( ) && key . getAnnotation ( ) == null && COMMON_AMBIGUOUS_TYPES . contains ( key . getTypeLiteral ( ) . getRawType ( ) ) ) { // We don't recommend using such simple types without annotations. sb . append ( format ( "%nThe key seems very generic, did you forget an annotation?" ) ) ; } return addMessage ( sb . toString ( ) ) ; }


Input: TODO ( lukes ) : inline into callers [CODESPLIT] public static String format ( String messageFormat , Object ... arguments ) { return Messages . format ( messageFormat , arguments ) ; }


Input: TODO ( lukes ) : inline in callers . There are some callers outside of guice so this is difficult [CODESPLIT] public static Object convert ( Object o , ElementSource source ) { return Messages . convert ( o , source ) ; }


Input: Implementation of newSetBinder . [CODESPLIT] public static < T > RealMultibinder < T > newRealSetBinder ( Binder binder , Key < T > key ) { binder = binder . skipSources ( RealMultibinder . class ) ; RealMultibinder < T > result = new RealMultibinder <> ( binder , key ) ; binder . install ( result ) ; return result ; }


Input: Adds a new entry to the set and returns the key for it . [CODESPLIT] Key < T > getKeyForNewItem ( ) { checkConfiguration ( ! bindingSelection . isInitialized ( ) , "Multibinder was already initialized" ) ; return Key . get ( bindingSelection . getElementTypeLiteral ( ) , new RealElement ( bindingSelection . getSetName ( ) , MULTIBINDER , "" ) ) ; }


Input: Iterates over the remaining filter definitions . Returns the first applicable filter or null if none apply . [CODESPLIT] private Filter findNextFilter ( HttpServletRequest request ) { while ( ++ index < filterDefinitions . length ) { Filter filter = filterDefinitions [ index ] . getFilterIfMatching ( request ) ; if ( filter != null ) { return filter ; } } return null ; }


Input: Returns true if the inject annotation is on the constructor . [CODESPLIT] private static boolean hasAtInject ( Constructor cxtor ) { return cxtor . isAnnotationPresent ( Inject . class ) || cxtor . isAnnotationPresent ( javax . inject . Inject . class ) ; }


Input: Returns an injection point that can be used to clean up the constructor store . [CODESPLIT] InjectionPoint getInternalConstructor ( ) { if ( factory . constructorInjector != null ) { return factory . constructorInjector . getConstructionProxy ( ) . getInjectionPoint ( ) ; } else { return constructorInjectionPoint ; } }


Input: Returns a set of dependencies that can be iterated over to clean up stray JIT bindings . [CODESPLIT] Set < Dependency < ? > > getInternalDependencies ( ) { ImmutableSet . Builder < InjectionPoint > builder = ImmutableSet . builder ( ) ; if ( factory . constructorInjector == null ) { builder . add ( constructorInjectionPoint ) ; // If the below throws, it's OK -- we just ignore those dependencies, because no one // could have used them anyway. try { builder . addAll ( InjectionPoint . forInstanceMethodsAndFields ( constructorInjectionPoint . getDeclaringType ( ) ) ) ; } catch ( ConfigurationException ignored ) { } } else { builder . add ( getConstructor ( ) ) . addAll ( getInjectableMembers ( ) ) ; } return Dependency . forInjectionPoints ( builder . build ( ) ) ; }


Input: / * if [ AOP ] [CODESPLIT] @ Override public Map < Method , List < org . aopalliance . intercept . MethodInterceptor > > getMethodInterceptors ( ) { checkState ( factory . constructorInjector != null , "Binding is not ready" ) ; return factory . constructorInjector . getConstructionProxy ( ) . getMethodInterceptors ( ) ; }


Input: / * end [ AOP ] [CODESPLIT] @ Override public Set < Dependency < ? > > getDependencies ( ) { return Dependency . forInjectionPoints ( new ImmutableSet . Builder < InjectionPoint > ( ) . add ( getConstructor ( ) ) . addAll ( getInjectableMembers ( ) ) . build ( ) ) ; }


Input: Returns the instance methods and fields of { @code instance } that will be injected to fulfill this request . [CODESPLIT] public Set < InjectionPoint > getInjectionPoints ( ) throws ConfigurationException { return InjectionPoint . forInstanceMethodsAndFields ( instance != null ? TypeLiteral . get ( instance . getClass ( ) ) : type ) ; }


Input: Gets the system option indicated by the specified key ; runs as a privileged action . [CODESPLIT] private static < T extends Enum < T > > T getSystemOption ( final String name , T defaultValue ) { return getSystemOption ( name , defaultValue , defaultValue ) ; }


Input: Gets the system option indicated by the specified key ; runs as a privileged action . [CODESPLIT] private static < T extends Enum < T > > T getSystemOption ( final String name , T defaultValue , T secureValue ) { Class < T > enumType = defaultValue . getDeclaringClass ( ) ; String value = null ; try { value = AccessController . doPrivileged ( new PrivilegedAction < String > ( ) { @ Override public String run ( ) { return System . getProperty ( name ) ; } } ) ; return ( value != null && value . length ( ) > 0 ) ? Enum . valueOf ( enumType , value ) : defaultValue ; } catch ( SecurityException e ) { return secureValue ; } catch ( IllegalArgumentException e ) { logger . warning ( value + " is not a valid flag value for " + name + ". " + " Values must be one of " + Arrays . asList ( enumType . getEnumConstants ( ) ) ) ; return defaultValue ; } }


Input: Returns a name for a Guice source object . This will typically be either a { [CODESPLIT] @ Override public String getSourceName ( Object source ) { if ( source instanceof ElementSource ) { source = ( ( ElementSource ) source ) . getDeclaringSource ( ) ; } if ( source instanceof Method ) { source = StackTraceElements . forMember ( ( Method ) source ) ; } if ( source instanceof StackTraceElement ) { return getFileString ( ( StackTraceElement ) source ) ; } return stripPackages ( source . toString ( ) ) ; }


Input: Returns a new parameterized type applying { @code typeArguments } to { @code rawType } . The returned type does not have an owner type . [CODESPLIT] public static ParameterizedType newParameterizedType ( Type rawType , Type ... typeArguments ) { return newParameterizedTypeWithOwner ( null , rawType , typeArguments ) ; }


Input: Returns a new parameterized type applying { @code typeArguments } to { @code rawType } and enclosed by { @code ownerType } . [CODESPLIT] public static ParameterizedType newParameterizedTypeWithOwner ( Type ownerType , Type rawType , Type ... typeArguments ) { return new ParameterizedTypeImpl ( ownerType , rawType , typeArguments ) ; }


Input: Returns a type modelling a { @link Map } whose keys are of type { @code keyType } and whose values are of type { @code valueType } . [CODESPLIT] public static ParameterizedType mapOf ( Type keyType , Type valueType ) { return newParameterizedType ( Map . class , keyType , valueType ) ; }


Input: Returns a type modelling a { @link javax . inject . Provider } that provides elements of type { @code elementType } . [CODESPLIT] public static Type javaxProviderOf ( Type type ) { return Types . newParameterizedType ( javax . inject . Provider . class , type ) ; }


Input: Returns a module which creates bindings methods in the module that match the scanner . [CODESPLIT] public static Module forModule ( Object module , ModuleAnnotatedMethodScanner scanner ) { return forObject ( module , false , scanner ) ; }


Input: Returns the annotation that is claimed by the scanner or null if there is none . [CODESPLIT] private Annotation getAnnotation ( Binder binder , Method method ) { if ( method . isBridge ( ) || method . isSynthetic ( ) ) { return null ; } Annotation annotation = null ; for ( Class < ? extends Annotation > annotationClass : scanner . annotationClasses ( ) ) { Annotation foundAnnotation = method . getAnnotation ( annotationClass ) ; if ( foundAnnotation != null ) { if ( annotation != null ) { binder . addError ( "More than one annotation claimed by %s on method %s." + " Methods can only have one annotation claimed per scanner." , scanner , method ) ; return null ; } annotation = foundAnnotation ; } } return annotation ; }


Input: Creates a constant binding to { [CODESPLIT] public static void bindProperties ( Binder binder , Map < String , String > properties ) { binder = binder . skipSources ( Names . class ) ; for ( Map . Entry < String , String > entry : properties . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; binder . bind ( Key . get ( String . class , new NamedImpl ( key ) ) ) . toInstance ( value ) ; } }


Input: Creates a constant binding to { [CODESPLIT] public static void bindProperties ( Binder binder , Properties properties ) { binder = binder . skipSources ( Names . class ) ; // use enumeration to include the default properties for ( Enumeration < ? > e = properties . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { String propertyName = ( String ) e . nextElement ( ) ; String value = properties . getProperty ( propertyName ) ; binder . bind ( Key . get ( String . class , new NamedImpl ( propertyName ) ) ) . toInstance ( value ) ; } }


Input: Creates an injector for the given set of modules in a given development stage . [CODESPLIT] public static Injector createInjector ( Stage stage , Module ... modules ) { return createInjector ( stage , Arrays . asList ( modules ) ) ; }


Input: Creates an injector for the given set of modules in a given development stage . [CODESPLIT] public static Injector createInjector ( Stage stage , Iterable < ? extends Module > modules ) { return new InternalInjectorCreator ( ) . stage ( stage ) . addModules ( modules ) . build ( ) ; }


Input: Returns the position of { @link com . google . inject . Module#configure configure ( Binder ) } method call in the { @link #getStackTrace stack trace } for modules that their classes returned by { @link #getModuleClassNames } . For example if the stack trace looks like the following : [CODESPLIT] public List < Integer > getModuleConfigurePositionsInStackTrace ( ) { int size = moduleSource . size ( ) ; Integer [ ] positions = new Integer [ size ] ; int chunkSize = partialCallStack . length ; positions [ 0 ] = chunkSize - 1 ; ModuleSource current = moduleSource ; for ( int cursor = 1 ; cursor < size ; cursor ++ ) { chunkSize = current . getPartialCallStackSize ( ) ; positions [ cursor ] = positions [ cursor - 1 ] + chunkSize ; current = current . getParent ( ) ; } return ImmutableList . < Integer > copyOf ( positions ) ; }


Input: Returns the sequence of method calls that ends at one of { [CODESPLIT] public StackTraceElement [ ] getStackTrace ( ) { int modulesCallStackSize = moduleSource . getStackTraceSize ( ) ; int chunkSize = partialCallStack . length ; int size = moduleSource . getStackTraceSize ( ) + chunkSize ; StackTraceElement [ ] callStack = new StackTraceElement [ size ] ; System . arraycopy ( StackTraceElements . convertToStackTraceElement ( partialCallStack ) , 0 , callStack , 0 , chunkSize ) ; System . arraycopy ( moduleSource . getStackTrace ( ) , 0 , callStack , chunkSize , modulesCallStackSize ) ; return callStack ; }


Input: Get the line number associated with the given member . [CODESPLIT] public Integer getLineNumber ( Member member ) { Preconditions . checkArgument ( type == member . getDeclaringClass ( ) , "Member %s belongs to %s, not %s" , member , member . getDeclaringClass ( ) , type ) ; return lines . get ( memberKey ( member ) ) ; }


Input: Initialize the specified lookups either immediately or when the injector is created . [CODESPLIT] void initialize ( Errors errors ) { injector . lookups = injector ; new LookupProcessor ( errors ) . process ( injector , lookups ) ; }


Input: Wraps the given callable in a contextual callable that continues the HTTP request in another thread . This acts as a way of transporting request context data from the request processing thread to to worker threads . [CODESPLIT] @ Deprecated public static < T > Callable < T > continueRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { return wrap ( callable , continueRequest ( seedMap ) ) ; }


Input: Wraps the given callable in a contextual callable that transfers the request to another thread . This acts as a way of transporting request context data from the current thread to a future thread . [CODESPLIT] public static < T > Callable < T > transferRequest ( Callable < T > callable ) { return wrap ( callable , transferRequest ( ) ) ; }


Input: Scopes the given callable inside a request scope . This is not the same as the HTTP request scope but is used if no HTTP request scope is in progress . In this way keys can be scoped as @RequestScoped and exist in non - HTTP requests ( for example : RPC requests ) as well as in HTTP request threads . [CODESPLIT] public static < T > Callable < T > scopeRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { return wrap ( callable , scopeRequest ( seedMap ) ) ; }


Input: Validates the key and object ensuring the value matches the key type and canonicalizing null objects to the null sentinel . [CODESPLIT] private static Object validateAndCanonicalizeValue ( Key < ? > key , Object object ) { if ( object == null || object == NullObject . INSTANCE ) { return NullObject . INSTANCE ; } if ( ! key . getTypeLiteral ( ) . getRawType ( ) . isInstance ( object ) ) { throw new IllegalArgumentException ( "Value[" + object + "] of type[" + object . getClass ( ) . getName ( ) + "] is not compatible with key[" + key + "]" ) ; } return object ; }


Input: Returns a new complete members injector with injection listeners registered . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) // the MembersInjector type always agrees with the passed type public < T > MembersInjectorImpl < T > get ( TypeLiteral < T > key , Errors errors ) throws ErrorsException { return ( MembersInjectorImpl < T > ) cache . get ( key , errors ) ; }


Input: Creates a new members injector and attaches both injection listeners and method aspects . [CODESPLIT] private < T > MembersInjectorImpl < T > createWithListeners ( TypeLiteral < T > type , Errors errors ) throws ErrorsException { int numErrorsBefore = errors . size ( ) ; Set < InjectionPoint > injectionPoints ; try { injectionPoints = InjectionPoint . forInstanceMethodsAndFields ( type ) ; } catch ( ConfigurationException e ) { errors . merge ( e . getErrorMessages ( ) ) ; injectionPoints = e . getPartialValue ( ) ; } ImmutableList < SingleMemberInjector > injectors = getInjectors ( injectionPoints , errors ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; EncounterImpl < T > encounter = new EncounterImpl <> ( errors , injector . lookups ) ; Set < TypeListener > alreadySeenListeners = Sets . newHashSet ( ) ; for ( TypeListenerBinding binding : typeListenerBindings ) { TypeListener typeListener = binding . getListener ( ) ; if ( ! alreadySeenListeners . contains ( typeListener ) && binding . getTypeMatcher ( ) . matches ( type ) ) { alreadySeenListeners . add ( typeListener ) ; try { typeListener . hear ( type , encounter ) ; } catch ( RuntimeException e ) { errors . errorNotifyingTypeListener ( binding , type , e ) ; } } } encounter . invalidate ( ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; return new MembersInjectorImpl < T > ( injector , type , encounter , injectors ) ; }


Input: Returns the injectors for the specified injection points . [CODESPLIT] ImmutableList < SingleMemberInjector > getInjectors ( Set < InjectionPoint > injectionPoints , Errors errors ) { List < SingleMemberInjector > injectors = Lists . newArrayList ( ) ; for ( InjectionPoint injectionPoint : injectionPoints ) { try { Errors errorsForMember = injectionPoint . isOptional ( ) ? new Errors ( injectionPoint ) : errors . withSource ( injectionPoint ) ; SingleMemberInjector injector = injectionPoint . getMember ( ) instanceof Field ? new SingleFieldInjector ( this . injector , injectionPoint , errorsForMember ) : new SingleMethodInjector ( this . injector , injectionPoint , errorsForMember ) ; injectors . add ( injector ) ; } catch ( ErrorsException ignoredForNow ) { // ignored for now } } return ImmutableList . copyOf ( injectors ) ; }


Input: VisibleForTesting [CODESPLIT] @ Inject static void setPipeline ( FilterPipeline pipeline ) { // This can happen if you create many injectors and they all have their own // servlet module. This is legal, caveat a small warning. if ( GuiceFilter . pipeline instanceof ManagedFilterPipeline ) { LOGGER . warning ( MULTIPLE_INJECTORS_WARNING ) ; } // We overwrite the default pipeline GuiceFilter . pipeline = pipeline ; }


Input: Gets a key for an injection type and an annotation strategy . [CODESPLIT] static < T > Key < T > get ( Class < T > type , AnnotationStrategy annotationStrategy ) { return new Key < T > ( type , annotationStrategy ) ; }


Input: Gets a key for an injection type . [CODESPLIT] public static < T > Key < T > get ( Class < T > type ) { return new Key < T > ( type , NullAnnotationStrategy . INSTANCE ) ; }


Input: Gets a key for an injection type and an annotation type . [CODESPLIT] public static < T > Key < T > get ( Class < T > type , Class < ? extends Annotation > annotationType ) { return new Key < T > ( type , strategyFor ( annotationType ) ) ; }


Input: Gets a key for an injection type and an annotation . [CODESPLIT] public static < T > Key < T > get ( Class < T > type , Annotation annotation ) { return new Key < T > ( type , strategyFor ( annotation ) ) ; }


Input: Gets a key for an injection type and an annotation type . [CODESPLIT] public static Key < ? > get ( Type type , Class < ? extends Annotation > annotationType ) { return new Key < Object > ( type , strategyFor ( annotationType ) ) ; }


Input: Gets a key for an injection type and an annotation . [CODESPLIT] public static Key < ? > get ( Type type , Annotation annotation ) { return new Key < Object > ( type , strategyFor ( annotation ) ) ; }


Input: Gets a key for an injection type . [CODESPLIT] public static < T > Key < T > get ( TypeLiteral < T > typeLiteral ) { return new Key < T > ( typeLiteral , NullAnnotationStrategy . INSTANCE ) ; }


Input: Gets a key for an injection type and an annotation type . [CODESPLIT] public static < T > Key < T > get ( TypeLiteral < T > typeLiteral , Class < ? extends Annotation > annotationType ) { return new Key < T > ( typeLiteral , strategyFor ( annotationType ) ) ; }


Input: Gets a key for an injection type and an annotation . [CODESPLIT] public static < T > Key < T > get ( TypeLiteral < T > typeLiteral , Annotation annotation ) { return new Key < T > ( typeLiteral , strategyFor ( annotation ) ) ; }


Input: Returns a new key of the specified type with the same annotation as this key . [CODESPLIT] public < T > Key < T > ofType ( Class < T > type ) { return new Key < T > ( type , annotationStrategy ) ; }


Input: Returns a new key of the specified type with the same annotation as this key . [CODESPLIT] public < T > Key < T > ofType ( TypeLiteral < T > type ) { return new Key < T > ( type , annotationStrategy ) ; }


Input: Gets the strategy for an annotation . [CODESPLIT] static AnnotationStrategy strategyFor ( Annotation annotation ) { checkNotNull ( annotation , "annotation" ) ; Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; ensureRetainedAtRuntime ( annotationType ) ; ensureIsBindingAnnotation ( annotationType ) ; if ( Annotations . isMarker ( annotationType ) ) { return new AnnotationTypeStrategy ( annotationType , annotation ) ; } return new AnnotationInstanceStrategy ( Annotations . canonicalizeIfNamed ( annotation ) ) ; }


Input: Gets the strategy for an annotation type . [CODESPLIT] static AnnotationStrategy strategyFor ( Class < ? extends Annotation > annotationType ) { annotationType = Annotations . canonicalizeIfNamed ( annotationType ) ; if ( isAllDefaultMethods ( annotationType ) ) { return strategyFor ( generateAnnotation ( annotationType ) ) ; } checkNotNull ( annotationType , "annotation type" ) ; ensureRetainedAtRuntime ( annotationType ) ; ensureIsBindingAnnotation ( annotationType ) ; return new AnnotationTypeStrategy ( annotationType , null ) ; }


Input: Records the elements executed by { [CODESPLIT] public static List < Element > getElements ( Module ... modules ) { return getElements ( Stage . DEVELOPMENT , Arrays . asList ( modules ) ) ; }


Input: Records the elements executed by { [CODESPLIT] public static List < Element > getElements ( Iterable < ? extends Module > modules ) { return getElements ( Stage . DEVELOPMENT , modules ) ; }


Input: Records the elements executed by { [CODESPLIT] public static List < Element > getElements ( Stage stage , Iterable < ? extends Module > modules ) { RecordingBinder binder = new RecordingBinder ( stage ) ; for ( Module module : modules ) { binder . install ( module ) ; } binder . scanForAnnotatedMethods ( ) ; for ( RecordingBinder child : binder . privateBinders ) { child . scanForAnnotatedMethods ( ) ; } // Free the memory consumed by the stack trace elements cache StackTraceElements . clearCache ( ) ; return Collections . unmodifiableList ( binder . elements ) ; }


Input: Removes stacktrace elements related to AOP internal mechanics from the throwable s stack trace and any causes it may have . [CODESPLIT] private void pruneStacktrace ( Throwable throwable ) { for ( Throwable t = throwable ; t != null ; t = t . getCause ( ) ) { StackTraceElement [ ] stackTrace = t . getStackTrace ( ) ; List < StackTraceElement > pruned = Lists . newArrayList ( ) ; for ( StackTraceElement element : stackTrace ) { String className = element . getClassName ( ) ; if ( ! AOP_INTERNAL_CLASSES . contains ( className ) && ! className . contains ( "$EnhancerByGuice$" ) ) { pruned . add ( element ) ; } } t . setStackTrace ( pruned . toArray ( new StackTraceElement [ pruned . size ( ) ] ) ) ; } }


Input: Returns a new { [CODESPLIT] @ SuppressWarnings ( "unchecked" ) // the ProvisionListenerStackCallback type always agrees with the passed type public < T > ProvisionListenerStackCallback < T > get ( Binding < T > binding ) { // Never notify any listeners for internal bindings. if ( ! INTERNAL_BINDINGS . contains ( binding . getKey ( ) ) ) { ProvisionListenerStackCallback < T > callback = ( ProvisionListenerStackCallback < T > ) cache . getUnchecked ( new KeyBinding ( binding . getKey ( ) , binding ) ) ; return callback . hasListeners ( ) ? callback : null ; } return null ; }


Input: Creates a new { [CODESPLIT] private < T > ProvisionListenerStackCallback < T > create ( Binding < T > binding ) { List < ProvisionListener > listeners = null ; for ( ProvisionListenerBinding provisionBinding : listenerBindings ) { if ( provisionBinding . getBindingMatcher ( ) . matches ( binding ) ) { if ( listeners == null ) { listeners = Lists . newArrayList ( ) ; } listeners . addAll ( provisionBinding . getListeners ( ) ) ; } } if ( listeners == null || listeners . isEmpty ( ) ) { // Optimization: don't bother constructing the callback if there are // no listeners. return ProvisionListenerStackCallback . emptyListener ( ) ; } return new ProvisionListenerStackCallback < T > ( binding , listeners ) ; }


Input: Returns a string describing where this dependency was bound . If the binding was just - in - time there is no valid binding source so this describes the class in question . [CODESPLIT] public String getBindingSource ( ) { if ( source instanceof Class ) { return StackTraceElements . forType ( ( Class ) source ) . toString ( ) ; } else if ( source instanceof Member ) { return StackTraceElements . forMember ( ( Member ) source ) . toString ( ) ; } else { return source . toString ( ) ; } }


Input: / * if [ AOP ] [CODESPLIT] ImmutableList < MethodAspect > getAspects ( ) { return aspects == null ? ImmutableList . < MethodAspect > of ( ) : ImmutableList . copyOf ( aspects ) ; }


Input: / * end [ AOP ] [CODESPLIT] ImmutableSet < MembersInjector < ? super T > > getMembersInjectors ( ) { return membersInjectors == null ? ImmutableSet . < MembersInjector < ? super T > > of ( ) : ImmutableSet . copyOf ( membersInjectors ) ; }


Input: Prepends the list of sources to the given { [CODESPLIT] static Message mergeSources ( List < Object > sources , Message message ) { List < Object > messageSources = message . getSources ( ) ; // It is possible that the end of getSources() and the beginning of message.getSources() are // equivalent, in this case we should drop the repeated source when joining the lists.  The // most likely scenario where this would happen is when a scoped binding throws an exception, // due to the fact that InternalFactoryToProviderAdapter applies the binding source when // merging errors. if ( ! sources . isEmpty ( ) && ! messageSources . isEmpty ( ) && Objects . equal ( messageSources . get ( 0 ) , sources . get ( sources . size ( ) - 1 ) ) ) { messageSources = messageSources . subList ( 1 , messageSources . size ( ) ) ; } return new Message ( ImmutableList . builder ( ) . addAll ( sources ) . addAll ( messageSources ) . build ( ) , message . getMessage ( ) , message . getCause ( ) ) ; }


Input: Calls { [CODESPLIT] public static String format ( String messageFormat , Object ... arguments ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { arguments [ i ] = convert ( arguments [ i ] ) ; } return String . format ( messageFormat , arguments ) ; }


Input: Returns the formatted message for an exception with the specified messages . [CODESPLIT] public static String formatMessages ( String heading , Collection < Message > errorMessages ) { Formatter fmt = new Formatter ( ) . format ( heading ) . format ( ":%n%n" ) ; int index = 1 ; boolean displayCauses = getOnlyCause ( errorMessages ) == null ; Map < Equivalence . Wrapper < Throwable > , Integer > causes = Maps . newHashMap ( ) ; for ( Message errorMessage : errorMessages ) { int thisIdx = index ++ ; fmt . format ( "%s) %s%n" , thisIdx , errorMessage . getMessage ( ) ) ; List < Object > dependencies = errorMessage . getSources ( ) ; for ( int i = dependencies . size ( ) - 1 ; i >= 0 ; i -- ) { Object source = dependencies . get ( i ) ; formatSource ( fmt , source ) ; } Throwable cause = errorMessage . getCause ( ) ; if ( displayCauses && cause != null ) { Equivalence . Wrapper < Throwable > causeEquivalence = ThrowableEquivalence . INSTANCE . wrap ( cause ) ; if ( ! causes . containsKey ( causeEquivalence ) ) { causes . put ( causeEquivalence , thisIdx ) ; fmt . format ( "Caused by: %s" , Throwables . getStackTraceAsString ( cause ) ) ; } else { int causeIdx = causes . get ( causeEquivalence ) ; fmt . format ( "Caused by: %s (same stack trace as error #%s)" , cause . getClass ( ) . getName ( ) , causeIdx ) ; } } fmt . format ( "%n" ) ; } if ( errorMessages . size ( ) == 1 ) { fmt . format ( "1 error" ) ; } else { fmt . format ( "%s errors" , errorMessages . size ( ) ) ; } return fmt . toString ( ) ; }


Input: Creates a new Message without a cause . [CODESPLIT] public static Message create ( String messageFormat , Object ... arguments ) { return create ( null , messageFormat , arguments ) ; }


Input: Creates a new Message with the given cause . [CODESPLIT] public static Message create ( Throwable cause , String messageFormat , Object ... arguments ) { return create ( cause , ImmutableList . of ( ) , messageFormat , arguments ) ; }


Input: Creates a new Message with the given cause and a binding source stack . [CODESPLIT] public static Message create ( Throwable cause , List < Object > sources , String messageFormat , Object ... arguments ) { String message = format ( messageFormat , arguments ) ; return new Message ( sources , message , cause ) ; }


Input: Formats an object in a user friendly way . [CODESPLIT] static Object convert ( Object o ) { ElementSource source = null ; if ( o instanceof ElementSource ) { source = ( ElementSource ) o ; o = source . getDeclaringSource ( ) ; } return convert ( o , source ) ; }


Input: Returns the cause throwable if there is exactly one cause in { [CODESPLIT] public static Throwable getOnlyCause ( Collection < Message > messages ) { Throwable onlyCause = null ; for ( Message message : messages ) { Throwable messageCause = message . getCause ( ) ; if ( messageCause == null ) { continue ; } if ( onlyCause != null && ! ThrowableEquivalence . INSTANCE . equivalent ( onlyCause , messageCause ) ) { return null ; } onlyCause = messageCause ; } return onlyCause ; }


Input: Returns the class names of modules in this module source . The first element ( index 0 ) is filled by this object { [CODESPLIT] List < String > getModuleClassNames ( ) { ImmutableList . Builder < String > classNames = ImmutableList . builder ( ) ; ModuleSource current = this ; while ( current != null ) { String className = current . moduleClassName ; classNames . add ( className ) ; current = current . parent ; } return classNames . build ( ) ; }


Input: Returns the full call stack that ends just before the module { [CODESPLIT] StackTraceElement [ ] getStackTrace ( ) { int stackTraceSize = getStackTraceSize ( ) ; StackTraceElement [ ] callStack = new StackTraceElement [ stackTraceSize ] ; int cursor = 0 ; ModuleSource current = this ; while ( current != null ) { StackTraceElement [ ] chunk = StackTraceElements . convertToStackTraceElement ( current . partialCallStack ) ; int chunkSize = chunk . length ; System . arraycopy ( chunk , 0 , callStack , cursor , chunkSize ) ; current = current . parent ; cursor = cursor + chunkSize ; } return callStack ; }


Input: Creates an injector defined by { @code modules } and immediately uses it to create an instance of { @code type } . The modules can be of any type and must contain { @code @Provides } methods . [CODESPLIT] public static < T > T inject ( Class < T > type , Object ... modules ) { Key key = new Key ( type , null ) ; MiniGuice miniGuice = new MiniGuice ( ) ; for ( Object module : modules ) { miniGuice . install ( module ) ; } miniGuice . requireKey ( key , "root injection" ) ; miniGuice . addJitBindings ( ) ; miniGuice . addProviderBindings ( ) ; miniGuice . eagerlyLoadSingletons ( ) ; Provider < ? > provider = miniGuice . bindings . get ( key ) ; return type . cast ( provider . get ( ) ) ; }


Input: Returns true if the className should be skipped . [CODESPLIT] private boolean shouldBeSkipped ( String className ) { return ( parent != null && parent . shouldBeSkipped ( className ) ) || classNamesToSkip . contains ( className ) ; }


Input: Returns the class names as Strings [CODESPLIT] private static List < String > asStrings ( Class ... classes ) { List < String > strings = Lists . newArrayList ( ) ; for ( Class c : classes ) { strings . add ( c . getName ( ) ) ; } return strings ; }


Input: Returns the calling line of code . The selected line is the nearest to the top of the stack that is not skipped . [CODESPLIT] public StackTraceElement get ( StackTraceElement [ ] stackTraceElements ) { Preconditions . checkNotNull ( stackTraceElements , "The stack trace elements cannot be null." ) ; for ( final StackTraceElement element : stackTraceElements ) { String className = element . getClassName ( ) ; if ( ! shouldBeSkipped ( className ) ) { return element ; } } throw new AssertionError ( ) ; }


Input: Returns the non - skipped module class name . [CODESPLIT] public Object getFromClassNames ( List < String > moduleClassNames ) { Preconditions . checkNotNull ( moduleClassNames , "The list of module class names cannot be null." ) ; for ( final String moduleClassName : moduleClassNames ) { if ( ! shouldBeSkipped ( moduleClassName ) ) { return new StackTraceElement ( moduleClassName , "configure" , null , - 1 ) ; } } return UNKNOWN_SOURCE ; }


Input: Registers all the bindings of an Injector with the platform MBean server . Consider using the name of your root { [CODESPLIT] public static void manage ( String domain , Injector injector ) { manage ( ManagementFactory . getPlatformMBeanServer ( ) , domain , injector ) ; }


Input: Registers all the bindings of an Injector with the given MBean server . Consider using the name of your root { [CODESPLIT] public static void manage ( MBeanServer server , String domain , Injector injector ) { // Register each binding independently. for ( Binding < ? > binding : injector . getBindings ( ) . values ( ) ) { // Construct the name manually so we can ensure proper ordering of the // key/value pairs. StringBuilder name = new StringBuilder ( ) ; name . append ( domain ) . append ( ":" ) ; Key < ? > key = binding . getKey ( ) ; name . append ( "type=" ) . append ( quote ( key . getTypeLiteral ( ) . toString ( ) ) ) ; Annotation annotation = key . getAnnotation ( ) ; if ( annotation != null ) { name . append ( ",annotation=" ) . append ( quote ( annotation . toString ( ) ) ) ; } else { Class < ? extends Annotation > annotationType = key . getAnnotationType ( ) ; if ( annotationType != null ) { name . append ( ",annotation=" ) . append ( quote ( "@" + annotationType . getName ( ) ) ) ; } } try { server . registerMBean ( new ManagedBinding ( binding ) , new ObjectName ( name . toString ( ) ) ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( "Bad object name: " + name , e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }


Input: Run with no arguments for usage instructions . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { if ( args . length != 1 ) { System . err . println ( "Usage: java -Dcom.sun.management.jmxremote " + Manager . class . getName ( ) + " [module class name]" ) ; System . err . println ( "Then run 'jconsole' to connect." ) ; System . exit ( 1 ) ; } Module module = ( Module ) Class . forName ( args [ 0 ] ) . newInstance ( ) ; Injector injector = Guice . createInjector ( module ) ; manage ( args [ 0 ] , injector ) ; System . out . println ( "Press Ctrl+C to exit..." ) ; // Sleep forever. Thread . sleep ( Long . MAX_VALUE ) ; }


Input: Returns encoded in - memory version of { [CODESPLIT] public static InMemoryStackTraceElement [ ] convertToInMemoryStackTraceElement ( StackTraceElement [ ] stackTraceElements ) { if ( stackTraceElements . length == 0 ) { return EMPTY_INMEMORY_STACK_TRACE ; } InMemoryStackTraceElement [ ] inMemoryStackTraceElements = new InMemoryStackTraceElement [ stackTraceElements . length ] ; for ( int i = 0 ; i < stackTraceElements . length ; i ++ ) { inMemoryStackTraceElements [ i ] = weakIntern ( new InMemoryStackTraceElement ( stackTraceElements [ i ] ) ) ; } return inMemoryStackTraceElements ; }


Input: Decodes in - memory stack trace elements to regular { [CODESPLIT] public static StackTraceElement [ ] convertToStackTraceElement ( InMemoryStackTraceElement [ ] inMemoryStackTraceElements ) { if ( inMemoryStackTraceElements . length == 0 ) { return EMPTY_STACK_TRACE ; } StackTraceElement [ ] stackTraceElements = new StackTraceElement [ inMemoryStackTraceElements . length ] ; for ( int i = 0 ; i < inMemoryStackTraceElements . length ; i ++ ) { String declaringClass = inMemoryStackTraceElements [ i ] . getClassName ( ) ; String methodName = inMemoryStackTraceElements [ i ] . getMethodName ( ) ; int lineNumber = inMemoryStackTraceElements [ i ] . getLineNumber ( ) ; stackTraceElements [ i ] = new StackTraceElement ( declaringClass , methodName , UNKNOWN_SOURCE , lineNumber ) ; } return stackTraceElements ; }


Input: Sets the new current dependency & adds it to the state . [CODESPLIT] Dependency < ? > pushDependency ( Dependency < ? > dependency , Object source ) { Dependency < ? > previous = this . dependency ; this . dependency = dependency ; doPushState ( dependency , source ) ; return previous ; }


Input: Adds to the state without setting the dependency . [CODESPLIT] void pushState ( com . google . inject . Key < ? > key , Object source ) { doPushState ( key , source ) ; }


Input: Returns the current dependency chain ( all the state stored in the dependencyStack ) . [CODESPLIT] java . util . List < com . google . inject . spi . DependencyAndSource > getDependencyChain ( ) { com . google . common . collect . ImmutableList . Builder < com . google . inject . spi . DependencyAndSource > builder = com . google . common . collect . ImmutableList . builder ( ) ; for ( int i = 0 ; i < dependencyStackSize ; i += 2 ) { Object evenEntry = dependencyStack [ i ] ; Dependency < ? > dependency ; if ( evenEntry instanceof com . google . inject . Key ) { dependency = Dependency . get ( ( com . google . inject . Key < ? > ) evenEntry ) ; } else { dependency = ( Dependency < ? > ) evenEntry ; } builder . add ( new com . google . inject . spi . DependencyAndSource ( dependency , dependencyStack [ i + 1 ] ) ) ; } return builder . build ( ) ; }


Input: Returns an initializable for an instance that requires no initialization . [CODESPLIT] static < T > Initializable < T > of ( final T instance ) { return new Initializable < T > ( ) { @ Override public T get ( ) { return instance ; } @ Override public String toString ( ) { return String . valueOf ( instance ) ; } } ; }


Input: Utility that delegates to the actual service method of the servlet wrapped with a contextual request ( i . e . with correctly computed path info ) . [CODESPLIT] void doService ( final ServletRequest servletRequest , ServletResponse servletResponse ) throws ServletException , IOException { HttpServletRequest request = new HttpServletRequestWrapper ( ( HttpServletRequest ) servletRequest ) { private boolean pathComputed ; private String path ; private boolean pathInfoComputed ; private String pathInfo ; @ Override public String getPathInfo ( ) { if ( ! isPathInfoComputed ( ) ) { String servletPath = getServletPath ( ) ; int servletPathLength = servletPath . length ( ) ; String requestUri = getRequestURI ( ) ; pathInfo = requestUri . substring ( getContextPath ( ) . length ( ) ) . replaceAll ( "[/]{2,}" , "/" ) ; // See: https://github.com/google/guice/issues/372 if ( pathInfo . startsWith ( servletPath ) ) { pathInfo = pathInfo . substring ( servletPathLength ) ; // Corner case: when servlet path & request path match exactly (without trailing '/'), // then pathinfo is null. if ( pathInfo . isEmpty ( ) && servletPathLength > 0 ) { pathInfo = null ; } else { try { pathInfo = new URI ( pathInfo ) . getPath ( ) ; } catch ( URISyntaxException e ) { // ugh, just leave it alone then } } } else { pathInfo = null ; // we know nothing additional about the URI. } pathInfoComputed = true ; } return pathInfo ; } // NOTE(dhanji): These two are a bit of a hack to help ensure that request dispatcher-sent // requests don't use the same path info that was memoized for the original request. // NOTE(iqshum): I don't think this is possible, since the dispatcher-sent request would // perform its own wrapping. private boolean isPathInfoComputed ( ) { return pathInfoComputed && servletRequest . getAttribute ( REQUEST_DISPATCHER_REQUEST ) == null ; } private boolean isPathComputed ( ) { return pathComputed && servletRequest . getAttribute ( REQUEST_DISPATCHER_REQUEST ) == null ; } @ Override public String getServletPath ( ) { return computePath ( ) ; } @ Override public String getPathTranslated ( ) { final String info = getPathInfo ( ) ; return ( null == info ) ? null : getRealPath ( info ) ; } // Memoizer pattern. private String computePath ( ) { if ( ! isPathComputed ( ) ) { String servletPath = super . getServletPath ( ) ; path = patternMatcher . extractPath ( servletPath ) ; pathComputed = true ; if ( null == path ) { path = servletPath ; } } return path ; } } ; doServiceImpl ( request , ( HttpServletResponse ) servletResponse ) ; }


Input: Provisions a new instance . Subclasses should override this to catch exceptions & rethrow as ErrorsExceptions . [CODESPLIT] protected T provision ( Provider < ? extends T > provider , Dependency < ? > dependency , ConstructionContext < T > constructionContext ) throws InternalProvisionException { T t = provider . get ( ) ; if ( t == null && ! dependency . isNullable ( ) ) { InternalProvisionException . onNullInjectedIntoNonNullableDependency ( source , dependency ) ; } constructionContext . setProxyDelegates ( t ) ; return t ; }


Input: Dispatch events . [CODESPLIT] public void onEvent ( ConnectionEventType type , String remoteAddr , Connection conn ) { List < ConnectionEventProcessor > processorList = this . processors . get ( type ) ; if ( processorList != null ) { for ( ConnectionEventProcessor processor : processorList ) { processor . onEvent ( remoteAddr , conn ) ; } } }


Input: Add event processor . [CODESPLIT] public void addConnectionEventProcessor ( ConnectionEventType type , ConnectionEventProcessor processor ) { List < ConnectionEventProcessor > processorList = this . processors . get ( type ) ; if ( processorList == null ) { this . processors . putIfAbsent ( type , new ArrayList < ConnectionEventProcessor > ( 1 ) ) ; processorList = this . processors . get ( type ) ; } processorList . add ( processor ) ; }


Input: get the result of a future task [CODESPLIT] public static < T > T getFutureTaskResult ( RunStateRecordedFutureTask < T > task , Logger logger ) { T t = null ; if ( null != task ) { try { t = task . getAfterRun ( ) ; } catch ( InterruptedException e ) { logger . error ( "Future task interrupted!" , e ) ; } catch ( ExecutionException e ) { logger . error ( "Future task execute failed!" , e ) ; } catch ( FutureTaskNotRunYetException e ) { logger . error ( "Future task has not run yet!" , e ) ; } catch ( FutureTaskNotCompleted e ) { logger . error ( "Future task has not completed!" , e ) ; } } return t ; }


Input: launder the throwable [CODESPLIT] public static void launderThrowable ( Throwable t ) { if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } else { throw new IllegalStateException ( "Not unchecked!" , t ) ; } }


Input: Register processor to process command that has the command code of cmdCode . [CODESPLIT] public void registerProcessor ( CommandCode cmdCode , RemotingProcessor < ? > processor ) { if ( this . cmd2processors . containsKey ( cmdCode ) ) { logger . warn ( "Processor for cmd={} is already registered, the processor is {}, and changed to {}" , cmdCode , cmd2processors . get ( cmdCode ) . getClass ( ) . getName ( ) , processor . getClass ( ) . getName ( ) ) ; } this . cmd2processors . put ( cmdCode , processor ) ; }


Input: Register the default processor to process command with no specific processor registered . [CODESPLIT] public void registerDefaultProcessor ( RemotingProcessor < ? > processor ) { if ( this . defaultProcessor == null ) { this . defaultProcessor = processor ; } else { throw new IllegalStateException ( "The defaultProcessor has already been registered: " + this . defaultProcessor . getClass ( ) ) ; } }


Input: Get the specific processor with command code of cmdCode if registered otherwise the default processor is returned . [CODESPLIT] public RemotingProcessor < ? > getProcessor ( CommandCode cmdCode ) { RemotingProcessor < ? > processor = this . cmd2processors . get ( cmdCode ) ; if ( processor != null ) { return processor ; } return this . defaultProcessor ; }


Input: try get from cache [CODESPLIT] private Url tryGet ( String url ) { SoftReference < Url > softRef = Url . parsedUrls . get ( url ) ; return ( null == softRef ) ? null : softRef . get ( ) ; }


Input: decode the protocol code [CODESPLIT] protected ProtocolCode decodeProtocolCode ( ByteBuf in ) { if ( in . readableBytes ( ) >= protocolCodeLength ) { byte [ ] protocolCodeBytes = new byte [ protocolCodeLength ] ; in . readBytes ( protocolCodeBytes ) ; return ProtocolCode . fromBytes ( protocolCodeBytes ) ; } return null ; }


Input: Get all connections of all poolKey . [CODESPLIT] @ Override public Map < String , List < Connection > > getAll ( ) { Map < String , List < Connection > > allConnections = new HashMap < String , List < Connection > > ( ) ; Iterator < Map . Entry < String , RunStateRecordedFutureTask < ConnectionPool > > > iterator = this . getConnPools ( ) . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < String , RunStateRecordedFutureTask < ConnectionPool > > entry = iterator . next ( ) ; ConnectionPool pool = FutureTaskUtil . getFutureTaskResult ( entry . getValue ( ) , logger ) ; if ( null != pool ) { allConnections . put ( entry . getKey ( ) , pool . getAll ( ) ) ; } } return allConnections ; }


Input: Warning! This is weakly consistent implementation to prevent lock the whole { @link ConcurrentHashMap } . [CODESPLIT] @ Override public void removeAll ( ) { if ( null == this . connTasks || this . connTasks . isEmpty ( ) ) { return ; } if ( null != this . connTasks && ! this . connTasks . isEmpty ( ) ) { Iterator < String > iter = this . connTasks . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String poolKey = iter . next ( ) ; this . removeTask ( poolKey ) ; iter . remove ( ) ; } logger . warn ( "All connection pool and connections have been removed!" ) ; } }


Input: in case of cache pollution and connection leak to do schedule scan [CODESPLIT] @ Override public void scan ( ) { if ( null != this . connTasks && ! this . connTasks . isEmpty ( ) ) { Iterator < String > iter = this . connTasks . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String poolKey = iter . next ( ) ; ConnectionPool pool = this . getConnectionPool ( this . connTasks . get ( poolKey ) ) ; if ( null != pool ) { pool . scan ( ) ; if ( pool . isEmpty ( ) ) { if ( ( System . currentTimeMillis ( ) - pool . getLastAccessTimestamp ( ) ) > DEFAULT_EXPIRE_TIME ) { iter . remove ( ) ; logger . warn ( "Remove expired pool task of poolKey {} which is empty." , poolKey ) ; } } } } } }


Input: If no task cached create one and initialize the connections . [CODESPLIT] @ Override public Connection getAndCreateIfAbsent ( Url url ) throws InterruptedException , RemotingException { // get and create a connection pool with initialized connections. ConnectionPool pool = this . getConnectionPoolAndCreateIfAbsent ( url . getUniqueKey ( ) , new ConnectionPoolCall ( url ) ) ; if ( null != pool ) { return pool . get ( ) ; } else { logger . error ( "[NOTIFYME] bug detected! pool here must not be null!" ) ; return null ; } }


Input: If no task cached create one and initialize the connections . If task cached check whether the number of connections adequate if not then heal it . [CODESPLIT] @ Override public void createConnectionAndHealIfNeed ( Url url ) throws InterruptedException , RemotingException { // get and create a connection pool with initialized connections. ConnectionPool pool = this . getConnectionPoolAndCreateIfAbsent ( url . getUniqueKey ( ) , new ConnectionPoolCall ( url ) ) ; if ( null != pool ) { healIfNeed ( pool , url ) ; } else { logger . error ( "[NOTIFYME] bug detected! pool here must not be null!" ) ; } }


Input: Get the mapping instance of { @link ConnectionPool } with the specified poolKey or create one if there is none mapping in connTasks . [CODESPLIT] private ConnectionPool getConnectionPoolAndCreateIfAbsent ( String poolKey , Callable < ConnectionPool > callable ) throws RemotingException , InterruptedException { RunStateRecordedFutureTask < ConnectionPool > initialTask = null ; ConnectionPool pool = null ; int retry = DEFAULT_RETRY_TIMES ; int timesOfResultNull = 0 ; int timesOfInterrupt = 0 ; for ( int i = 0 ; ( i < retry ) && ( pool == null ) ; ++ i ) { initialTask = this . connTasks . get ( poolKey ) ; if ( null == initialTask ) { initialTask = new RunStateRecordedFutureTask < ConnectionPool > ( callable ) ; initialTask = this . connTasks . putIfAbsent ( poolKey , initialTask ) ; if ( null == initialTask ) { initialTask = this . connTasks . get ( poolKey ) ; initialTask . run ( ) ; } } try { pool = initialTask . get ( ) ; if ( null == pool ) { if ( i + 1 < retry ) { timesOfResultNull ++ ; continue ; } this . connTasks . remove ( poolKey ) ; String errMsg = "Get future task result null for poolKey [" + poolKey + "] after [" + ( timesOfResultNull + 1 ) + "] times try." ; throw new RemotingException ( errMsg ) ; } } catch ( InterruptedException e ) { if ( i + 1 < retry ) { timesOfInterrupt ++ ; continue ; // retry if interrupted } this . connTasks . remove ( poolKey ) ; logger . warn ( "Future task of poolKey {} interrupted {} times. InterruptedException thrown and stop retry." , poolKey , ( timesOfInterrupt + 1 ) , e ) ; throw e ; } catch ( ExecutionException e ) { // DO NOT retry if ExecutionException occurred this . connTasks . remove ( poolKey ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RemotingException ) { throw ( RemotingException ) cause ; } else { FutureTaskUtil . launderThrowable ( cause ) ; } } } return pool ; }


Input: remove task and remove all connections [CODESPLIT] private void removeTask ( String poolKey ) { RunStateRecordedFutureTask < ConnectionPool > task = this . connTasks . remove ( poolKey ) ; if ( null != task ) { ConnectionPool pool = FutureTaskUtil . getFutureTaskResult ( task , logger ) ; if ( null != pool ) { pool . removeAllAndTryClose ( ) ; } } }


Input: execute heal connection tasks if the actual number of connections in pool is less than expected [CODESPLIT] private void healIfNeed ( ConnectionPool pool , Url url ) throws RemotingException , InterruptedException { String poolKey = url . getUniqueKey ( ) ; // only when async creating connections done // and the actual size of connections less than expected, the healing task can be run. if ( pool . isAsyncCreationDone ( ) && pool . size ( ) < url . getConnNum ( ) ) { FutureTask < Integer > task = this . healTasks . get ( poolKey ) ; if ( null == task ) { task = new FutureTask < Integer > ( new HealConnectionCall ( url , pool ) ) ; task = this . healTasks . putIfAbsent ( poolKey , task ) ; if ( null == task ) { task = this . healTasks . get ( poolKey ) ; task . run ( ) ; } } try { int numAfterHeal = task . get ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "[NOTIFYME] - conn num after heal {}, expected {}, warmup {}" , numAfterHeal , url . getConnNum ( ) , url . isConnWarmup ( ) ) ; } } catch ( InterruptedException e ) { this . healTasks . remove ( poolKey ) ; throw e ; } catch ( ExecutionException e ) { this . healTasks . remove ( poolKey ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RemotingException ) { throw ( RemotingException ) cause ; } else { FutureTaskUtil . launderThrowable ( cause ) ; } } // heal task is one-off, remove from cache directly after run this . healTasks . remove ( poolKey ) ; } }


Input: do create connections [CODESPLIT] private void doCreate ( final Url url , final ConnectionPool pool , final String taskName , final int syncCreateNumWhenNotWarmup ) throws RemotingException { final int actualNum = pool . size ( ) ; final int expectNum = url . getConnNum ( ) ; if ( actualNum < expectNum ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "actual num {}, expect num {}, task name {}" , actualNum , expectNum , taskName ) ; } if ( url . isConnWarmup ( ) ) { for ( int i = actualNum ; i < expectNum ; ++ i ) { Connection connection = create ( url ) ; pool . add ( connection ) ; } } else { if ( syncCreateNumWhenNotWarmup < 0 || syncCreateNumWhenNotWarmup > url . getConnNum ( ) ) { throw new IllegalArgumentException ( "sync create number when not warmup should be [0," + url . getConnNum ( ) + "]" ) ; } // create connection in sync way if ( syncCreateNumWhenNotWarmup > 0 ) { for ( int i = 0 ; i < syncCreateNumWhenNotWarmup ; ++ i ) { Connection connection = create ( url ) ; pool . add ( connection ) ; } if ( syncCreateNumWhenNotWarmup == url . getConnNum ( ) ) { return ; } } // initialize executor in lazy way initializeExecutor ( ) ; pool . markAsyncCreationStart ( ) ; // mark the start of async try { this . asyncCreateConnectionExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { try { for ( int i = pool . size ( ) ; i < url . getConnNum ( ) ; ++ i ) { Connection conn = null ; try { conn = create ( url ) ; } catch ( RemotingException e ) { logger . error ( "Exception occurred in async create connection thread for {}, taskName {}" , url . getUniqueKey ( ) , taskName , e ) ; } pool . add ( conn ) ; } } finally { pool . markAsyncCreationDone ( ) ; // mark the end of async } } } ) ; } catch ( RejectedExecutionException e ) { pool . markAsyncCreationDone ( ) ; // mark the end of async when reject throw e ; } } // end of NOT warm up } // end of if }


Input: initialize executor [CODESPLIT] private void initializeExecutor ( ) { if ( ! this . executorInitialized ) { this . executorInitialized = true ; this . asyncCreateConnectionExecutor = new ThreadPoolExecutor ( minPoolSize , maxPoolSize , keepAliveTime , TimeUnit . SECONDS , new ArrayBlockingQueue < Runnable > ( queueSize ) , new NamedThreadFactory ( "Bolt-conn-warmup-executor" , true ) ) ; } }


Input: Shutdown . <p > Notice : <br > <li > Rpc client can not be used any more after shutdown . <li > If you need you should destroy it and instantiate another one . [CODESPLIT] public void shutdown ( ) { this . connectionManager . removeAll ( ) ; logger . warn ( "Close all connections from client side!" ) ; this . taskScanner . shutdown ( ) ; logger . warn ( "Rpc client shutdown!" ) ; if ( reconnectManager != null ) { reconnectManager . stop ( ) ; } if ( connectionMonitor != null ) { connectionMonitor . destroy ( ) ; } }


Input:
One way invocation using a string address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2

 Notice :

  DO NOT modify the request object concurrently when this method is called .

 When do invocation use the string address to find a available connection if none then create one .

 You can use { @link RpcConfigs#CONNECT_TIMEOUT_KEY } to specify connection timeout time unit is milliseconds e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTTIMEOUT = 3000 ]
 You can use { @link RpcConfigs#CONNECTION_NUM_KEY } to specify connection number for each ip and port e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONNUM = 30 ]
 You can use { @link RpcConfigs#CONNECTION_WARMUP_KEY } to specify whether need warmup all connections for the first time you call this method e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONWARMUP = false ]

 You should use { @link #closeConnection ( String addr ) } to close it if you want .
 [CODESPLIT] public void oneway ( final String addr , final Object request ) throws RemotingException , InterruptedException { this . rpcRemoting . oneway ( addr , request , null ) ; }


Input:
One way invocation using a { @link Connection }

 Notice :
  DO NOT modify the request object concurrently when this method is called .  [CODESPLIT] public void oneway ( final Connection conn , final Object request ) throws RemotingException { this . rpcRemoting . oneway ( conn , request , null ) ; }


Input: Oneway invocation with a { @link InvokeContext } common api notice please see { @link #oneway ( Connection Object ) } [CODESPLIT] public void oneway ( final Connection conn , final Object request , final InvokeContext invokeContext ) throws RemotingException { this . rpcRemoting . oneway ( conn , request , invokeContext ) ; }


Input:
Synchronous invocation using a string address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2

 Notice :

  DO NOT modify the request object concurrently when this method is called .

 When do invocation use the string address to find a available connection if none then create one .

 You can use { @link RpcConfigs#CONNECT_TIMEOUT_KEY } to specify connection timeout time unit is milliseconds e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTTIMEOUT = 3000 ]
 You can use { @link RpcConfigs#CONNECTION_NUM_KEY } to specify connection number for each ip and port e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONNUM = 30 ]
 You can use { @link RpcConfigs#CONNECTION_WARMUP_KEY } to specify whether need warmup all connections for the first time you call this method e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONWARMUP = false ]

 You should use { @link #closeConnection ( String addr ) } to close it if you want .
 [CODESPLIT] public Object invokeSync ( final String addr , final Object request , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( addr , request , null , timeoutMillis ) ; }


Input: Synchronous invocation with a { @link InvokeContext } common api notice please see { @link #invokeSync ( String Object int ) } [CODESPLIT] public Object invokeSync ( final String addr , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( addr , request , invokeContext , timeoutMillis ) ; }