use of com.google.inject.TypeLiteral in project che by eclipse.
the class PostgreSqlTckModule method configure.
@Override
protected void configure() {
final String dbUrl = System.getProperty("jdbc.url");
final String dbUser = System.getProperty("jdbc.user");
final String dbPassword = System.getProperty("jdbc.password");
waitConnectionIsEstablished(dbUrl, dbUser, dbPassword);
// jpa
install(new PersistTestModuleBuilder().setDriver(Driver.class).setUrl(dbUrl).setUser(dbUser).setPassword(dbPassword).setExceptionHandler(PostgreSqlExceptionHandler.class).addEntityClasses(AccountImpl.class, UserImpl.class, ProfileImpl.class, PreferenceEntity.class, WorkspaceImpl.class, WorkspaceConfigImpl.class, ProjectConfigImpl.class, EnvironmentImpl.class, EnvironmentRecipeImpl.class, ExtendedMachineImpl.class, SourceStorageImpl.class, ServerConf2Impl.class, StackImpl.class, CommandImpl.class, SnapshotImpl.class, RecipeImpl.class, SshPairImpl.class).addEntityClass("org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl$Attribute").build());
bind(TckResourcesCleaner.class).to(JpaCleaner.class);
// db initialization
bind(DBInitializer.class).asEagerSingleton();
final PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPassword);
dataSource.setUrl(dbUrl);
bind(SchemaInitializer.class).toInstance(new FlywaySchemaInitializer(dataSource, "che-schema"));
// account
bind(AccountDao.class).to(JpaAccountDao.class);
bind(new TypeLiteral<TckRepository<AccountImpl>>() {
}).toInstance(new JpaTckRepository<>(AccountImpl.class));
// user
bind(UserDao.class).to(JpaUserDao.class);
bind(ProfileDao.class).to(JpaProfileDao.class);
bind(PreferenceDao.class).to(JpaPreferenceDao.class);
bind(new TypeLiteral<TckRepository<UserImpl>>() {
}).to(UserRepo.class);
bind(new TypeLiteral<TckRepository<Pair<String, Map<String, String>>>>() {
}).to(PreferencesRepo.class);
bind(new TypeLiteral<TckRepository<ProfileImpl>>() {
}).toInstance(new JpaTckRepository<>(ProfileImpl.class));
bind(PasswordEncryptor.class).to(SHA512PasswordEncryptor.class);
// machine
bind(RecipeDao.class).to(JpaRecipeDao.class);
bind(SnapshotDao.class).to(JpaSnapshotDao.class);
bind(new TypeLiteral<TckRepository<RecipeImpl>>() {
}).toInstance(new JpaTckRepository<>(RecipeImpl.class));
bind(new TypeLiteral<TckRepository<SnapshotImpl>>() {
}).toInstance(new JpaTckRepository<>(SnapshotImpl.class));
bind(new TypeLiteral<TckRepository<Workspace>>() {
}).toInstance(new WorkspaceRepoForSnapshots());
// ssh
bind(SshDao.class).to(JpaSshDao.class);
bind(new TypeLiteral<TckRepository<SshPairImpl>>() {
}).toInstance(new JpaTckRepository<>(SshPairImpl.class));
// workspace
bind(WorkspaceDao.class).to(JpaWorkspaceDao.class);
bind(StackDao.class).to(JpaStackDao.class);
bind(new TypeLiteral<TckRepository<WorkspaceImpl>>() {
}).toInstance(new WorkspaceRepository());
bind(new TypeLiteral<TckRepository<StackImpl>>() {
}).toInstance(new StackRepository());
}
use of com.google.inject.TypeLiteral in project guice by google.
the class InjectionPoint method getInjectionPoints.
/**
* Returns an ordered, immutable set of injection points for the given type. Members in
* superclasses come before members in subclasses. Within a class, fields come before methods.
* Overridden methods are filtered out.
*
* @param statics true is this method should return static members, false for instance members
* @param errors used to record errors
*/
private static Set<InjectionPoint> getInjectionPoints(final TypeLiteral<?> type, boolean statics, Errors errors) {
InjectableMembers injectableMembers = new InjectableMembers();
OverrideIndex overrideIndex = null;
List<TypeLiteral<?>> hierarchy = hierarchyFor(type);
int topIndex = hierarchy.size() - 1;
for (int i = topIndex; i >= 0; i--) {
if (overrideIndex != null && i < topIndex) {
// Knowing the position within the hierarchy helps us make optimizations.
if (i == 0) {
overrideIndex.position = Position.BOTTOM;
} else {
overrideIndex.position = Position.MIDDLE;
}
}
TypeLiteral<?> current = hierarchy.get(i);
for (Field field : current.getRawType().getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) == statics) {
Annotation atInject = getAtInject(field);
if (atInject != null) {
InjectableField injectableField = new InjectableField(current, field, atInject);
if (injectableField.jsr330 && Modifier.isFinal(field.getModifiers())) {
errors.cannotInjectFinalField(field);
}
injectableMembers.add(injectableField);
}
}
}
for (Method method : current.getRawType().getDeclaredMethods()) {
if (isEligibleForInjection(method, statics)) {
Annotation atInject = getAtInject(method);
if (atInject != null) {
InjectableMethod injectableMethod = new InjectableMethod(current, method, atInject);
if (checkForMisplacedBindingAnnotations(method, errors) || !isValidMethod(injectableMethod, errors)) {
if (overrideIndex != null) {
boolean removed = overrideIndex.removeIfOverriddenBy(method, false, injectableMethod);
if (removed) {
logger.log(Level.WARNING, "Method: {0} is not a valid injectable method (" + "because it either has misplaced binding annotations " + "or specifies type parameters) but is overriding a method that is valid. " + "Because it is not valid, the method will not be injected. " + "To fix this, make the method a valid injectable method.", method);
}
}
continue;
}
if (statics) {
injectableMembers.add(injectableMethod);
} else {
if (overrideIndex == null) {
/*
* Creating the override index lazily means that the first type in the hierarchy
* with injectable methods (not necessarily the top most type) will be treated as
* the TOP position and will enjoy the same optimizations (no checks for overridden
* methods, etc.).
*/
overrideIndex = new OverrideIndex(injectableMembers);
} else {
// Forcibly remove the overriden method, otherwise we'll inject
// it twice.
overrideIndex.removeIfOverriddenBy(method, true, injectableMethod);
}
overrideIndex.add(injectableMethod);
}
} else {
if (overrideIndex != null) {
boolean removed = overrideIndex.removeIfOverriddenBy(method, false, null);
if (removed) {
logger.log(Level.WARNING, "Method: {0} is not annotated with @Inject but " + "is overriding a method that is annotated with @javax.inject.Inject. Because " + "it is not annotated with @Inject, the method will not be injected. " + "To fix this, annotate the method with @Inject.", method);
}
}
}
}
}
}
if (injectableMembers.isEmpty()) {
return Collections.emptySet();
}
ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder();
for (InjectableMember im = injectableMembers.head; im != null; im = im.next) {
try {
builder.add(im.toInjectionPoint());
} catch (ConfigurationException ignorable) {
if (!im.optional) {
errors.merge(ignorable.getErrorMessages());
}
}
}
return builder.build();
}
use of com.google.inject.TypeLiteral in project guice by google.
the class MultibinderTest method testModuleOverrideRepeatedInstallsAndMultibindings_toConstructor.
public void testModuleOverrideRepeatedInstallsAndMultibindings_toConstructor() {
TypeLiteral<Set<StringGrabber>> setOfStringGrabber = new TypeLiteral<Set<StringGrabber>>() {
};
Module ab = new AbstractModule() {
@Override
protected void configure() {
Key<String> aKey = Key.get(String.class, Names.named("A_string"));
Key<String> bKey = Key.get(String.class, Names.named("B_string"));
bind(aKey).toInstance("A");
bind(bKey).toInstance("B");
// used to disambiguate constructors
bind(Integer.class).toInstance(0);
Multibinder<StringGrabber> multibinder = Multibinder.newSetBinder(binder(), StringGrabber.class);
try {
multibinder.addBinding().toConstructor(StringGrabber.class.getConstructor(String.class));
multibinder.addBinding().toConstructor(StringGrabber.class.getConstructor(String.class, int.class));
} catch (NoSuchMethodException e) {
fail("No such method: " + e.getMessage());
}
}
};
// Guice guarantees this assertion, as the same module cannot be installed twice.
assertEquals(ImmutableSet.of("A", "B"), StringGrabber.values(Guice.createInjector(ab, ab).getInstance(Key.get(setOfStringGrabber))));
// Guice will only guarantee this assertion if Multibinder ensures the bindings match.
Injector injector = Guice.createInjector(ab, Modules.override(ab).with(ab));
assertEquals(ImmutableSet.of("A", "B"), StringGrabber.values(injector.getInstance(Key.get(setOfStringGrabber))));
}
use of com.google.inject.TypeLiteral in project guice by google.
the class MultibinderTest method testMultibinderMatching.
@Marker
public void testMultibinderMatching() throws Exception {
Method m = MultibinderTest.class.getDeclaredMethod("testMultibinderMatching");
assertNotNull(m);
final Annotation marker = m.getAnnotation(Marker.class);
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
public void configure() {
Multibinder<Integer> mb1 = Multibinder.newSetBinder(binder(), Integer.class, Marker.class);
Multibinder<Integer> mb2 = Multibinder.newSetBinder(binder(), Integer.class, marker);
mb1.addBinding().toInstance(1);
mb2.addBinding().toInstance(2);
// This assures us that the two binders are equivalent, so we expect the instance added to
// each to have been added to one set.
assertEquals(mb1, mb2);
}
});
TypeLiteral<Set<Integer>> t = new TypeLiteral<Set<Integer>>() {
};
Set<Integer> s1 = injector.getInstance(Key.get(t, Marker.class));
Set<Integer> s2 = injector.getInstance(Key.get(t, marker));
// This assures us that the two sets are in fact equal. They may not be same set (as in Java
// object identical), but we shouldn't expect that, since probably Guice creates the set each
// time in case the elements are dependent on scope.
assertEquals(s1, s2);
// This ensures that MultiBinder is internally using the correct set name --
// making sure that instances of marker annotations have the same set name as
// MarkerAnnotation.class.
Set<Integer> expected = new HashSet<Integer>();
expected.add(1);
expected.add(2);
assertEquals(expected, s1);
}
use of com.google.inject.TypeLiteral in project guice by google.
the class FactoryProvider2 method getBindingFromNewInjector.
/**
* Creates a child injector that binds the args, and returns the binding for the method's result.
*/
public Binding<?> getBindingFromNewInjector(final Method method, final Object[] args, final AssistData data) {
checkState(injector != null, "Factories.create() factories cannot be used until they're initialized by Guice.");
final Key<?> returnType = data.returnType;
// We ignore any pre-existing binding annotation.
final Key<?> returnKey = Key.get(returnType.getTypeLiteral(), RETURN_ANNOTATION);
Module assistedModule = new AbstractModule() {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected // raw keys are necessary for the args array and return value
void configure() {
Binder binder = binder().withSource(method);
int p = 0;
if (!data.optimized) {
for (Key<?> paramKey : data.paramTypes) {
// Wrap in a Provider to cover null, and to prevent Guice from injecting the parameter
binder.bind((Key) paramKey).toProvider(Providers.of(args[p++]));
}
} else {
for (Key<?> paramKey : data.paramTypes) {
// Bind to our ThreadLocalProviders.
binder.bind((Key) paramKey).toProvider(data.providers.get(p++));
}
}
Constructor constructor = data.constructor;
// message for the user.
if (constructor != null) {
binder.bind(returnKey).toConstructor(constructor, (TypeLiteral) data.implementationType).in(// make sure we erase any scope on the implementation type
Scopes.NO_SCOPE);
}
}
};
Injector forCreate = injector.createChildInjector(assistedModule);
Binding<?> binding = forCreate.getBinding(returnKey);
// If we have providers cached in data, cache the binding for future optimizations.
if (data.optimized) {
data.cachedBinding = binding;
}
return binding;
}
Aggregations