com.google.inject.Stage Java Examples

The following examples show how to use com.google.inject.Stage. 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: GuiceBundle.java    From dropwizard-guicier with Apache License 2.0 7 votes vote down vote up
private GuiceBundle(final Class<T> configClass,
                    final ImmutableSet<Module> guiceModules,
                    final ImmutableSet<DropwizardAwareModule<T>> dropwizardAwareModules,
                    final Stage guiceStage,
                    final boolean allowUnknownFields,
                    final boolean enableGuiceEnforcer,
                    final InjectorFactory injectorFactory) {
  this.configClass = configClass;

  this.guiceModules = guiceModules;
  this.dropwizardAwareModules = dropwizardAwareModules;
  this.guiceStage = guiceStage;
  this.allowUnknownFields = allowUnknownFields;
  this.enableGuiceEnforcer = enableGuiceEnforcer;
  this.injectorFactory = injectorFactory;
}
 
Example #2
Source File: Client.java    From J-Kinopoisk2IMDB with Apache License 2.0 7 votes vote down vote up
public Client(@NonNull Path filePath, @NonNull Config config, boolean cleanRun, @NonNull List<?> listeners) {
    this.filePath = checkFile(filePath);
    this.cleanRun = cleanRun;
    this.config = config;

    Injector injector = Guice.createInjector(
            Stage.PRODUCTION,
            new ConfigurationModule(ConfigValidator.checkValid(config.withFallback(ConfigFactory.load()))),
            new JpaRepositoryModule(),
            new ServiceModule()
    );

    persistService = injector.getInstance(PersistService.class);
    persistService.start();

    handlerType = injector.getInstance(MovieHandler.Type.class);
    handlerChain = injector.getInstance(MovieHandler.class);
    importProgressService = injector.getInstance(ImportProgressService.class);

    eventBus = new EventBus();
    listeners.forEach(eventBus::register);
}
 
Example #3
Source File: UtilCoreManifest.java    From ProjectAres with GNU Affero General Public License v3.0 7 votes vote down vote up
@Override
protected void configure() {
    // @InjectorScoped annotation
    install(new InjectorScopeModule());

    // Provide a global, catch-all exception handler
    bind(LoggingExceptionHandler.class).in(Singleton.class);
    bind(ExceptionHandler.class).to(LoggingExceptionHandler.class);
    bind(new TypeLiteral<ExceptionHandler<Throwable>>(){}).to(LoggingExceptionHandler.class);
    bind(Thread.UncaughtExceptionHandler.class).to(LoggingExceptionHandler.class);

    // Evil decorator thing
    // Create it manually so we can use it before the injector is ready
    bind(DecoratorFactory.class).toInstance(DecoratorFactory.get());

    install(new NumberFactory.Manifest());

    install(new ParsersManifest());

    requestStaticInjection(SystemFutureCallback.class);

    if(currentStage() == Stage.DEVELOPMENT) {
        // This is useful, but it makes the LeakDetector unhappy
        //install(new RepeatInjectionDetector());
    }
}
 
Example #4
Source File: GuacamoleServletContextListener.java    From guacamole-client with Apache License 2.0 7 votes vote down vote up
@Override
protected Injector getInjector() {

    // Create injector
    Injector injector = Guice.createInjector(Stage.PRODUCTION,
        new EnvironmentModule(environment),
        new LogModule(environment),
        new ExtensionModule(environment),
        new RESTServiceModule(sessionMap),
        new TunnelModule()
    );

    // Inject any annotated members of this class
    injector.injectMembers(this);

    return injector;

}
 
Example #5
Source File: GuacamoleServletContextListener.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
@Override
protected Injector getInjector() {

    // Create injector
    Injector injector = Guice.createInjector(Stage.PRODUCTION,
        new EnvironmentModule(environment),
        new LogModule(environment),
        new ExtensionModule(environment),
        new RESTServiceModule(sessionMap),
        new TunnelModule()
    );

    // Inject any annotated members of this class
    injector.injectMembers(this);

    return injector;

}
 
Example #6
Source File: Initializer.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
protected Injector getInjector() {
    boolean success = false;

    final StringWriter errorOut = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errorOut);
    try {
        this.injector = Guice.createInjector(Stage.PRODUCTION, this.getModules());
        success = true;
    } catch (Exception e){
        System.err.println("[HMDM-INITIALIZER]: Unexpected error during injector initialization: " + e);
        e.printStackTrace();
        e.printStackTrace(errorWriter);
    }
    if (success) {
        System.out.println("[HMDM-INITIALIZER]: Application initialization was successful");
        onInitializationCompletion(null);
    } else {
        System.out.println("[HMDM-INITIALIZER]: Application initialization has failed");
        onInitializationCompletion(errorOut);
    }
    return injector;
}
 
Example #7
Source File: BackendStartupListener.java    From HotswapAgentExamples with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {

	/*
	 * TODO switch to production
	 */
	injector = Guice.createInjector(Stage.DEVELOPMENT,
			new DevelopersSharedModule(),
			new DevelopersSharedServletModule(),
			new BackendServletModule());
	logger.info("created injector");

	super.contextInitialized(sce);

	return;
}
 
Example #8
Source File: WebMappingsRenderer.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private void renderGuiceWeb(final TreeNode filter) throws Exception {
    final List<String> servlets = new ArrayList<>();
    final List<String> filters = new ArrayList<>();

    for (Element element : Elements.getElements(Stage.TOOL, modules)) {
        if (!(element instanceof Binding)) {
            continue;
        }
        @SuppressWarnings("unchecked") final WebElementModel model =
                (WebElementModel) ((Binding) element).acceptTargetVisitor(VISITOR);
        if (model == null) {
            continue;
        }
        final String line = renderGuiceWebElement(model, element);
        if (model.getType().equals(WebElementType.FILTER)) {
            filters.add(line);
        } else {
            servlets.add(line);
        }
    }
    renderGucieWebElements(servlets, filters, filter);
}
 
Example #9
Source File: AppModuleUnitTest.java    From Scribengin with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testModuleMapping() throws Exception {
  Map<String, String> props = new HashMap<String, String>() ;
  props.put("hello", "Hello Property") ;
  props.put("registry.connect", "127.0.0.1:2181") ;
  props.put("registry.db-domain", "/scribengin/v2") ;
  
  Injector container1 = 
      Guice.createInjector(Stage.PRODUCTION, new CloseableModule(), new Jsr250Module(), new MycilaJmxModuleExt("test-domain"), new AppModule(props));
  
  Hello hello = container1.getInstance(Hello.class);
  hello.sayHello();
  
  MycilaJMXService service = container1.getInstance(MycilaJMXService.class);
  service.increment(1);
  
  //MycilaJMXService service2 = container2.getInstance(MycilaJMXService.class);
  //service2.increment(1);
  
  
  Assert.assertTrue(container1.getInstance(Pojo.class) == container1.getInstance(Pojo.class));
  Pojo pojo = container1.getInstance(Pojo.class) ;
  Assert.assertEquals("127.0.0.1:2181", pojo.getConnect());
  Assert.assertEquals("/scribengin/v2", pojo.getDbDomain());
  container1.getInstance(CloseableInjector.class).close();
}
 
Example #10
Source File: HiveMQMainModuleTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_topic_matcher_not_same() {

    final Injector injector = Guice.createInjector(Stage.PRODUCTION,
            new HiveMQMainModule(),
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(EventExecutorGroup.class).toInstance(Mockito.mock(EventExecutorGroup.class));
                }
            });

    final TopicMatcher instance1 = injector.getInstance(TopicMatcher.class);
    final TopicMatcher instance2 = injector.getInstance(TopicMatcher.class);

    assertNotSame(instance1, instance2);

}
 
Example #11
Source File: SecurityModuleTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_ssl_factory_same() {

    final Injector injector = Guice.createInjector(Stage.PRODUCTION, new SecurityModule(), new AbstractModule() {
        @Override
        protected void configure() {
            bind(EventExecutorGroup.class).toInstance(mock(EventExecutorGroup.class));
            bind(ShutdownHooks.class).toInstance(mock(ShutdownHooks.class));
            bindScope(LazySingleton.class, LazySingletonScope.get());
        }
    });

    final SslFactory instance1 = injector.getInstance(SslFactory.class);
    final SslFactory instance2 = injector.getInstance(SslFactory.class);

    assertSame(instance1, instance2);

}
 
Example #12
Source File: GuiceBootstrap.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
public static @NotNull Injector persistenceInjector(
        final @NotNull SystemInformation systemInformation,
        final @NotNull MetricRegistry metricRegistry,
        final @NotNull HivemqId hiveMQId,
        final @NotNull FullConfigurationService configService) {

    final ImmutableList.Builder<AbstractModule> modules = ImmutableList.builder();

    modules.add(new SystemInformationModule(systemInformation),
            new ConfigurationModule(configService, hiveMQId),
            new LazySingletonModule(),
            LifecycleModule.get(),
            new PersistenceMigrationModule(metricRegistry, configService.persistenceConfigurationService()));

    return Guice.createInjector(Stage.PRODUCTION, modules.build());
}
 
Example #13
Source File: Jersey2Module.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@Override
protected void configure() {
    checkHkFirstMode();
    final EnumSet<DispatcherType> types = context.option(GuiceFilterRegistration);
    final boolean guiceServletSupport = !types.isEmpty();

    // injector not available at this point, so using provider
    final InjectorProvider provider = new InjectorProvider(application);
    install(new GuiceBindingsModule(provider, guiceServletSupport));
    final GuiceFeature component =
            new GuiceFeature(provider, context.stat(), context.lifecycle(), context.option(UseHkBridge));
    bind(InjectionManager.class).toProvider(component);
    // avoid registration when called within guice report
    if (currentStage() != Stage.TOOL) {
        environment.jersey().register(component);
    }

    if (guiceServletSupport) {
        install(new GuiceWebModule(environment, types));
    }
}
 
Example #14
Source File: SingularityClientModuleTest.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Test
public void testModuleWithHosts() {
  final Injector injector = Guice.createInjector(
    Stage.PRODUCTION,
    new GuiceDisableModule(),
    new SingularityClientModule(Collections.singletonList("http://example.com"))
  );

  injector.injectMembers(this);
}
 
Example #15
Source File: ServiceRuntimeConfigurationIntegrationTest.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
@Test
void runtimeConfigurationTest(@TempDir Path tmpArtifactDir) throws Exception {
  int port = 0; // any port
  // Use 'production' stage as it involves up-front error checking of the configured bindings
  Injector injector = Guice.createInjector(Stage.PRODUCTION,
      new FrameworkModule(tmpArtifactDir, port, emptyMap()));

  // Create the runtime
  ServiceRuntime runtime = injector.getInstance(ServiceRuntime.class);

  try (TemporaryDb database = TemporaryDb.newInstance();
      Cleaner cleaner = new Cleaner()) {
    // Initialize it
    runtime.initialize(mock(NodeProxy.class));

    // Deploy the service to the runtime
    runtime.deployArtifact(ARTIFACT_ID, ARTIFACT_FILENAME);
    assertTrue(runtime.isArtifactDeployed(ARTIFACT_ID));

    // Initialize and register a service instance
    String name = "s1";
    ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(name, 1, ARTIFACT_ID);
    InstanceStatus instanceStatus = InstanceStatus.newBuilder().setSimple(Simple.ACTIVE).build();
    Fork fork = database.createFork(cleaner);
    BlockchainData blockchainData = BlockchainData.fromRawAccess(fork, name);
    runtime.initiateAddingService(blockchainData, instanceSpec, new byte[0]);
    runtime.updateInstanceStatus(instanceSpec, instanceStatus);
    assertThat(runtime.findService(name)).isNotEmpty();
  }

  // Shutdown the runtime
  runtime.shutdown();
}
 
Example #16
Source File: AirpalApplicationBase.java    From airpal with Apache License 2.0 5 votes vote down vote up
@Override
public void run(T config, Environment environment)
        throws Exception
{
    this.injector = Guice.createInjector(Stage.PRODUCTION, getModules(config, environment));

    System.setProperty(IO_BUFFER_SIZE, String.valueOf(config.getBufferSize().toBytes()));

    environment.healthChecks().register("presto", injector.getInstance(PrestoHealthCheck.class));

    environment.jersey().register(injector.getInstance(ExecuteResource.class));
    environment.jersey().register(injector.getInstance(QueryResource.class));
    environment.jersey().register(injector.getInstance(QueriesResource.class));
    environment.jersey().register(injector.getInstance(UserResource.class));
    environment.jersey().register(injector.getInstance(UsersResource.class));
    environment.jersey().register(injector.getInstance(TablesResource.class));
    environment.jersey().register(injector.getInstance(HealthResource.class));
    environment.jersey().register(injector.getInstance(PingResource.class));
    environment.jersey().register(injector.getInstance(SessionResource.class));
    environment.jersey().register(injector.getInstance(FilesResource.class));
    environment.jersey().register(injector.getInstance(ResultsPreviewResource.class));
    environment.jersey().register(injector.getInstance(S3FilesResource.class));

    environment.jersey().register(injector.getInstance(AirpalUserFactory.class));

    // Setup SSE (Server Sent Events)
    ServletRegistration.Dynamic sseServlet = environment.servlets()
            .addServlet("updates", injector.getInstance(SSEEventSourceServlet.class));
    sseServlet.setAsyncSupported(true);
    sseServlet.addMapping("/api/updates/subscribe");

    // Disable GZIP content encoding for SSE endpoints
    environment.lifecycle().addServerLifecycleListener(server -> {
        for (Handler handler : server.getChildHandlersByClass(BiDiGzipHandler.class)) {
            ((BiDiGzipHandler) handler).addExcludedMimeTypes(SERVER_SENT_EVENTS);
        }
    });
}
 
Example #17
Source File: FoxtrotServer.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Bootstrap<FoxtrotServerConfiguration> bootstrap) {
    bootstrap.setConfigurationSourceProvider(
            new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false)));
    bootstrap.addBundle(new AssetsBundle("/console/echo/", "/", "browse-events.htm", "console"));
    bootstrap.addBundle(new OorBundle<FoxtrotServerConfiguration>() {
        public boolean withOor() {
            return false;
        }
    });

    final SwaggerBundleConfiguration swaggerBundleConfiguration = getSwaggerBundleConfiguration();

    bootstrap.addBundle(new SwaggerBundle<FoxtrotServerConfiguration>() {
        @Override
        protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(FoxtrotServerConfiguration configuration) {
            return swaggerBundleConfiguration;
        }
    });

    bootstrap.addBundle(GuiceBundle.<FoxtrotServerConfiguration>builder()
                                .enableAutoConfig("com.flipkart.foxtrot")
                                .modules(
                                        new FoxtrotModule())
                                .useWebInstallers()
                                .printDiagnosticInfo()
                                .build(Stage.PRODUCTION));
    bootstrap.addCommand(new InitializerCommand());
    configureObjectMapper(bootstrap.getObjectMapper());
}
 
Example #18
Source File: Guice.java    From smartapp-sdk-java with Apache License 2.0 5 votes vote down vote up
static SmartAppDefinition smartapp(Consumer<BindingsSpec> consumer) {
    List<Module> modules = new ArrayList<>();
    DefaultBindingsSpec bindingsSpec = new DefaultBindingsSpec(modules);
    consumer.accept(bindingsSpec);
    Injector injector = createInjector(Stage.PRODUCTION, modules);
    return new GuiceSmartAppDefinition(injector);
}
 
Example #19
Source File: SingularityExecutorCleanupRunner.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) {
  final long start = System.currentTimeMillis();

  try {
    final Injector injector = Guice.createInjector(
      Stage.PRODUCTION,
      new SingularityRunnerBaseModule(
        SingularityExecutorCleanupConfiguration.class,
        ImmutableSet.of(
          SingularityS3Configuration.class,
          SingularityExecutorConfiguration.class
        )
      ),
      new SingularityExecutorModule(),
      new SingularityExecutorCleanupModule(),
      new SingularityClientModule(),
      new SingularityMesosClientModule()
    );

    final SingularityExecutorCleanupRunner runner = injector.getInstance(
      SingularityExecutorCleanupRunner.class
    );

    LOG.info("Starting cleanup");

    final SingularityExecutorCleanupStatistics statistics = runner.cleanup();

    LOG.info("Finished with {} after {}", statistics, JavaUtils.duration(start));

    System.exit(0);
  } catch (Throwable t) {
    LOG.error("Finished after {} with error", JavaUtils.duration(start), t);
    System.exit(1);
  }
}
 
Example #20
Source File: BaragonServiceClientModuleTest.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Test
public void testModuleWithHosts() {
  final Injector injector = Guice.createInjector(Stage.PRODUCTION,
          new GuiceDisableModule(),
          new BaragonClientModule(Collections.singletonList("http://example.com")));

  injector.injectMembers(this);
}
 
Example #21
Source File: ParaServer.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the Para core modules and allows the user to override them. Call this method first.
 *	This method calls {@code Para.initialize()}.
 * @param modules a list of modules that override the main modules
 */
public static void initialize(Module... modules) {
	Stage stage = Config.IN_PRODUCTION ? Stage.PRODUCTION : Stage.DEVELOPMENT;

	List<Module> coreModules = Arrays.asList(modules);
	List<Module> externalModules = getExternalModules();

	if (coreModules.isEmpty() && externalModules.isEmpty()) {
		logger.warn("No implementing modules found. Aborting...");
		destroy();
		return;
	}

	if (!externalModules.isEmpty()) {
		injector = Guice.createInjector(stage, Modules.override(coreModules).with(externalModules));
	} else {
		injector = Guice.createInjector(stage, coreModules);
	}

	Para.addInitListener(HealthUtils.getInstance());
	Para.addInitListener(MetricsUtils.getInstance());

	Para.getInitListeners().forEach((initListener) -> {
		injectInto(initListener);
	});

	if (Config.WEBHOOKS_ENABLED) {
		Para.addIOListener(new WebhookIOListener());
	}

	Para.initialize();

	// this enables the "river" feature - polls the default queue for objects and imports them into Para
	// additionally, the polling feature is used for implementing a webhooks worker node
	if ((Config.getConfigBoolean("queue_link_enabled", false) || Config.WEBHOOKS_ENABLED) &&
			HealthUtils.getInstance().isHealthy()) {
		Para.getQueue().startPolling();
	}
}
 
Example #22
Source File: ModuleTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindings() {
       //given
	Injector guice = Application.getInjector();
	
       //when
	Binding<Stage> stage = guice.getBinding(Stage.class);
	Binding<Injector> injector = guice.getBinding(Injector.class);
	Binding<Logger> logger = guice.getBinding(Logger.class);
	Binding<Config> config = guice.getBinding(Config.class);
	Binding<JobFactory> jobFactory = guice.getBinding(JobFactory.class);
	Binding<Cache> cache = guice.getBinding(Cache.class);
	Binding<TemplateEngine> templateEngine = guice.getBinding(TemplateEngine.class);		
	Binding<OncePerRequestFilter> mangooRequestFilter = guice.getBinding(OncePerRequestFilter.class);
	Binding<MangooBootstrap> mangooBootstrap = guice.getBinding(MangooBootstrap.class);
	
	//then
	assertThat(stage.getKey().getTypeLiteral().getType().getTypeName(), equalTo("com.google.inject.Stage"));
	assertThat(injector.getKey().getTypeLiteral().getType().getTypeName(), equalTo("com.google.inject.Injector"));
	assertThat(logger.getKey().getTypeLiteral().getType().getTypeName(), equalTo("java.util.logging.Logger"));
	assertThat(config.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.core.Config"));
	assertThat(jobFactory.getKey().getTypeLiteral().getType().getTypeName(), equalTo("org.quartz.spi.JobFactory"));
	assertThat(cache.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.cache.Cache"));
	assertThat(templateEngine.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.templating.TemplateEngine"));
	assertThat(mangooRequestFilter.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.filters.OncePerRequestFilter"));
	assertThat(mangooBootstrap.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.MangooBootstrap"));
}
 
Example #23
Source File: GuiceBundle.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void initialize(Bootstrap<?> bootstrap) {
    deModule = new DropwizardEnvironmentModule<>(type);
    modules.add(new JerseyModule());
    modules.add(deModule);
    injector = Guice.createInjector(Stage.PRODUCTION, modules);

}
 
Example #24
Source File: DefaultStartupListener.java    From HotswapAgentExamples with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {

	/*
	 * TODO switch to production
	 */
	logger.info("created injector");
	injector = Guice.createInjector(Stage.DEVELOPMENT,
			new DevelopersSharedModule(),
			new DevelopersSharedServletModule(),
			new DefaultServletModule());

	super.contextInitialized(sce);
}
 
Example #25
Source File: GuiceBindingsRenderer.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public String renderReport(final GuiceConfig config) {
    // analyze modules
    final List<ModuleDeclaration> moduleItems = filter(
            GuiceModelParser.parse(injector, Elements.getElements(Stage.TOOL, modules)), config);
    final Map<Key, BindingDeclaration> moduleBindings = GuiceModelUtils.index(moduleItems);

    // don't show extensions if no guice module analysis actually performed
    if (analysisEnabled) {
        markExtensions(moduleBindings);
    }

    // analyze overrides
    final List<ModuleDeclaration> overrideItems = filter(overridden.isEmpty()
            ? Collections.emptyList() : GuiceModelParser.parse(injector,
            Elements.getElements(Stage.TOOL, overridden)), config);
    final Map<Key, BindingDeclaration> overrideBindings = GuiceModelUtils.index(overrideItems);

    markOverrides(moduleBindings, overrideBindings);

    final StringBuilder res = new StringBuilder();
    res.append(Reporter.NEWLINE).append(Reporter.NEWLINE);

    // put all known bindings together for remaining reports
    renderModules(res, moduleItems, moduleBindings);
    renderOverrides(res, overrideItems, overrideBindings);
    moduleBindings.putAll(overrideBindings);

    renderJitBindings(res, moduleBindings, config, extensions);
    renderBindingChains(res, moduleBindings);
    return res.toString();
}
 
Example #26
Source File: JerseyProviderInstaller.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public void extensionBound(final Stage stage, final Class<?> type) {
    if (stage != Stage.TOOL) {
        // reporting (common for both registration types)
        final boolean hkManaged = isJerseyExtension(type);
        reporter.provider(type, hkManaged, false);
    }
}
 
Example #27
Source File: EagerSingletonInstaller.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public <T> void manualBinding(final Binder binder, final Class<T> type, final Binding<T> binding) {
    // we can only validate existing binding here (actually entire extension is pretty useless in case of manual
    // binding)
    final Class<? extends Annotation> scope = binding.acceptScopingVisitor(VISITOR);
    // in production all services will work as eager singletons, for report (TOOL stage) consider also valid
    Preconditions.checkArgument(scope.equals(EagerSingleton.class)
                    || (!binder.currentStage().equals(Stage.DEVELOPMENT)
                    && scope.equals(Singleton.class)),
            // intentially no "at" before stacktrtace because idea may hide error in some cases
            "Eager bean, declared manually is not marked .asEagerSingleton(): %s (%s)",
            type.getName(), BindingUtils.getDeclarationSource(binding));
}
 
Example #28
Source File: EagerSingletonInstaller.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public void extensionBound(final Stage stage, final Class<?> type) {
    if (stage != Stage.TOOL) {
        // may be called multiple times if bindings report enabled, but log must be counted just once
        prerender.add(String.format("%s", RenderUtils.renderClassLine(type)));
    }
}
 
Example #29
Source File: BindingsOverrideInjectorFactory.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public Injector createInjector(final Stage stage, final Iterable<? extends Module> modules) {
    final Module[] override = OVERRIDING_MODULES.get();
    OVERRIDING_MODULES.remove();
    TOO_LATE.set(true);
    if (override != null) {
        printOverridingModules(override);
    }
    return Guice.createInjector(stage, override == null ? modules
            : Lists.newArrayList(Modules.override(modules).with(override)));
}
 
Example #30
Source File: GuiceWebModule.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
protected void configureServlets() {
    // avoid registrations for guice reports (performing modules analysis and so calling this code many times)
    if (currentStage() != Stage.TOOL) {
        final GuiceFilter guiceFilter = new GuiceFilter();
        environment.servlets().addFilter(GUICE_FILTER, guiceFilter)
                .addMappingForUrlPatterns(dispatcherTypes, false, ROOT_PATH);
        environment.admin().addFilter(GUICE_FILTER, new AdminGuiceFilter(guiceFilter))
                .addMappingForUrlPatterns(dispatcherTypes, false, ROOT_PATH);
    }
}