Java Code Examples for com.google.inject.Injector#createChildInjector()

The following examples show how to use com.google.inject.Injector#createChildInjector() . 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: AbstractSarlBatchCompilerMojo.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
protected void prepareExecution() throws MojoExecutionException {
	if (this.injector == null) {
		final Injector mainInjector = SARLStandaloneSetup.doSetup();
		this.injector = mainInjector.createChildInjector(Arrays.asList(new MavenPrivateModule()));
	}
	if (this.sarlBatchCompilerProvider == null) {
		this.sarlBatchCompilerProvider = this.injector.getProvider(SarlBatchCompiler.class);
	}
	if (this.reflect == null) {
		this.reflect = this.injector.getInstance(ReflectExtensions.class);
	}
	if (this.sarlBatchCompilerProvider == null || this.reflect == null) {
		throw new MojoExecutionException(Messages.AbstractSarlBatchCompilerMojo_0);
	}
}
 
Example 2
Source File: PlainInjectorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testChildInjector() {
	Injector parentInjector = Guice.createInjector();
	Injector injector = parentInjector.createChildInjector(new Module() {
		@Override
		public void configure(Binder binder) {
			binder.bind(CharSequence.class).to(String.class);
		}
	});
	Assert.assertNotNull(injector.getExistingBinding(Key.get(CharSequence.class)));
	// Parent allows JIT bindings and those are always created in the ancestor
	Assert.assertNotNull(injector.getExistingBinding(Key.get(String.class)));
	CharSequence emptyString = injector.getInstance(CharSequence.class);
	Assert.assertEquals("", emptyString);
	Assert.assertNotNull(injector.getExistingBinding(Key.get(String.class)));
	Assert.assertNotNull(parentInjector.getExistingBinding(Key.get(String.class)));
}
 
Example 3
Source File: TestRunner.java    From qaf with MIT License 6 votes vote down vote up
@Override
public Injector getInjector(IClass iClass) {
  Annotation annotation = AnnotationHelper.findAnnotationSuperClasses(Guice.class, iClass.getRealClass());
  if (annotation == null) return null;
  if (iClass instanceof TestClass) {
    iClass = ((TestClass)iClass).getIClass();
  }
  if (!(iClass instanceof ClassImpl)) return null;
  Injector parentInjector = ((ClassImpl)iClass).getParentInjector();

  Guice guice = (Guice) annotation;
  List<Module> moduleInstances = Lists.newArrayList(getModules(guice, parentInjector, iClass.getRealClass()));

  // Reuse the previous injector, if any
  Injector injector = getInjector(moduleInstances);
  if (injector == null) {
    injector = parentInjector.createChildInjector(moduleInstances);
    addInjector(moduleInstances, injector);
  }
  return injector;
}
 
Example 4
Source File: RunnerUiModule.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Injector load(final String moduleId) throws Exception {
	if (RUNNER_UI_MODULE_ID.equals(moduleId)) {
		final Injector parentInjector = N4JSActivator.getInstance().getInjector(
				N4JSActivator.ORG_ECLIPSE_N4JS_N4JS);
		return parentInjector.createChildInjector(new RunnerUiModule());
	}
	throw new IllegalArgumentException("Unknown module ID: " + moduleId);
}
 
Example 5
Source File: AbstractJoynrJavaGeneratorTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
public void setup(boolean generateProxy, boolean generateProvider) throws Exception {
    temporaryOutputDirectory = Files.createTempDirectory(null).toFile();
    temporaryOutputDirectory.deleteOnExit();
    InvocationArguments arguments = new InvocationArguments();
    arguments.setGenerationLanguage("java");
    arguments.setModelPath("src/test/resources");
    arguments.setOutputPath(temporaryOutputDirectory.getAbsolutePath());
    if (generateProxy && !generateProvider) {
        arguments.setTarget("proxy");
    } else if (!generateProxy && generateProvider) {
        arguments.setTarget("provider");
    }

    Injector francaInjector = new FrancaIDLStandaloneSetup().createInjectorAndDoEMFRegistration()
                                                            .createChildInjector(new AbstractModule() {

                                                                @Override
                                                                protected void configure() {
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_CLEAN))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_GENERATE))
                                                                                  .to(true);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named("generateProxyCode"))
                                                                                  .to(arguments.getGenerateProxyCode());
                                                                    bindConstant().annotatedWith(Names.named("generateProviderCode"))
                                                                                  .to(arguments.getGenerateProviderCode());
                                                                    bind(IFileSystemAccess.class).to(JavaIoFileSystemAccess.class);
                                                                }
                                                            });
    francaInjector.injectMembers(this);
    generator = new JoynrJavaGenerator();
    Injector injector = francaInjector.createChildInjector(generator.getGeneratorModule());
    injector.injectMembers(this);
    injector.injectMembers(generator);
    FileSystemAccessUtil.createFileSystemAccess(outputFileSystem, arguments.getOutputPath());
}
 
Example 6
Source File: InjectorFactory.java    From spoofax with Apache License 2.0 5 votes vote down vote up
public static Injector createChild(Injector parent, Module... modules) throws MetaborgException {
    try {
        return parent.createChildInjector(modules);
    } catch(CreationException e) {
        throw new MetaborgException("Could not create child injector because of dependency injection errors", e);
    }
}
 
Example 7
Source File: InjectorFactory.java    From spoofax with Apache License 2.0 5 votes vote down vote up
public static Injector createChild(Injector parent, Iterable<Module> modules) throws MetaborgException {
    try {
        return parent.createChildInjector(modules);
    } catch(CreationException e) {
        throw new MetaborgException("Could not create child injector because of dependency injection errors", e);
    }
}
 
Example 8
Source File: HandlersConfigurerDi.java    From vespa with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private Injector createFallbackInjector(com.yahoo.container.Container vespaContainer, Injector discInjector) {
    return discInjector.createChildInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(com.yahoo.container.Container.class).toInstance(vespaContainer);
            bind(com.yahoo.statistics.Statistics.class).toInstance(Statistics.nullImplementation);
            bind(AccessLog.class).toInstance(new AccessLog(new ComponentRegistry<>()));
            bind(Executor.class).toInstance(Executors.newCachedThreadPool(ThreadFactoryFactory.getThreadFactory("HandlersConfigurerDI")));

            if (vespaContainer.getFileAcquirer() != null)
                bind(com.yahoo.filedistribution.fileacquirer.FileAcquirer.class).toInstance(vespaContainer.getFileAcquirer());
        }
    });
}
 
Example 9
Source File: TestTaskStatusService.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  Injector parentInjector = getInjector();
  parentInjector.createChildInjector(new AbstractModule() {
    @Override
    protected void configure() {
      taskStatusService = new TaskStatusService();
      bind(TaskStatusService.class).toInstance(taskStatusService);
    }
  });
}
 
Example 10
Source File: SeleniumTestHandler.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** Injects dependencies into the given test class using {@link Guice} and custom injectors. */
private void injectDependencies(ITestContext testContext, Object testInstance) throws Exception {
  Injector injector = testContext.getSuite().getParentInjector();

  List<Module> childModules = new ArrayList<>(getChildModules());
  childModules.add(new SeleniumClassModule());

  Injector classInjector = injector.createChildInjector(childModules);
  classInjector.injectMembers(testInstance);

  pageObjectsInjector.injectMembers(testInstance, classInjector);
}
 
Example 11
Source File: Executor.java    From joynr with Apache License 2.0 5 votes vote down vote up
public Executor(final InvocationArguments arguments) throws ClassNotFoundException,
                                                     InstantiationException,
                                                     IllegalAccessException {
    arguments.checkArguments();
    this.arguments = arguments;

    // Get an injector and inject into the current instance
    Injector francaInjector = new FrancaIDLStandaloneSetup().createInjectorAndDoEMFRegistration();

    // Use a child injector that contains configuration parameters passed to this Executor
    Injector injector = francaInjector.createChildInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(IFileSystemAccess.class).to(JavaIoFileSystemAccess.class);
            String generationId = arguments.getGenerationId();
            if (generationId != null) {
                bindConstant().annotatedWith(Names.named("generationId")).to(generationId);
            } else {
                // Guice does not allow null binding - use an empty string to show there is no generationId
                bindConstant().annotatedWith(Names.named("generationId")).to("");
            }
            bindConstant().annotatedWith(Names.named("generateProxyCode")).to(arguments.getGenerateProxyCode());
            bindConstant().annotatedWith(Names.named("generateProviderCode"))
                          .to(arguments.getGenerateProviderCode());

            bind(Boolean.class).annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_GENERATE))
                               .toInstance(arguments.generate());
            bind(Boolean.class).annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_CLEAN))
                               .toInstance(arguments.clean());
            bind(Boolean.class).annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                               .toInstance(arguments.addVersionToPackage());
            bind(Boolean.class).annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION))
                               .toInstance(arguments.addVersionToName());
        }
    });
    this.outputFileSystem = injector.getInstance(IFileSystemAccess.class);
    this.generator = createGenerator(injector);
}
 
Example 12
Source File: Executor.java    From joynr with Apache License 2.0 5 votes vote down vote up
private IGenerator createGenerator(Injector injector) throws ClassNotFoundException, InstantiationException,
                                                      IllegalAccessException {
    String rootGenerator = arguments.getRootGenerator();
    Class<?> rootGeneratorClass = Class.forName(rootGenerator,
                                                true,
                                                Thread.currentThread().getContextClassLoader());
    Object templateRootInstance = rootGeneratorClass.newInstance();

    if (templateRootInstance instanceof IGenerator) {
        // This is a standard generator
        IGenerator generator = (IGenerator) templateRootInstance;
        if (generator instanceof IJoynrGenerator) {
            IJoynrGenerator joynrGenerator = (IJoynrGenerator) generator;
            if (joynrGenerator.getGeneratorModule() != null) {
                injector = injector.createChildInjector(joynrGenerator.getGeneratorModule());
            }
            injector.injectMembers(generator);
            joynrGenerator.setParameters(arguments.getParameter());
        } else {
            injector.injectMembers(generator);
        }
        return generator;
    } else {
        throw new IllegalStateException("Root generator \"" + "\" is not implementing interface \""
                + IGenerator.class.getName() + "\"");
    }

}
 
Example 13
Source File: AbstractJoynrTSGeneratorTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
public void setup(boolean generateProxy, boolean generateProvider) throws Exception {
    temporaryOutputDirectory = Files.createTempDirectory(null).toFile();
    temporaryOutputDirectory.deleteOnExit();
    InvocationArguments arguments = new InvocationArguments();
    arguments.setGenerationLanguage("javascript");
    arguments.setModelPath("src/test/resources");
    arguments.setOutputPath(temporaryOutputDirectory.getAbsolutePath());
    if (generateProxy && !generateProvider) {
        arguments.setTarget("proxy");
    } else if (!generateProxy && generateProvider) {
        arguments.setTarget("provider");
    }

    Injector francaInjector = new FrancaIDLStandaloneSetup().createInjectorAndDoEMFRegistration()
                                                            .createChildInjector(new AbstractModule() {

                                                                @Override
                                                                protected void configure() {
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_CLEAN))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_GENERATE))
                                                                                  .to(true);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named("generateProxyCode"))
                                                                                  .to(arguments.getGenerateProxyCode());
                                                                    bindConstant().annotatedWith(Names.named("generateProviderCode"))
                                                                                  .to(arguments.getGenerateProviderCode());
                                                                    bind(IFileSystemAccess.class).to(JavaIoFileSystemAccess.class);
                                                                }
                                                            });
    francaInjector.injectMembers(this);
    generator = new JoynrJSGenerator();
    Injector injector = francaInjector.createChildInjector(generator.getGeneratorModule());
    injector.injectMembers(this);
    injector.injectMembers(generator);
    FileSystemAccessUtil.createFileSystemAccess(outputFileSystem, arguments.getOutputPath());
}
 
Example 14
Source File: GuiceGenericLoader.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Inject
public GuiceGenericLoader(Injector injector, ExtendedClassLoader extendedClassLoader, ExtensionConfiguration extensionConfiguration) {

    this.extendedClassLoader = extendedClassLoader;

    Module additionalExtensionBindings = Modules.combine(extensionConfiguration.getAdditionalGuiceModulesForExtensions()
        .stream()
        .map(Throwing.<ClassName, Module>function(className -> instantiateNoChildModule(injector, className)))
        .peek(module -> LOGGER.info("Enabling injects contained in " + module.getClass().getCanonicalName()))
        .collect(Guavate.toImmutableList()));
    this.injector = injector.createChildInjector(additionalExtensionBindings);
}
 
Example 15
Source File: DefaultPackageExplorerLabelProviderBuilder.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Change the injector.
 *
 * @param injector the injector.
 */
@Inject
public void setInjector(Injector injector) {
	this.injector = injector.createChildInjector(new PrivateModule());
}
 
Example 16
Source File: ServerMain.java    From swellrt with Apache License 2.0 4 votes vote down vote up
public static void run(Module coreSettings) throws PersistenceException,
    ConfigurationException, WaveServerException {
  Injector injector = Guice.createInjector(coreSettings);
  Module profilingModule = injector.getInstance(StatModule.class);
  ExecutorsModule executorsModule = injector.getInstance(ExecutorsModule.class);
  injector = injector.createChildInjector(profilingModule, executorsModule);

  Config config = injector.getInstance(Config.class);
  boolean enableFederation = config.getBoolean("federation.enable_federation");

  Module serverModule = injector.getInstance(ServerModule.class);
  Module federationModule = buildFederationModule(injector, enableFederation);
  PersistenceModule persistenceModule = injector.getInstance(PersistenceModule.class);
  // Module searchModule = injector.getInstance(SearchModule.class);
  // Module profileFetcherModule = injector.getInstance(ProfileFetcherModule.class);
  Module emailModule = injector.getInstance(EmailModule.class); // SwellRT
  // injector = injector.createChildInjector(serverModule, persistenceModule, robotApiModule,
  //    federationModule, searchModule, profileFetcherModule);
  injector = injector.createChildInjector(serverModule, persistenceModule, federationModule, emailModule);

  ServerRpcProvider server = injector.getInstance(ServerRpcProvider.class);
  WaveBus waveBus = injector.getInstance(WaveBus.class);

  String domain = config.getString("core.wave_server_domain");
  if (!ParticipantIdUtil.isDomainAddress(ParticipantIdUtil.makeDomainAddress(domain))) {
    throw new WaveServerException("Invalid wave domain: " + domain);
  }

  initializeServer(injector, domain);
  initializeServlets(server, config);
  // initializeRobotAgents(server);
  // initializeRobots(injector, waveBus);
  initializeFrontend(injector, server);
  initializeFederation(injector);
  // initializeSearch(injector, waveBus);
  initializeShutdownHandler(server);
  initializeSwellRt(injector, waveBus);

  LOG.info("Starting server");
  server.startWebSocketServer(injector);
}
 
Example 17
Source File: AbstractConsulTests.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
protected void injects() {
    final Injector injector = Globals.get(Injector.class);
    injector.createChildInjector(binder -> binder.requestInjection(this));
}
 
Example 18
Source File: AbstractRocketMQTests.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
protected void injects() {
    final Injector injector = Globals.get(Injector.class);
    injector.createChildInjector(binder -> binder.requestInjection(this));
}
 
Example 19
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
public void startWebSocketServer(final Injector injector) {
  httpServer = new Server();

  List<Connector> connectors = getSelectChannelConnectors(httpAddresses);
  if (connectors.isEmpty()) {
    LOG.severe("No valid http end point address provided!");
  }
  for (Connector connector : connectors) {
    httpServer.addConnector(connector);
  }
  final WebAppContext context = new WebAppContext();

  context.setParentLoaderPriority(true);

  if (jettySessionManager != null) {
    // This disables JSessionIDs in URLs redirects
    // see: http://stackoverflow.com/questions/7727534/how-do-you-disable-jsessionid-for-jetty-running-with-the-eclipse-jetty-maven-plu
    // and: http://jira.codehaus.org/browse/JETTY-467?focusedCommentId=114884&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-114884
    jettySessionManager.setSessionIdPathParameterName(null);

    context.getSessionHandler().setSessionManager(jettySessionManager);
  }
  final ResourceCollection resources = new ResourceCollection(resourceBases);
  context.setBaseResource(resources);

  addWebSocketServlets();

  try {

    final ServletModule servletModule = getServletModule();

    ServletContextListener contextListener = new GuiceServletContextListener() {

      private final Injector childInjector = injector.createChildInjector(servletModule);

      @Override
      protected Injector getInjector() {
        return childInjector;
      }
    };

    context.addEventListener(contextListener);
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class));
    httpServer.setHandler(context);

    httpServer.start();
    restoreSessions();

  } catch (Exception e) { // yes, .start() throws "Exception"
    LOG.severe("Fatal error starting http server.", e);
    return;
  }
  LOG.fine("WebSocket server running.");
}
 
Example 20
Source File: DataMigrationTool.java    From incubator-retired-wave with Apache License 2.0 3 votes vote down vote up
public static void main(String... args) {

    if (args.length != 3) usageError();

    String dataType = args[0];

    Module sourceSettings = bindCmdLineSettings(args[1]);
    Injector sourceSettingsInjector = Guice.createInjector(sourceSettings);
    Module sourcePersistenceModule = sourceSettingsInjector.getInstance(PersistenceModule.class);
    Injector sourceInjector = sourceSettingsInjector.createChildInjector(sourcePersistenceModule);


    Module targetSettings = bindCmdLineSettings(args[2]);
    Injector targetSettingsInjector = Guice.createInjector(targetSettings);
    Module targetPersistenceModule = targetSettingsInjector.getInstance(PersistenceModule.class);
    Injector targetInjector = targetSettingsInjector.createChildInjector(targetPersistenceModule);


    if (dataType.equals("deltas")) {
      runDeltasMigration(sourceInjector, targetInjector);

    } else {
      usageError("Wrong data type");
    }


  }