com.google.inject.spi.TypeEncounter Java Examples

The following examples show how to use com.google.inject.spi.TypeEncounter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LifecycleModule.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
private <I> void executePostConstruct(final TypeEncounter<I> encounter, final Class<? super I> rawType,
                                      final LifecycleRegistry lifecycleRegistry) {
    //We're going recursive up to every superclass until we hit Object.class
    if (rawType.getSuperclass() != null) {
        executePostConstruct(encounter, rawType.getSuperclass(), lifecycleRegistry);
    }

    final Method postConstructFound = findPostConstruct(rawType);
    final Method preDestroy = findPreDestroy(rawType);

    if (postConstructFound != null) {
        invokePostConstruct(encounter, postConstructFound);
    }

    if (preDestroy != null) {
        addPreDestroyToRegistry(encounter, preDestroy, lifecycleRegistry);
    }
}
 
Example #2
Source File: LifecycleModule.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
private <I> void invokePostConstruct(final TypeEncounter<I> encounter, final Method postConstruct) {
    encounter.register(new InjectionListener<I>() {
        @Override
        public void afterInjection(final I injectee) {
            try {
                postConstruct.setAccessible(true);
                postConstruct.invoke(injectee);
            } catch (final IllegalAccessException | InvocationTargetException e) {
                if (e.getCause() instanceof UnrecoverableException) {
                    if (((UnrecoverableException) e.getCause()).isShowException()) {
                        log.error("An unrecoverable Exception occurred. Exiting HiveMQ", e);
                    }
                    System.exit(1);
                }
                throw new ProvisionException("An error occurred while calling @PostConstruct", e);
            }
        }
    });
}
 
Example #3
Source File: LifecycleModule.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {

    final boolean newRegistry = lifecycleRegistry.compareAndSet(null, new LifecycleRegistry());
    bind(LifecycleRegistry.class).toInstance(lifecycleRegistry.get());

    if (newRegistry) {
        bind(LifecycleShutdownRegistration.class).asEagerSingleton();
    }

    bindListener(Matchers.any(), new TypeListener() {
        @Override
        public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
            executePostConstruct(encounter, type.getRawType(), lifecycleRegistry.get());
        }
    });
}
 
Example #4
Source File: OrienteerTestModule.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
	
	bind(Boolean.class).annotatedWith(Names.named("testing")).toInstance(true);
	bindListener(InstanceOfMatcher.createFor(WebApplication.class), new TypeListener() {
		
		@Override
		public <I> void hear(TypeLiteral<I> type, final TypeEncounter<I> encounter) {
			final Provider<Injector> injectorProvider = encounter.getProvider(Injector.class);
			encounter.register((InjectionListener<Object>) injected -> {
                   WebApplication app = (WebApplication) injected;
                   app.getComponentInstantiationListeners().add(new GuiceComponentInjector(app, injectorProvider.get()));
               });
		}
	});
	bind(OrienteerTester.class).asEagerSingleton();
	Provider<OrienteerTester> provider = binder().getProvider(OrienteerTester.class);
	bind(WicketTester.class).toProvider(provider);
	bind(WicketOrientDbTester.class).toProvider(provider);
}
 
Example #5
Source File: CliTypeListener.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
    Set<Field> fields = new HashSet<>();
    CliCommand cliCommand = null;
    for (Class<?> c = typeLiteral.getRawType(); c != Object.class; c = c.getSuperclass()) {
        if (cliCommand == null) {
            cliCommand = c.getAnnotation(CliCommand.class);
        } else if (c.isAnnotationPresent(CliCommand.class)) {
            throw SeedException.createNew(CliErrorCode.CONFLICTING_COMMAND_ANNOTATIONS)
                    .put("class", c.getCanonicalName());
        }
        Arrays.stream(c.getDeclaredFields()).filter(this::isCandidate).forEach(fields::add);
    }

    if (!fields.isEmpty()) {
        typeEncounter.register(new CliMembersInjector<>(
                cliContext,
                cliCommand == null ? typeLiteral.getType().getTypeName() : cliCommand.value(),
                fields)
        );
    }
}
 
Example #6
Source File: ConfigurationTypeListener.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
    Set<ConfigurationMembersInjector.ConfigurableField> fields = new HashSet<>();
    for (Class<?> c = typeLiteral.getRawType(); c != Object.class; c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            Configuration annotation = field.getAnnotation(Configuration.class);
            if (annotation != null) {
                fields.add(new ConfigurationMembersInjector.ConfigurableField(field, annotation));
            }
        }
    }

    if (!fields.isEmpty()) {
        typeEncounter.register(new ConfigurationMembersInjector<>(configuration, fields));
    }
}
 
Example #7
Source File: LoggingTypeListener.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
    Set<Field> fields = new HashSet<>();
    for (Class<?> c = typeLiteral.getRawType(); c != Object.class; c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            if (field.isAnnotationPresent(Logging.class)) {
                if (field.getType() == Logger.class) {
                    fields.add(field);
                } else {
                    throw SeedException.createNew(CoreErrorCode.BAD_LOGGER_TYPE)
                            .put("field", format("%s.%s", field.getDeclaringClass().getName(), field.getName()))
                            .put("expectedType", Logger.class.getName())
                            .put("givenType", field.getType().getName());
                }
            }
        }
    }

    if (!fields.isEmpty()) {
        typeEncounter.register(new LoggingMembersInjector<>(fields));
    }
}
 
Example #8
Source File: RuntimeModule.java    From EDDI with Apache License 2.0 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 #9
Source File: AbstractMethodTypeListener.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Allows traverse the input klass hierarchy.
 *
 * @param parentType the owning type being heard
 * @param klass      encountered by Guice.
 * @param encounter  the injection context.
 */
private <I> void hear(final TypeLiteral<I> parentType, Class<? super I> klass, TypeEncounter<I> encounter) {
    Package pkg;
    if (klass == null || ((pkg = klass.getPackage()) != null && pkg.getName().startsWith(JAVA_PACKAGE))) {
        return;
    }

    for (Class<? extends Annotation> annotationType : annotationTypes) {
        for (Method method : klass.getDeclaredMethods()) {
            if (method.isAnnotationPresent(annotationType)) {
                if (method.getParameterTypes().length != 0) {
                    encounter.addError("Annotated methods with @%s must not accept any argument, found %s",
                        annotationType.getName(), method);
                }

                hear(method, parentType, encounter, annotationType);
            }
        }
    }

    hear(parentType, klass.getSuperclass(), encounter);
}
 
Example #10
Source File: SeleniumClassModule.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
  traverseClassHierarchy(
      type.getRawType(),
      (clazz) -> {
        for (Field field : clazz.getDeclaredFields()) {
          if (field.getType() == TestWorkspace.class
              && field.isAnnotationPresent(InjectTestWorkspace.class)) {
            encounter.register(
                new TestWorkspaceInjector<>(
                    field,
                    field.getAnnotation(InjectTestWorkspace.class),
                    injectorProvider.get()));
          }
        }
      });
}
 
Example #11
Source File: LifeCycleStageModule.java    From james-project with Apache License 2.0 6 votes vote down vote up
private <A extends Annotation> void bind(BindingBuilder<A> binding) {
    final Stager<A> stager = binding.stager;
    final StageableTypeMapper typeMapper = binding.typeMapper;
    bind(type(stager.getStage())).toInstance(stager);

    bindListener(binding.typeMatcher, new AbstractMethodTypeListener(asList(stager.getStage())) {
        @Override
        protected <I> void hear(final Method stageMethod, final TypeLiteral<I> parentType,
                                final TypeEncounter<I> encounter, final Class<? extends Annotation> annotationType) {
            encounter.register((InjectionListener<I>) injectee -> {
                Stageable stageable = new StageableMethod(stageMethod, injectee);
                stager.register(stageable);
                typeMapper.registerType(stageable, parentType);
            });
        }
    });
}
 
Example #12
Source File: DestroyModule.java    From che with Eclipse Public License 2.0 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 #13
Source File: FieldInjectModule.java    From nano-framework with Apache License 2.0 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 #14
Source File: MycilaJmxModuleExt.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {
  bindListener(ClassToTypeLiteralMatcherAdapter.adapt(Matchers.annotatedWith(JmxBean.class)), new TypeListener() {
    @Override
    public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
      final Provider<JmxExporter> exporter = encounter.getProvider(JmxExporter.class);
      encounter.register(new InjectionListener<I>() {
        @Override
        public void afterInjection(I injectee) {
          exporter.get().register(injectee);
        }
      });
    }
  });
}
 
Example #15
Source File: IndexedCorpusModule.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
     Class<?> clazz = typeLiteral.getRawType();
     while (clazz != null) {
       for (Field field : clazz.getDeclaredFields()) {
         boolean injectAnnoPresent = 
         		field.isAnnotationPresent(fr.univnantes.termsuite.framework.InjectLogger.class);
if (field.getType() == Logger.class &&
           injectAnnoPresent) {
           typeEncounter.register(new Slf4JMembersInjector<T>(field));
         }
       }
       clazz = clazz.getSuperclass();
     }
   }
 
Example #16
Source File: ConfigurationListener.java    From Guice-configuration with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
    getClasses(typeLiteral.getRawType(), new ArrayList<>()).stream()
            .filter(c -> c.isAnnotationPresent(BindConfig.class))
            .forEach(c -> injectorBuilder.build(c)
                    .forEach(typeEncounter::register));
}
 
Example #17
Source File: AppModule.java    From PeerWasp with MIT License 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 #18
Source File: ResourceTypeListener.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
    for (Class<?> c = typeLiteral.getRawType(); c != Object.class; c = c.getSuperclass()) {
        for (Field field : typeLiteral.getRawType().getDeclaredFields()) {
            Resource resourceAnnotation = field.getAnnotation(Resource.class);
            if (resourceAnnotation != null) {
                String resourceName = resourceAnnotation.name();
                Context contextToLookup = defaultContext;
                String contextName = "default";

                // Check if this injection is from an additional context
                JndiContext jndiContextAnnotation = field.getAnnotation(JndiContext.class);
                if (jndiContextAnnotation != null) {
                    contextName = jndiContextAnnotation.value();
                    contextToLookup = jndiContexts.get(contextName);
                    if (contextToLookup == null) {
                        throw SeedException.createNew(JndiErrorCode.UNKNOWN_JNDI_CONTEXT)
                                .put("field", field)
                                .put("context", contextName);
                    }
                }

                // Register the members injector
                if (!resourceName.isEmpty()) {
                    typeEncounter.register(new ResourceMembersInjector<>(field,
                            contextToLookup,
                            contextName,
                            resourceName));
                }
            }
        }
    }
}
 
Example #19
Source File: PaasModule.java    From staash with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    LOG.info("Loading PaasModule");
    
    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);
                }
            });
        }
    });

    bind(TaskManager.class).to(InlineTaskManager.class);

    // Constants
    bind(String.class).annotatedWith(Names.named("namespace")).toInstance("com.netflix.pass.");
    bind(String.class).annotatedWith(Names.named("appname"  )).toInstance("paas");
    
    bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance());

    // Configuration
    bind(PaasConfiguration.class).to(ArchaeusPaasConfiguration.class).in(Scopes.SINGLETON);
    
    // Stuff
    bind(ScheduledExecutorService.class).annotatedWith(Names.named("tasks")).toInstance(Executors.newScheduledThreadPool(10));
    
    bind(DaoProvider.class).in(Scopes.SINGLETON);
    
    // Rest resources
    bind(DataResource.class).in(Scopes.SINGLETON);
    bind(SchemaAdminResource.class).to(JerseySchemaAdminResourceImpl.class).in(Scopes.SINGLETON);
    bind(SchemaService.class).to(DaoSchemaService.class).in(Scopes.SINGLETON);
    
}
 
Example #20
Source File: ServerLifeCycleModule.java    From digdag with Apache License 2.0 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 #21
Source File: LifecycleModule.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
private <I> void addPreDestroyToRegistry(final TypeEncounter<I> encounter, final Method preDestroy, final LifecycleRegistry registry) {
    encounter.register(new InjectionListener<I>() {
        @Override
        public void afterInjection(final I injectee) {
            registry.addPreDestroyMethod(preDestroy, injectee);

        }
    });
}
 
Example #22
Source File: InjectionLogger.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
    logger.info("Encountered type " + type);
    encounter.register((InjectionListener<I>) injectee -> {
        logger.info("Injected " + injectee);
    });
}
 
Example #23
Source File: Slf4jTypeListener.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> iTypeLiteral, TypeEncounter<I> iTypeEncounter) {
    for (Field field : iTypeLiteral.getRawType().getDeclaredFields()) {
        if (field.getType() == Logger.class
            && field.isAnnotationPresent(InjectLogger.class)) {
            iTypeEncounter.register(new Slf4jMembersInjector<I>(field));
        }
    }
}
 
Example #24
Source File: PageObjectTypeListener.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * Automatically called by Guice during injection of any object. Checks if the injected object's type is
 * annotated as PageObject. If yes, it will register PageObjectInjectorListener in the TypeEncounter, so
 * that PageObjectInjectorListener will be able to perform custom injections.
 */
@Override
public <I> void hear(TypeLiteral<I> typeLiteral, final TypeEncounter<I> typeEncounter) {
  if (typeLiteral.getRawType().isAnnotationPresent(PageObject.class)) {
    typeEncounter.register(new PageObjectInjectorListener(typeEncounter));
  }
}
 
Example #25
Source File: PageObjectInjectorListener.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor of the listener. Initializes all the fields.
 *
 * @param typeEncounter Type encounter instance, provided by Guice.
 */
public PageObjectInjectorListener(TypeEncounter<?> typeEncounter) {
  this.webDriverProvider = typeEncounter.getProvider(WebDriver.class);
  this.locatorStackProvider = typeEncounter.getProvider(ContextStack.class);
  this.registry = typeEncounter.getProvider(FieldProviderRegistry.class);
  this.frameMap = typeEncounter.getProvider(FrameMap.class);
  this.bobcatWebElementFactoryProvider = typeEncounter.getProvider(BobcatWebElementFactory.class);
}
 
Example #26
Source File: ParameterizedTimedListener.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> literal, TypeEncounter<I> encounter) {
    Class<? super I> type = literal.getRawType();
    for (Method method : type.getMethods()) {
        ParameterizedTimed annotation = method.getAnnotation(ParameterizedTimed.class);
        if (annotation == null) {
            continue;
        }

        String metricType = annotation.type();
        if(metricType == null || metricType.isEmpty()) {
            metricType = type.getSimpleName().replaceAll("\\$$", "");
        }
        String metricName = annotation.name();
        if(metricName == null || metricName.isEmpty()) {
            metricName = method.getName();
        }
        String metric = MetricRegistry.name(_group, metricType, metricName);
        final Timer timer = _metricRegistry.timer(metric);

        encounter.bindInterceptor(Matchers.only(method), new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                Timer.Context time = timer.time();
                try {
                    return invocation.proceed();
                } finally {
                    time.stop();
                }
            }
        });
    }
}
 
Example #27
Source File: InjectConfigTest.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter)
{
  for (Class<?> c = typeLiteral.getRawType(); c != Object.class; c = c.getSuperclass()) {
    LOG.debug("Inspecting fields for " + c);
    for (Field field : c.getDeclaredFields()) {
      if (field.isAnnotationPresent(InjectConfig.class)) {
        typeEncounter.register(new ConfigurationInjector<T>(field, field.getAnnotation(InjectConfig.class)));
      }
    }
  }
}
 
Example #28
Source File: SeleniumClassModule.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
  Class<?> clazz = type.getRawType();
  for (Field field : clazz.getDeclaredFields()) {
    if (field.getType() == TestOrganization.class
        && field.isAnnotationPresent(InjectTestOrganization.class)) {
      encounter.register(
          new TestOrganizationInjector<>(
              field, field.getAnnotation(InjectTestOrganization.class), injectorProvider));
    }
  }
}
 
Example #29
Source File: LogModule.java    From herald with Apache License 2.0 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 #30
Source File: StartablesModule.java    From james-project with Apache License 2.0 4 votes vote down vote up
private <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
    InjectionListener<? super I> injectionListener = ignored -> startables.add(type.getRawType().asSubclass(Startable.class));
    encounter.register(injectionListener);
}