Java Code Examples for com.google.inject.spi.TypeListener

The following are top voted examples for showing how to use com.google.inject.spi.TypeListener. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: EDDI   File: RuntimeModule.java   View source code 6 votes vote down vote up
@Override
protected void configure() {
    registerConfigFiles(this.configFiles);

    //init system runtime eagerly
    bind(SystemRuntime.IRuntime.class).to(BaseRuntime.class).asEagerSingleton();

    bind(IResourceClientLibrary.class).to(ResourceClientLibrary.class).in(Scopes.SINGLETON);
    bind(IBotStoreClientLibrary.class).to(BotStoreClientLibrary.class).in(Scopes.SINGLETON);
    bind(IPackageStoreClientLibrary.class).to(PackageStoreClientLibrary.class).in(Scopes.SINGLETON);
    bind(IPackageStoreService.class).to(PackageStoreService.class).in(Scopes.SINGLETON);
    bind(IBotStoreService.class).to(BotStoreService.class).in(Scopes.SINGLETON);

    bind(IBotFactory.class).to(BotFactory.class).in(Scopes.SINGLETON);
    bind(IPackageFactory.class).to(PackageFactory.class).in(Scopes.SINGLETON);

    bind(IAutoBotDeployment.class).to(AutoBotDeployment.class).in(Scopes.SINGLETON);

    //call init method of system runtime after creation
    bindListener(HasInitMethod.INSTANCE, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
            encounter.register(InitInvoker.INSTANCE);
        }
    });
}
 
Example 2
Project: che   File: DestroyModule.java   View source code 6 votes vote down vote up
@Override
protected void configure() {
  final Destroyer destroyer = new Destroyer(errorHandler);
  bind(Destroyer.class).toInstance(destroyer);
  bindListener(
      Matchers.any(),
      new TypeListener() {
        @Override
        public <T> void hear(TypeLiteral<T> type, TypeEncounter<T> encounter) {
          encounter.register(
              new InjectionListener<T>() {
                @Override
                public void afterInjection(T injectee) {
                  final Method[] methods = get(injectee.getClass(), annotationType);
                  if (methods.length > 0) {
                    // copy array when pass it outside
                    final Method[] copy = new Method[methods.length];
                    System.arraycopy(methods, 0, copy, 0, methods.length);
                    destroyer.add(injectee, copy);
                  }
                }
              });
        }
      });
}
 
Example 3
Project: agon   File: AgonModule.java   View source code 6 votes vote down vote up
@Override
protected void configure() {
    bind(ActionRepository.class).to(CassandraActionRepository.class);
    bind(PlayerRepository.class).to(CassandraPlayerRepository.class);
    bind(BadgeRepository.class).to(CassandraBadgeRepository.class);
    bind(EventRepository.class).to(CassandraEventRepository.class);
    bind(EventTypeRepository.class).to(CassandraEventTypeRepository.class);

    this.eventBus =  new AsyncEventBus(java.util.concurrent.Executors.newCachedThreadPool());
    bind(EventBus.class).toInstance(eventBus);

    bindListener(Matchers.any(), new TypeListener() {
        public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
            typeEncounter.register(new InjectionListener<I>() {
                public void afterInjection(I i) {
                    eventBus.register(i);
                }
            });
        }
    });
}
 
Example 4
Project: guice   File: BindingTest.java   View source code 6 votes vote down vote up
public void testToConstructorSpiData() throws NoSuchMethodException {
  final Set<TypeLiteral<?>> heardTypes = Sets.newHashSet();

  final Constructor<D> constructor = D.class.getConstructor(Stage.class);
  final TypeListener listener =
      new TypeListener() {
        @Override
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          if (!heardTypes.add(type)) {
            fail("Heard " + type + " multiple times!");
          }
        }
      };

  Guice.createInjector(
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(Object.class).toConstructor(constructor);
          bind(D.class).toConstructor(constructor);
          bindListener(Matchers.any(), listener);
        }
      });
  
  assertEquals(ImmutableSet.of(TypeLiteral.get(D.class)), heardTypes);
}
 
Example 5
Project: guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testTypeListenersAreFired() {
  final AtomicInteger firedCount = new AtomicInteger();

  final TypeListener typeListener =
      new TypeListener() {
        @Override
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          assertEquals(new TypeLiteral<A>() {}, type);
          firedCount.incrementAndGet();
        }
      };

  Guice.createInjector(
      new AbstractModule() {
        @Override
        protected void configure() {
          bindListener(onlyAbcd, typeListener);
          bind(A.class);
        }
      });

  assertEquals(1, firedCount.get());
}
 
Example 6
Project: guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testLookupsPostCreate() {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bindListener(
                  only(TypeLiteral.get(C.class)),
                  new TypeListener() {
                    @Override
                    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                      assertNotNull(encounter.getProvider(B.class).get());

                      A a = new A();
                      encounter.getMembersInjector(A.class).injectMembers(a);
                      assertNotNull(a.injector);
                    }
                  });
            }
          });

  injector.getInstance(C.class);
}
 
Example 7
Project: guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
/**
 * We had a bug where we weren't notifying of types encountered for member injection when those
 * types had no members to be injected. Constructed types are always injected because they always
 * have at least one injection point: the class constructor.
 */
public void testTypesWithNoInjectableMembersAreNotified() {
  final AtomicInteger notificationCount = new AtomicInteger();

  Guice.createInjector(
      new AbstractModule() {
        @Override
        protected void configure() {
          bindListener(
              onlyAbcd,
              new TypeListener() {
                @Override
                public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                  notificationCount.incrementAndGet();
                }
              });

          bind(C.class).toInstance(new C());
        }
      });

  assertEquals(1, notificationCount.get());
}
 
Example 8
Project: guice-old   File: BindingTest.java   View source code 6 votes vote down vote up
public void testToConstructorSpiData() throws NoSuchMethodException {
  final Set<TypeLiteral<?>> heardTypes = Sets.newHashSet();

  final Constructor<D> constructor = D.class.getConstructor(Stage.class);
  final TypeListener listener = new TypeListener() {
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      if (!heardTypes.add(type)) {
        fail("Heard " + type + " multiple times!");
      }
    }
  };

  Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bind(Object.class).toConstructor(constructor);
      bind(D.class).toConstructor(constructor);
      bindListener(Matchers.any(), listener);
    }
  });
  
  assertEquals(ImmutableSet.of(TypeLiteral.get(D.class)), heardTypes);
}
 
Example 9
Project: guice-old   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testTypeListenersAreFired() {
  final AtomicInteger firedCount = new AtomicInteger();

  final TypeListener typeListener = new TypeListener() {
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      assertEquals(new TypeLiteral<A>() {}, type);
      firedCount.incrementAndGet();
    }
  };

  Guice.createInjector(new AbstractModule() {
    @Override protected void configure() {
      bindListener(onlyAbcd, typeListener);
      bind(A.class);
    }
  });

  assertEquals(1, firedCount.get());
}
 
Example 10
Project: guice-old   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testAddingInterceptors() throws NoSuchMethodException {
  final Matcher<Object> buzz = only(C.class.getMethod("buzz"));

  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override protected void configure() {
      bindInterceptor(any(), buzz, prefixInterceptor("ka"));
      bindInterceptor(any(), any(), prefixInterceptor("fe"));

      bindListener(onlyAbcd, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          encounter.bindInterceptor(any(), prefixInterceptor("li"));
          encounter.bindInterceptor(buzz, prefixInterceptor("no"));
        }
      });
    }
  });

  // interceptors must be invoked in the order they're bound.
  C c = injector.getInstance(C.class);
  assertEquals("kafelinobuzz", c.buzz());
  assertEquals("felibeep", c.beep());
}
 
Example 11
Project: guice-old   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testLookupsPostCreate() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override protected void configure() {
      bindListener(only(TypeLiteral.get(C.class)), new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          assertNotNull(encounter.getProvider(B.class).get());

          A a = new A();
          encounter.getMembersInjector(A.class).injectMembers(a);
          assertNotNull(a.injector);
        }
      });
    }
  });
  
  injector.getInstance(C.class);
}
 
Example 12
Project: guice-old   File: TypeListenerTest.java   View source code 6 votes vote down vote up
/**
 * We had a bug where we weren't notifying of types encountered for member injection when those
 * types had no members to be injected. Constructed types are always injected because they always
 * have at least one injection point: the class constructor.
 */
public void testTypesWithNoInjectableMembersAreNotified() {
  final AtomicInteger notificationCount = new AtomicInteger();

  Guice.createInjector(new AbstractModule() {
    @Override protected void configure() {
      bindListener(onlyAbcd, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          notificationCount.incrementAndGet();
        }
      });

      bind(C.class).toInstance(new C());
    }
  });

  assertEquals(1, notificationCount.get());
}
 
Example 13
Project: guice-old   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testAddErrors() {
  try {
    Guice.createInjector(new AbstractModule() {
      @Override protected void configure() {
        requestInjection(new Object());
        bindListener(Matchers.any(), new TypeListener() {
          public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
            encounter.addError("There was an error on %s", type);
            encounter.addError(new IllegalArgumentException("whoops!"));
            encounter.addError(new Message("And another problem"));
            encounter.addError(new IllegalStateException());
          }
        });
      }
    });
    fail();
  } catch (CreationException expected) {
    assertContains(expected.getMessage(),
        "1) There was an error on java.lang.Object",
        "2) An exception was caught and reported. Message: whoops!",
        "3) And another problem",
        "4) An exception was caught and reported. Message: null",
        "4 errors");
  }
}
 
Example 14
Project: google-guice   File: BindingTest.java   View source code 6 votes vote down vote up
public void testToConstructorSpiData() throws NoSuchMethodException {
  final Set<TypeLiteral<?>> heardTypes = Sets.newHashSet();

  final Constructor<D> constructor = D.class.getConstructor(Stage.class);
  final TypeListener listener = new TypeListener() {
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      if (!heardTypes.add(type)) {
        fail("Heard " + type + " multiple times!");
      }
    }
  };

  Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bind(Object.class).toConstructor(constructor);
      bind(D.class).toConstructor(constructor);
      bindListener(Matchers.any(), listener);
    }
  });
  
  assertEquals(ImmutableSet.of(TypeLiteral.get(D.class)), heardTypes);
}
 
Example 15
Project: google-guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testTypeListenersAreFired() throws NoSuchMethodException {
  final AtomicInteger firedCount = new AtomicInteger();

  final TypeListener typeListener = new TypeListener() {
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      assertEquals(new TypeLiteral<A>() {}, type);
      firedCount.incrementAndGet();
    }
  };

  Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bindListener(onlyAbcd, typeListener);
      bind(A.class);
    }
  });

  assertEquals(1, firedCount.get());
}
 
Example 16
Project: google-guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testAddingInterceptors() throws NoSuchMethodException {
  final Matcher<Object> buzz = only(C.class.getMethod("buzz"));

  Injector injector = Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bindInterceptor(any(), buzz, prefixInterceptor("ka"));
      bindInterceptor(any(), any(), prefixInterceptor("fe"));

      bindListener(onlyAbcd, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          encounter.bindInterceptor(any(), prefixInterceptor("li"));
          encounter.bindInterceptor(buzz, prefixInterceptor("no"));
        }
      });
    }
  });

  // interceptors must be invoked in the order they're bound.
  C c = injector.getInstance(C.class);
  assertEquals("kafelinobuzz", c.buzz());
  assertEquals("felibeep", c.beep());
}
 
Example 17
Project: google-guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testLookupsPostCreate() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bindListener(only(TypeLiteral.get(C.class)), new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          assertNotNull(encounter.getProvider(B.class).get());

          A a = new A();
          encounter.getMembersInjector(A.class).injectMembers(a);
          assertNotNull(a.injector);
        }
      });
    }
  });
  
  injector.getInstance(C.class);
}
 
Example 18
Project: google-guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
/**
 * We had a bug where we weren't notifying of types encountered for member injection when those
 * types had no members to be injected. Constructed types are always injected because they always
 * have at least one injection point: the class constructor.
 */
public void testTypesWithNoInjectableMembersAreNotified() {
  final AtomicInteger notificationCount = new AtomicInteger();

  Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bindListener(onlyAbcd, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          notificationCount.incrementAndGet();
        }
      });

      bind(C.class).toInstance(new C());
    }
  });

  assertEquals(1, notificationCount.get());
}
 
Example 19
Project: google-guice   File: TypeListenerTest.java   View source code 6 votes vote down vote up
public void testAddErrors() {
  try {
    Guice.createInjector(new AbstractModule() {
      protected void configure() {
        requestInjection(new Object());
        bindListener(Matchers.any(), new TypeListener() {
          public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
            encounter.addError("There was an error on %s", type);
            encounter.addError(new IllegalArgumentException("whoops!"));
            encounter.addError(new Message("And another problem"));
            encounter.addError(new IllegalStateException());
          }
        });
      }
    });
    fail();
  } catch (CreationException expected) {
    assertContains(expected.getMessage(),
        "1) There was an error on java.lang.Object",
        "2) An exception was caught and reported. Message: whoops!",
        "3) And another problem",
        "4) An exception was caught and reported. Message: null",
        "4 errors");
  }
}
 
Example 20
Project: simplejavayoutubeuploader   File: UploaderModule.java   View source code 6 votes vote down vote up
private void mapUtil() {
	final EventBus eventBus = new EventBus();
	bind(EventBus.class).toInstance(eventBus);
	bindListener(Matchers.any(), new TypeListener() {
		@Override
		public <I> void hear(@SuppressWarnings("unused") final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
			encounter.register(new InjectionListener<I>() {
				@Override
				public void afterInjection(final I injectee) {
					eventBus.register(injectee);
				}
			});
		}
	});

	requestStaticInjection(TextUtil.class);
}
 
Example 21
Project: jalphanode   File: InjectorModule.java   View source code 6 votes vote down vote up
protected void bindMBeanListener() {
    final MBeanAnnotationScanner scanner = new MBeanAnnotationScanner();
    this.bindListener(Matchers.any(), new TypeListener() {

            @Override
            public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
                final MBeanMetadata metadata = scanner.scan(type.getRawType());

                if (metadata != null) {
                    encounter.register((InjectionListener<I>) injectee -> {
                        try {
                            final ResourceDynamicMBean dynamicMBean = new ResourceDynamicMBean(injectee,
                                    metadata);

                            mBeanRegistry.register(dynamicMBean, metadata.getObjectName());
                        } catch (Exception e) {
                            LOG.error("Could not register MBean {}", metadata.getObjectName(), e);
                        }
                    });
                }
            }
        });
}
 
Example 22
Project: empiria.player   File: TestGuiceModule.java   View source code 5 votes vote down vote up
private void addPostConstructInterceptor(GuiceModuleConfiguration guiceModuleConfiguration) {
    HasPostConstructMethod hasPostConstruct = new HasPostConstructMethod(guiceModuleConfiguration.getClassWithDisabledPostConstruct());
    final PostConstructInvoker postConstructInvoker = new PostConstructInvoker();
    bindListener(hasPostConstruct, new TypeListener() {
        @Override
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
            encounter.register(postConstructInvoker);
        }
    });
}
 
Example 23
Project: Equella   File: SimpleEquellaModule.java   View source code 5 votes vote down vote up
@Override
protected void configure()
{
	bindListener(Matchers.any(), new TypeListener()
	{
		@Override
		public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter)
		{
			PluginResourceHandler.inst().getForClass(type.getRawType());
		}
	});
}
 
Example 24
Project: AutoAnnotateApp   File: AfterInjectionModule.java   View source code 5 votes vote down vote up
@Override
protected void configure() {
	// Call methods annotated with @AfterInjection after injection, mainly used to create UIs
	bindListener(new AfterInjectionMatcher(), new TypeListener() {
		AfterInjectionInvoker invoker = new AfterInjectionInvoker();
		@Override
		public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
			encounter.register(invoker);
		}
	});
}
 
Example 25
Project: guice-bootstrap   File: LifeCycleModule.java   View source code 5 votes vote down vote up
@Override
public void configure(Binder binder)
{
    binder.disableCircularProxies();

    binder.bindListener(any(), new TypeListener()
    {
        @Override
        public <T> void hear(TypeLiteral<T> type, TypeEncounter<T> encounter)
        {
            encounter.register(new InjectionListener<T>()
            {
                @Override
                public void afterInjection(T obj)
                {
                    if (isLifeCycleClass(obj.getClass())) {
                        LifeCycleManager lifeCycleManager = lifeCycleManagerRef.get();
                        if (lifeCycleManager != null) {
                            try {
                                lifeCycleManager.addInstance(obj);
                            }
                            catch (Exception e) {
                                throw new Error(e);
                            }
                        }
                        else {
                            injectedInstances.add(obj);
                        }
                    }
                }
            });
        }
    });
}
 
Example 26
Project: jop-discontinued   File: CoreModule.java   View source code 5 votes vote down vote up
/**
 * Configures module - binds all core interfaces to their (default) implementations.
 */
@Override
public void configure() {
  // binding for object populator
  bind(ObjectPopulator.class).to(ObjectPopulatorImpl.class);

  // binding of factories
  bind(ClassProviderFactory.class).to(ClassProviderFactoryImpl.class);
  bind(ConstructionStrategyFactory.class).to(ConstructionStrategyFactoryImpl.class);
  bind(ValueGeneratorFactory.class).to(ValueGeneratorFactoryImpl.class);
  bind(InstanceMatcherFactory.class).to(InstanceMatcherFactoryImpl.class);
  bind(PropertyPopulatorFactory.class).to(PropertyPopulatorFactoryImpl.class);
  bind(PopulatingStrategyFactory.class).to(PopulatingStrategyFactoryImpl.class);

  // binding of interlayers
  bind(ClassProviderInvoker.class).to(ClassProviderInvokerImpl.class);
  bind(ConstructionStrategyInvoker.class).to(ConstructionStrategyInvokerImpl.class);
  bind(ValueGeneratorInvoker.class).to(ValueGeneratorInvokerImpl.class);
  bind(InstanceMatcherInvoker.class).to(InstanceMatcherInvokerImpl.class);
  bind(PropertyPopulatorInvoker.class).to(PropertyPopulatorInvokerImpl.class);
  bind(PopulatingStrategyInvoker.class).to(PopulatingStrategyInvokerImpl.class);

  // binding of sessions
  bind(ClassLoaderSession.class).to(ClassLoaderSessionImpl.class);
  bind(RandomGeneratorSession.class).to(RandomGeneratorSessionImpl.class);
  bind(RandomGeneratorSession.class).annotatedWith(Names.named(NamedScopes.EXTENDED_IMPL)).to(ExtendedRandomGeneratorSessionImpl.class);
  bind(PopulatingSession.class).to(GlobalPopulatingSession.class);

  // binding of named implementations
  bind(PopulatingStrategy.class).annotatedWith(Names.named(NamedScopes.DEFAULT_IMPL)).to(DefaultStrategy.class);
  bind(new TypeLiteral<PropertyPopulator<?>>() {}).annotatedWith(Names.named(NamedScopes.DEFAULT_IMPL)).to(DefaultPropertyPopulator.class);
  bind(ConstructionStrategy.class).annotatedWith(Names.named(NamedScopes.DEFAULT_IMPL)).to(ConstructionStrategyImpl.class);

  // bind listener of classes implementing callback interfaces.
  bindListener(new SubclassesMatcher(Initializable.class), new TypeListener() {
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      encounter.register(new CallbacksInjectionListener<I>());
    }
  });
}
 
Example 27
Project: digdag   File: ServerLifeCycleModule.java   View source code 5 votes vote down vote up
@Override
public void configure(Binder binder)
{
    binder.disableCircularProxies();

    binder.bindListener(Matchers.any(), new TypeListener()
    {
        @Override
        public <T> void hear(TypeLiteral<T> type, TypeEncounter<T> encounter)
        {
            encounter.register(new InjectionListener<T>()
            {
                @Override
                public void afterInjection(T obj)
                {
                    ServerLifeCycleManager initialized = lifeCycleManagerRef.get();
                    if (initialized == null) {
                        earlyInjected.add(obj);
                    }
                    else {
                        try {
                            initialized.manageInstance(obj);
                        }
                        catch (Exception e) {
                            // really nothing we can do here
                            throw new Error(e);
                        }
                    }
                }
            });
        }
    });
}
 
Example 28
Project: herald   File: LogModule.java   View source code 5 votes vote down vote up
private TypeListener createTypeListener() {
    return new TypeListener() {
        @Override
        public <I> void hear(final TypeLiteral<I> typeLiteral, final TypeEncounter<I> typeEncounter) {
            typeEncounter.register((InjectionListener<I>) LoggerInjector::inject);
        }
    };
}
 
Example 29
Project: houdini   File: ObjectConverterModule.java   View source code 5 votes vote down vote up
private TypeListener createTypeListener(final ObjectConverterRegistry registry) {
    return new TypeListener() {
        @Override
        public <I> void hear(final TypeLiteral<I> typeLiteral, final TypeEncounter<I> typeEncounter) {
            typeEncounter.register(new InjectionListener<I>() {
                @Override
                public void afterInjection(final I injectee) {
                    registry.registerConverters(injectee);
                }
            });
        }
    };
}
 
Example 30
Project: nano-framework   File: FieldInjectModule.java   View source code 5 votes vote down vote up
@Override
public void configure(final Binder binder) {
    binder.bindListener(Matchers.any(), new TypeListener() {
        @Override
        public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
            final List<Field> fields = fields(Lists.newArrayList(), type.getRawType());
            fields.stream().filter(field -> field.isAnnotationPresent(FieldInject.class)).forEach(field -> {
                final FieldInject inject = field.getAnnotation(FieldInject.class);
                encounter.register(ReflectUtils.newInstance(inject.value(), field));
            });
        }
    });
}
 
Example 31
Project: cinnamon   File: WebDriverModule.java   View source code 5 votes vote down vote up
@Override
public void configure() {
    final FindByKeyInjectionListener findByKeyInjectionListener = new FindByKeyInjectionListener();
    bind(FindByKeyInjectionListener.class).toInstance(findByKeyInjectionListener);

    bindListener(Matchers.any(), new TypeListener() {
        @Override
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
            if (hasFindByKeyAnnotation(type.getRawType())) {
                encounter.register(findByKeyInjectionListener);
            }
        }

        private boolean hasFindByKeyAnnotation(Class<?> clazz) {
            while (clazz != null) {
                for (Field field : clazz.getDeclaredFields()) {
                    if (field.isAnnotationPresent(FindByKey.class) || field.isAnnotationPresent(FindBy.class) || field
                            .isAnnotationPresent(FindAll.class)) {
                        return true;
                    }
                }
                // If this Class represents either the Object class, an interface, a primitive type, or void, then
                // null is returned.
                clazz = clazz.getSuperclass();
            }
            return false;
        }
    });
}
 
Example 32
Project: guice   File: RequestInjectionTest.java   View source code 5 votes vote down vote up
public void testEarlyInjectableReferencesWithSameIdentity() {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              // Add a listener to trigger all toInstance bindings to get an Initializable.
              bindListener(
                  Matchers.any(),
                  new TypeListener() {
                    @Override
                    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {}
                  });

              // Bind two different Keys to the IDENTITICAL object
              // ORDER MATTERS! We want the String binding to push out the Object one
              String fail = new String("better not fail!");
              bind(Object.class).toInstance(fail);
              bind(String.class).toInstance(fail);

              // Then try to inject those objects in a requestInjection,
              // letting us get into InjectableReference.get before it has
              // finished running through all its injections.
              // Each of these technically has its own InjectableReference internally.
              // ORDER MATTERS!.. because Object is injected first, that InjectableReference
              // attempts to process its members injector, but it wasn't initialized,
              // because String pushed it out of the queue!
              requestInjection(
                  new Object() {
                    @SuppressWarnings("unused")
                    @Inject
                    Object obj;

                    @SuppressWarnings("unused")
                    @Inject
                    String str;
                  });
            }
          });
}
 
Example 33
Project: guice   File: TypeListenerTest.java   View source code 5 votes vote down vote up
public void testAddingInterceptors() throws NoSuchMethodException {
  final Matcher<Object> buzz = only(C.class.getMethod("buzz"));

  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bindInterceptor(any(), buzz, prefixInterceptor("ka"));
              bindInterceptor(any(), any(), prefixInterceptor("fe"));

              bindListener(
                  onlyAbcd,
                  new TypeListener() {
                    @Override
                    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                      encounter.bindInterceptor(any(), prefixInterceptor("li"));
                      encounter.bindInterceptor(buzz, prefixInterceptor("no"));
                    }
                  });
            }
          });

  // interceptors must be invoked in the order they're bound.
  C c = injector.getInstance(C.class);
  assertEquals("kafelinobuzz", c.buzz());
  assertEquals("felibeep", c.beep());
}
 
Example 34
Project: guice   File: TypeListenerTest.java   View source code 5 votes vote down vote up
public void testAddErrors() {
  try {
    Guice.createInjector(
        new AbstractModule() {
          @Override
          protected void configure() {
            requestInjection(new Object());
            bindListener(
                Matchers.any(),
                new TypeListener() {
                  @Override
                  public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                    encounter.addError("There was an error on %s", type);
                    encounter.addError(new IllegalArgumentException("whoops!"));
                    encounter.addError(new Message("And another problem"));
                    encounter.addError(new IllegalStateException());
                  }
                });
          }
        });
    fail();
  } catch (CreationException expected) {
    assertContains(
        expected.getMessage(),
        "1) There was an error on java.lang.Object",
        "2) An exception was caught and reported. Message: whoops!",
        "3) And another problem",
        "4) An exception was caught and reported. Message: null",
        "4 errors");
  }
}
 
Example 35
Project: PeerWasp   File: AppModule.java   View source code 5 votes vote down vote up
private void messageBusRegisterRule() {
	// This rule registers all objects created by Guice with the message bus.
	// As a result, all instances created by Guice can receive messages without explicit
	// subscription.
	bindListener(Matchers.any(), new TypeListener() {
		@Override
        public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
            typeEncounter.register(new InjectionListener<I>() {
                public void afterInjection(I i) {
                    messageBus.subscribe(i);
                }
            });
        }
    });
}
 
Example 36
Project: ddp-client-java   File: SampleApplicationModule.java   View source code 5 votes vote down vote up
@Override
protected void configure() {
    bind(SampleApplication.class);

    bind(MessageConverter.class).to(JsonMessageConverter.class).in(Singleton.class);
    bind(ObjectConverter.class).to(JsonObjectConverter.class).in(Singleton.class);
    bind(SubscriptionAdapter.class).to(MapSubscriptionAdapter.class).in(Singleton.class);
    bind(DDPMessageEndpoint.class).to(DDPMessageEndpointImpl.class).in(Singleton.class);
    bind(SubscriptionEventDispatcher.class).asEagerSingleton();
    bind(MeteorCollectionRepository.class).to(MeteorCollectionRepositoryImpl.class).in(Singleton.class);
    bind(RPCClient.class).to(RPCClientImpl.class).in(Singleton.class);
    bind(EventBus.class).in(Singleton.class);

    bindListener(
            new AbstractMatcher<TypeLiteral<?>>() {
                @Override
                public boolean matches(TypeLiteral<?> typeLiteral) {
                    return typeLiteral.getRawType().isAnnotationPresent(Presents.class);
                }
            },
            new TypeListener() {
                @Override
                public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
                    final Presents presents = type.getRawType().getAnnotation(Presents.class);
                    encounter.register((InjectionListener<I>) injectee -> {
                        final FXMLLoader loader = new FXMLLoader(injectee.getClass().getResource(presents.value()));
                        loader.setController(injectee);
                        try {
                            loader.load();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }
            }
    );
}
 
Example 37
Project: guice-old   File: RequestInjectionTest.java   View source code 5 votes vote down vote up
public void testEarlyInjectableReferencesWithSameIdentity() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      // Add a listener to trigger all toInstance bindings to get an Initializable.
      bindListener(Matchers.any(), new TypeListener() {
        @Override
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
        }
      });
      
      // Bind two different Keys to the IDENTITICAL object
      // ORDER MATTERS! We want the String binding to push out the Object one
      String fail = new String("better not fail!");
      bind(Object.class).toInstance(fail);
      bind(String.class).toInstance(fail);
      
      // Then try to inject those objects in a requestInjection,
      // letting us get into InjectableReference.get before it has
      // finished running through all its injections.
      // Each of these technically has its own InjectableReference internally.
      // ORDER MATTERS!.. because Object is injected first, that InjectableReference
      // attempts to process its members injector, but it wasn't initialized,
      // because String pushed it out of the queue!
      requestInjection(new Object() {
        @SuppressWarnings("unused") @Inject Object obj;
        @SuppressWarnings("unused") @Inject String str;
      });
    }
  });
}
 
Example 38
Project: guice-old   File: TypeListenerTest.java   View source code 5 votes vote down vote up
public void testInstallingInjectionListener() {
  final List<Object> injectees = Lists.newArrayList();
  final InjectionListener<Object> injectionListener = new InjectionListener<Object>() {
    public void afterInjection(Object injectee) {
      injectees.add(injectee);
    }
  };

  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override protected void configure() {
      bindListener(onlyAbcd, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          encounter.register(injectionListener);
        }
      });
      bind(A.class);
    }
  });

  assertEquals(ImmutableList.of(), injectees);

  Object a1 = injector.getInstance(A.class);
  assertEquals(ImmutableList.of(a1), injectees);

  Object a2 = injector.getInstance(A.class);
  assertEquals(ImmutableList.of(a1, a2), injectees);

  Object b1 = injector.getInstance(B.class);
  assertEquals(ImmutableList.of(a1, a2, b1), injectees);

  Provider<A> aProvider = injector.getProvider(A.class);
  assertEquals(ImmutableList.of(a1, a2, b1), injectees);
  A a3 = aProvider.get();
  A a4 = aProvider.get();
  assertEquals(ImmutableList.of(a1, a2, b1, a3, a4), injectees);
}
 
Example 39
Project: google-guice   File: RequestInjectionTest.java   View source code 5 votes vote down vote up
public void testEarlyInjectableReferencesWithSameIdentity() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      // Add a listener to trigger all toInstance bindings to get an Initializable.
      bindListener(Matchers.any(), new TypeListener() {
        @Override
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
        }
      });
      
      // Bind two different Keys to the IDENTITICAL object
      // ORDER MATTERS! We want the String binding to push out the Object one
      String fail = new String("better not fail!");
      bind(Object.class).toInstance(fail);
      bind(String.class).toInstance(fail);
      
      // Then try to inject those objects in a requestInjection,
      // letting us get into InjectableReference.get before it has
      // finished running through all its injections.
      // Each of these technically has its own InjectableReference internally.
      // ORDER MATTERS!.. because Object is injected first, that InjectableReference
      // attempts to process its members injector, but it wasn't initialized,
      // because String pushed it out of the queue!
      requestInjection(new Object() {
        @SuppressWarnings("unused") @Inject Object obj;
        @SuppressWarnings("unused") @Inject String str;
      });
    }
  });
}
 
Example 40
Project: google-guice   File: TypeListenerTest.java   View source code 5 votes vote down vote up
public void testInstallingInjectionListener() {
  final List<Object> injectees = Lists.newArrayList();
  final InjectionListener<Object> injectionListener = new InjectionListener<Object>() {
    public void afterInjection(Object injectee) {
      injectees.add(injectee);
    }
  };

  Injector injector = Guice.createInjector(new AbstractModule() {
    protected void configure() {
      bindListener(onlyAbcd, new TypeListener() {
        public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
          encounter.register(injectionListener);
        }
      });
      bind(A.class);
    }
  });

  assertEquals(ImmutableList.of(), injectees);

  Object a1 = injector.getInstance(A.class);
  assertEquals(ImmutableList.of(a1), injectees);

  Object a2 = injector.getInstance(A.class);
  assertEquals(ImmutableList.of(a1, a2), injectees);

  Object b1 = injector.getInstance(B.class);
  assertEquals(ImmutableList.of(a1, a2, b1), injectees);

  Provider<A> aProvider = injector.getProvider(A.class);
  assertEquals(ImmutableList.of(a1, a2, b1), injectees);
  A a3 = aProvider.get();
  A a4 = aProvider.get();
  assertEquals(ImmutableList.of(a1, a2, b1, a3, a4), injectees);
}