public RequestSpecBuilder addCookie(String key, Object value, Object... cookieNameValuePairs) {
        spec.cookie(key, value, cookieNameValuePairs);
        return this;
    }

public RequestSpecBuilder addCookie ( String key , Object value , Object ... cookieNameValuePairs ) { spec . cookie ( key , value , cookieNameValuePairs ) ; return this ; }

Add a cookie to be sent with the request.

@param key                  The cookie key
@param value                The cookie value
@param cookieNameValuePairs Additional cookies values. This will actually create two cookies with the same name but with different values.
@return The request specification builder

Add a cookie to be sent with the request .


public RequestSpecBuilder addParam(String parameterName, Object... parameterValues) {
        spec.param(parameterName, parameterValues);
        return this;
    }

public RequestSpecBuilder addParam ( String parameterName , Object ... parameterValues ) { spec . param ( parameterName , parameterValues ) ; return this ; }

Add a parameter to be sent with the request.

@param parameterName   The parameter name
@param parameterValues Zero to many parameter values for this parameter name.
@return The request specification builder

Add a parameter to be sent with the request .


public RequestSpecBuilder addParam(String parameterName, Collection<?> parameterValues) {
        spec.param(parameterName, parameterValues);
        return this;
    }

public RequestSpecBuilder addParam ( String parameterName , Collection < ? > parameterValues ) { spec . param ( parameterName , parameterValues ) ; return this ; }

Add a multi-value parameter to be sent with the request.

@param parameterName   The parameter key
@param parameterValues The parameter values
@return The request specification builder

Add a multi - value parameter to be sent with the request .


public MockMvcParamConfig formParamsUpdateStrategy(UpdateStrategy updateStrategy) {
        return new MockMvcParamConfig(queryParamsUpdateStrategy, updateStrategy, requestParameterUpdateStrategy, attributeUpdateStrategy, sessionUpdateStrategy, true);
    }

public MockMvcParamConfig formParamsUpdateStrategy ( UpdateStrategy updateStrategy ) { return new MockMvcParamConfig ( queryParamsUpdateStrategy , updateStrategy , requestParameterUpdateStrategy , attributeUpdateStrategy , sessionUpdateStrategy , true ) ; }

Set form parameter update strategy to the given value.

@param updateStrategy The update strategy to use for form parameters
@return A new instance of {@link MockMvcParamConfig}

Set form parameter update strategy to the given value .


public static Filter logResponseToIfMatches(PrintStream stream, Matcher<Integer> matcher) {
        return new ResponseLoggingFilter(stream, matcher);
    }

public static Filter logResponseToIfMatches ( PrintStream stream , Matcher < Integer > matcher ) { return new ResponseLoggingFilter ( stream , matcher ) ; }

Create a new logging filter without using the "new" operator.
Will make the DSL look nicer.

@param stream The print stream to log to
@param matcher The matcher that must be fulfilled in order for logging to occur
@return a new instance of the filter

Create a new logging filter without using the new operator . Will make the DSL look nicer .


public static Cookies cookies(Cookie cookie, Cookie... additionalCookies) {
        AssertParameter.notNull(cookie, "Cookie");
        final List<Cookie> cookieList = new LinkedList<Cookie>();
        cookieList.add(cookie);
        Collections.addAll(cookieList, additionalCookies);
        return new Cookies(cookieList);
    }

public static Cookies cookies ( Cookie cookie , Cookie ... additionalCookies ) { AssertParameter . notNull ( cookie , "Cookie" ) ; final List < Cookie > cookieList = new LinkedList < Cookie > ( ) ; cookieList . add ( cookie ) ; Collections . addAll ( cookieList , additionalCookies ) ; return new Cookies ( cookieList ) ; }

An alternative way to create a Cookies object from the constructor.

@param cookie            The cookie to be included
@param additionalCookies Additional cookies to be included (optional)
@return A new cookies object containing the specified cookies

An alternative way to create a Cookies object from the constructor .


private void cleanUpForCollectedState(Set<KeyAndSource> keysAndSources) {
    synchronized (lock) {
      for (KeyAndSource keyAndSource : keysAndSources) {
        Multiset<Object> set = backingMap.get(keyAndSource.key);
        if (set != null) {
          set.remove(keyAndSource.source);
          if (set.isEmpty()) {
            backingMap.remove(keyAndSource.key);
          }
        }
      }
    }
  }

private void cleanUpForCollectedState ( Set < KeyAndSource > keysAndSources ) { synchronized ( lock ) { for ( KeyAndSource keyAndSource : keysAndSources ) { Multiset < Object > set = backingMap . get ( keyAndSource . key ) ; if ( set != null ) { set . remove ( keyAndSource . source ) ; if ( set . isEmpty ( ) ) { backingMap . remove ( keyAndSource . key ) ; } } } } }

There may be multiple child injectors blacklisting a certain key so only remove the source
that's relevant.

There may be multiple child injectors blacklisting a certain key so only remove the source that s relevant .


void index() {
    for (Binding<?> binding : state.getExplicitBindingsThisLevel().values()) {
      bindingsMultimap.put(binding.getKey().getTypeLiteral(), binding);
    }
  }

void index ( ) { for ( Binding < ? > binding : state . getExplicitBindingsThisLevel ( ) . values ( ) ) { bindingsMultimap . put ( binding . getKey ( ) . getTypeLiteral ( ) , binding ) ; } }


<T> BindingImpl<T> getBindingOrThrow(Key<T> key, Errors errors, JitLimitation jitType)
      throws ErrorsException {
    // Check explicit bindings, i.e. bindings created by modules.
    BindingImpl<T> binding = state.getExplicitBinding(key);
    if (binding != null) {
      return binding;
    }

    // Look for an on-demand binding.
    return getJustInTimeBinding(key, errors, jitType);
  }

Gets a binding implementation. First, it check to see if the parent has a binding. If the
parent has a binding and the binding is scoped, it will use that binding. Otherwise, this
checks for an explicit binding. If no explicit binding is found, it looks for a just-in-time
binding.

Gets a binding implementation . First it check to see if the parent has a binding . If the parent has a binding and the binding is scoped it will use that binding . Otherwise this checks for an explicit binding . If no explicit binding is found it looks for a just - in - time binding .


private <T> BindingImpl<T> convertConstantStringBinding(Key<T> key, Errors errors)
      throws ErrorsException {
    // Find a constant string binding.
    Key<String> stringKey = key.ofType(STRING_TYPE);
    BindingImpl<String> stringBinding = state.getExplicitBinding(stringKey);
    if (stringBinding == null || !stringBinding.isConstant()) {
      return null;
    }

    // We can't call getProvider().get() because this InstanceBinding may not have been inintialized
    // yet (because we may have been called during InternalInjectorCreator.initializeStatically and
    // instance binding validation hasn't happened yet.)
    @SuppressWarnings("unchecked")
    String stringValue = ((InstanceBinding<String>) stringBinding).getInstance();
    Object source = stringBinding.getSource();

    // Find a matching type converter.
    TypeLiteral<T> type = key.getTypeLiteral();
    TypeConverterBinding typeConverterBinding =
        state.getConverter(stringValue, type, errors, source);

    if (typeConverterBinding == null) {
      // No converter can handle the given type.
      return null;
    }

    // Try to convert the string. A failed conversion results in an error.
    try {
      @SuppressWarnings("unchecked") // This cast is safe because we double check below.
      T converted = (T) typeConverterBinding.getTypeConverter().convert(stringValue, type);

      if (converted == null) {
        throw errors
            .converterReturnedNull(stringValue, source, type, typeConverterBinding)
            .toException();
      }

      if (!type.getRawType().isInstance(converted)) {
        throw errors
            .conversionTypeError(stringValue, source, type, typeConverterBinding, converted)
            .toException();
      }

      return new ConvertedConstantBindingImpl<T>(
          this, key, converted, stringBinding, typeConverterBinding);
    } catch (ErrorsException e) {
      throw e;
    } catch (RuntimeException e) {
      throw errors
          .conversionError(stringValue, source, type, typeConverterBinding, e)
          .toException();
    }
  }

Converts a constant string binding to the required type.

@return the binding if it could be resolved, or null if the binding doesn't exist
@throws com.google.inject.internal.ErrorsException if there was an error resolving the binding

Converts a constant string binding to the required type .


private boolean cleanup(BindingImpl<?> binding, Set<Key> encountered) {
    boolean bindingFailed = false;
    Set<Dependency<?>> deps = getInternalDependencies(binding);
    for (Dependency dep : deps) {
      Key<?> depKey = dep.getKey();
      InjectionPoint ip = dep.getInjectionPoint();
      if (encountered.add(depKey)) { // only check if we haven't looked at this key yet
        BindingImpl depBinding = jitBindings.get(depKey);
        if (depBinding != null) { // if the binding still exists, validate
          boolean failed = cleanup(depBinding, encountered); // if children fail, we fail
          if (depBinding instanceof ConstructorBindingImpl) {
            ConstructorBindingImpl ctorBinding = (ConstructorBindingImpl) depBinding;
            ip = ctorBinding.getInternalConstructor();
            if (!ctorBinding.isInitialized()) {
              failed = true;
            }
          }
          if (failed) {
            removeFailedJitBinding(depBinding, ip);
            bindingFailed = true;
          }
        } else if (state.getExplicitBinding(depKey) == null) {
          // ignore keys if they were explicitly bound, but if neither JIT
          // nor explicit, it's also invalid & should let parent know.
          bindingFailed = true;
        }
      }
    }
    return bindingFailed;
  }

Iterates through the binding's dependencies to clean up any stray bindings that were leftover
from a failed JIT binding. This is required because the bindings are eagerly & optimistically
added to allow circular dependency support, so dependencies may pass where they should have
failed.

Iterates through the binding s dependencies to clean up any stray bindings that were leftover from a failed JIT binding . This is required because the bindings are eagerly & optimistically added to allow circular dependency support so dependencies may pass where they should have failed .


private void removeFailedJitBinding(Binding<?> binding, InjectionPoint ip) {
    failedJitBindings.add(binding.getKey());
    jitBindings.remove(binding.getKey());
    membersInjectorStore.remove(binding.getKey().getTypeLiteral());
    provisionListenerStore.remove(binding);
    if (ip != null) {
      constructors.remove(ip);
    }
  }

private void removeFailedJitBinding ( Binding < ? > binding , InjectionPoint ip ) { failedJitBindings . add ( binding . getKey ( ) ) ; jitBindings . remove ( binding . getKey ( ) ) ; membersInjectorStore . remove ( binding . getKey ( ) . getTypeLiteral ( ) ) ; provisionListenerStore . remove ( binding ) ; if ( ip != null ) { constructors . remove ( ip ) ; } }

Cleans up any state that may have been cached when constructing the JIT binding.

Cleans up any state that may have been cached when constructing the JIT binding .


@SuppressWarnings("unchecked")
  private Set<Dependency<?>> getInternalDependencies(BindingImpl<?> binding) {
    if (binding instanceof ConstructorBindingImpl) {
      return ((ConstructorBindingImpl) binding).getInternalDependencies();
    } else if (binding instanceof HasDependencies) {
      return ((HasDependencies) binding).getDependencies();
    } else {
      return ImmutableSet.of();
    }
  }

@ SuppressWarnings ( "unchecked" ) private Set < Dependency < ? > > getInternalDependencies ( BindingImpl < ? > binding ) { if ( binding instanceof ConstructorBindingImpl ) { return ( ( ConstructorBindingImpl ) binding ) . getInternalDependencies ( ) ; } else if ( binding instanceof HasDependencies ) { return ( ( HasDependencies ) binding ) . getDependencies ( ) ; } else { return ImmutableSet . of ( ) ; } }

Safely gets the dependencies of possibly not initialized bindings.

Safely gets the dependencies of possibly not initialized bindings .


<T> BindingImpl<T> createUninitializedBinding(
      Key<T> key, Scoping scoping, Object source, Errors errors, boolean jitBinding)
      throws ErrorsException {
    Class<?> rawType = key.getTypeLiteral().getRawType();

    ImplementedBy implementedBy = rawType.getAnnotation(ImplementedBy.class);

    // Don't try to inject arrays or enums annotated with @ImplementedBy.
    if (rawType.isArray() || (rawType.isEnum() && implementedBy != null)) {
      throw errors.missingImplementationWithHint(key, this).toException();
    }

    // Handle TypeLiteral<T> by binding the inner type
    if (rawType == TypeLiteral.class) {
      @SuppressWarnings("unchecked") // we have to fudge the inner type as Object
      BindingImpl<T> binding =
          (BindingImpl<T>) createTypeLiteralBinding((Key<TypeLiteral<Object>>) key, errors);
      return binding;
    }

    // Handle @ImplementedBy
    if (implementedBy != null) {
      Annotations.checkForMisplacedScopeAnnotations(rawType, source, errors);
      return createImplementedByBinding(key, scoping, implementedBy, errors);
    }

    // Handle @ProvidedBy.
    ProvidedBy providedBy = rawType.getAnnotation(ProvidedBy.class);
    if (providedBy != null) {
      Annotations.checkForMisplacedScopeAnnotations(rawType, source, errors);
      return createProvidedByBinding(key, scoping, providedBy, errors);
    }

    return ConstructorBindingImpl.create(
        this,
        key,
        null, /* use default constructor */
        source,
        scoping,
        errors,
        jitBinding && options.jitDisabled,
        options.atInjectRequired);
  }

Creates a binding for an injectable type with the given scope. Looks for a scope on the type if
none is specified.

Creates a binding for an injectable type with the given scope . Looks for a scope on the type if none is specified .


static Object[] getAll(InternalContext context, SingleParameterInjector<?>[] parameterInjectors)
      throws InternalProvisionException {
    if (parameterInjectors == null) {
      return NO_ARGUMENTS;
    }

    int size = parameterInjectors.length;
    Object[] parameters = new Object[size];

    // optimization: use manual for/each to save allocating an iterator here
    for (int i = 0; i < size; i++) {
      parameters[i] = parameterInjectors[i].inject(context);
    }
    return parameters;
  }


private static void bindInjector(InjectorImpl injector) {
    Key<Injector> key = Key.get(Injector.class);
    InjectorFactory injectorFactory = new InjectorFactory(injector);
    injector.state.putBinding(
        key,
        new ProviderInstanceBindingImpl<Injector>(
            injector,
            key,
            SourceProvider.UNKNOWN_SOURCE,
            injectorFactory,
            Scoping.UNSCOPED,
            injectorFactory,
            ImmutableSet.<InjectionPoint>of()));
  }

private static void bindInjector ( InjectorImpl injector ) { Key < Injector > key = Key . get ( Injector . class ) ; InjectorFactory injectorFactory = new InjectorFactory ( injector ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Injector > ( injector , key , SourceProvider . UNKNOWN_SOURCE , injectorFactory , Scoping . UNSCOPED , injectorFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; }

The Injector is a special case because we allow both parent and child injectors to both have a
binding for that key.

The Injector is a special case because we allow both parent and child injectors to both have a binding for that key .


private static void bindLogger(InjectorImpl injector) {
    Key<Logger> key = Key.get(Logger.class);
    LoggerFactory loggerFactory = new LoggerFactory();
    injector.state.putBinding(
        key,
        new ProviderInstanceBindingImpl<Logger>(
            injector,
            key,
            SourceProvider.UNKNOWN_SOURCE,
            loggerFactory,
            Scoping.UNSCOPED,
            loggerFactory,
            ImmutableSet.<InjectionPoint>of()));
  }

private static void bindLogger ( InjectorImpl injector ) { Key < Logger > key = Key . get ( Logger . class ) ; LoggerFactory loggerFactory = new LoggerFactory ( ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Logger > ( injector , key , SourceProvider . UNKNOWN_SOURCE , loggerFactory , Scoping . UNSCOPED , loggerFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; }

The Logger is a special case because it knows the injection point of the injected member. It's
the only binding that does this.

The Logger is a special case because it knows the injection point of the injected member . It s the only binding that does this .


private static boolean checkForMisplacedBindingAnnotations(Member member, Errors errors) {
    Annotation misplacedBindingAnnotation =
        Annotations.findBindingAnnotation(
            errors, member, ((AnnotatedElement) member).getAnnotations());
    if (misplacedBindingAnnotation == null) {
      return false;
    }

    // don't warn about misplaced binding annotations on methods when there's a field with the same
    // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242.
    if (member instanceof Method) {
      try {
        if (member.getDeclaringClass().getDeclaredField(member.getName()) != null) {
          return false;
        }
      } catch (NoSuchFieldException ignore) {
      }
    }

    errors.misplacedBindingAnnotation(member, misplacedBindingAnnotation);
    return true;
  }

Returns true if the binding annotation is in the wrong place.

Returns true if the binding annotation is in the wrong place .


private static boolean overrides(Method a, Method b) {
    // See JLS section 8.4.8.1
    int modifiers = b.getModifiers();
    if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
      return true;
    }
    if (Modifier.isPrivate(modifiers)) {
      return false;
    }
    // b must be package-private
    return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage());
  }

private
static
boolean
overrides
(
Method
a
,
Method
b
)
{
// See JLS section 8.4.8.1
int
modifiers
=
b
.
getModifiers
(
)
;
if
(
Modifier
.
isPublic
(
modifiers
)
||
Modifier
.
isProtected
(
modifiers
)
)
{
return
true
;
}
if
(
Modifier
.
isPrivate
(
modifiers
)
)
{
return
false
;
}
// b must be package-private
return
a
.
getDeclaringClass
(
)
.
getPackage
(
)
.
equals
(
b
.
getDeclaringClass
(
)
.
getPackage
(
)
)
;
}

Returns true if a overrides b. Assumes signatures of a and b are the same and a's declaring
class is a subclass of b's declaring class.

Returns true if a overrides b . Assumes signatures of a and b are the same and a s declaring class is a subclass of b s declaring class .


public void initializeDelegate(MembersInjector<T> delegate) {
    checkState(this.delegate == null, "delegate already initialized");
    this.delegate = checkNotNull(delegate, "delegate");
  }

public
void
initializeDelegate
(
MembersInjector
<
T
>
delegate
)
{
checkState
(
this
.
delegate
==
,
"delegate already initialized"
)
;
this
.
delegate
=
checkNotNull
(
delegate
,
"delegate"
)
;
}

Sets the actual members injector.

@throws IllegalStateException if the delegate is already set


@SuppressWarnings("unchecked")
  final TypeLiteral<Provider<T>> providerType() {
    // This cast is safe and wouldn't generate a warning if Type had a type
    // parameter.
    return (TypeLiteral<Provider<T>>) get(Types.providerOf(getType()));
  }


private List<TypeLiteral<?>> resolveAll(Type[] types) {
    TypeLiteral<?>[] result = new TypeLiteral<?>[types.length];
    for (int t = 0; t < types.length; t++) {
      result[t] = resolve(types[t]);
    }
    return ImmutableList.copyOf(result);
  }

private List < TypeLiteral < ? > > resolveAll ( Type [ ] types ) { TypeLiteral < ? > [ ] result = new TypeLiteral < ? > [ types . length ] ; for ( int t = 0 ; t < types . length ; t ++ ) { result [ t ] = resolve ( types [ t ] ) ; } return ImmutableList . copyOf ( result ) ; }

Returns an immutable list of the resolved types.

Returns an immutable list of the resolved types .


public static <T> TypeLiteral<T> canonicalizeForKey(TypeLiteral<T> typeLiteral) {
    Type type = typeLiteral.getType();
    if (!isFullySpecified(type)) {
      Errors errors = new Errors().keyNotFullySpecified(typeLiteral);
      throw new ConfigurationException(errors.getMessages());
    }

    if (typeLiteral.getRawType() == javax.inject.Provider.class) {
      ParameterizedType parameterizedType = (ParameterizedType) type;

      // the following casts are generally unsafe, but com.google.inject.Provider extends
      // javax.inject.Provider and is covariant
      @SuppressWarnings("unchecked")
      TypeLiteral<T> guiceProviderType =
          (TypeLiteral<T>)
              TypeLiteral.get(Types.providerOf(parameterizedType.getActualTypeArguments()[0]));
      return guiceProviderType;
    }

    @SuppressWarnings("unchecked")
    TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(typeLiteral);
    if (wrappedPrimitives != null) {
      return wrappedPrimitives;
    }

    // If we know this isn't a subclass, return as-is.
    if (typeLiteral.getClass() == TypeLiteral.class) {
      return typeLiteral;
    }

    // recreate the TypeLiteral to avoid anonymous TypeLiterals from holding refs to their
    // surrounding classes.
    @SuppressWarnings("unchecked")
    TypeLiteral<T> recreated = (TypeLiteral<T>) TypeLiteral.get(typeLiteral.getType());
    return recreated;
  }

Returns an type that's appropriate for use in a key.

If the raw type of {@code typeLiteral} is a {@code javax.inject.Provider}, this returns a
{@code com.google.inject.Provider} with the same type parameters.

If the type is a primitive, the corresponding wrapper type will be returned.

@throws ConfigurationException if {@code type} contains a type variable

Returns an type that s appropriate for use in a key .


static void prepareBuiltInConverters(InjectorImpl injector) {
    // Configure type converters.
    convertToPrimitiveType(injector, int.class, Integer.class);
    convertToPrimitiveType(injector, long.class, Long.class);
    convertToPrimitiveType(injector, boolean.class, Boolean.class);
    convertToPrimitiveType(injector, byte.class, Byte.class);
    convertToPrimitiveType(injector, short.class, Short.class);
    convertToPrimitiveType(injector, float.class, Float.class);
    convertToPrimitiveType(injector, double.class, Double.class);

    convertToClass(
        injector,
        Character.class,
        new TypeConverter() {
          @Override
          public Object convert(String value, TypeLiteral<?> toType) {
            value = value.trim();
            if (value.length() != 1) {
              throw new RuntimeException("Length != 1.");
            }
            return value.charAt(0);
          }

          @Override
          public String toString() {
            return "TypeConverter<Character>";
          }
        });

    convertToClasses(
        injector,
        Matchers.subclassesOf(Enum.class),
        new TypeConverter() {
          @Override
          @SuppressWarnings("unchecked")
          public Object convert(String value, TypeLiteral<?> toType) {
            return Enum.valueOf((Class) toType.getRawType(), value);
          }

          @Override
          public String toString() {
            return "TypeConverter<E extends Enum<E>>";
          }
        });

    internalConvertToTypes(
        injector,
        new AbstractMatcher<TypeLiteral<?>>() {
          @Override
          public boolean matches(TypeLiteral<?> typeLiteral) {
            return typeLiteral.getRawType() == Class.class;
          }

          @Override
          public String toString() {
            return "Class<?>";
          }
        },
        new TypeConverter() {
          @Override
          @SuppressWarnings("unchecked")
          public Object convert(String value, TypeLiteral<?> toType) {
            try {
              return Class.forName(value);
            } catch (ClassNotFoundException e) {
              throw new RuntimeException(e.getMessage());
            }
          }

          @Override
          public String toString() {
            return "TypeConverter<Class<?>>";
          }
        });
  }

static
void
prepareBuiltInConverters
(
InjectorImpl
injector
)
{
// Configure type converters.
convertToPrimitiveType
(
injector
,
int
.
class
,
Integer
.
class
)
;
convertToPrimitiveType
(
injector
,
long
.
class
,
Long
.
class
)
;
convertToPrimitiveType
(
injector
,
boolean
.
class
,
Boolean
.
class
)
;
convertToPrimitiveType
(
injector
,
byte
.
class
,
Byte
.
class
)
;
convertToPrimitiveType
(
injector
,
short
.
class
,
Short
.
class
)
;
convertToPrimitiveType
(
injector
,
float
.
class
,
Float
.
class
)
;
convertToPrimitiveType
(
injector
,
double
.
class
,
Double
.
class
)
;
convertToClass
(
injector
,
Character
.
class
,
new
TypeConverter
(
)
{
@
Override
public
Object
convert
(
String
value
,
TypeLiteral
<
>
toType
)
{
value
=
value
.
trim
(
)
;
if
(
value
.
length
(
)
!=
1
)
{
throw
new
RuntimeException
(
"Length != 1."
)
;
}
return
value
.
charAt
(
0
)
;
}
@
Override
public
String
toString
(
)
{
return
"TypeConverter<Character>"
;
}
}
)
;
convertToClasses
(
injector
,
Matchers
.
subclassesOf
(
Enum
.
class
)
,
new
TypeConverter
(
)
{
@
Override
@
SuppressWarnings
(
"unchecked"
)
public
Object
convert
(
String
value
,
TypeLiteral
<
>
toType
)
{
return
Enum
.
valueOf
(
(
Class
)
toType
.
getRawType
(
)
,
value
)
;
}
@
Override
public
String
toString
(
)
{
return
"TypeConverter<E extends Enum<E>>"
;
}
}
)
;
internalConvertToTypes
(
injector
,
new
AbstractMatcher
<
TypeLiteral
<
>
>
(
)
{
@
Override
public
boolean
matches
(
TypeLiteral
<
>
typeLiteral
)
{
return
typeLiteral
.
getRawType
(
)
==
Class
.
class
;
}
@
Override
public
String
toString
(
)
{
return
"Class<?>"
;
}
}
,
new
TypeConverter
(
)
{
@
Override
@
SuppressWarnings
(
"unchecked"
)
public
Object
convert
(
String
value
,
TypeLiteral
<
>
toType
)
{
try
{
return
Class
.
forName
(
value
)
;
}
catch
(
ClassNotFoundException
e
)
{
throw
new
RuntimeException
(
e
.
getMessage
(
)
)
;
}
}
@
Override
public
String
toString
(
)
{
return
"TypeConverter<Class<?>>"
;
}
}
)
;
}

Installs default converters for primitives, enums, and class literals.

Installs default converters for primitives enums and class literals .


private static ClassLoader canonicalize(ClassLoader classLoader) {
    return classLoader != null ? classLoader : SystemBridgeHolder.SYSTEM_BRIDGE.getParent();
  }

private static ClassLoader canonicalize ( ClassLoader classLoader ) { return classLoader != null ? classLoader : SystemBridgeHolder . SYSTEM_BRIDGE . getParent ( ) ; }

Attempts to canonicalize null references to the system class loader. May return null if for
some reason the system loader is unavailable.

Attempts to canonicalize null references to the system class loader . May return null if for some reason the system loader is unavailable .


private static boolean hasSameVersionOfCglib(ClassLoader classLoader) {
    Class<?> fc = net.sf.cglib.reflect.FastClass.class;
    try {
      return classLoader.loadClass(fc.getName()) == fc;
    } catch (ClassNotFoundException e) {
      return false;
    }
  }

private static boolean hasSameVersionOfCglib ( ClassLoader classLoader ) { Class < ? > fc = net . sf . cglib . reflect . FastClass . class ; try { return classLoader . loadClass ( fc . getName ( ) ) == fc ; } catch ( ClassNotFoundException e ) { return false ; } }

Returns true if the types classloader has the same version of cglib that BytecodeGen has. This
only returns false in strange OSGI situations, but it prevents us from using FastClass for non
public members.

Returns true if the types classloader has the same version of cglib that BytecodeGen has . This only returns false in strange OSGI situations but it prevents us from using FastClass for non public members .


private static boolean isPubliclyCallable(Member member) {
    if (!Modifier.isPublic(member.getModifiers())) {
      return false;
    }
    Class<?>[] parameterTypes;
    if (member instanceof Constructor) {
      parameterTypes = ((Constructor) member).getParameterTypes();
    } else {
      Method method = (Method) member;
      if (!Modifier.isPublic(method.getReturnType().getModifiers())) {
        return false;
      }
      parameterTypes = method.getParameterTypes();
    }

    for (Class<?> type : parameterTypes) {
      if (!Modifier.isPublic(type.getModifiers())) {
        return false;
      }
    }
    return true;
  }

private static boolean isPubliclyCallable ( Member member ) { if ( ! Modifier . isPublic ( member . getModifiers ( ) ) ) { return false ; } Class < ? > [ ] parameterTypes ; if ( member instanceof Constructor ) { parameterTypes = ( ( Constructor ) member ) . getParameterTypes ( ) ; } else { Method method = ( Method ) member ; if ( ! Modifier . isPublic ( method . getReturnType ( ) . getModifiers ( ) ) ) { return false ; } parameterTypes = method . getParameterTypes ( ) ; } for ( Class < ? > type : parameterTypes ) { if ( ! Modifier . isPublic ( type . getModifiers ( ) ) ) { return false ; } } return true ; }

Returns true if the member can be called by a fast class generated in a different classloader.

Returns true if the member can be called by a fast class generated in a different classloader .


public Key<?> fixAnnotations(Key<?> key) {
    return key.getAnnotation() == null
        ? key
        : Key.get(key.getTypeLiteral(), key.getAnnotation().annotationType());
  }

public Key < ? > fixAnnotations ( Key < ? > key ) { return key . getAnnotation ( ) == null ? key : Key . get ( key . getTypeLiteral ( ) , key . getAnnotation ( ) . annotationType ( ) ) ; }

Replace annotation instances with annotation types, this is only appropriate for testing if a
key is bound and not for injecting.

<p>See Guice bug 125, https://github.com/google/guice/issues/125

Replace annotation instances with annotation types this is only appropriate for testing if a key is bound and not for injecting .


<T> Initializable<T> requestInjection(
      InjectorImpl injector,
      T instance,
      Binding<T> binding,
      Object source,
      Set<InjectionPoint> injectionPoints) {
    checkNotNull(source);
    Preconditions.checkState(
        !validationStarted, "Member injection could not be requested after validation is started");
    ProvisionListenerStackCallback<T> provisionCallback =
        binding == null ? null : injector.provisionListenerStore.get(binding);

    // short circuit if the object has no injections or listeners.
    if (instance == null
        || (injectionPoints.isEmpty()
            && !injector.membersInjectorStore.hasTypeListeners()
            && provisionCallback == null)) {
      return Initializables.of(instance);
    }

    if (initializablesCache.containsKey(instance)) {
      @SuppressWarnings("unchecked") // Map from T to InjectableReference<T>
      Initializable<T> cached = (Initializable<T>) initializablesCache.get(instance);
      return cached;
    }

    InjectableReference<T> injectableReference =
        new InjectableReference<T>(
            injector,
            instance,
            binding == null ? null : binding.getKey(),
            provisionCallback,
            source,
            cycleDetectingLockFactory.create(instance.getClass()));
    initializablesCache.put(instance, injectableReference);
    pendingInjections.add(injectableReference);
    return injectableReference;
  }

Registers an instance for member injection when that step is performed.

@param instance an instance that optionally has members to be injected (each annotated
with @Inject).
@param binding the binding that caused this initializable to be created, if it exists.
@param source the source location that this injection was requested

Registers an instance for member injection when that step is performed .


void validateOustandingInjections(Errors errors) {
    validationStarted = true;
    initializablesCache.clear();
    for (InjectableReference<?> reference : pendingInjections) {
      try {
        reference.validate(errors);
      } catch (ErrorsException e) {
        errors.merge(e.getErrors());
      }
    }
  }

void validateOustandingInjections ( Errors errors ) { validationStarted = true ; initializablesCache . clear ( ) ; for ( InjectableReference < ? > reference : pendingInjections ) { try { reference . validate ( errors ) ; } catch ( ErrorsException e ) { errors . merge ( e . getErrors ( ) ) ; } } }

Prepares member injectors for all injected instances. This prompts Guice to do static analysis
on the injected instances.

Prepares member injectors for all injected instances . This prompts Guice to do static analysis on the injected instances .


public T newInstance(Object[] args) throws Throwable {
    constructor.setAccessible(true);
    try {
      return constructor.newInstance(args);
    } catch (InvocationTargetException e) {
      throw e.getCause();
    }
  }

public T newInstance ( Object [ ] args ) throws Throwable { constructor . setAccessible ( true ) ; try { return constructor . newInstance ( args ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } }

Returns an instance of T, constructed using this constructor, with the supplied arguments.

Returns an instance of T constructed using this constructor with the supplied arguments .


@SuppressWarnings({"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);
      }
    };
  }

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.

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.

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).

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 .


static <T> InternalFactory<? extends T> scope(
      Key<T> key,
      InjectorImpl injector,
      InternalFactory<? extends T> creator,
      Object source,
      Scoping scoping) {

    if (scoping.isNoScope()) {
      return creator;
    }

    Scope scope = scoping.getScopeInstance();

    // NOTE: SingletonScope relies on the fact that we are passing a
    // ProviderToInternalFactoryAdapter here.  If you change the type make sure to update
    // SingletonScope as well.
    Provider<T> scoped =
        scope.scope(key, new ProviderToInternalFactoryAdapter<T>(injector, creator));
    return new InternalFactoryToProviderAdapter<T>(scoped, source);
  }


static Scoping makeInjectable(Scoping scoping, InjectorImpl injector, Errors errors) {
    Class<? extends Annotation> scopeAnnotation = scoping.getScopeAnnotation();
    if (scopeAnnotation == null) {
      return scoping;
    }

    ScopeBinding scope = injector.state.getScopeBinding(scopeAnnotation);
    if (scope != null) {
      return forInstance(scope.getScope());
    }

    errors.scopeNotFound(scopeAnnotation);
    return UNSCOPED;
  }

static Scoping makeInjectable ( Scoping scoping , InjectorImpl injector , Errors errors ) { Class < ? extends Annotation > scopeAnnotation = scoping . getScopeAnnotation ( ) ; if ( scopeAnnotation == null ) { return scoping ; } ScopeBinding scope = injector . state . getScopeBinding ( scopeAnnotation ) ; if ( scope != null ) { return forInstance ( scope . getScope ( ) ) ; } errors . scopeNotFound ( scopeAnnotation ) ; return UNSCOPED ; }

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.

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

Normalizes a path by unescaping all safe, percent encoded characters.

Normalizes a path by unescaping all safe percent encoded characters .


public static <T extends Annotation> T generateAnnotation(Class<T> annotationType) {
    Preconditions.checkState(
        isAllDefaultMethods(annotationType), "%s is not all default methods", annotationType);
    return (T) cache.getUnchecked(annotationType);
  }

public
static
<
T
extends
Annotation
>
T
generateAnnotation
(
Class
<
T
>
annotationType
)
{
Preconditions
.
checkState
(
isAllDefaultMethods
(
annotationType
)
,
"%s is not all default methods"
,
annotationType
)
;
return
(
T
)
cache
.
getUnchecked
(
annotationType
)
;
}

Generates an Annotation for the annotation class. Requires that the annotation is all
optionals.

Generates an Annotation for the annotation class . Requires that the annotation is all optionals .


public static boolean isRetainedAtRuntime(Class<? extends Annotation> annotationType) {
    Retention retention = annotationType.getAnnotation(Retention.class);
    return retention != null && retention.value() == RetentionPolicy.RUNTIME;
  }

public static boolean isRetainedAtRuntime ( Class < ? extends Annotation > annotationType ) { Retention retention = annotationType . getAnnotation ( Retention . class ) ; return retention != null && retention . value ( ) == RetentionPolicy . RUNTIME ; }

Returns true if the given annotation is retained at runtime.

Returns true if the given annotation is retained at runtime .


public static Class<? extends Annotation> findScopeAnnotation(
      Errors errors, Annotation[] annotations) {
    Class<? extends Annotation> found = null;

    for (Annotation annotation : annotations) {
      Class<? extends Annotation> annotationType = annotation.annotationType();
      if (isScopeAnnotation(annotationType)) {
        if (found != null) {
          errors.duplicateScopeAnnotations(found, annotationType);
        } else {
          found = annotationType;
        }
      }
    }

    return found;
  }

public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Annotation [ ] annotations ) { Class < ? extends Annotation > found = null ; for ( Annotation annotation : annotations ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; if ( isScopeAnnotation ( annotationType ) ) { if ( found != null ) { errors . duplicateScopeAnnotations ( found , annotationType ) ; } else { found = annotationType ; } } } return found ; }

Returns the scoping annotation, or null if there isn't one.

Returns the scoping annotation or null if there isn t one .


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

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

Gets a key for the given type, member and annotations.

Gets a key for the given type member and annotations .


public static String nameOf(Key<?> key) {
    Annotation annotation = key.getAnnotation();
    Class<? extends Annotation> annotationType = key.getAnnotationType();
    if (annotation != null && !isMarker(annotationType)) {
      return key.getAnnotation().toString();
    } else if (key.getAnnotationType() != null) {
      return "@" + key.getAnnotationType().getName();
    } else {
      return "";
    }
  }

public static String nameOf ( Key < ? > key ) { Annotation annotation = key . getAnnotation ( ) ; Class < ? extends Annotation > annotationType = key . getAnnotationType ( ) ; if ( annotation != null && ! isMarker ( annotationType ) ) { return key . getAnnotation ( ) . toString ( ) ; } else if ( key . getAnnotationType ( ) != null ) { return "@" + key . getAnnotationType ( ) . getName ( ) ; } else { return "" ; } }

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.

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 void initializeDelegate(Provider<T> delegate) {
    checkState(this.delegate == null, "delegate already initialized");
    this.delegate = checkNotNull(delegate, "delegate");
  }

public
void
initializeDelegate
(
Provider
<
T
>
delegate
)
{
checkState
(
this
.
delegate
==
,
"delegate already initialized"
)
;
this
.
delegate
=
checkNotNull
(
delegate
,
"delegate"
)
;
}

Sets the actual provider.

@throws IllegalStateException if the delegate is already set


private void addDirectTypeBinding(Binder binder) {
    binder
        .bind(bindingSelection.getDirectKey())
        .toProvider(new RealDirectTypeProvider<T>(bindingSelection));
  }

private void addDirectTypeBinding ( Binder binder ) { binder . bind ( bindingSelection . getDirectKey ( ) ) . toProvider ( new RealDirectTypeProvider < T > ( bindingSelection ) ) ; }

Adds a binding for T. Multiple calls to this are safe, and will be collapsed as duplicate
bindings.

Adds a binding for T . Multiple calls to this are safe and will be collapsed as duplicate bindings .


public ConstructorInjector<?> get(InjectionPoint constructorInjector, Errors errors)
      throws ErrorsException {
    return cache.get(constructorInjector, errors);
  }

public ConstructorInjector < ? > get ( InjectionPoint constructorInjector , Errors errors ) throws ErrorsException { return cache . get ( constructorInjector , errors ) ; }

Returns a new complete constructor injector with injection listeners registered.

Returns a new complete constructor injector with injection listeners registered .


private static boolean hasScope(Class<? extends Interceptor> interceptorClass) {
    for (Annotation annotation : interceptorClass.getAnnotations()) {
      if (Annotations.isScopeAnnotation(annotation.annotationType())) {
        return true;
      }
    }
    return false;
  }

private static boolean hasScope ( Class < ? extends Interceptor > interceptorClass ) { for ( Annotation annotation : interceptorClass . getAnnotations ( ) ) { if ( Annotations . isScopeAnnotation ( annotation . annotationType ( ) ) ) { return true ; } } return false ; }

Returns true if the given class has a scope annotation.

Returns true if the given class has a scope annotation .


static <K, V> RealMapBinder<K, V> newRealMapBinder(
      Binder binder, TypeLiteral<K> keyType, Key<V> valueTypeAndAnnotation) {
    binder = binder.skipSources(RealMapBinder.class);
    TypeLiteral<V> valueType = valueTypeAndAnnotation.getTypeLiteral();
    return newRealMapBinder(
        binder,
        keyType,
        valueType,
        valueTypeAndAnnotation.ofType(mapOf(keyType, valueType)),
        RealMultibinder.newRealSetBinder(
            binder, valueTypeAndAnnotation.ofType(entryOfProviderOf(keyType, valueType))));
  }

static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , Key < V > valueTypeAndAnnotation ) { binder = binder . skipSources ( RealMapBinder . class ) ; TypeLiteral < V > valueType = valueTypeAndAnnotation . getTypeLiteral ( ) ; return newRealMapBinder ( binder , keyType , valueType , valueTypeAndAnnotation . ofType ( mapOf ( keyType , valueType ) ) , RealMultibinder . newRealSetBinder ( binder , valueTypeAndAnnotation . ofType ( entryOfProviderOf ( keyType , valueType ) ) ) ) ; }

since it's an easy way to group a type and an optional annotation type or instance.

since it s an easy way to group a type and an optional annotation type or instance .


Key<V> getKeyForNewValue(K key) {
    checkNotNull(key, "key");
    checkConfiguration(!bindingSelection.isInitialized(), "MapBinder was already initialized");
    RealMultibinder<Map.Entry<K, Provider<V>>> entrySetBinder =
        bindingSelection.getEntrySetBinder();

    Key<V> valueKey =
        Key.get(
            bindingSelection.getValueType(),
            new RealElement(
                entrySetBinder.getSetName(), MAPBINDER, bindingSelection.getKeyType().toString()));
    entrySetBinder.addBinding().toProvider(new ProviderMapEntry<K, V>(key, valueKey));
    return valueKey;
  }

Key
<
V
>
getKeyForNewValue
(
K
key
)
{
checkNotNull
(
key
,
"key"
)
;
checkConfiguration
(
!
bindingSelection
.
isInitialized
(
)
,
"MapBinder was already initialized"
)
;
RealMultibinder
<
Map
.
Entry
<
K
,
Provider
<
V
>
>
>
entrySetBinder
=
bindingSelection
.
getEntrySetBinder
(
)
;
Key
<
V
>
valueKey
=
Key
.
get
(
bindingSelection
.
getValueType
(
)
,
new
RealElement
(
entrySetBinder
.
getSetName
(
)
,
MAPBINDER
,
bindingSelection
.
getKeyType
(
)
.
toString
(
)
)
)
;
entrySetBinder
.
addBinding
(
)
.
toProvider
(
new
ProviderMapEntry
<
K
,
V
>
(
key
,
valueKey
)
)
;
return
valueKey
;
}

Adds a binding to the map for the given key.

Adds a binding to the map for the given key .


private T provision(InternalContext context, ConstructionContext<T> constructionContext)
      throws InternalProvisionException {
    try {
      T t;
      try {
        Object[] parameters = SingleParameterInjector.getAll(context, parameterInjectors);
        t = constructionProxy.newInstance(parameters);
        constructionContext.setProxyDelegates(t);
      } finally {
        constructionContext.finishConstruction();
      }

      // Store reference. If an injector re-enters this factory, they'll get the same reference.
      constructionContext.setCurrentReference(t);

      MembersInjectorImpl<T> localMembersInjector = membersInjector;
      localMembersInjector.injectMembers(t, context, false);
      localMembersInjector.notifyListeners(t);

      return t;
    } catch (InvocationTargetException userException) {
      Throwable cause = userException.getCause() != null ? userException.getCause() : userException;
      throw InternalProvisionException.errorInjectingConstructor(cause)
          .addSource(constructionProxy.getInjectionPoint());
    } finally {
      constructionContext.removeCurrentReference();
    }
  }


private Object writeReplace() throws ObjectStreamException {
    Object[] sourcesAsStrings = sources.toArray();
    for (int i = 0; i < sourcesAsStrings.length; i++) {
      sourcesAsStrings[i] = Errors.convert(sourcesAsStrings[i]).toString();
    }
    return new Message(ImmutableList.copyOf(sourcesAsStrings), message, cause);
  }

private Object writeReplace ( ) throws ObjectStreamException { Object [ ] sourcesAsStrings = sources . toArray ( ) ; for ( int i = 0 ; i < sourcesAsStrings . length ; i ++ ) { sourcesAsStrings [ i ] = Errors . convert ( sourcesAsStrings [ i ] ) . toString ( ) ; } return new Message ( ImmutableList . copyOf ( sourcesAsStrings ) , message , cause ) ; }

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.

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 .


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

    return new CheckedProviderMethodsModule(module);
  }

Returns a module which creates bindings for provider methods from the given module.

Returns a module which creates bindings for provider methods from the given module .


@Override
  @SuppressWarnings("unchecked")
  public Collection<AssistedMethod> getAssistedMethods() {
    return (Collection<AssistedMethod>) (Collection<?>) assistDataByMethod.values();
  }

@ Override @ SuppressWarnings ( "unchecked" ) public Collection < AssistedMethod > getAssistedMethods ( ) { return ( Collection < AssistedMethod > ) ( Collection < ? > ) assistDataByMethod . values ( ) ; }


private boolean isTypeNotSpecified(TypeLiteral<?> typeLiteral, ConfigurationException ce) {
    Collection<Message> messages = ce.getErrorMessages();
    if (messages.size() == 1) {
      Message msg =
          Iterables.getOnlyElement(new Errors().keyNotFullySpecified(typeLiteral).getMessages());
      return msg.getMessage().equals(Iterables.getOnlyElement(messages).getMessage());
    } else {
      return false;
    }
  }

private boolean isTypeNotSpecified ( TypeLiteral < ? > typeLiteral , ConfigurationException ce ) { Collection < Message > messages = ce . getErrorMessages ( ) ; if ( messages . size ( ) == 1 ) { Message msg = Iterables . getOnlyElement ( new Errors ( ) . keyNotFullySpecified ( typeLiteral ) . getMessages ( ) ) ; return msg . getMessage ( ) . equals ( Iterables . getOnlyElement ( messages ) . getMessage ( ) ) ; } else { return false ; } }

Returns true if the ConfigurationException is due to an error of TypeLiteral not being fully
specified.

Returns true if the ConfigurationException is due to an error of TypeLiteral not being fully specified .


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

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.

Matching logic for constructors annotated with AssistedInject . This returns true if and only if all


private Set<Dependency<?>> getDependencies(
      InjectionPoint ctorPoint, TypeLiteral<?> implementation) {
    ImmutableSet.Builder<Dependency<?>> builder = ImmutableSet.builder();
    builder.addAll(ctorPoint.getDependencies());
    if (!implementation.getRawType().isInterface()) {
      for (InjectionPoint ip : InjectionPoint.forInstanceMethodsAndFields(implementation)) {
        builder.addAll(ip.getDependencies());
      }
    }
    return builder.build();
  }

private Set < Dependency < ? > > getDependencies ( InjectionPoint ctorPoint , TypeLiteral < ? > implementation ) { ImmutableSet . Builder < Dependency < ? > > builder = ImmutableSet . builder ( ) ; builder . addAll ( ctorPoint . getDependencies ( ) ) ; if ( ! implementation . getRawType ( ) . isInterface ( ) ) { for ( InjectionPoint ip : InjectionPoint . forInstanceMethodsAndFields ( implementation ) ) { builder . addAll ( ip . getDependencies ( ) ) ; } } return builder . build ( ) ; }

Calculates all dependencies required by the implementation and constructor.

Calculates all dependencies required by the implementation and constructor .


private Set<Dependency<?>> removeAssistedDeps(Set<Dependency<?>> deps) {
    ImmutableSet.Builder<Dependency<?>> builder = ImmutableSet.builder();
    for (Dependency<?> dep : deps) {
      Class<?> annotationType = dep.getKey().getAnnotationType();
      if (annotationType == null || !annotationType.equals(Assisted.class)) {
        builder.add(dep);
      }
    }
    return builder.build();
  }

private Set < Dependency < ? > > removeAssistedDeps ( Set < Dependency < ? > > deps ) { ImmutableSet . Builder < Dependency < ? > > builder = ImmutableSet . builder ( ) ; for ( Dependency < ? > dep : deps ) { Class < ? > annotationType = dep . getKey ( ) . getAnnotationType ( ) ; if ( annotationType == null || ! annotationType . equals ( Assisted . class ) ) { builder . add ( dep ) ; } } return builder . build ( ) ; }

Return all non - assisted dependencies .


private boolean isValidForOptimizedAssistedInject(
      Set<Dependency<?>> dependencies, Class<?> implementation, TypeLiteral<?> factoryType) {
    Set<Dependency<?>> badDeps = null; // optimization: create lazily
    for (Dependency<?> dep : dependencies) {
      if (isInjectorOrAssistedProvider(dep)) {
        if (badDeps == null) {
          badDeps = Sets.newHashSet();
        }
        badDeps.add(dep);
      }
    }
    if (badDeps != null && !badDeps.isEmpty()) {
      logger.log(
          Level.WARNING,
          "AssistedInject factory {0} will be slow "
              + "because {1} has assisted Provider dependencies or injects the Injector. "
              + "Stop injecting @Assisted Provider<T> (instead use @Assisted T) "
              + "or Injector to speed things up. (It will be a ~6500% speed bump!)  "
              + "The exact offending deps are: {2}",
          new Object[] {factoryType, implementation, badDeps});
      return false;
    }
    return true;
  }

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.

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 .


public Binding<?> getBindingFromNewInjector(
      final Method method, final Object[] args, final AssistData data) {
    checkState(
        injector != null,
        "Factories.create() factories cannot be used until they're initialized by Guice.");

    final Key<?> returnType = data.returnType;

    // We ignore any pre-existing binding annotation.
    final Key<?> returnKey = Key.get(returnType.getTypeLiteral(), RETURN_ANNOTATION);

    Module assistedModule =
        new AbstractModule() {
          @Override
          @SuppressWarnings({
            "unchecked",
            "rawtypes"
          }) // raw keys are necessary for the args array and return value
          protected void configure() {
            Binder binder = binder().withSource(method);

            int p = 0;
            if (!data.optimized) {
              for (Key<?> paramKey : data.paramTypes) {
                // Wrap in a Provider to cover null, and to prevent Guice from injecting the
                // parameter
                binder.bind((Key) paramKey).toProvider(Providers.of(args[p++]));
              }
            } else {
              for (Key<?> paramKey : data.paramTypes) {
                // Bind to our ThreadLocalProviders.
                binder.bind((Key) paramKey).toProvider(data.providers.get(p++));
              }
            }

            Constructor constructor = data.constructor;
            // Constructor *should* always be non-null here,
            // but if it isn't, we'll end up throwing a fairly good error
            // message for the user.
            if (constructor != null) {
              binder
                  .bind(returnKey)
                  .toConstructor(constructor, (TypeLiteral) data.implementationType)
                  .in(Scopes.NO_SCOPE); // make sure we erase any scope on the implementation type
            }
          }
        };

    Injector forCreate = injector.createChildInjector(assistedModule);
    Binding<?> binding = forCreate.getBinding(returnKey);
    // If we have providers cached in data, cache the binding for future optimizations.
    if (data.optimized) {
      data.cachedBinding = binding;
    }
    return binding;
  }

Creates a child injector that binds the args, and returns the binding for the method's result.

Creates a child injector that binds the args and returns the binding for the method s result .


@Override
  public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
    // If we setup a method handle earlier for this method, call it.
    // This is necessary for default methods that java8 creates, so we
    // can call the default method implementation (and not our proxied version of it).
    if (methodHandleByMethod.containsKey(method)) {
      return methodHandleByMethod.get(method).invokeWithArguments(args);
    }

    if (method.getDeclaringClass().equals(Object.class)) {
      if ("equals".equals(method.getName())) {
        return proxy == args[0];
      } else if ("hashCode".equals(method.getName())) {
        return System.identityHashCode(proxy);
      } else {
        return method.invoke(this, args);
      }
    }

    AssistData data = assistDataByMethod.get(method);
    checkState(data != null, "No data for method: %s", method);
    Provider<?> provider;
    if (data.cachedBinding != null) { // Try to get optimized form...
      provider = data.cachedBinding.getProvider();
    } else {
      provider = getBindingFromNewInjector(method, args, data).getProvider();
    }
    try {
      int p = 0;
      for (ThreadLocalProvider tlp : data.providers) {
        tlp.set(args[p++]);
      }
      return provider.get();
    } catch (ProvisionException e) {
      // if this is an exception declared by the factory method, throw it as-is
      if (e.getErrorMessages().size() == 1) {
        Message onlyError = getOnlyElement(e.getErrorMessages());
        Throwable cause = onlyError.getCause();
        if (cause != null && canRethrow(method, cause)) {
          throw cause;
        }
      }
      throw e;
    } finally {
      for (ThreadLocalProvider tlp : data.providers) {
        tlp.remove();
      }
    }
  }

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.

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 .


<T> Errors missingImplementationWithHint(Key<T> key, Injector injector) {
    StringBuilder sb = new StringBuilder();

    sb.append(format("No implementation for %s was bound.", key));

    // Keys which have similar strings as the desired key
    List<String> possibleMatches = new ArrayList<>();

    // Check for other keys that may have the same type,
    // but not the same annotation
    TypeLiteral<T> type = key.getTypeLiteral();
    List<Binding<T>> sameTypes = injector.findBindingsByType(type);
    if (!sameTypes.isEmpty()) {
      sb.append(format("%n  Did you mean?"));
      int howMany = Math.min(sameTypes.size(), MAX_MATCHING_TYPES_REPORTED);
      for (int i = 0; i < howMany; ++i) {
        // TODO: Look into a better way to prioritize suggestions. For example, possbily
        // use levenshtein distance of the given annotation vs actual annotation.
        sb.append(format("%n    * %s", sameTypes.get(i).getKey()));
      }
      int remaining = sameTypes.size() - MAX_MATCHING_TYPES_REPORTED;
      if (remaining > 0) {
        String plural = (remaining == 1) ? "" : "s";
        sb.append(format("%n    %d more binding%s with other annotations.", remaining, plural));
      }
    } else {
      // For now, do a simple substring search for possibilities. This can help spot
      // issues when there are generics being used (such as a wrapper class) and the
      // user has forgotten they need to bind based on the wrapper, not the underlying
      // class. In the future, consider doing a strict in-depth type search.
      // TODO: Look into a better way to prioritize suggestions. For example, possbily
      // use levenshtein distance of the type literal strings.
      String want = type.toString();
      Map<Key<?>, Binding<?>> bindingMap = injector.getAllBindings();
      for (Key<?> bindingKey : bindingMap.keySet()) {
        String have = bindingKey.getTypeLiteral().toString();
        if (have.contains(want) || want.contains(have)) {
          Formatter fmt = new Formatter();
          Messages.formatSource(fmt, bindingMap.get(bindingKey).getSource());
          String match = String.format("%s bound%s", convert(bindingKey), fmt.toString());
          possibleMatches.add(match);
          // TODO: Consider a check that if there are more than some number of results,
          // don't suggest any.
          if (possibleMatches.size() > MAX_RELATED_TYPES_REPORTED) {
            // Early exit if we have found more than we need.
            break;
          }
        }
      }

      if ((possibleMatches.size() > 0) && (possibleMatches.size() <= MAX_RELATED_TYPES_REPORTED)) {
        sb.append(format("%n  Did you mean?"));
        for (String possibleMatch : possibleMatches) {
          sb.append(format("%n    %s", possibleMatch));
        }
      }
    }

    // If where are no possibilities to suggest, then handle the case of missing
    // annotations on simple types. This is usually a bad idea.
    if (sameTypes.isEmpty()
        && possibleMatches.isEmpty()
        && key.getAnnotation() == null
        && COMMON_AMBIGUOUS_TYPES.contains(key.getTypeLiteral().getRawType())) {
      // We don't recommend using such simple types without annotations.
      sb.append(format("%nThe key seems very generic, did you forget an annotation?"));
    }

    return addMessage(sb.toString());
  }

Within guice's core, allow for better missing binding messages

Within guice s core allow for better missing binding messages


public static <T> RealMultibinder<T> newRealSetBinder(Binder binder, Key<T> key) {
    binder = binder.skipSources(RealMultibinder.class);
    RealMultibinder<T> result = new RealMultibinder<>(binder, key);
    binder.install(result);
    return result;
  }

public static < T > RealMultibinder < T > newRealSetBinder ( Binder binder , Key < T > key ) { binder = binder . skipSources ( RealMultibinder . class ) ; RealMultibinder < T > result = new RealMultibinder <> ( binder , key ) ; binder . install ( result ) ; return result ; }


Key<T> getKeyForNewItem() {
    checkConfiguration(!bindingSelection.isInitialized(), "Multibinder was already initialized");
    return Key.get(
        bindingSelection.getElementTypeLiteral(),
        new RealElement(bindingSelection.getSetName(), MULTIBINDER, ""));
  }

Key
<
T
>
getKeyForNewItem
(
)
{
checkConfiguration
(
!
bindingSelection
.
isInitialized
(
)
,
"Multibinder was already initialized"
)
;
return
Key
.
get
(
bindingSelection
.
getElementTypeLiteral
(
)
,
new
RealElement
(
bindingSelection
.
getSetName
(
)
,
MULTIBINDER
,
""
)
)
;
}

Adds a new entry to the set and returns the key for it.

Adds a new entry to the set and returns the key for it .


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

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

Iterates over the remaining filter definitions. Returns the first applicable filter, or null if
none apply.

Iterates over the remaining filter definitions . Returns the first applicable filter or null if none apply .


private static boolean hasAtInject(Constructor cxtor) {
    return cxtor.isAnnotationPresent(Inject.class)
        || cxtor.isAnnotationPresent(javax.inject.Inject.class);
  }

private static boolean hasAtInject ( Constructor cxtor ) { return cxtor . isAnnotationPresent ( Inject . class ) || cxtor . isAnnotationPresent ( javax . inject . Inject . class ) ; }

Returns true if the inject annotation is on the constructor.

Returns true if the inject annotation is on the constructor .


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

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

Returns an injection point that can be used to clean up the constructor store.

Returns an injection point that can be used to clean up the constructor store .


Set<Dependency<?>> getInternalDependencies() {
    ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder();
    if (factory.constructorInjector == null) {
      builder.add(constructorInjectionPoint);
      // If the below throws, it's OK -- we just ignore those dependencies, because no one
      // could have used them anyway.
      try {
        builder.addAll(
            InjectionPoint.forInstanceMethodsAndFields(
                constructorInjectionPoint.getDeclaringType()));
      } catch (ConfigurationException ignored) {
      }
    } else {
      builder.add(getConstructor()).addAll(getInjectableMembers());
    }

    return Dependency.forInjectionPoints(builder.build());
  }

Returns a set of dependencies that can be iterated over to clean up stray JIT bindings.

Returns a set of dependencies that can be iterated over to clean up stray JIT bindings .


public static Module forModule(Object module, ModuleAnnotatedMethodScanner scanner) {
    return forObject(module, false, scanner);
  }

public static Module forModule ( Object module , ModuleAnnotatedMethodScanner scanner ) { return forObject ( module , false , scanner ) ; }

Returns a module which creates bindings methods in the module that match the scanner.

Returns a module which creates bindings methods in the module that match the scanner .


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

Returns the annotation that is claimed by the scanner, or null if there is none.

Returns the annotation that is claimed by the scanner or null if there is none .


public Integer getLineNumber(Member member) {
    Preconditions.checkArgument(
        type == member.getDeclaringClass(),
        "Member %s belongs to %s, not %s",
        member,
        member.getDeclaringClass(),
        type);
    return lines.get(memberKey(member));
  }

public
Integer
getLineNumber
(
Member
member
)
{
Preconditions
.
checkArgument
(
type
==
member
.
getDeclaringClass
(
)
,
"Member %s belongs to %s, not %s"
,
member
,
member
.
getDeclaringClass
(
)
,
type
)
;
return
lines
.
get
(
memberKey
(
member
)
)
;
}

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

Get the line number associated with the given member .


void initialize(Errors errors) {
    injector.lookups = injector;
    new LookupProcessor(errors).process(injector, lookups);
  }

void initialize ( Errors errors ) { injector . lookups = injector ; new LookupProcessor ( errors ) . process ( injector , lookups ) ; }

Initialize the specified lookups, either immediately or when the injector is created.

Initialize the specified lookups either immediately or when the injector is created .


@Deprecated
  public static <T> Callable<T> continueRequest(Callable<T> callable, Map<Key<?>, Object> seedMap) {
    return wrap(callable, continueRequest(seedMap));
  }

@ Deprecated public static < T > Callable < T > continueRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { return wrap ( callable , continueRequest ( seedMap ) ) ; }

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.

There are some limitations:

Derived objects (i.e. anything marked @RequestScoped will not be transported.

State changes to the HttpServletRequest after this method is called will not be seen in the
continued thread.

Only the HttpServletRequest, ServletContext and request parameter map are available in the
continued thread. The response and session are not available.

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

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 .


public static <T> Callable<T> transferRequest(Callable<T> callable) {
    return wrap(callable, transferRequest());
  }

public static < T > Callable < T > transferRequest ( Callable < T > callable ) { return wrap ( callable , transferRequest ( ) ) ; }

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.

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.

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

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 .


private static Object validateAndCanonicalizeValue(Key<?> key, Object object) {
    if (object == null || object == NullObject.INSTANCE) {
      return NullObject.INSTANCE;
    }

    if (!key.getTypeLiteral().getRawType().isInstance(object)) {
      throw new IllegalArgumentException(
          "Value["
              + object
              + "] of type["
              + object.getClass().getName()
              + "] is not compatible with key["
              + key
              + "]");
    }

    return object;
  }

private
static
Object
validateAndCanonicalizeValue
(
Key
<
>
key
,
Object
object
)
{
if
(
object
==
||
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
;
}

Validates the key and object, ensuring the value matches the key type, and canonicalizing null
objects to the null sentinel.

Validates the key and object ensuring the value matches the key type and canonicalizing null objects to the null sentinel .


@SuppressWarnings("unchecked") // the MembersInjector type always agrees with the passed type
  public <T> MembersInjectorImpl<T> get(TypeLiteral<T> key, Errors errors) throws ErrorsException {
    return (MembersInjectorImpl<T>) cache.get(key, errors);
  }

Returns a new complete members injector with injection listeners registered.

Returns a new complete members injector with injection listeners registered .


private <T> MembersInjectorImpl<T> createWithListeners(TypeLiteral<T> type, Errors errors)
      throws ErrorsException {
    int numErrorsBefore = errors.size();

    Set<InjectionPoint> injectionPoints;
    try {
      injectionPoints = InjectionPoint.forInstanceMethodsAndFields(type);
    } catch (ConfigurationException e) {
      errors.merge(e.getErrorMessages());
      injectionPoints = e.getPartialValue();
    }
    ImmutableList<SingleMemberInjector> injectors = getInjectors(injectionPoints, errors);
    errors.throwIfNewErrors(numErrorsBefore);

    EncounterImpl<T> encounter = new EncounterImpl<>(errors, injector.lookups);
    Set<TypeListener> alreadySeenListeners = Sets.newHashSet();
    for (TypeListenerBinding binding : typeListenerBindings) {
      TypeListener typeListener = binding.getListener();
      if (!alreadySeenListeners.contains(typeListener) && binding.getTypeMatcher().matches(type)) {
        alreadySeenListeners.add(typeListener);
        try {
          typeListener.hear(type, encounter);
        } catch (RuntimeException e) {
          errors.errorNotifyingTypeListener(binding, type, e);
        }
      }
    }
    encounter.invalidate();
    errors.throwIfNewErrors(numErrorsBefore);

    return new MembersInjectorImpl<T>(injector, type, encounter, injectors);
  }

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

Creates a new members injector and attaches both injection listeners and method aspects.

Creates a new members injector and attaches both injection listeners and method aspects .


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

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

Returns the injectors for the specified injection points.

Returns the injectors for the specified injection points .


static <T> Key<T> get(Class<T> type, AnnotationStrategy annotationStrategy) {
    return new Key<T>(type, annotationStrategy);
  }

static < T > Key < T > get ( Class < T > type , AnnotationStrategy annotationStrategy ) { return new Key < T > ( type , annotationStrategy ) ; }

Gets a key for an injection type and an annotation strategy.

Gets a key for an injection type and an annotation strategy .


static AnnotationStrategy strategyFor(Annotation annotation) {
    checkNotNull(annotation, "annotation");
    Class<? extends Annotation> annotationType = annotation.annotationType();
    ensureRetainedAtRuntime(annotationType);
    ensureIsBindingAnnotation(annotationType);

    if (Annotations.isMarker(annotationType)) {
      return new AnnotationTypeStrategy(annotationType, annotation);
    }

    return new AnnotationInstanceStrategy(Annotations.canonicalizeIfNamed(annotation));
  }

static AnnotationStrategy strategyFor ( Annotation annotation ) { checkNotNull ( annotation , "annotation" ) ; Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; ensureRetainedAtRuntime ( annotationType ) ; ensureIsBindingAnnotation ( annotationType ) ; if ( Annotations . isMarker ( annotationType ) ) { return new AnnotationTypeStrategy ( annotationType , annotation ) ; } return new AnnotationInstanceStrategy ( Annotations . canonicalizeIfNamed ( annotation ) ) ; }


static AnnotationStrategy strategyFor(Class<? extends Annotation> annotationType) {
    annotationType = Annotations.canonicalizeIfNamed(annotationType);
    if (isAllDefaultMethods(annotationType)) {
      return strategyFor(generateAnnotation(annotationType));
    }

    checkNotNull(annotationType, "annotation type");
    ensureRetainedAtRuntime(annotationType);
    ensureIsBindingAnnotation(annotationType);
    return new AnnotationTypeStrategy(annotationType, null);
  }

static
AnnotationStrategy
strategyFor
(
Class
<
extends
Annotation
>
annotationType
)
{
annotationType
=
Annotations
.
canonicalizeIfNamed
(
annotationType
)
;
if
(
isAllDefaultMethods
(
annotationType
)
)
{
return
strategyFor
(
generateAnnotation
(
annotationType
)
)
;
}
checkNotNull
(
annotationType
,
"annotation type"
)
;
ensureRetainedAtRuntime
(
annotationType
)
;
ensureIsBindingAnnotation
(
annotationType
)
;
return
new
AnnotationTypeStrategy
(
annotationType
,
)
;
}

Gets the strategy for an annotation type.

Gets the strategy for an annotation type .


private void pruneStacktrace(Throwable throwable) {
    for (Throwable t = throwable; t != null; t = t.getCause()) {
      StackTraceElement[] stackTrace = t.getStackTrace();
      List<StackTraceElement> pruned = Lists.newArrayList();
      for (StackTraceElement element : stackTrace) {
        String className = element.getClassName();
        if (!AOP_INTERNAL_CLASSES.contains(className) && !className.contains("$EnhancerByGuice$")) {
          pruned.add(element);
        }
      }
      t.setStackTrace(pruned.toArray(new StackTraceElement[pruned.size()]));
    }
  }

private void pruneStacktrace ( Throwable throwable ) { for ( Throwable t = throwable ; t != null ; t = t . getCause ( ) ) { StackTraceElement [ ] stackTrace = t . getStackTrace ( ) ; List < StackTraceElement > pruned = Lists . newArrayList ( ) ; for ( StackTraceElement element : stackTrace ) { String className = element . getClassName ( ) ; if ( ! AOP_INTERNAL_CLASSES . contains ( className ) && ! className . contains ( "$EnhancerByGuice$" ) ) { pruned . add ( element ) ; } } t . setStackTrace ( pruned . toArray ( new StackTraceElement [ pruned . size ( ) ] ) ) ; } }

Removes stacktrace elements related to AOP internal mechanics from the throwable's stack trace
and any causes it may have.

Removes stacktrace elements related to AOP internal mechanics from the throwable s stack trace and any causes it may have .


public String getBindingSource() {
    if (source instanceof Class) {
      return StackTraceElements.forType((Class) source).toString();
    } else if (source instanceof Member) {
      return StackTraceElements.forMember((Member) source).toString();
    } else {
      return source.toString();
    }
  }

public String getBindingSource ( ) { if ( source instanceof Class ) { return StackTraceElements . forType ( ( Class ) source ) . toString ( ) ; } else if ( source instanceof Member ) { return StackTraceElements . forMember ( ( Member ) source ) . toString ( ) ; } else { return source . toString ( ) ; } }

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.

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 static String formatMessages(String heading, Collection<Message> errorMessages) {
    Formatter fmt = new Formatter().format(heading).format(":%n%n");
    int index = 1;
    boolean displayCauses = getOnlyCause(errorMessages) == null;

    Map<Equivalence.Wrapper<Throwable>, Integer> causes = Maps.newHashMap();
    for (Message errorMessage : errorMessages) {
      int thisIdx = index++;
      fmt.format("%s) %s%n", thisIdx, errorMessage.getMessage());

      List<Object> dependencies = errorMessage.getSources();
      for (int i = dependencies.size() - 1; i >= 0; i--) {
        Object source = dependencies.get(i);
        formatSource(fmt, source);
      }

      Throwable cause = errorMessage.getCause();
      if (displayCauses && cause != null) {
        Equivalence.Wrapper<Throwable> causeEquivalence = ThrowableEquivalence.INSTANCE.wrap(cause);
        if (!causes.containsKey(causeEquivalence)) {
          causes.put(causeEquivalence, thisIdx);
          fmt.format("Caused by: %s", Throwables.getStackTraceAsString(cause));
        } else {
          int causeIdx = causes.get(causeEquivalence);
          fmt.format(
              "Caused by: %s (same stack trace as error #%s)",
              cause.getClass().getName(), causeIdx);
        }
      }

      fmt.format("%n");
    }

    if (errorMessages.size() == 1) {
      fmt.format("1 error");
    } else {
      fmt.format("%s errors", errorMessages.size());
    }

    return fmt.toString();
  }

Returns the formatted message for an exception with the specified messages.

Returns the formatted message for an exception with the specified messages .


public static Message create(String messageFormat, Object... arguments) {
    return create(null, messageFormat, arguments);
  }

public static Message create ( String messageFormat , Object ... arguments ) { return create ( null , messageFormat , arguments ) ; }

Creates a new Message without a cause.

@param messageFormat Format string
@param arguments format string arguments


public static Message create(Throwable cause, String messageFormat, Object... arguments) {
    return create(cause, ImmutableList.of(), messageFormat, arguments);
  }

public static Message create ( Throwable cause , String messageFormat , Object ... arguments ) { return create ( cause , ImmutableList . of ( ) , messageFormat , arguments ) ; }

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

Creates a new Message with the given cause .


public static Message create(
      Throwable cause, List<Object> sources, String messageFormat, Object... arguments) {
    String message = format(messageFormat, arguments);
    return new Message(sources, message, cause);
  }

public static Message create ( Throwable cause , List < Object > sources , String messageFormat , Object ... arguments ) { String message = format ( messageFormat , arguments ) ; return new Message ( sources , message , cause ) ; }

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

Creates a new Message with the given cause and a binding source stack .


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

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

Formats an object in a user friendly way.

Formats an object in a user friendly way .


private boolean shouldBeSkipped(String className) {
    return (parent != null && parent.shouldBeSkipped(className))
        || classNamesToSkip.contains(className);
  }

private boolean shouldBeSkipped ( String className ) { return ( parent != null && parent . shouldBeSkipped ( className ) ) || classNamesToSkip . contains ( className ) ; }

Returns true if the className should be skipped.

Returns true if the className should be skipped .


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

Returns the non-skipped module class name.

Returns the non - skipped module class name .


public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println(
          "Usage: java -Dcom.sun.management.jmxremote "
              + Manager.class.getName()
              + " [module class name]");
      System.err.println("Then run 'jconsole' to connect.");
      System.exit(1);
    }

    Module module = (Module) Class.forName(args[0]).newInstance();
    Injector injector = Guice.createInjector(module);

    manage(args[0], injector);

    System.out.println("Press Ctrl+C to exit...");

    // Sleep forever.
    Thread.sleep(Long.MAX_VALUE);
  }

Run with no arguments for usage instructions.

Run with no arguments for usage instructions .


Dependency<?> pushDependency(Dependency<?> dependency, Object source) {
    Dependency<?> previous = this.dependency;
    this.dependency = dependency;
    doPushState(dependency, source);
    return previous;
  }

Dependency < ? > pushDependency ( Dependency < ? > dependency , Object source ) { Dependency < ? > previous = this . dependency ; this . dependency = dependency ; doPushState ( dependency , source ) ; return previous ; }

Sets the new current dependency & adds it to the state.

Sets the new current dependency & adds it to the state .


void pushState(com.google.inject.Key<?> key, Object source) {
    doPushState(key, source);
  }

void pushState ( com . google . inject . Key < ? > key , Object source ) { doPushState ( key , source ) ; }

Adds to the state without setting the dependency.

Adds to the state without setting the dependency .


static <T> Initializable<T> of(final T instance) {
    return new Initializable<T>() {
      @Override
      public T get() {
        return instance;
      }

      @Override
      public String toString() {
        return String.valueOf(instance);
      }
    };
  }

static < T > Initializable < T > of ( final T instance ) { return new Initializable < T > ( ) { @ Override public T get ( ) { return instance ; } @ Override public String toString ( ) { return String . valueOf ( instance ) ; } } ; }

Returns an initializable for an instance that requires no initialization.

Returns an initializable for an instance that requires no initialization .


protected T provision(
      Provider<? extends T> provider,
      Dependency<?> dependency,
      ConstructionContext<T> constructionContext)
      throws InternalProvisionException {
    T t = provider.get();
    if (t == null && !dependency.isNullable()) {
      InternalProvisionException.onNullInjectedIntoNonNullableDependency(source, dependency);
    }
    constructionContext.setProxyDelegates(t);
    return t;
  }

protected T provision ( Provider < ? extends T > provider , Dependency < ? > dependency , ConstructionContext < T > constructionContext ) throws InternalProvisionException { T t = provider . get ( ) ; if ( t == null && ! dependency . isNullable ( ) ) { InternalProvisionException . onNullInjectedIntoNonNullableDependency ( source , dependency ) ; } constructionContext . setProxyDelegates ( t ) ; return t ; }

Provisions a new instance. Subclasses should override this to catch exceptions & rethrow as
ErrorsExceptions.

Provisions a new instance . Subclasses should override this to catch exceptions & rethrow as ErrorsExceptions .


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

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

Dispatch events.

@param type
@param remoteAddr
@param conn


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

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

Add event processor.

@param type
@param processor


public static <T> T getFutureTaskResult(RunStateRecordedFutureTask<T> task, Logger logger) {
        T t = null;
        if (null != task) {
            try {
                t = task.getAfterRun();
            } catch (InterruptedException e) {
                logger.error("Future task interrupted!", e);
            } catch (ExecutionException e) {
                logger.error("Future task execute failed!", e);
            } catch (FutureTaskNotRunYetException e) {
                logger.error("Future task has not run yet!", e);
            } catch (FutureTaskNotCompleted e) {
                logger.error("Future task has not completed!", e);
            }
        }
        return t;
    }

public
static
<
T
>
T
getFutureTaskResult
(
RunStateRecordedFutureTask
<
T
>
task
,
Logger
logger
)
{
T
t
=
;
if
(
!=
task
)
{
try
{
t
=
task
.
getAfterRun
(
)
;
}
catch
(
InterruptedException
e
)
{
logger
.
error
(
"Future task interrupted!"
,
e
)
;
}
catch
(
ExecutionException
e
)
{
logger
.
error
(
"Future task execute failed!"
,
e
)
;
}
catch
(
FutureTaskNotRunYetException
e
)
{
logger
.
error
(
"Future task has not run yet!"
,
e
)
;
}
catch
(
FutureTaskNotCompleted
e
)
{
logger
.
error
(
"Future task has not completed!"
,
e
)
;
}
}
return
t
;
}

get the result of a future task

Notice: the run method of this task should have been called at first.

@param task
@param <T>
@return


public static void launderThrowable(Throwable t) {
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new IllegalStateException("Not unchecked!", t);
        }
    }

public
static
void
launderThrowable
(
Throwable
t
)
{
if
(
t
instanceof
RuntimeException
)
{
throw
(
RuntimeException
)
t
;
}
else
if
(
t
instanceof
Error
)
{
throw
(
Error
)
t
;
}
else
{
throw
new
IllegalStateException
(
"Not unchecked!"
,
t
)
;
}
}


public void registerProcessor(CommandCode cmdCode, RemotingProcessor<?> processor) {
        if (this.cmd2processors.containsKey(cmdCode)) {
            logger
                .warn(
                    "Processor for cmd={} is already registered, the processor is {}, and changed to {}",
                    cmdCode, cmd2processors.get(cmdCode).getClass().getName(), processor.getClass()
                        .getName());
        }
        this.cmd2processors.put(cmdCode, processor);
    }

Register processor to process command that has the command code of cmdCode.

@param cmdCode
@param processor

Register processor to process command that has the command code of cmdCode .