类com.google.inject.spi.TypeEncounter源码实例Demo

下面列出了怎么用com.google.inject.spi.TypeEncounter的API类实例代码及写法,或者点击链接到github查看源代码。

@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());
        }
    });
}
 
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);
    }
}
 
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);
            }
        }
    });
}
 
源代码4 项目: EDDI   文件: RuntimeModule.java
@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);
        }
    });
}
 
源代码5 项目: che   文件: SeleniumClassModule.java
@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()));
          }
        }
      });
}
 
源代码6 项目: che   文件: DestroyModule.java
@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);
                  }
                }
              });
        }
      });
}
 
源代码7 项目: james-project   文件: LifeCycleStageModule.java
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);
            });
        }
    });
}
 
/**
 * 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);
}
 
源代码9 项目: seed   文件: LoggingTypeListener.java
@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));
    }
}
 
源代码10 项目: seed   文件: ConfigurationTypeListener.java
@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));
    }
}
 
源代码11 项目: seed   文件: CliTypeListener.java
@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)
        );
    }
}
 
源代码12 项目: Orienteer   文件: OrienteerTestModule.java
@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);
}
 
源代码13 项目: hivemq-community-edition   文件: LifecycleModule.java
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);

        }
    });
}
 
源代码14 项目: ProjectAres   文件: InjectionLogger.java
@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);
    });
}
 
源代码15 项目: blueocean-plugin   文件: Slf4jTypeListener.java
@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));
        }
    }
}
 
源代码16 项目: bobcat   文件: PageObjectTypeListener.java
/**
 * 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));
  }
}
 
源代码17 项目: bobcat   文件: PageObjectInjectorListener.java
/**
 * 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);
}
 
源代码18 项目: emodb   文件: ParameterizedTimedListener.java
@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();
                }
            }
        });
    }
}
 
源代码19 项目: attic-apex-core   文件: InjectConfigTest.java
@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)));
      }
    }
  }
}
 
源代码20 项目: che   文件: SeleniumClassModule.java
@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));
    }
  }
}
 
源代码21 项目: digdag   文件: ServerLifeCycleModule.java
@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);
                        }
                    }
                }
            });
        }
    });
}
 
源代码22 项目: herald   文件: LogModule.java
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);
        }
    };
}
 
源代码23 项目: nano-framework   文件: FieldInjectModule.java
@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));
            });
        }
    });
}
 
源代码24 项目: termsuite-core   文件: IndexedCorpusModule.java
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();
     }
   }
 
@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));
}
 
源代码26 项目: PeerWasp   文件: AppModule.java
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);
                }
            });
        }
    });
}
 
源代码27 项目: seed   文件: ResourceTypeListener.java
@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));
                }
            }
        }
    }
}
 
源代码28 项目: staash   文件: PaasModule.java
@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);
    
}
 
源代码29 项目: Scribengin   文件: MycilaJmxModuleExt.java
@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);
        }
      });
    }
  });
}
 
源代码30 项目: gef   文件: AdaptableTypeListener.java
@SuppressWarnings("unchecked")
@Override
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
	if (IAdaptable.class.isAssignableFrom(type.getRawType())) {
		// TODO: method check should be moved into members injector,
		// here, only the type + an additional operation should be checked.
		for (final Method method : type.getRawType().getMethods()) {
			// check that AdapterMap annotation is not used to mark
			// injection points (but only in bindings).
			for (int i = 0; i < method
					.getParameterAnnotations().length; i++) {
				AdapterMap adapterMapAnnotation = getAnnotation(
						method.getParameterAnnotations()[i],
						AdapterMap.class);
				if (adapterMapAnnotation != null) {
					encounter.addError(
							"@AdapterMap annotation may only be used in adapter map bindings, not to mark an injection point. Annotate method with @InjectAdapters instead.",
							method);
				}
			}

			// we have a method annotated with AdapterBinding
			if (eligibleForAdapterInjection(method)) {
				// check that no Guice @Inject annotation is present on the
				// method (so no interference occurs).
				Inject injectAnnotation = method
						.getAnnotation(Inject.class);
				if (injectAnnotation != null) {
					encounter.addError(
							"To prevent that Guice member injection interferes with adapter injection, no @Inject annotation may be used on a method that provides an @InjectAdapters annotation.");
				}

				// register member injector on the IAdaptable (and provide
				// the method to it, so it does not have to look it up
				// again).
				AdapterInjector membersInjector = new AdapterInjector(
						method, loggingMode);
				if (injector != null) {
					injector.injectMembers(membersInjector);
				} else {
					nonInjectedMemberInjectors.add(membersInjector);
				}
				// System.out.println("Registering member injector to "
				// + type);
				encounter.register((MembersInjector<I>) membersInjector);
			}
		}
	}
}
 
 类所在包
 类方法
 同包方法