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

The following examples show how to use com.google.inject.Injector#injectMembers() . 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: 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 2
Source File: PropertiesRegistrationGuiceModuleTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_registration_works() {
    String stringKey = "stringkey";
    String stringVal = UUID.randomUUID().toString();
    String intKey = "intkey";
    int intVal = 42;

    Injector injector = Guice.createInjector(new PropertiesRegistrationGuiceModule() {
        @Override
        protected Map<String, String> getPropertiesMap() {
            return MapBuilder.builder(stringKey, stringVal)
                             .put(intKey, String.valueOf(intVal))
                             .build();
        }
    });

    injector.injectMembers(this);

    assertThat(injectedString).isEqualTo(stringVal);
    assertThat(injectedInt).isEqualTo(intVal);
}
 
Example 3
Source File: XtextParametrizedRunner.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Implements behavior from: org.junit.runners.Parameterized$TestClassRunnerForParameters
 * org.eclipse.xtext.testing.XtextRunner
 */
@Override
public Object createTest() throws Exception {
	Object object;
	// Functionality of
	// org.junit.runners.Parameterized$TestClassRunnerForParameters
	if (fieldsAreAnnotated()) {
		object = createTestUsingFieldInjection();
	} else {
		object = createTestUsingConstructorInjection();
	}

	// Functionality of org.eclipse.xtext.testing.XtextRunner
	IInjectorProvider injectorProvider = getOrCreateInjectorProvider();
	if (injectorProvider != null) {
		Injector injector = injectorProvider.getInjector();
		if (injector != null)
			injector.injectMembers(object);
	}
	return object;
}
 
Example 4
Source File: NodeModulePassTest.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
private CompilerUtil createCompiler(
    ImmutableSet<Path> externs, ImmutableSet<Path> modules, boolean excludeNodeExterns) {
  for (Path path : concat(externs, modules)) {
    Path parent = path.getParent();
    if (parent != null) {
      try {
        Files.createDirectories(parent);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
  Injector injector =
      GuiceRule.builder(new Object())
          .setInputFs(fs)
          .setModuleExterns(externs)
          .setModules(modules)
          .setUseNodeLibrary(!excludeNodeExterns)
          .build()
          .createInjector();
  injector.injectMembers(this);
  CompilerUtil util = injector.getInstance(CompilerUtil.class);
  util.getOptions().setCheckTypes(true);
  return util;
}
 
Example 5
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 6
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 7
Source File: ViewSpec.java    From javalite with Apache License 2.0 5 votes vote down vote up
/**
 * Use to register a tag before the test.
 *
 * @param name name of tag as used in a template.
 * @param tag tag instance
 */
@Override
protected void registerTag(String name, FreeMarkerTag tag) {
    manager.registerTag(name, tag);
    Injector injector = Configuration.getInjector();
    if(injector != null)
        injector.injectMembers(tag);
}
 
Example 8
Source File: CompilerConfigModule.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Provide a Java batch compiler based on the Bootique configuration.
 *
 * @param injector the injector.
 * @param config the bootique configuration.
 * @return the batch compiler.
 * @since 0.8
 */
@SuppressWarnings("static-method")
@Provides
@Singleton
public IJavaBatchCompiler providesJavaBatchCompiler(Injector injector, Provider<SarlcConfig> config) {
	final SarlcConfig cfg = config.get();
	final IJavaBatchCompiler compiler = cfg.getCompiler().getJavaCompiler().newCompilerInstance();
	injector.injectMembers(compiler);
	return compiler;
}
 
Example 9
Source File: Generator2AdapterSetup.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private IXtextGeneratorLanguage createLanguage(Injector generatorInjector) {
	XtextGeneratorLanguage xtextGeneratorLanguage = new XtextGeneratorLanguage();
	xtextGeneratorLanguage.setGrammarUri(languageConfig.getGrammar().eResource().getURI().toString());
	xtextGeneratorLanguage.setResourceSet(languageConfig.getGrammar().eResource().getResourceSet());
	xtextGeneratorLanguage
			.setFileExtensions(Joiner.on(',').join(languageConfig.getFileExtensions(languageConfig.getGrammar())));
	generatorInjector.injectMembers(xtextGeneratorLanguage);
	xtextGeneratorLanguage.initialize(languageConfig.getGrammar());
	return xtextGeneratorLanguage;
}
 
Example 10
Source File: TypeCollectionPassTest.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
@Test
public void detectsNodeExternUsage() throws IOException {
  Injector injector =
      guice
          .toBuilder()
          .setModulePrefix("modules")
          .setModules("one.js")
          .setModuleExterns("externs/two.js")
          .build()
          .createInjector();

  injector.injectMembers(this);

  // Module externs are loaded directly.
  Path path = fs.getPath("externs/two.js");
  Files.createDirectories(path.getParent());
  Files.write(
      path,
      "module.exports = function(a, b) { return a + b; };".getBytes(StandardCharsets.UTF_8));

  util.compile(
      createSourceFile(
          fs.getPath("modules/one.js"),
          "var two = require('two');",
          "exports.path = two('a', 'b');"));

  assertThat(typeRegistry.getAllTypes())
      .containsExactly(typeRegistry.getType("module$exports$module$modules$one"));

  NodeLibrary library = injector.getInstance(NodeLibrary.class);
  assertThat(library.canRequireId("two")).isTrue();
}
 
Example 11
Source File: EcoreSupport.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.5
 */
@Override
public Injector createInjectorAndDoEMFRegistration() {
	Injector injector = Guice.createInjector(getGuiceModule());
	injector.injectMembers(this);
	registerInRegistry(false);
	return injector;
}
 
Example 12
Source File: InjectionExtension.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void beforeEach(ExtensionContext context) throws Exception {
	IInjectorProvider injectorProvider = getOrCreateInjectorProvider(context);
	if (injectorProvider instanceof IRegistryConfigurator) {
		final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
		registryConfigurator.setupRegistry();
	}
	if (injectorProvider != null) {
		Injector injector = injectorProvider.getInjector();
		if (injector != null) {
			Object testInstance = context.getRequiredTestInstance();
			injector.injectMembers(testInstance);
			try {
				TestInstances requiredTestInstances = context.getRequiredTestInstances();
				for (Object o : requiredTestInstances.getEnclosingInstances()) {
					injector.injectMembers(o);
				}
			} catch (NoSuchMethodError e) {
				if (!Modifier.isStatic(testInstance.getClass().getModifiers())) {
					if (testInstance.getClass().getDeclaringClass() != null) {
						throw new ExtensionConfigurationException("Injection of nested classes needs Junit5 >= 5.4", e);
					}
				}
				// OK, getRequiredTestInstances is not there in Junit5 < 5.4
			}
		}
	}
}
 
Example 13
Source File: SARLProjectConfigurator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Constructor.
 */
public SARLProjectConfigurator() {
	final Injector injector = SARLEclipseExecutableExtensionFactory.getSARLInjector();
	final String fileExtension = injector.getInstance(
			Key.get(String.class, Names.named(Constants.FILE_EXTENSIONS)));
	if (Strings.isNullOrEmpty(fileExtension)) {
		this.fileExtension = null;
	} else {
		this.fileExtension = "." + fileExtension; //$NON-NLS-1$
	}
	injector.injectMembers(this);
	this.candidates = new ArrayList<>();
	this.candidates.addAll(Arrays.asList(BundleUtil.SRC_FOLDERS));
	this.candidates.add(SARLConfig.FOLDER_TEST_SOURCE_SARL);
}
 
Example 14
Source File: XtextParametersRunnerFactory.java    From solidity-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Object createTest() throws Exception {
	Object object = getTestClass().getOnlyConstructor().newInstance(parameters.toArray());
	IInjectorProvider injectorProvider = getOrCreateInjectorProvider();
	if (injectorProvider != null) {
		Injector injector = injectorProvider.getInjector();
		if (injector != null)
			injector.injectMembers(object);
	}
	return object;
}
 
Example 15
Source File: AbstractSarlBatchCompilerMojo.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public IJavaBatchCompiler providesJavaBatchCompiler(Injector injector) {
	final JavaCompiler cmp = getJavaCompiler();
	final IJavaBatchCompiler compiler = cmp.newCompilerInstance(getProject(),
			AbstractSarlBatchCompilerMojo.this.mavenHelper,
			isTestContext());
	injector.injectMembers(compiler);
	return compiler;
}
 
Example 16
Source File: AdapterInjectorTests.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void injectAdapters() {
	Module module = new AbstractModule() {
		@Override
		protected void configure() {
			install(new AdapterInjectionSupport());

			MapBinder<AdapterKey<?>, Object> adapterMapBinder = AdapterMaps
					.getAdapterMapBinder(binder(), AdapterStore.class);

			// constructor binding
			adapterMapBinder.addBinding(AdapterKey
					.get(new TypeToken<ParameterizedSubType<Integer>>() {
					}, "a1"))
					.to(new TypeLiteral<ParameterizedSubType<Integer>>() {
					});

			// instance binding
			adapterMapBinder.addBinding(
					AdapterKey.get(new TypeToken<Provider<Integer>>() {
					}, "a2")).toInstance(new Provider<Integer>() {

						@Override
						public Integer get() {
							return 5;
						}
					});

			// provider binding
			adapterMapBinder.addBinding(
					AdapterKey.get(new TypeToken<Provider<Integer>>() {
					}, "a3")).toProvider(new Provider<Provider<Integer>>() {

						@Override
						public Provider<Integer> get() {
							return new Provider<Integer>() {

								@Override
								public Integer get() {
									return 5;
								}
							};
						}
					});
		}
	};
	Injector injector = Guice.createInjector(module);
	AdapterStore adapterStore = new AdapterStore();
	injector.injectMembers(adapterStore);
	assertNotNull(adapterStore.getAdapter(
			AdapterKey.get(new TypeToken<ParameterizedSubType<Integer>>() {
			}, "a1")));
	// retrieve a parameterized type bound as instance
	assertNotNull(adapterStore
			.getAdapter(AdapterKey.get(new TypeToken<Provider<Integer>>() {
			}, "a2")));
	assertNotNull(adapterStore
			.getAdapter(AdapterKey.get(new TypeToken<Provider<Integer>>() {
			}, "a3")));
}
 
Example 17
Source File: Json2JavaConfigurable.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
Json2JavaConfigurable(@SuppressWarnings("unused") @Nonnull Project project, @Nonnull GuiceManager guiceManager) {
    final Injector injector = guiceManager.getInjector();
    injector.injectMembers(this);
}
 
Example 18
Source File: N4IDEXpectFileSetup.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates setup with provided context. Adds members to provided injector.
 */
public N4IDEXpectFileSetup(FileSetupContext ctx, Injector injector) {
	this.ctx = ctx;
	injector.injectMembers(this);
}
 
Example 19
Source File: AbstractFreeMarkerConfig.java    From javalite with Apache License 2.0 4 votes vote down vote up
/**
 * Injects user tags with members
 *
 * @param injector user tags with members using this injector.
 */
public void inject(Injector injector) {
    for (FreeMarkerTag tag: userTags) {
        injector.injectMembers(tag);
    }
}
 
Example 20
Source File: AbstractFXView.java    From gef with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Constructs a new {@link AbstractFXView} that uses the given
 * {@link Injector} to inject its members.
 *
 * @param injector
 *            The {@link Injector} that is used to inject the members of
 *            this {@link AbstractFXView}.
 */
// TOOD: use executable extension factory to inject this class
public AbstractFXView(final Injector injector) {
	injector.injectMembers(this);
}