signature:
public class Initializer { /** * Performs creation - time injections on all objects that require it . Whenever fulfilling an
 * injection depends on another object that requires injection , we inject it first . If the two
 * instances are codependent ( directly or transitively ) , ordering of injection is arbitrary . */
void injectAll ( final Errors errors ) { } }

implementation: Preconditions . checkState ( validationStarted , "Validation should be done before injection" ) ; for ( InjectableReference < ? > reference : pendingInjections ) { try { reference . get ( ) ; } catch ( InternalProvisionException ipe ) { errors . merge ( ipe ) ; } } pendingInjections . clear ( ) ;


signature:
public class AssistedConstructor { /** * Returns an instance of T , constructed using this constructor , with the supplied arguments . */
public T newInstance ( Object [ ] args ) throws Throwable { } }

implementation: constructor . setAccessible ( true ) ; try { return constructor . newInstance ( args ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; }


signature:
public class ManagedFilterPipeline { /** * Introspects the injector and collects all instances of bound { @ code List < FilterDefinition > }
 * into a master list .
 * < p > We have a guarantee that { @ link com . google . inject . Injector # getBindings ( ) } returns a map that
 * preserves insertion order in entry - set iterators . */
private FilterDefinition [ ] collectFilterDefinitions ( Injector injector ) { } }

implementation:
List < FilterDefinition > filterDefinitions = Lists . newArrayList ( ) ; for ( Binding < FilterDefinition > entry : injector . findBindingsByType ( FILTER_DEFS ) ) { filterDefinitions . add ( entry . getProvider ( ) . get ( ) ) ; } // Copy to a fixed - size array for speed of iteration .
return filterDefinitions . toArray ( new FilterDefinition [ filterDefinitions . size ( ) ] ) ;


signature:
public class ManagedFilterPipeline { /** * Used to create an proxy that dispatches either to the guice - servlet pipeline or the regular
 * pipeline based on uri - path match . This proxy also provides minimal forwarding support .
 * < p > We cannot forward from a web . xml Servlet / JSP to a guice - servlet ( because the filter pipeline
 * is not called again ) . However , we can wrap requests with our own dispatcher to forward the
 * * other * way . web . xml Servlets / JSPs can forward to themselves as per normal .
 * < p > This is not a problem cuz we intend for people to migrate from web . xml to guice - servlet ,
 * incrementally , but not the other way around ( which , we should actively discourage ) . */
@ SuppressWarnings ( { } }

implementation:
"JavaDoc" , "deprecation" } ) private ServletRequest withDispatcher ( ServletRequest servletRequest , final ManagedServletPipeline servletPipeline ) { // don ' t wrap the request if there are no servlets mapped . This prevents us from inserting our
// wrapper unless it ' s actually going to be used . This is necessary for compatibility for apps
// that downcast their HttpServletRequests to a concrete implementation .
if ( ! servletPipeline . hasServletsMapped ( ) ) { return servletRequest ; } HttpServletRequest request = ( HttpServletRequest ) servletRequest ; // noinspection OverlyComplexAnonymousInnerClass
return new HttpServletRequestWrapper ( request ) { @ Override public RequestDispatcher getRequestDispatcher ( String path ) { final RequestDispatcher dispatcher = servletPipeline . getRequestDispatcher ( path ) ; return ( null != dispatcher ) ? dispatcher : super . getRequestDispatcher ( path ) ; } } ;


signature:
public class AbstractInjectorGrapher { /** * Transitively resolves aliases . Given aliases ( X to Y ) and ( Y to Z ) , it will return mappings ( X
 * to Z ) and ( Y to Z ) . */
private Map < NodeId , NodeId > resolveAliases ( Iterable < Alias > aliases ) { } }

implementation: 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 ;


signature:
public class Scoping { /** * Returns true if this scope is a singleton that should be loaded eagerly in { @ code stage } . */
public boolean isEagerSingleton ( Stage stage ) { } }

implementation: if ( this == EAGER_SINGLETON ) { return true ; } if ( stage == Stage . PRODUCTION ) { return this == SINGLETON_ANNOTATION || this == SINGLETON_INSTANCE ; } return false ;


signature:
public class Scoping { /** * Scopes an internal factory . */
static < T > InternalFactory < ? extends T > scope ( Key < T > key , InjectorImpl injector , InternalFactory < ? extends T > creator , Object source , Scoping scoping ) { } }

implementation:
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 ) ;


signature:
public class Scoping { /** * 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 . */
static Scoping makeInjectable ( Scoping scoping , InjectorImpl injector , Errors errors ) { } }

implementation: 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 ;


signature:
public class ServletUtils { /** * Normalizes a path by unescaping all safe , percent encoded characters . */
static String normalizePath ( String path ) { } }

implementation:
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 ( ) ;


signature:
public class ServletUtils { /** * 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 " ) .
 * @ param string a percent - encoded US - ASCII string
 * @ param encoding a character encoding
 * @ param decodePlus boolean to indicate whether to decode ' + ' as ' '
 * @ return a Unicode string */
private static String lenientDecode ( String string , Charset encoding , boolean decodePlus ) { } }

implementation:
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 ( ) ;


signature:
public class AbstractBindingProcessor { /** * We tolerate duplicate bindings if one exposes the other or if the two bindings are considered
 * duplicates ( see { @ link Bindings # areDuplicates ( BindingImpl , BindingImpl ) } .
 * @ param original the binding in the parent injector ( candidate for an exposing binding )
 * @ param binding the binding to check ( candidate for the exposed binding ) */
private boolean isOkayDuplicate ( BindingImpl < ? > original , BindingImpl < ? > binding , State state ) { } }

implementation:
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 ) ; } }


signature:
public class Annotations { /** * Generates an Annotation for the annotation class . Requires that the annotation is all
 * optionals . */
public static < T extends Annotation > T generateAnnotation ( Class < T > annotationType ) { } }

implementation: Preconditions . checkState ( isAllDefaultMethods ( annotationType ) , "%s is not all default methods" , annotationType ) ; return ( T ) cache . getUnchecked ( annotationType ) ;


signature:
public class Annotations { /** * Implements { @ link Annotation # equals } . */
private static boolean annotationEquals ( Class < ? extends Annotation > type , Map < String , Object > members , Object other ) throws Exception { } }

implementation: 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 ;


signature:
public class Annotations { /** * Implements { @ link Annotation # hashCode } . */
private static int annotationHashCode ( Class < ? extends Annotation > type , Map < String , Object > members ) throws Exception { } }

implementation: 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 ;


signature:
public class Annotations { /** * Implements { @ link Annotation # toString } . */
private static String annotationToString ( Class < ? extends Annotation > type , Map < String , Object > members ) throws Exception { } }

implementation:
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 ( ) ;


signature:
public class Annotations { /** * Returns true if the given annotation is retained at runtime . */
public static boolean isRetainedAtRuntime ( Class < ? extends Annotation > annotationType ) { } }

implementation: Retention retention = annotationType . getAnnotation ( Retention . class ) ; return retention != null && retention . value ( ) == RetentionPolicy . RUNTIME ;


signature:
public class Annotations { /** * Returns the scope annotation on { @ code type } , or null if none is specified . */
public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Class < ? > implementation ) { } }

implementation: return findScopeAnnotation ( errors , implementation . getAnnotations ( ) ) ;


signature:
public class Annotations { /** * Returns the scoping annotation , or null if there isn ' t one . */
public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Annotation [ ] annotations ) { } }

implementation: 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 ;


signature:
public class Annotations { /** * Adds an error if there is a misplaced annotations on { @ code type } . Scoping annotations are not
 * allowed on abstract classes or interfaces . */
public static void checkForMisplacedScopeAnnotations ( Class < ? > type , Object source , Errors errors ) { } }

implementation:
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 ) ; }


signature:
public class Annotations { /** * Gets a key for the given type , member and annotations . */
public static Key < ? > getKey ( TypeLiteral < ? > type , Member member , Annotation [ ] annotations , Errors errors ) throws ErrorsException { } }

implementation: int numErrorsBefore = errors . size ( ) ; Annotation found = findBindingAnnotation ( errors , member , annotations ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; return found == null ? Key . get ( type ) : Key . get ( type , found ) ;


signature:
public class Annotations { /** * Returns the binding annotation on { @ code member } , or null if there isn ' t one . */
public static Annotation findBindingAnnotation ( Errors errors , Member member , Annotation [ ] annotations ) { } }

implementation: 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 ;


signature:
public class Annotations { /** * If the annotation is an instance of { @ code javax . inject . Named } , canonicalizes to
 * com . google . guice . name . Named . Returns the given annotation otherwise . */
public static Annotation canonicalizeIfNamed ( Annotation annotation ) { } }

implementation: if ( annotation instanceof javax . inject . Named ) { return Names . named ( ( ( javax . inject . Named ) annotation ) . value ( ) ) ; } else { return annotation ; }


signature:
public class Annotations { /** * If the annotation is the class { @ code javax . inject . Named } , canonicalizes to
 * com . google . guice . name . Named . Returns the given annotation class otherwise . */
public static Class < ? extends Annotation > canonicalizeIfNamed ( Class < ? extends Annotation > annotationType ) { } }

implementation: if ( annotationType == javax . inject . Named . class ) { return Named . class ; } else { return annotationType ; }


signature:
public class Annotations { /** * 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 . */
public static String nameOf ( Key < ? > key ) { } }

implementation: 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 "" ; }


signature:
public class ProviderLookup { /** * Sets the actual provider .
 * @ throws IllegalStateException if the delegate is already set */
public void initializeDelegate ( Provider < T > delegate ) { } }

implementation: checkState ( this . delegate == null , "delegate already initialized" ) ; this . delegate = checkNotNull ( delegate , "delegate" ) ;


signature:
public class ProviderLookup { /** * 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 { @ code
 * IllegalStateException } if you try to use it beforehand . */
public Provider < T > getProvider ( ) { } }

implementation:
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 ( ) + ">" ; } } ;


signature:
public class Classes { /** * Returns { @ code Field . class } , { @ code Method . class } or { @ code Constructor . class } . */
public static Class < ? extends Member > memberType ( Member member ) { } }

implementation: 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 ( ) ) ; }


signature:
public class MapBinder { /** * Returns a new mapbinder that collects entries of { @ code keyType } / { @ code valueType } in a { @ link
 * Map } that is itself bound with no binding annotation . */
public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType ) { } }

implementation: return new MapBinder < K , V > ( newMapRealBinder ( binder . skipSources ( MapBinder . class ) , keyType , valueType ) ) ;


signature:
public class MapBinder { /** * Returns a new mapbinder that collects entries of { @ code keyType } / { @ code valueType } in a { @ link
 * Map } that is itself bound with no binding annotation . */
public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , Class < K > keyType , Class < V > valueType ) { } }

implementation: return newMapBinder ( binder , TypeLiteral . get ( keyType ) , TypeLiteral . get ( valueType ) ) ;


signature:
public class MapBinder { /** * Returns a new mapbinder that collects entries of { @ code keyType } / { @ code valueType } in a { @ link
 * Map } that is itself bound with { @ code annotation } . */
public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType , Annotation annotation ) { } }

implementation: return new MapBinder < K , V > ( newRealMapBinder ( binder . skipSources ( MapBinder . class ) , keyType , valueType , annotation ) ) ;


signature:
public class RealOptionalBinder { /** * Adds a binding for T . Multiple calls to this are safe , and will be collapsed as duplicate
 * bindings . */
private void addDirectTypeBinding ( Binder binder ) { } }

implementation: binder . bind ( bindingSelection . getDirectKey ( ) ) . toProvider ( new RealDirectTypeProvider < T > ( bindingSelection ) ) ;


signature:
public class ConstructorInjectorStore { /** * Returns a new complete constructor injector with injection listeners registered . */
public ConstructorInjector < ? > get ( InjectionPoint constructorInjector , Errors errors ) throws ErrorsException { } }

implementation: return cache . get ( constructorInjector , errors ) ;


signature:
public class Struts2Factory { /** * Returns true if the given class has a scope annotation . */
private static boolean hasScope ( Class < ? extends Interceptor > interceptorClass ) { } }

implementation: for ( Annotation annotation : interceptorClass . getAnnotations ( ) ) { if ( Annotations . isScopeAnnotation ( annotation . annotationType ( ) ) ) { return true ; } } return false ;


signature:
public class RealMapBinder { /** * Returns a new mapbinder that collects entries of { @ code keyType } / { @ code valueType } in a { @ link
 * Map } that is itself bound with { @ code annotation } . */
public static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType , Annotation annotation ) { } }

implementation: 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 ) ) ) ;


signature:
public class RealMapBinder { /** * provider map < K , V > is safely a Map < K , javax . inject . Provider < V > > > */
@ SuppressWarnings ( "unchecked" ) static < K , V > TypeLiteral < Map < K , javax . inject . Provider < V > > > mapOfJavaxProviderOf ( TypeLiteral < K > keyType , TypeLiteral < V > valueType ) { } }

implementation: return ( TypeLiteral < Map < K , javax . inject . Provider < V > > > ) TypeLiteral . get ( Types . mapOf ( keyType . getType ( ) , newParameterizedType ( javax . inject . Provider . class , valueType . getType ( ) ) ) ) ;


signature:
public class RealMapBinder { /** * Given a Key < T > will return a Key < Provider < T > > */
@ SuppressWarnings ( "unchecked" ) private static < T > Key < Provider < T > > getKeyOfProvider ( Key < T > valueKey ) { } }

implementation: return ( Key < Provider < T > > ) valueKey . ofType ( Types . providerOf ( valueKey . getTypeLiteral ( ) . getType ( ) ) ) ;


signature:
public class RealMapBinder { /** * since it ' s an easy way to group a type and an optional annotation type or instance . */
static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , Key < V > valueTypeAndAnnotation ) { } }

implementation: 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 ) ) ) ) ;


signature:
public class RealMapBinder { /** * Adds a binding to the map for the given key . */
Key < V > getKeyForNewValue ( K key ) { } }

implementation: 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 ;


signature:
public class DynamicFinder { /** * Returns some metadata if the method is annotated { @ code @ Finder } or null .
 * @ param method a method you want to test as a dynamic finder */
public static DynamicFinder from ( Method method ) { } }

implementation: return method . isAnnotationPresent ( Finder . class ) ? new DynamicFinder ( method ) : null ;


signature:
public class InternalProvisionException { /** * Returns { @ code value } if it is non - null or allowed to be null . Otherwise a message is added and
 * an { @ code InternalProvisionException } is thrown . */
static void onNullInjectedIntoNonNullableDependency ( Object source , Dependency < ? > dependency ) throws InternalProvisionException { } }

implementation:
// 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 ) ;


signature:
public class InternalProvisionException { /** * Prepends the given { @ code source } to the stack of binding sources for the errors reported in
 * this exception .
 * < p > See { @ link Errors # withSource ( Object ) }
 * < p > It is expected that this method is called as the exception propagates up the stack .
 * @ param source
 * @ return { @ code this } */
InternalProvisionException addSource ( Object source ) { } }

implementation:
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 ;


signature:
public class ConstructorInjector { /** * Construct an instance . Returns { @ code Object } instead of { @ code T } because it may return a
 * proxy . */
Object construct ( final InternalContext context , Dependency < ? > dependency , /* @ Nullable */
ProvisionListenerStackCallback < T > provisionCallback ) throws InternalProvisionException { } }

implementation:
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 ( ) ; }


signature:
public class ConstructorInjector { /** * Provisions a new T . */
private T provision ( InternalContext context , ConstructionContext < T > constructionContext ) throws InternalProvisionException { } }

implementation:
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 ( ) ; }


signature:
public class AbstractBindingBuilder { /** * Sets the binding to a copy with the specified annotation on the bound key */
protected BindingImpl < T > annotatedWithInternal ( Class < ? extends Annotation > annotationType ) { } }

implementation: checkNotNull ( annotationType , "annotationType" ) ; checkNotAnnotated ( ) ; return setBinding ( binding . withKey ( Key . get ( this . binding . getKey ( ) . getTypeLiteral ( ) , annotationType ) ) ) ;


signature:
public class AbstractBindingBuilder { /** * Sets the binding to a copy with the specified annotation on the bound key */
protected BindingImpl < T > annotatedWithInternal ( Annotation annotation ) { } }

implementation: checkNotNull ( annotation , "annotation" ) ; checkNotAnnotated ( ) ; return setBinding ( binding . withKey ( Key . get ( this . binding . getKey ( ) . getTypeLiteral ( ) , annotation ) ) ) ;


signature:
public class Message { /** * 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 . */
private Object writeReplace ( ) throws ObjectStreamException { } }

implementation: 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 ) ;


signature:
public class CheckedProviderMethodsModule { /** * Returns a module which creates bindings for provider methods from the given module . */
static Module forModule ( Module module ) { } }

implementation:
// avoid infinite recursion , since installing a module always installs itself
if ( module instanceof CheckedProviderMethodsModule ) { return Modules . EMPTY_MODULE ; } return new CheckedProviderMethodsModule ( module ) ;


signature:
public class FactoryProvider2 { /** * the collection is immutable . */
@ Override @ SuppressWarnings ( "unchecked" ) public Collection < AssistedMethod > getAssistedMethods ( ) { } }

implementation: return ( Collection < AssistedMethod > ) ( Collection < ? > ) assistDataByMethod . values ( ) ;


signature:
public class FactoryProvider2 { /** * Returns true if the ConfigurationException is due to an error of TypeLiteral not being fully
 * specified . */
private boolean isTypeNotSpecified ( TypeLiteral < ? > typeLiteral , ConfigurationException ce ) { } }

implementation: 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 ; }


signature:
public class FactoryProvider2 { /** * Finds a constructor suitable for the method . If the implementation contained any constructors
 * marked with { @ link AssistedInject } , this requires all { @ link Assisted } parameters to exactly
 * match the parameters ( in any order ) listed in the method . Otherwise , if no { @ link
 * AssistedInject } constructors exist , this will default to looking for an { @ literal @ } { @ link
 * Inject } constructor . */
private < T > InjectionPoint findMatchingConstructorInjectionPoint ( Method method , Key < ? > returnType , TypeLiteral < T > implementation , List < Key < ? > > paramList ) throws ErrorsException { } }

implementation:
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 ( ) ; } }


signature:
public class FactoryProvider2 { /** * Matching logic for constructors annotated with AssistedInject . This returns true if and only if
 * all @ Assisted parameters in the constructor exactly match ( in any order ) all @ Assisted
 * parameters the method ' s parameter . */
private boolean constructorHasMatchingParams ( TypeLiteral < ? > type , Constructor < ? > constructor , List < Key < ? > > paramList , Errors errors ) throws ErrorsException { } }

implementation:
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 ;


signature:
public class FactoryProvider2 { /** * Calculates all dependencies required by the implementation and constructor . */
private Set < Dependency < ? > > getDependencies ( InjectionPoint ctorPoint , TypeLiteral < ? > implementation ) { } }

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 ( ) ;


signature:
public class FactoryProvider2 { /** * Return all non - assisted dependencies . */
private Set < Dependency < ? > > removeAssistedDeps ( Set < Dependency < ? > > deps ) { } }

implementation: 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 ( ) ;


signature:
public class FactoryProvider2 { /** * 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 . */
private boolean isValidForOptimizedAssistedInject ( Set < Dependency < ? > > dependencies , Class < ? > implementation , TypeLiteral < ? > factoryType ) { } }

implementation:
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 ;


signature:
public class FactoryProvider2 { /** * Returns true if the dependency is for { @ link Injector } or if the dependency is a { @ link
 * Provider } for a parameter that is { @ literal @ } { @ link Assisted } . */
private boolean isInjectorOrAssistedProvider ( Dependency < ? > dependency ) { } }

implementation:
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 ;


signature:
public class FactoryProvider2 { /** * 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 . */
@ Inject @ Toolable void initialize ( Injector injector ) { } }

implementation:
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
}


signature:
public class FactoryProvider2 { /** * Creates a child injector that binds the args , and returns the binding for the method ' s result . */
public Binding < ? > getBindingFromNewInjector ( final Method method , final Object [ ] args , final AssistData data ) { } }

implementation:
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 ;


signature:
public class FactoryProvider2 { /** * 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 . */
@ Override public Object invoke ( Object proxy , final Method method , final Object [ ] args ) throws Throwable { } }

implementation:
// 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 ( ) ; } }


signature:
public class FactoryProvider2 { /** * Returns true if { @ code thrown } can be thrown by { @ code invoked } without wrapping . */
static boolean canRethrow ( Method invoked , Throwable thrown ) { } }

implementation: if ( thrown instanceof Error || thrown instanceof RuntimeException ) { return true ; } for ( Class < ? > declared : invoked . getExceptionTypes ( ) ) { if ( declared . isInstance ( thrown ) ) { return true ; } } return false ;


signature:
public class Errors { /** * Throws a ConfigurationException with an NullPointerExceptions as the cause if the given
 * reference is { @ code null } . */
static < T > T checkNotNull ( T reference , String name ) { } }

implementation: if ( reference != null ) { return reference ; } NullPointerException npe = new NullPointerException ( name ) ; throw new ConfigurationException ( ImmutableSet . of ( new Message ( npe . toString ( ) , npe ) ) ) ;


signature:
public class Errors { /** * Throws a ConfigurationException with a formatted { @ link Message } if this condition is { @ code
 * false } . */
static void checkConfiguration ( boolean condition , String format , Object ... args ) { } }

implementation: if ( condition ) { return ; } throw new ConfigurationException ( ImmutableSet . of ( new Message ( Errors . format ( format , args ) ) ) ) ;


signature:
public class Errors { /** * Returns an instance that uses { @ code source } as a reference point for newly added errors . */
public Errors withSource ( Object source ) { } }

implementation: return source == this . source || source == SourceProvider . UNKNOWN_SOURCE ? this : new Errors ( this , source ) ;


signature:
public class Errors { /** * Within guice ' s core , allow for better missing binding messages */
< T > Errors missingImplementationWithHint ( Key < T > key , Injector injector ) { } }

implementation:
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 ( ) ) ;


signature:
public class Errors { /** * TODO ( lukes ) : inline into callers */
public static String format ( String messageFormat , Object ... arguments ) { } }

implementation: return Messages . format ( messageFormat , arguments ) ;


signature:
public class Errors { /** * TODO ( lukes ) : inline in callers . There are some callers outside of guice , so this is difficult */
public static Object convert ( Object o , ElementSource source ) { } }

implementation: return Messages . convert ( o , source ) ;


signature:
public class RealMultibinder { /** * Implementation of newSetBinder . */
public static < T > RealMultibinder < T > newRealSetBinder ( Binder binder , Key < T > key ) { } }

implementation: binder = binder . skipSources ( RealMultibinder . class ) ; RealMultibinder < T > result = new RealMultibinder < > ( binder , key ) ; binder . install ( result ) ; return result ;


signature:
public class RealMultibinder { /** * Adds a new entry to the set and returns the key for it . */
Key < T > getKeyForNewItem ( ) { } }

implementation: checkConfiguration ( ! bindingSelection . isInitialized ( ) , "Multibinder was already initialized" ) ; return Key . get ( bindingSelection . getElementTypeLiteral ( ) , new RealElement ( bindingSelection . getSetName ( ) , MULTIBINDER , "" ) ) ;


signature:
public class FilterChainInvocation { /** * Iterates over the remaining filter definitions . Returns the first applicable filter , or null if
 * none apply . */
private Filter findNextFilter ( HttpServletRequest request ) { } }

implementation: while ( ++ index < filterDefinitions . length ) { Filter filter = filterDefinitions [ index ] . getFilterIfMatching ( request ) ; if ( filter != null ) { return filter ; } } return null ;


signature:
public class ConstructorBindingImpl { /** * Returns true if the inject annotation is on the constructor . */
private static boolean hasAtInject ( Constructor cxtor ) { } }

implementation: return cxtor . isAnnotationPresent ( Inject . class ) || cxtor . isAnnotationPresent ( javax . inject . Inject . class ) ;


signature:
public class ConstructorBindingImpl { /** * Returns an injection point that can be used to clean up the constructor store . */
InjectionPoint getInternalConstructor ( ) { } }

implementation: if ( factory . constructorInjector != null ) { return factory . constructorInjector . getConstructionProxy ( ) . getInjectionPoint ( ) ; } else { return constructorInjectionPoint ; }


signature:
public class ConstructorBindingImpl { /** * Returns a set of dependencies that can be iterated over to clean up stray JIT bindings . */
Set < Dependency < ? > > getInternalDependencies ( ) { } }

implementation:
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 ( ) ) ;


signature:
public class ConstructorBindingImpl { /** * / * if [ AOP ] */
@ Override public Map < Method , List < org . aopalliance . intercept . MethodInterceptor > > getMethodInterceptors ( ) { } }

implementation: checkState ( factory . constructorInjector != null , "Binding is not ready" ) ; return factory . constructorInjector . getConstructionProxy ( ) . getMethodInterceptors ( ) ;


signature:
public class ConstructorBindingImpl { /** * / * end [ AOP ] */
@ Override public Set < Dependency < ? > > getDependencies ( ) { } }

implementation: return Dependency . forInjectionPoints ( new ImmutableSet . Builder < InjectionPoint > ( ) . add ( getConstructor ( ) ) . addAll ( getInjectableMembers ( ) ) . build ( ) ) ;


signature:
public class InjectionRequest { /** * Returns the instance methods and fields of { @ code instance } that will be injected to fulfill
 * this request .
 * @ return a possibly empty set of injection points . The set has a specified iteration order . All
 * fields are returned and then all methods . Within the fields , supertype fields are returned
 * before subtype fields . Similarly , supertype methods are returned before subtype methods .
 * @ throws ConfigurationException if there is a malformed injection point on the class of { @ code
 * instance } , such as a field with multiple binding annotations . The exception ' s { @ link
 * ConfigurationException # getPartialValue ( ) partial value } is a { @ code Set < InjectionPoint > } of
 * the valid injection points . */
public Set < InjectionPoint > getInjectionPoints ( ) throws ConfigurationException { } }

implementation: return InjectionPoint . forInstanceMethodsAndFields ( instance != null ? TypeLiteral . get ( instance . getClass ( ) ) : type ) ;


signature:
public class InternalFlags { /** * Gets the system option indicated by the specified key ; runs as a privileged action .
 * @ param name of the system option
 * @ param defaultValue if the option is not set
 * @ return value of the option , defaultValue if not set */
private static < T extends Enum < T > > T getSystemOption ( final String name , T defaultValue ) { } }

implementation: return getSystemOption ( name , defaultValue , defaultValue ) ;


signature:
public class InternalFlags { /** * Gets the system option indicated by the specified key ; runs as a privileged action .
 * @ param name of the system option
 * @ param defaultValue if the option is not set
 * @ param secureValue if the security manager disallows access to the option
 * @ return value of the option , defaultValue if not set , secureValue if no access */
private static < T extends Enum < T > > T getSystemOption ( final String name , T defaultValue , T secureValue ) { } }

implementation: 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 ; }


signature:
public class ShortNameFactory { /** * Returns a name for a Guice " source " object . This will typically be either a { @ link
 * StackTraceElement } for when the binding is made to the instance , or a { @ link Method } when a
 * provider method is used . */
@ Override public String getSourceName ( Object source ) { } }

implementation: 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 ( ) ) ;


signature:
public class Types { /** * Returns a new parameterized type , applying { @ code typeArguments } to { @ code rawType } . The
 * returned type does not have an owner type .
 * @ return a { @ link java . io . Serializable serializable } parameterized type . */
public static ParameterizedType newParameterizedType ( Type rawType , Type ... typeArguments ) { } }

implementation: return newParameterizedTypeWithOwner ( null , rawType , typeArguments ) ;


signature:
public class Types { /** * Returns a new parameterized type , applying { @ code typeArguments } to { @ code rawType } and
 * enclosed by { @ code ownerType } .
 * @ return a { @ link java . io . Serializable serializable } parameterized type . */
public static ParameterizedType newParameterizedTypeWithOwner ( Type ownerType , Type rawType , Type ... typeArguments ) { } }

implementation: return new ParameterizedTypeImpl ( ownerType , rawType , typeArguments ) ;


signature:
public class Types { /** * Returns a type modelling a { @ link Map } whose keys are of type { @ code keyType } and whose values
 * are of type { @ code valueType } .
 * @ return a { @ link java . io . Serializable serializable } parameterized type . */
public static ParameterizedType mapOf ( Type keyType , Type valueType ) { } }

implementation: return newParameterizedType ( Map . class , keyType , valueType ) ;


signature:
public class Types { /** * Returns a type modelling a { @ link javax . inject . Provider } that provides elements of type { @ code
 * elementType } .
 * @ return a { @ link java . io . Serializable serializable } parameterized type . */
public static Type javaxProviderOf ( Type type ) { } }

implementation: return Types . newParameterizedType ( javax . inject . Provider . class , type ) ;


signature:
public class ProviderMethodsModule { /** * Returns a module which creates bindings methods in the module that match the scanner . */
public static Module forModule ( Object module , ModuleAnnotatedMethodScanner scanner ) { } }

implementation: return forObject ( module , false , scanner ) ;


signature:
public class ProviderMethodsModule { /** * Returns the annotation that is claimed by the scanner , or null if there is none . */
private Annotation getAnnotation ( Binder binder , Method method ) { } }

implementation: 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 ;


signature:
public class Names { /** * Creates a constant binding to { @ code @ Named ( key ) } for each entry in { @ code properties } . */
public static void bindProperties ( Binder binder , Map < String , String > properties ) { } }

implementation: 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 ) ; }


signature:
public class Names { /** * Creates a constant binding to { @ code @ Named ( key ) } for each property . This method binds all
 * properties including those inherited from { @ link Properties # defaults defaults } . */
public static void bindProperties ( Binder binder , Properties properties ) { } }

implementation:
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 ) ; }


signature:
public class Guice { /** * Creates an injector for the given set of modules , in a given development stage .
 * @ throws CreationException if one or more errors occur during injector creation . */
public static Injector createInjector ( Stage stage , Module ... modules ) { } }

implementation: return createInjector ( stage , Arrays . asList ( modules ) ) ;


signature:
public class Guice { /** * Creates an injector for the given set of modules , in a given development stage .
 * @ throws CreationException if one or more errors occur during injector construction */
public static Injector createInjector ( Stage stage , Iterable < ? extends Module > modules ) { } }

implementation: return new InternalInjectorCreator ( ) . stage ( stage ) . addModules ( modules ) . build ( ) ;


signature:
public class ElementSource { /** * 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 :
 * < ol >
 * < li > { @ code Binder . bind ( ) }
 * < li > { @ code ModuleTwo . configure ( ) }
 * < li > { @ code Binder . install ( ) }
 * < li > { @ code ModuleOne . configure ( ) }
 * < li > { @ code theRest ( ) .
 * < / ol >
 * < p > 1 and 3 are returned .
 * < p > In the cases where stack trace is not available ( i . e . , the stack trace was not collected ) ,
 * it returns - 1 for all module positions . */
public List < Integer > getModuleConfigurePositionsInStackTrace ( ) { } }

implementation: 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 ) ;


signature:
public class ElementSource { /** * Returns the sequence of method calls that ends at one of { @ link com . google . inject . Binder }
 * { @ code bindXXX ( ) } methods and eventually defines the element . Note that { @ link # getStackTrace }
 * lists { @ link StackTraceElement StackTraceElements } in reverse chronological order . The first
 * element ( index zero ) is the last method call and the last element is the first method
 * invocation . In the cases where stack trace is not available ( i . e . , the stack trace was not
 * collected ) , it returns an empty array . */
public StackTraceElement [ ] getStackTrace ( ) { } }

implementation: 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 ;


signature:
public class LineNumbers { /** * Get the line number associated with the given member .
 * @ param member a field , constructor , or method belonging to the class used during construction
 * @ return the wrapped line number , or null if not available
 * @ throws IllegalArgumentException if the member does not belong to the class used during
 * construction */
public Integer getLineNumber ( Member member ) { } }

implementation: Preconditions . checkArgument ( type == member . getDeclaringClass ( ) , "Member %s belongs to %s, not %s" , member , member . getDeclaringClass ( ) , type ) ; return lines . get ( memberKey ( member ) ) ;


signature:
public class DeferredLookups { /** * Initialize the specified lookups , either immediately or when the injector is created . */
void initialize ( Errors errors ) { } }

implementation: injector . lookups = injector ; new LookupProcessor ( errors ) . process ( injector , lookups ) ;


signature:
public class ServletScopes { /** * 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 .
 * < p > There are some limitations :
 * < ul >
 * < li > Derived objects ( i . e . anything marked @ RequestScoped will not be transported .
 * < li > State changes to the HttpServletRequest after this method is called will not be seen in the
 * continued thread .
 * < li > Only the HttpServletRequest , ServletContext and request parameter map are available in the
 * continued thread . The response and session are not available .
 * < / ul >
 * < p > The returned callable will throw a { @ link ScopingException } when called if the HTTP request
 * scope is still active on the current thread .
 * @ param callable code to be executed in another thread , which depends on the request scope .
 * @ param seedMap the initial set of scoped instances for Guice to seed the request scope with . To
 * seed a key with null , use { @ code null } as the value .
 * @ return a callable that will invoke the given callable , making the request context available to
 * it .
 * @ throws OutOfScopeException if this method is called from a non - request thread , or if the
 * request has completed .
 * @ since 3.0
 * @ deprecated You probably want to use { @ code transferRequest } instead */
@ Deprecated public static < T > Callable < T > continueRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { } }

implementation: return wrap ( callable , continueRequest ( seedMap ) ) ;


signature:
public class ServletScopes { /** * 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 .
 * < p > As opposed to { @ link # continueRequest } , this method propagates all existing scoped objects .
 * The primary use case is in server implementations where you can detach the request processing
 * thread while waiting for data , and reattach to a different thread to finish processing at a
 * later time .
 * < p > Because request - scoped objects are not typically thread - safe , the callable returned by this
 * method must not be run on a different thread until the current request scope has terminated .
 * The returned callable will block until the current thread has released the request scope .
 * @ param callable code to be executed in another thread , which depends on the request scope .
 * @ return a callable that will invoke the given callable , making the request context available to
 * it .
 * @ throws OutOfScopeException if this method is called from a non - request thread , or if the
 * request has completed .
 * @ since 4.0 */
public static < T > Callable < T > transferRequest ( Callable < T > callable ) { } }

implementation: return wrap ( callable , transferRequest ( ) ) ;


signature:
public class ServletScopes { /** * 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 .
 * < p > The returned callable will throw a { @ link ScopingException } when called if there is a
 * request scope already active on the current thread .
 * @ param callable code to be executed which depends on the request scope . Typically in another
 * thread , but not necessarily so .
 * @ param seedMap the initial set of scoped instances for Guice to seed the request scope with . To
 * seed a key with null , use { @ code null } as the value .
 * @ return a callable that when called will run inside the a request scope that exposes the
 * instances in the { @ code seedMap } as scoped keys .
 * @ since 3.0 */
public static < T > Callable < T > scopeRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { } }

implementation: return wrap ( callable , scopeRequest ( seedMap ) ) ;


signature:
public class ServletScopes { /** * Validates the key and object , ensuring the value matches the key type , and canonicalizing null
 * objects to the null sentinel . */
private static Object validateAndCanonicalizeValue ( Key < ? > key , Object object ) { } }

implementation: 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 ;


signature:
public class MembersInjectorStore { /** * Returns a new complete members injector with injection listeners registered . */
@ SuppressWarnings ( "unchecked" ) // the MembersInjector type always agrees with the passed type
public < T > MembersInjectorImpl < T > get ( TypeLiteral < T > key , Errors errors ) throws ErrorsException { } }

implementation: return ( MembersInjectorImpl < T > ) cache . get ( key , errors ) ;


signature:
public class MembersInjectorStore { /** * Creates a new members injector and attaches both injection listeners and method aspects . */
private < T > MembersInjectorImpl < T > createWithListeners ( TypeLiteral < T > type , Errors errors ) throws ErrorsException { } }

implementation: 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 ) ;


signature:
public class MembersInjectorStore { /** * Returns the injectors for the specified injection points . */
ImmutableList < SingleMemberInjector > getInjectors ( Set < InjectionPoint > injectionPoints , Errors errors ) { } }

implementation:
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 ) ;


signature:
public class GuiceFilter { /** * VisibleForTesting */
@ Inject static void setPipeline ( FilterPipeline pipeline ) { } }

implementation:
// 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 ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation strategy . */
static < T > Key < T > get ( Class < T > type , AnnotationStrategy annotationStrategy ) { } }

implementation: return new Key < T > ( type , annotationStrategy ) ;


signature:
public class Key { /** * Gets a key for an injection type . */
public static < T > Key < T > get ( Class < T > type ) { } }

implementation: return new Key < T > ( type , NullAnnotationStrategy . INSTANCE ) ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation type . */
public static < T > Key < T > get ( Class < T > type , Class < ? extends Annotation > annotationType ) { } }

implementation: return new Key < T > ( type , strategyFor ( annotationType ) ) ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation . */
public static < T > Key < T > get ( Class < T > type , Annotation annotation ) { } }

implementation: return new Key < T > ( type , strategyFor ( annotation ) ) ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation type . */
public static Key < ? > get ( Type type , Class < ? extends Annotation > annotationType ) { } }

implementation: return new Key < Object > ( type , strategyFor ( annotationType ) ) ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation . */
public static Key < ? > get ( Type type , Annotation annotation ) { } }

implementation: return new Key < Object > ( type , strategyFor ( annotation ) ) ;


signature:
public class Key { /** * Gets a key for an injection type . */
public static < T > Key < T > get ( TypeLiteral < T > typeLiteral ) { } }

implementation: return new Key < T > ( typeLiteral , NullAnnotationStrategy . INSTANCE ) ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation type . */
public static < T > Key < T > get ( TypeLiteral < T > typeLiteral , Class < ? extends Annotation > annotationType ) { } }

implementation: return new Key < T > ( typeLiteral , strategyFor ( annotationType ) ) ;


signature:
public class Key { /** * Gets a key for an injection type and an annotation . */
public static < T > Key < T > get ( TypeLiteral < T > typeLiteral , Annotation annotation ) { } }

implementation: return new Key < T > ( typeLiteral , strategyFor ( annotation ) ) ;


signature:
public class Key { /** * Returns a new key of the specified type with the same annotation as this key .
 * @ since 3.0 */
public < T > Key < T > ofType ( Class < T > type ) { } }


signature:
public class Key { /** * Returns a new key of the specified type with the same annotation as this key .
 * @ since 3.0 */
public < T > Key < T > ofType ( TypeLiteral < T > type ) { } }


signature:
public class Key { /** * Gets the strategy for an annotation . */
static AnnotationStrategy strategyFor ( Annotation annotation ) { } }

implementation: 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 ) ) ;


signature:
public class Key { /** * Gets the strategy for an annotation type . */
static AnnotationStrategy strategyFor ( Class < ? extends Annotation > annotationType ) { } }

implementation: annotationType = Annotations . canonicalizeIfNamed ( annotationType ) ; if ( isAllDefaultMethods ( annotationType ) ) { return strategyFor ( generateAnnotation ( annotationType ) ) ; } checkNotNull ( annotationType , "annotation type" ) ; ensureRetainedAtRuntime ( annotationType ) ; ensureIsBindingAnnotation ( annotationType ) ; return new AnnotationTypeStrategy ( annotationType , null ) ;


signature:
public class Elements { /** * Records the elements executed by { @ code modules } . */
public static List < Element > getElements ( Module ... modules ) { } }

implementation: return getElements ( Stage . DEVELOPMENT , Arrays . asList ( modules ) ) ;


signature:
public class Elements { /** * Records the elements executed by { @ code modules } . */
public static List < Element > getElements ( Iterable < ? extends Module > modules ) { } }

implementation: return getElements ( Stage . DEVELOPMENT , modules ) ;


signature:
public class Elements { /** * Records the elements executed by { @ code modules } . */
public static List < Element > getElements ( Stage stage , Iterable < ? extends Module > modules ) { } }

implementation:
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 ) ;


signature:
public class InterceptorStackCallback { /** * Removes stacktrace elements related to AOP internal mechanics from the throwable ' s stack trace
 * and any causes it may have . */
private void pruneStacktrace ( Throwable throwable ) { } }

implementation: 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 ( ) ] ) ) ; }


signature:
public class ProvisionListenerCallbackStore { /** * Returns a new { @ link ProvisionListenerStackCallback } for the key or { @ code null } if there are
 * no listeners */
@ SuppressWarnings ( "unchecked" ) // the ProvisionListenerStackCallback type always agrees with the passed type
public < T > ProvisionListenerStackCallback < T > get ( Binding < T > binding ) { } }

implementation:
// 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 ;


signature:
public class ProvisionListenerCallbackStore { /** * Creates a new { @ link ProvisionListenerStackCallback } with the correct listeners for the key . */
private < T > ProvisionListenerStackCallback < T > create ( Binding < T > binding ) { } }

implementation:
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 ) ;


signature:
public class DependencyAndSource { /** * 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 . */
public String getBindingSource ( ) { } }

implementation: 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 ( ) ; }


signature:
public class EncounterImpl { /** * / * if [ AOP ] */
ImmutableList < MethodAspect > getAspects ( ) { } }

implementation: return aspects == null ? ImmutableList . < MethodAspect > of ( ) : ImmutableList . copyOf ( aspects ) ;


signature:
public class EncounterImpl { /** * / * end [ AOP ] */
ImmutableSet < MembersInjector < ? super T > > getMembersInjectors ( ) { } }

implementation: return membersInjectors == null ? ImmutableSet . < MembersInjector < ? super T > > of ( ) : ImmutableSet . copyOf ( membersInjectors ) ;


signature:
public class Messages { /** * Prepends the list of sources to the given { @ link Message } */
static Message mergeSources ( List < Object > sources , Message message ) { } }

implementation:
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 ( ) ) ;


signature:
public class Messages { /** * Calls { @ link String # format } after converting the arguments using some standard guice formatting
 * for { @ link Key } , { @ link Class } and { @ link Member } objects . */
public static String format ( String messageFormat , Object ... arguments ) { } }

implementation: for ( int i = 0 ; i < arguments . length ; i ++ ) { arguments [ i ] = convert ( arguments [ i ] ) ; } return String . format ( messageFormat , arguments ) ;


signature:
public class Messages { /** * Returns the formatted message for an exception with the specified messages . */
public static String formatMessages ( String heading , Collection < Message > errorMessages ) { } }

implementation: 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 ( ) ;


signature:
public class Messages { /** * Creates a new Message without a cause .
 * @ param messageFormat Format string
 * @ param arguments format string arguments */
public static Message create ( String messageFormat , Object ... arguments ) { } }

implementation: return create ( null , messageFormat , arguments ) ;


signature:
public class Messages { /** * Creates a new Message with the given cause .
 * @ param cause The exception that caused the error
 * @ param messageFormat Format string
 * @ param arguments format string arguments */
public static Message create ( Throwable cause , String messageFormat , Object ... arguments ) { } }

implementation: return create ( cause , ImmutableList . of ( ) , messageFormat , arguments ) ;


signature:
public class Messages { /** * Creates a new Message with the given cause and a binding source stack .
 * @ param cause The exception that caused the error
 * @ param sources The binding sources for the source stack
 * @ param messageFormat Format string
 * @ param arguments format string arguments */
public static Message create ( Throwable cause , List < Object > sources , String messageFormat , Object ... arguments ) { } }

implementation: String message = format ( messageFormat , arguments ) ; return new Message ( sources , message , cause ) ;


signature:
public class Messages { /** * Formats an object in a user friendly way . */
static Object convert ( Object o ) { } }

implementation: ElementSource source = null ; if ( o instanceof ElementSource ) { source = ( ElementSource ) o ; o = source . getDeclaringSource ( ) ; } return convert ( o , source ) ;


signature:
public class Messages { /** * Returns the cause throwable if there is exactly one cause in { @ code messages } . If there are
 * zero or multiple messages with causes , null is returned . */
public static Throwable getOnlyCause ( Collection < Message > messages ) { } }

implementation: 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 ;


signature:
public class ModuleSource { /** * Returns the class names of modules in this module source . The first element ( index 0 ) is filled
 * by this object { @ link # getModuleClassName ( ) } . The second element is filled by the parent ' s
 * { @ link # getModuleClassName ( ) } and so on . */
List < String > getModuleClassNames ( ) { } }

implementation: 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 ( ) ;


signature:
public class ModuleSource { /** * Returns the full call stack that ends just before the module { @ link Module # configure ( Binder )
 * configure ( Binder ) } method invocation . The return array is non - empty if stack trace collection
 * on . */
StackTraceElement [ ] getStackTrace ( ) { } }

implementation: 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 ;


signature:
public class MiniGuice { /** * 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 .
 * < p > The following injection features are supported :
 * < ul >
 * < li > Field injection . A class may have any number of field injections , and fields may be of any
 * visibility . Static fields will be injected each time an instance is injected .
 * < li > Constructor injection . A class may have a single { @ code @ Inject } - annotated constructor .
 * Classes that have fields injected may omit the { @ link @ Inject } annotation if they have a
 * public no - arguments constructor .
 * < li > Injection of { @ code @ Provides } method parameters .
 * < li > { @ code @ Provides } methods annotated { @ code @ Singleton } .
 * < li > Constructor - injected classes annotated { @ code @ Singleton } .
 * < li > Injection of { @ link Provider } s .
 * < li > Binding annotations on injected parameters and fields .
 * < li > Guice annotations .
 * < li > JSR 330 annotations .
 * < li > Eager loading of singletons .
 * < / ul >
 * < p > < strong > Note that method injection is not supported . < / strong > */
public static < T > T inject ( Class < T > type , Object ... modules ) { } }

implementation: 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 ( ) ) ;


signature:
public class SourceProvider { /** * Returns true if the className should be skipped . */
private boolean shouldBeSkipped ( String className ) { } }

implementation: return ( parent != null && parent . shouldBeSkipped ( className ) ) || classNamesToSkip . contains ( className ) ;


signature:
public class SourceProvider { /** * Returns the class names as Strings */
private static List < String > asStrings ( Class ... classes ) { } }

implementation: List < String > strings = Lists . newArrayList ( ) ; for ( Class c : classes ) { strings . add ( c . getName ( ) ) ; } return strings ;


signature:
public class SourceProvider { /** * Returns the calling line of code . The selected line is the nearest to the top of the stack that
 * is not skipped . */
public StackTraceElement get ( StackTraceElement [ ] stackTraceElements ) { } }

implementation: 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 ( ) ;


signature:
public class SourceProvider { /** * Returns the non - skipped module class name . */
public Object getFromClassNames ( List < String > moduleClassNames ) { } }

implementation: 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 ;


signature:
public class Manager { /** * Registers all the bindings of an Injector with the platform MBean server . Consider using the
 * name of your root { @ link Module } class as the domain . */
public static void manage ( String domain , Injector injector ) { } }

implementation: manage ( ManagementFactory . getPlatformMBeanServer ( ) , domain , injector ) ;


signature:
public class Manager { /** * Registers all the bindings of an Injector with the given MBean server . Consider using the name
 * of your root { @ link Module } class as the domain . */
public static void manage ( MBeanServer server , String domain , Injector injector ) { } }

implementation:
// 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 ) ; } }


signature:
public class Manager { /** * Run with no arguments for usage instructions . */
public static void main ( String [ ] args ) throws Exception { } }

implementation:
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 ) ;


signature:
public class StackTraceElements { /** * Returns encoded in - memory version of { @ link StackTraceElement StackTraceElements } . */
public static InMemoryStackTraceElement [ ] convertToInMemoryStackTraceElement ( StackTraceElement [ ] stackTraceElements ) { } }

implementation: 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 ;


signature:
public class StackTraceElements { /** * Decodes in - memory stack trace elements to regular { @ link StackTraceElement StackTraceElements } . */
public static StackTraceElement [ ] convertToStackTraceElement ( InMemoryStackTraceElement [ ] inMemoryStackTraceElements ) { } }

implementation: 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 ;