public void testToString() {
    final Key<String> key1 = Key.get(String.class, Names.named("KEY"));
    final Key<String> key2 = Key.get(String.class, Names.named("BAD"));

    final Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(key1).toProvider(new ToStringProvider());
                bind(key2).toProvider(new BadToStringProvider());
              }
            });

    final Entry<Named, String> entry1 =
        new LazyBeanEntry<Named, String>(
            (Named) key1.getAnnotation(), injector.getBinding(key1), 0);
    final Entry<Named, String> entry2 =
        new LazyBeanEntry<Named, String>(
            (Named) key2.getAnnotation(), injector.getBinding(key2), 0);

    Exception error = null;
    try {
      injector.getInstance(key2);
    } catch (final Exception e) {
      error = e;
    }

    assertEquals('@' + javax.inject.Named.class.getName() + "(value=KEY)=VALUE", entry1.toString());
    assertEquals(
        '@' + javax.inject.Named.class.getName() + "(value=BAD)=" + error, entry2.toString());
  }
  public void testDetails() {
    final Key<Bean> key1 = Key.get(Bean.class, Names.named("1"));
    final Key<Bean> key2 = Key.get(Bean.class, Names.named("2"));
    final Key<Bean> key3 = Key.get(Bean.class, Names.named("3"));
    final Key<Bean> key4 = Key.get(Bean.class, Names.named("4"));

    final Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(key1).to(DescribedBean.class).in(Scopes.SINGLETON);

                binder()
                    .withSource(
                        new BeanDescription() {
                          public String getDescription() {
                            return "Another test";
                          }
                        })
                    .bind(key2)
                    .toInstance(new BeanImpl());

                binder().withSource("where?").bind(key3).to(BeanImpl.class);

                bind(key4).toProvider(Providers.of(new BeanImpl()));
              }
            });

    final LazyBeanEntry<Annotation, Bean> bean1 =
        new LazyBeanEntry<Annotation, Bean>(key1.getAnnotation(), injector.getBinding(key1), 42);
    final LazyBeanEntry<Annotation, Bean> bean2 =
        new LazyBeanEntry<Annotation, Bean>(key2.getAnnotation(), injector.getBinding(key2), -24);
    final LazyBeanEntry<Annotation, Bean> bean3 =
        new LazyBeanEntry<Annotation, Bean>(key3.getAnnotation(), injector.getBinding(key3), 0);
    final LazyBeanEntry<Annotation, Bean> bean4 =
        new LazyBeanEntry<Annotation, Bean>(key4.getAnnotation(), injector.getBinding(key4), -1);

    assertEquals("This is a test", bean1.getDescription());
    assertTrue(bean1.getSource() instanceof StackTraceElement);
    assertEquals(DescribedBean.class, bean1.getImplementationClass());
    assertEquals(42, bean1.getRank());

    assertEquals("Another test", bean2.getDescription());
    assertTrue(bean2.getSource() instanceof BeanDescription);
    assertEquals(BeanImpl.class, bean2.getImplementationClass());
    assertEquals(-24, bean2.getRank());

    assertNull(bean3.getDescription());
    assertTrue(bean3.getSource() instanceof String);
    assertEquals(BeanImpl.class, bean3.getImplementationClass());
    assertEquals(0, bean3.getRank());

    assertNull(bean4.getDescription());
    assertTrue(bean4.getSource() instanceof StackTraceElement);
    assertEquals(null, bean4.getImplementationClass());
    assertEquals(-1, bean4.getRank());
  }
 /**
  * Computes a canonical {@link Qualifier} annotation for the given binding {@link Key}.
  *
  * @param key The key to qualify
  * @return Qualifier for the key
  */
 static final Annotation qualify(final Key<?> key) {
   if (key instanceof WildcardKey) {
     final Annotation qualifier = ((WildcardKey) key).getQualifier();
     return null != qualifier ? qualifier : DEFAULT_QUALIFIER;
   }
   return null != key.getAnnotationType() ? key.getAnnotation() : DEFAULT_QUALIFIER;
 }
Exemplo n.º 4
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;
  }
Exemplo n.º 5
0
  // TODO: Remove method parameter, which is unused
  protected SortedMap<Key<?>, Binding<?>> getPolymorphicAdapterMapBindings(
      final Class<?> adaptableType, final Method method, final AdapterMap methodAnnotation) {
    // find available keys
    final Map<Key<?>, Binding<?>> allBindings = injector.getAllBindings();
    // IMPORTANT: use a sorted map, where keys are sorted according to
    // hierarchy of annotation types (so we have polymorphic injection)
    final SortedMap<Key<?>, Binding<?>> polymorphicBindings =
        new TreeMap<Key<?>, Binding<?>>(
            new Comparator<Key<?>>() {

              @Override
              public int compare(final Key<?> o1, final Key<?> o2) {
                if (!AdapterMap.class.equals(o1.getAnnotationType())
                    || !AdapterMap.class.equals(o2.getAnnotationType())) {
                  throw new IllegalArgumentException(
                      "Can only compare keys with AdapterMap annotations");
                }
                final AdapterMap a1 = (AdapterMap) o1.getAnnotation();
                final AdapterMap a2 = (AdapterMap) o2.getAnnotation();
                if (a1.adaptableType().equals(a2.adaptableType())) {
                  return 0;
                } else if (a1.adaptableType().isAssignableFrom(a2.adaptableType())) {
                  return -1;
                } else {
                  return 1;
                }
              }
            });
    for (final Key<?> key : allBindings.keySet()) {
      if ((key.getAnnotationType() != null) && AdapterMap.class.equals(key.getAnnotationType())) {
        final AdapterMap keyAnnotation = (AdapterMap) key.getAnnotation();
        // Guice will already have injected all bindings where the
        // adaptableType used in the method annotation is the same as
        // the one used in the key annotation.
        if (!methodAnnotation.adaptableType().equals(keyAnnotation.adaptableType())
            /*
             * The annotation in the binding refers to a true
             * super-type of instance runtime type (check, because
             * if the type is the same, the default injector will
             * already inject the values) IMPORTANT: we use
             * 'adaptableType' instead of 'methodAnnotation
             * .adaptableType()' here, because the runtime type of
             * the to be injected IAdaptable is relevant
             */
            && keyAnnotation.adaptableType().isAssignableFrom(adaptableType)) {
          // System.out.println("Applying binding for " +
          // keyAnnotation.value() + " to " + type +
          // " as subtype of " + methodAnnotation.value());
          polymorphicBindings.put(key, allBindings.get(key));
        }
      }
    }
    return polymorphicBindings;
  }
  private static void bindHierarchy(final Binder binder, final Key rootKey) {
    final Class root = rootKey.getTypeLiteral().getRawType();

    Annotation qualifier = rootKey.getAnnotation();
    if (null == qualifier) {
      qualifier = Names.named(root.getName());
    }

    for (Class clazz = root; clazz != Object.class; clazz = clazz.getSuperclass()) {
      if (clazz != root && ExtensionPoint.class.isAssignableFrom(clazz)) {
        binder.bind(clazz).annotatedWith(qualifier).to(rootKey);
      }

      if (Descriptor.class.isAssignableFrom(clazz)) {
        binder.bind(Descriptor.class).annotatedWith(qualifier).to(rootKey);
      }

      for (final Class<?> iface : clazz.getInterfaces()) {
        if (ExtensionPoint.class.isAssignableFrom(iface)) {
          binder.bind(iface).annotatedWith(qualifier).to(rootKey);
        }
      }
    }
  }
 @Override
 final Annotation qualifies(final Key<?> requirement, final Binding<?> binding) {
   final Annotation qualifier = MARKED.qualifies(requirement, binding);
   return requirement.getAnnotation().equals(qualifier) ? qualifier : null;
 }
 @Override
 final Annotation qualifies(final Key<?> requirement, final Binding<?> binding) {
   final Annotation qualifier = qualify(binding.getKey());
   return requirement.getAnnotation().equals(qualifier) ? qualifier : null;
 }