Search in sources :

Example 1 with Stage

use of com.google.inject.Stage in project stdlib by petergeneric.

the class GuiceFactory method createInjector.

/**
 * Sets up a Guice Injector; this is achieved in the following stages:
 * <ol>
 * <li>Set up the Shutdown Manager</li>
 * <li>Set up the Metrics Registry</li>
 * <li>Call {@link GuiceRole#register} on all GuiceRoles - this allows modules supporting core plugin functionality to be set
 * up </li>
 * <li>Call {@link GuiceSetup#registerModules} on GuiceSetup to get the application's guice modules - this
 * allows the application to set up helper modules</li>
 * <li>Call {@link GuiceRole#injectorCreated} on all GuiceRoles with the newly-created {@link Injector} - this allows plugins
 * to do one-time
 * post-construction work that requires an Injector</li>
 * <li>Call {@link GuiceSetup#injectorCreated} with the newly-created {@link Injector} - this allows the
 * application
 * to do one-time post-construction work that requires an Injector</li>
 * </ol>
 *
 * @param registry
 * 		(optional) the {@link GuiceRegistry} to expose to the guice environment
 * @param scannerFactory
 * 		the classpath scanner
 * @param config
 * 		the system configuration
 * @param setup
 * 		the setup class
 * @param roles
 * 		guice roles to use
 *
 * @return
 */
private static Injector createInjector(GuiceRegistry registry, ClassScannerFactory scannerFactory, GuiceConfig config, GuiceSetup setup, List<GuiceRole> roles) {
    final long started = System.currentTimeMillis();
    AtomicReference<Injector> injectorRef = new AtomicReference<>();
    List<Module> modules = new ArrayList<>();
    final Stage stage = Stage.valueOf(config.get(GuiceProperties.STAGE_PROPERTY, Stage.DEVELOPMENT.name()));
    // Set up the shutdown module
    ShutdownModule shutdown = new ShutdownModule();
    // If a service manager endpoint is specified (and skip isn't set) then set up the service manager client
    if (config.get("service.service-manager.endpoint") != null && !config.getBoolean(GuiceProperties.SERVICE_MANAGER_SKIP, false)) {
        modules.add(new ServiceManagerClientGuiceModule(config, shutdown.getShutdownManager()));
    } else {
        // Don't store logs in memory waiting for the service manager, they will never be picked up
        ServiceManagerAppender.shutdown();
    }
    final MetricRegistry metricRegistry = CoreMetricsModule.buildRegistry();
    try {
        // Hold a strong reference to the ClassScanner instance to help the JVM not garbage collect it during startup
        // N.B. we don't actually do anything with the scanner in this method (other than read metrics)
        final ClassScanner scanner = scannerFactory.getInstance();
        modules.add(shutdown);
        if (registry != null)
            modules.add(new GuiceRegistryModule(registry));
        // Initialise all the roles
        for (GuiceRole role : roles) role.register(stage, scannerFactory, config, setup, modules, injectorRef, metricRegistry);
        // Initialise the Setup class
        setup.registerModules(modules, config);
        if (log.isTraceEnabled())
            log.trace("Creating Injector with modules: " + modules);
        final Injector injector = Guice.createInjector(stage, modules);
        injectorRef.set(injector);
        for (GuiceRole role : roles) role.injectorCreated(stage, scannerFactory, config, setup, modules, injectorRef, metricRegistry);
        setup.injectorCreated(injector);
        if (scannerFactory != null) {
            final long finished = System.currentTimeMillis();
            final String contextName = config.get(GuiceProperties.SERVLET_CONTEXT_NAME, "(app)");
            log.debug("Injector for " + contextName + " created in " + (finished - started) + " ms");
            if (scanner != null)
                log.debug("Class scanner stats: insts=" + scannerFactory.getMetricNewInstanceCount() + " cached createTime=" + scanner.getConstructionTime() + ", scanTime=" + scanner.getSearchTime());
        }
        return injector;
    } catch (Throwable t) {
        log.error("Error creating injector", t);
        shutdown.shutdown();
        throw t;
    }
}
Also used : MetricRegistry(com.codahale.metrics.MetricRegistry) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServiceManagerClientGuiceModule(com.peterphi.std.guice.common.logging.ServiceManagerClientGuiceModule) GuiceRole(com.peterphi.std.guice.apploader.GuiceRole) NetworkConfigGuiceRole(com.peterphi.std.guice.common.serviceprops.net.NetworkConfigGuiceRole) ClassScanner(com.peterphi.std.guice.common.ClassScanner) Injector(com.google.inject.Injector) ShutdownModule(com.peterphi.std.guice.common.shutdown.ShutdownModule) Stage(com.google.inject.Stage) Module(com.google.inject.Module) ServiceManagerClientGuiceModule(com.peterphi.std.guice.common.logging.ServiceManagerClientGuiceModule) CoreMetricsModule(com.peterphi.std.guice.common.metrics.CoreMetricsModule) ShutdownModule(com.peterphi.std.guice.common.shutdown.ShutdownModule)

Example 2 with Stage

use of com.google.inject.Stage in project SpongeVanilla by SpongePowered.

the class SpongeVanilla method start.

private static void start(String[] args) {
    // Attempt to load metadata
    MetadataContainer metadata = MetadataContainer.load();
    // Register Minecraft plugin container
    MinecraftPluginContainer.register();
    OptionSet options = VanillaCommandLine.parse(args);
    // Note: This launches the server instead of MinecraftServer.main
    // Keep command line options up-to-date with Vanilla
    Bootstrap.register();
    File worldDir = options.has(WORLD_DIR) ? options.valueOf(WORLD_DIR) : new File(".");
    YggdrasilAuthenticationService authenticationService = new YggdrasilAuthenticationService(Proxy.NO_PROXY, UUID.randomUUID().toString());
    MinecraftSessionService sessionService = authenticationService.createMinecraftSessionService();
    GameProfileRepository profileRepository = authenticationService.createProfileRepository();
    PlayerProfileCache profileCache = new PlayerProfileCache(profileRepository, new File(worldDir, USER_CACHE_FILE.getName()));
    DedicatedServer server = new DedicatedServer(worldDir, DataFixesManager.createFixer(), authenticationService, sessionService, profileRepository, profileCache);
    // We force-load NetHandlerPlayServer here.
    // Otherwise, VanillaChannelRegistrar causes it to be loaded from
    // within the Guice injector (see SpongeVanillaModule), thus swallowing
    // any Mixin exception that occurs.
    // 
    // See https://github.com/SpongePowered/SpongeVanilla/issues/235 for a more
    // in-depth explanation
    NetHandlerPlayServer.class.getName();
    final Stage stage = SpongeGuice.getInjectorStage(VanillaLaunch.ENVIRONMENT == DEVELOPMENT ? Stage.DEVELOPMENT : Stage.PRODUCTION);
    SpongeImpl.getLogger().debug("Creating injector in stage '{}'", stage);
    Guice.createInjector(stage, new SpongeModule(), new SpongeVanillaModule(server, metadata));
    if (options.has(WORLD_NAME)) {
        server.setFolderName(options.valueOf(WORLD_NAME));
    }
    if (options.has(PORT)) {
        server.setServerPort(options.valueOf(PORT));
    }
    if (options.has(BONUS_CHEST)) {
        server.canCreateBonusChest(true);
    }
    server.startServerThread();
    Runtime.getRuntime().addShutdownHook(new Thread(server::stopServer, "Server Shutdown Thread"));
}
Also used : MetadataContainer(org.spongepowered.server.plugin.MetadataContainer) SpongeModule(org.spongepowered.common.inject.SpongeModule) PlayerProfileCache(net.minecraft.server.management.PlayerProfileCache) GameProfileRepository(com.mojang.authlib.GameProfileRepository) Stage(com.google.inject.Stage) YggdrasilAuthenticationService(com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService) MinecraftSessionService(com.mojang.authlib.minecraft.MinecraftSessionService) DedicatedServer(net.minecraft.server.dedicated.DedicatedServer) OptionSet(joptsimple.OptionSet) File(java.io.File) SpongeVanillaModule(org.spongepowered.server.inject.SpongeVanillaModule)

Example 3 with Stage

use of com.google.inject.Stage in project wicket by apache.

the class GuiceWebApplicationFactory method createApplication.

/**
 * @see IWebApplicationFactory#createApplication(WicketFilter)
 */
@Override
public WebApplication createApplication(final WicketFilter filter) {
    Injector injector;
    String injectorContextAttribute = filter.getFilterConfig().getInitParameter("injectorContextAttribute");
    Stage stage = null;
    String stageContextAttribute = filter.getFilterConfig().getInitParameter(STAGE_PARAMETER);
    if (stageContextAttribute == null) {
        stageContextAttribute = filter.getFilterConfig().getServletContext().getInitParameter(STAGE_PARAMETER);
    }
    if (stageContextAttribute != null) {
        stage = Stage.valueOf(stageContextAttribute.trim());
    }
    if (injectorContextAttribute != null) {
        ServletContext sc = filter.getFilterConfig().getServletContext();
        // Try to dig the Injector out of the ServletContext, for integration with context
        // listener-based instantiation of Guice.
        injector = (Injector) sc.getAttribute(injectorContextAttribute);
        if (injector == null) {
            throw new RuntimeException("Could not find Guice Injector in the ServletContext under attribute: " + injectorContextAttribute);
        }
    } else if (filter.getFilterConfig().getInitParameter("module") != null) {
        String paramValue = filter.getFilterConfig().getInitParameter("module");
        String[] moduleNames = Strings.split(paramValue, ',');
        Module[] modules = new Module[moduleNames.length];
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        for (int i = 0; i < moduleNames.length; i++) {
            String moduleName = moduleNames[i].trim();
            try {
                // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500212
                Class<?> moduleClazz = Class.forName(moduleName, false, classLoader);
                Object moduleObject = moduleClazz.newInstance();
                modules[i] = (Module) moduleObject;
            } catch (InstantiationException e) {
                throw new RuntimeException("Could not create new instance of Guice Module class " + moduleName, e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Could not create new instance of Guice Module class " + moduleName, e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Could not create new instance of Guice Module class " + moduleName, e);
            }
        }
        if (stage != null) {
            injector = Guice.createInjector(stage, modules);
        } else {
            injector = Guice.createInjector(modules);
        }
    } else {
        throw new RuntimeException("To use GuiceWebApplicationFactory, you must specify either an 'injectorContextAttribute' or a 'module' init-param.");
    }
    WebApplication app = injector.getInstance(WebApplication.class);
    app.getComponentInstantiationListeners().add(new GuiceComponentInjector(app, injector));
    return app;
}
Also used : Injector(com.google.inject.Injector) Stage(com.google.inject.Stage) ServletContext(javax.servlet.ServletContext) Module(com.google.inject.Module) WebApplication(org.apache.wicket.protocol.http.WebApplication)

Example 4 with Stage

use of com.google.inject.Stage in project roboguice by roboguice.

the class OverrideModuleTest method testCorrectStage.

public void testCorrectStage() {
    final Stage stage = Stage.PRODUCTION;
    Module module = Modules.override(new AbstractModule() {

        @Override
        protected void configure() {
            if (currentStage() != Stage.PRODUCTION) {
                addError("Wronge stage in overridden module:" + currentStage());
            }
        }
    }).with(new AbstractModule() {

        @Override
        protected void configure() {
            if (currentStage() != Stage.PRODUCTION) {
                addError("Wronge stage in overriding module:" + currentStage());
            }
        }
    });
    Guice.createInjector(stage, module);
}
Also used : Stage(com.google.inject.Stage) Module(com.google.inject.Module) PrivateModule(com.google.inject.PrivateModule) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Example 5 with Stage

use of com.google.inject.Stage in project SpongeCommon by SpongePowered.

the class BootstrapMixin_Forge method forge$startLifecycle.

// @formatter:on
@Inject(method = "bootStrap", at = @At("HEAD"))
private static void forge$startLifecycle(final CallbackInfo ci) {
    if (BootstrapMixin_Forge.isBootstrapped) {
        return;
    }
    final ForgeLaunch launch = Launch.instance();
    final Stage stage = SpongeGuice.getInjectorStage(launch.injectionStage());
    SpongeCommon.logger().debug("Creating injector in stage '{}'", stage);
    final Injector bootstrapInjector = launch.createInjector();
    final SpongeLifecycle lifecycle = bootstrapInjector.getInstance(SpongeLifecycle.class);
    launch.setLifecycle(lifecycle);
    lifecycle.establishFactories();
    lifecycle.establishBuilders();
    lifecycle.initTimings();
}
Also used : Injector(com.google.inject.Injector) Stage(com.google.inject.Stage) SpongeLifecycle(org.spongepowered.common.SpongeLifecycle) ForgeLaunch(org.spongepowered.forge.launch.ForgeLaunch) Inject(org.spongepowered.asm.mixin.injection.Inject)

Aggregations

Stage (com.google.inject.Stage)7 Injector (com.google.inject.Injector)4 Module (com.google.inject.Module)4 AbstractModule (com.google.inject.AbstractModule)2 PrivateModule (com.google.inject.PrivateModule)2 SpongeLifecycle (org.spongepowered.common.SpongeLifecycle)2 MetricRegistry (com.codahale.metrics.MetricRegistry)1 GameProfileRepository (com.mojang.authlib.GameProfileRepository)1 MinecraftSessionService (com.mojang.authlib.minecraft.MinecraftSessionService)1 YggdrasilAuthenticationService (com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService)1 GuiceRole (com.peterphi.std.guice.apploader.GuiceRole)1 ClassScanner (com.peterphi.std.guice.common.ClassScanner)1 ServiceManagerClientGuiceModule (com.peterphi.std.guice.common.logging.ServiceManagerClientGuiceModule)1 CoreMetricsModule (com.peterphi.std.guice.common.metrics.CoreMetricsModule)1 NetworkConfigGuiceRole (com.peterphi.std.guice.common.serviceprops.net.NetworkConfigGuiceRole)1 ShutdownModule (com.peterphi.std.guice.common.shutdown.ShutdownModule)1 File (java.io.File)1 ArrayList (java.util.ArrayList)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 ServletContext (javax.servlet.ServletContext)1