Ejemplo n.º 1
0
  @Nonnull
  @Override
  public <T> Collection<Qualified<T>> getQualifiedInstances(@Nonnull Class<T> type)
      throws InstanceNotFoundException {
    requireNonNull(type, ERROR_TYPE_NULL);

    if (isClosed()) {
      throw new InstanceNotFoundException(type, new ClosedInjectorException(this));
    }

    List<Qualified<T>> instances = new ArrayList<>();

    List<com.google.inject.Binding<T>> bindings;
    try {
      bindings = delegate.findBindingsByType(TypeLiteral.get(type));
    } catch (RuntimeException e) {
      throw new InstanceNotFoundException(type, e);
    }
    if (bindings == null) {
      throw new InstanceNotFoundException(type);
    }

    for (com.google.inject.Binding<T> binding : bindings) {
      try {
        Key<T> key = binding.getKey();
        final T instance = delegate.getInstance(key);
        instances.add(new Qualified<>(instance, translate(key.getAnnotation())));
      } catch (RuntimeException e) {
        throw new InstanceNotFoundException(type, e);
      }
    }

    return instances;
  }
Ejemplo n.º 2
0
 public static BindingInfo create(Binding<?> binding, Key<?> boundKey, Object instance) {
   BindingInfo bindingInfo = new BindingInfo();
   bindingInfo.key = binding.getKey();
   bindingInfo.boundKey = boundKey;
   bindingInfo.boundInstance = instance;
   bindingInfo.scope = binding.acceptScopingVisitor(new GuiceScopingVisitor());
   return bindingInfo;
 }
Ejemplo n.º 3
0
 private Emitter findEmitter(String emitterType, List<Binding<Emitter>> emitterBindings) {
   for (Binding<Emitter> binding : emitterBindings) {
     if (Names.named(emitterType).equals(binding.getKey().getAnnotation())) {
       return binding.getProvider().get();
     }
   }
   return null;
 }
 private ContextListenerDefinition[] collectContextListenerDefinitions(Injector injector) {
   List<ContextListenerDefinition> contextListeners = new ArrayList<ContextListenerDefinition>();
   TypeLiteral<ContextListenerDefinition> LISTENER_DEFS =
       TypeLiteral.get(ContextListenerDefinition.class);
   for (Binding<ContextListenerDefinition> entry : injector.findBindingsByType(LISTENER_DEFS)) {
     contextListeners.add(entry.getProvider().get());
   }
   // Convert to a fixed size array for speed.
   return contextListeners.toArray(new ContextListenerDefinition[contextListeners.size()]);
 }
    @Override
    final Annotation qualifies(final Key<?> requirement, final Binding<?> binding) {
      final Class<? extends Annotation> markerType = requirement.getAnnotationType();

      final Annotation qualifier = qualify(binding.getKey());
      if (markerType.isInstance(qualifier)) {
        return qualifier;
      }

      final Class<?> implementation = binding.acceptTargetVisitor(ImplementationVisitor.THIS);
      return null != implementation ? implementation.getAnnotation(markerType) : null;
    }
 private HttpSessionListenerDefinition[] collectListenerDefinitions(Injector injector) {
   List<HttpSessionListenerDefinition> sessionListeners =
       new ArrayList<HttpSessionListenerDefinition>();
   TypeLiteral<HttpSessionListenerDefinition> LISTENER_DEFS =
       TypeLiteral.get(HttpSessionListenerDefinition.class);
   for (Binding<HttpSessionListenerDefinition> entry :
       injector.findBindingsByType(LISTENER_DEFS)) {
     sessionListeners.add(entry.getProvider().get());
   }
   // Convert to a fixed size array for speed.
   return sessionListeners.toArray(new HttpSessionListenerDefinition[sessionListeners.size()]);
 }
Ejemplo n.º 7
0
 @SuppressWarnings("unchecked")
 @Override
 public Void visit(PrivateElements privateElements) {
   Set<Key<?>> exposedKeys = privateElements.getExposedKeys();
   for (Element element : privateElements.getElements()) {
     if (element instanceof Binding<?>) {
       Binding<?> bindingElement = (Binding<?>) element;
       if (exposedKeys.contains(bindingElement.getKey())) {
         @SuppressWarnings("rawtypes")
         GuicePrivateBindingVisitor bindingVisitor = new GuicePrivateBindingVisitor();
         bindingElement.acceptTargetVisitor(bindingVisitor);
       }
     }
   }
   return null;
 }
  private static void validateBindingIsSingleton(Injector injector, Binding<?> binding)
      throws InspectionException {
    binding = resolveBinding(injector, binding);
    boolean singleton =
        binding.acceptScopingVisitor(
            new BindingScopingVisitor<Boolean>() {
              public Boolean visitEagerSingleton() {
                return true;
              }

              public Boolean visitNoScoping() {
                return false;
              }

              public Boolean visitScope(com.google.inject.Scope scope) {
                return scope == Scopes.SINGLETON || scope == MoreScopes.LAZY_SINGLETON;
              }

              public Boolean visitScopeAnnotation(
                  java.lang.Class<? extends Annotation> scopeAnnotation) {
                return false;
              }
            });

    if (!singleton) {
      throw new InspectionException(
          "must be singleton or lazysingleton annotation or be interface!");
    }
  }
  private static void setFieldContainerInstance(InspectionData data, Injector injector)
      throws Throwable {
    // no container instance for static data.
    if (!data.isStatic) {
      if (data.lookupClass == null) {
        // if the container had an enclosing class and it's not static, make sure the lookup
        // points to the enclosing class.
        if (data.actualClass.getEnclosingClass() != null
            && !Modifier.isStatic(data.actualClass.getModifiers())) {
          data.lookupClass = data.actualClass.getEnclosingClass();
        }
      }

      // check if this is an enclosed class
      if (data.lookupClass == null) {
        Binding<?> binding = injector.getBinding(data.actualClass);
        validateBindingIsSingleton(injector, binding);
        data.fieldContainerInstance = binding.getProvider().get();
      } else {
        // inner classes must be annotated properly
        Binding<?> binding = injector.getBinding(data.lookupClass);
        validateBindingIsSingleton(injector, binding);
        Object lookupObj = binding.getProvider().get();

        // If this was an enclosed class, validate that it has InspectableContainer.
        if (data.actualClass.getEnclosingClass() != null
            && !Modifier.isStatic(data.actualClass.getModifiers())) {
          if (data.actualClass.getAnnotation(InspectableContainer.class) == null) {
            throw new InspectionException("container must be annotated with InspectableContainer");
          }
          Constructor[] constructors = data.actualClass.getDeclaredConstructors();
          if (constructors.length != 1) {
            throw new InspectionException("wrong constructors length: " + constructors.length);
          }
          Class[] parameters = constructors[0].getParameterTypes();
          if (parameters.length != 1 || !data.lookupClass.isAssignableFrom(parameters[0])) {
            throw new InspectionException("wrong parameter count or type for constructor");
          }
          constructors[0].setAccessible(true);
          data.fieldContainerInstance = constructors[0].newInstance(lookupObj);
        } else {
          data.fieldContainerInstance = lookupObj;
        }
      }
    }
  }
Ejemplo n.º 10
0
  public void testSpi() throws Exception {
    Module m1 =
        new AbstractModule() {
          @Override
          protected void configure() {}

          @Provides
          @Named("foo")
          String provideFoo(Integer dep) {
            return "foo";
          }
        };
    Module m2 =
        new AbstractModule() {
          @Override
          protected void configure() {}

          @Provides
          Integer provideInt(@Named("foo") String dep) {
            return 42;
          }
        };
    Injector injector = Guice.createInjector(m1, m2);

    Binding<String> stringBinding = injector.getBinding(Key.get(String.class, Names.named("foo")));
    ProvidesMethodBinding<String> stringMethod =
        stringBinding.acceptTargetVisitor(new BindingCapturer<String>());
    assertEquals(m1, stringMethod.getEnclosingInstance());
    assertEquals(
        m1.getClass().getDeclaredMethod("provideFoo", Integer.class), stringMethod.getMethod());
    assertEquals(
        ((HasDependencies) stringBinding).getDependencies(), stringMethod.getDependencies());
    assertEquals(Key.get(String.class, Names.named("foo")), stringMethod.getKey());

    Binding<Integer> intBinding = injector.getBinding(Integer.class);
    ProvidesMethodBinding<Integer> intMethod =
        intBinding.acceptTargetVisitor(new BindingCapturer<Integer>());
    assertEquals(m2, intMethod.getEnclosingInstance());
    assertEquals(
        m2.getClass().getDeclaredMethod("provideInt", String.class), intMethod.getMethod());
    assertEquals(((HasDependencies) intBinding).getDependencies(), intMethod.getDependencies());
    assertEquals(Key.get(Integer.class), intMethod.getKey());
  }
Ejemplo n.º 11
0
  /**
   * Resolves a binding to the ultimate destination, ensuring we can check the scope of the proper
   * link.
   */
  private static Binding<?> resolveBinding(final Injector injector, final Binding<?> binding) {
    return binding.acceptTargetVisitor(
        new BindingTargetVisitor<Object, Binding<?>>() {

          @Override
          public Binding<?> visit(InstanceBinding<? extends Object> link) {
            return binding;
          }

          @Override
          public Binding<?> visit(ProviderInstanceBinding<? extends Object> link) {
            return binding;
          }

          @Override
          public Binding<?> visit(ProviderKeyBinding<? extends Object> link) {
            return resolveBinding(injector, injector.getBinding(link.getProviderKey()));
          }

          @Override
          public Binding<?> visit(LinkedKeyBinding<? extends Object> link) {
            return resolveBinding(injector, injector.getBinding(link.getLinkedKey()));
          }

          @Override
          public Binding<?> visit(ExposedBinding<? extends Object> link) {
            return binding;
          }

          @Override
          public Binding<?> visit(UntargettedBinding<? extends Object> link) {
            return binding;
          }

          @Override
          public Binding<?> visit(ConstructorBinding<? extends Object> link) {
            return binding;
          }

          @Override
          public Binding<?> visit(ConvertedConstantBinding<? extends Object> link) {
            return binding;
          }

          @Override
          public Binding<?> visit(ProviderBinding<? extends Object> link) {
            return resolveBinding(injector, injector.getBinding(link.getProvidedKey()));
          }
        });
  }
Ejemplo n.º 12
0
    @Inject
    public void inject(Injector injector) {
      final List<Binding<Emitter>> emitterBindings =
          injector.findBindingsByType(new TypeLiteral<Emitter>() {});

      emitter = findEmitter(emitterType, emitterBindings);

      if (emitter == null) {
        emitter = findEmitter(LogEmitterModule.EMITTER_TYPE, emitterBindings);
      }

      if (emitter == null) {
        List<String> knownTypes = Lists.newArrayList();
        for (Binding<Emitter> binding : emitterBindings) {
          final Annotation annotation = binding.getKey().getAnnotation();
          if (annotation != null) {
            knownTypes.add(((Named) annotation).value());
          }
        }
        throw new ISE(
            "Uknown emitter type[%s]=[%s], known types[%s]",
            EMITTER_PROPERTY, emitterType, knownTypes);
      }
    }
Ejemplo n.º 13
0
  @Override
  public void close() {
    if (isClosed()) {
      throw new ClosedInjectorException(this);
    }

    for (Key<?> key : delegate.getAllBindings().keySet()) {
      try {
        com.google.inject.Binding<?> binding = delegate.getExistingBinding(key);
        if (!Scopes.isSingleton(binding)) {
          continue;
        }
        invokeAnnotatedMethod(binding.getProvider().get(), PreDestroy.class);
      } catch (ProvisionException pe) {
        if (!(pe.getCause() instanceof TypeNotFoundException)) {
          pe.printStackTrace();
        }
      }
    }

    synchronized (lock) {
      closed = true;
    }
  }
Ejemplo n.º 14
0
  private Module create(
      final Logger LOG,
      final LifecycleManager manager,
      final Collection<Module> loadedModules,
      final List<Module> rootModules,
      final boolean isBootstrap,
      final Module bootstrapModule)
      throws Exception {
    LOG.info("Creating {} injector", isBootstrap ? "bootstrap" : "main");
    // Populate all the bootstrap state from the main module
    final List<Element> elements = Elements.getElements(Stage.DEVELOPMENT, rootModules);
    final Set<Key<?>> keys = ElementsEx.getAllInjectionKeys(elements);
    final List<String> moduleNames = ElementsEx.getAllSourceModules(elements);

    final Injector injector =
        Guice.createInjector(
            stage,
            new LifecycleModule(),
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(LifecycleManager.class).toInstance(manager);
                requestInjection(manager);
              }
            },
            Modules.override(
                    new DefaultModule() {
                      @Provides
                      public AutoContext getContext() {
                        return new AutoContext() {
                          @Override
                          public boolean hasProfile(String profile) {
                            return profiles.contains(profile);
                          }

                          @Override
                          public boolean hasModule(String className) {
                            return moduleNames.contains(className);
                          }

                          @Override
                          public boolean hasBinding(Key<?> key) {
                            return keys.contains(key);
                          }
                        };
                      }
                    })
                .with(bootstrapModule));

    PropertySource propertySource = injector.getInstance(PropertySource.class);

    // Iterate through all loaded modules and filter out any modules that
    // have failed the condition check.  Also, keep track of any override modules
    // for already installed modules.
    final List<Module> overrideModules = new ArrayList<>();
    final List<Module> moreModules = new ArrayList<>();
    for (Module module : loadedModules) {
      if (!isEnabled(propertySource, module.getClass().getName())) {
        LOG.info("Ignoring module {}", module.getClass().getName());
        continue;
      }

      Bootstrap bs = module.getClass().getAnnotation(Bootstrap.class);
      if (isBootstrap == (bs != null) && evaluateConditions(LOG, injector, module)) {
        OverrideModule override = module.getClass().getAnnotation(OverrideModule.class);
        if (override != null) {
          if (moduleNames.contains(override.value().getName())) {
            LOG.info("    Adding override module {}", module.getClass().getSimpleName());
            overrideModules.add(module);
          }
        } else {
          LOG.info("    Adding conditional module {}", module.getClass().getSimpleName());
          moreModules.add(module);
        }
      }
    }

    final List<Module> extModules = new ArrayList<>();
    List<Binding<ModuleProvider>> moduleProviders =
        injector.findBindingsByType(TypeLiteral.get(ModuleProvider.class));
    for (Binding<ModuleProvider> binding : moduleProviders) {
      Module module = binding.getProvider().get().get();
      LOG.debug("Adding exposed bootstrap module {}", module.getClass().getName());
      extModules.add(module);
    }

    LOG.debug("Root Modules     : " + rootModules);
    LOG.debug("More Modules     : " + moreModules);
    LOG.debug("Override Modules : " + overrideModules);
    LOG.debug("Ext Modules      : " + extModules);

    LOG.debug("Created {} injector", isBootstrap ? "bootstrap" : "main");

    Module m =
        Modules.override(
                new AbstractModule() {
                  @Override
                  protected void configure() {
                    install(Modules.combine(rootModules));
                    install(Modules.combine(moreModules));
                  }
                })
            .with(Modules.override(overrideModules).with(Modules.combine(extModules)));
    return m;
  }
Ejemplo n.º 15
0
 private Void addBinding(Binding<? extends T> binding) {
   return addBindingInfo(binding, binding.getKey(), null);
 }
 @Override
 final Annotation qualifies(final Key<?> requirement, final Binding<?> binding) {
   final Annotation qualifier = qualify(binding.getKey());
   return qualifier instanceof Named ? qualifier : null;
 }
Ejemplo n.º 17
0
 @Override
 public <T> Void visit(com.google.inject.Binding<T> command) {
   GuiceBindingVisitor<T> bindingVisitor = new GuiceBindingVisitor<>();
   command.acceptTargetVisitor(bindingVisitor);
   return null;
 }
 @Override
 final Annotation qualifies(final Key<?> requirement, final Binding<?> binding) {
   final Annotation qualifier = qualify(binding.getKey());
   return requirement.getAnnotation().equals(qualifier) ? qualifier : null;
 }
 @Override
 final Annotation qualifies(final Key<?> requirement, final Binding<?> binding) {
   final Annotation qualifier = qualify(binding.getKey());
   return null != qualifier ? qualifier : BLANK_QUALIFIER;
 }
 @Override
 public Object provide() {
   return binding.getProvider().get();
 }