Search in sources :

Example 71 with TypeLiteral

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());
}
Also used : TckResourcesCleaner(org.eclipse.che.commons.test.tck.TckResourcesCleaner) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) StackImpl(org.eclipse.che.api.workspace.server.model.impl.stack.StackImpl) SshPairImpl(org.eclipse.che.api.ssh.server.model.impl.SshPairImpl) PreferenceEntity(org.eclipse.che.api.user.server.jpa.PreferenceEntity) AccountImpl(org.eclipse.che.account.spi.AccountImpl) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) SchemaInitializer(org.eclipse.che.core.db.schema.SchemaInitializer) FlywaySchemaInitializer(org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer) FlywaySchemaInitializer(org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer) JpaProfileDao(org.eclipse.che.api.user.server.jpa.JpaProfileDao) ProfileDao(org.eclipse.che.api.user.server.spi.ProfileDao) JpaSnapshotDao(org.eclipse.che.api.machine.server.jpa.JpaSnapshotDao) SnapshotDao(org.eclipse.che.api.machine.server.spi.SnapshotDao) ServerConf2Impl(org.eclipse.che.api.workspace.server.model.impl.ServerConf2Impl) TypeLiteral(com.google.inject.TypeLiteral) UserDao(org.eclipse.che.api.user.server.spi.UserDao) JpaUserDao(org.eclipse.che.api.user.server.jpa.JpaUserDao) DBInitializer(org.eclipse.che.core.db.DBInitializer) JpaRecipeDao(org.eclipse.che.api.machine.server.jpa.JpaRecipeDao) RecipeDao(org.eclipse.che.api.machine.server.spi.RecipeDao) ExtendedMachineImpl(org.eclipse.che.api.workspace.server.model.impl.ExtendedMachineImpl) UserImpl(org.eclipse.che.api.user.server.model.impl.UserImpl) WorkspaceConfigImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl) PGSimpleDataSource(org.postgresql.ds.PGSimpleDataSource) EnvironmentRecipeImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentRecipeImpl) Pair(org.eclipse.che.commons.lang.Pair) CommandImpl(org.eclipse.che.api.machine.server.model.impl.CommandImpl) SnapshotImpl(org.eclipse.che.api.machine.server.model.impl.SnapshotImpl) PasswordEncryptor(org.eclipse.che.security.PasswordEncryptor) SHA512PasswordEncryptor(org.eclipse.che.security.SHA512PasswordEncryptor) AccountDao(org.eclipse.che.account.spi.AccountDao) JpaAccountDao(org.eclipse.che.account.spi.jpa.JpaAccountDao) JpaPreferenceDao(org.eclipse.che.api.user.server.jpa.JpaPreferenceDao) PreferenceDao(org.eclipse.che.api.user.server.spi.PreferenceDao) SshDao(org.eclipse.che.api.ssh.server.spi.SshDao) JpaSshDao(org.eclipse.che.api.ssh.server.jpa.JpaSshDao) SourceStorageImpl(org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl) PersistTestModuleBuilder(org.eclipse.che.commons.test.db.PersistTestModuleBuilder) ProfileImpl(org.eclipse.che.api.user.server.model.impl.ProfileImpl) JpaStackDao(org.eclipse.che.api.workspace.server.jpa.JpaStackDao) StackDao(org.eclipse.che.api.workspace.server.spi.StackDao) RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) EnvironmentRecipeImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentRecipeImpl) JpaWorkspaceDao(org.eclipse.che.api.workspace.server.jpa.JpaWorkspaceDao) WorkspaceDao(org.eclipse.che.api.workspace.server.spi.WorkspaceDao) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) Workspace(org.eclipse.che.api.core.model.workspace.Workspace)

Example 72 with TypeLiteral

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();
}
Also used : Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) Field(java.lang.reflect.Field) TypeLiteral(com.google.inject.TypeLiteral) ImmutableSet(com.google.common.collect.ImmutableSet) ConfigurationException(com.google.inject.ConfigurationException)

Example 73 with TypeLiteral

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))));
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Example 74 with TypeLiteral

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);
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) Multibinder(com.google.inject.multibindings.Multibinder) Method(java.lang.reflect.Method) BindingAnnotation(com.google.inject.BindingAnnotation) Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) HashSet(java.util.HashSet)

Example 75 with TypeLiteral

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;
}
Also used : Binder(com.google.inject.Binder) TypeLiteral(com.google.inject.TypeLiteral) Constructor(java.lang.reflect.Constructor) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) InjectionPoint(com.google.inject.spi.InjectionPoint) Key(com.google.inject.Key) AbstractModule(com.google.inject.AbstractModule)

Aggregations

TypeLiteral (com.google.inject.TypeLiteral)118 AbstractModule (com.google.inject.AbstractModule)43 Injector (com.google.inject.Injector)38 Module (com.google.inject.Module)15 Map (java.util.Map)14 Key (com.google.inject.Key)12 Provider (com.google.inject.Provider)12 ParameterizedType (java.lang.reflect.ParameterizedType)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Binding (com.google.inject.Binding)10 Annotation (java.lang.annotation.Annotation)10 HashMap (java.util.HashMap)10 Set (java.util.Set)10 Binder (com.google.inject.Binder)9 InjectionPoint (com.google.inject.spi.InjectionPoint)9 Method (java.lang.reflect.Method)9 Type (java.lang.reflect.Type)9 HashSet (java.util.HashSet)9 ProvisionException (com.google.inject.ProvisionException)7 FactoryModuleBuilder (com.google.inject.assistedinject.FactoryModuleBuilder)7