Search in sources :

Example 51 with TypeLiteral

use of com.google.inject.TypeLiteral in project gerrit by GerritCodeReview.

the class PluginGuiceEnvironment method copy.

private Module copy(Injector src) {
    Set<TypeLiteral<?>> dynamicTypes = new HashSet<>();
    Set<TypeLiteral<?>> dynamicItemTypes = new HashSet<>();
    for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
        TypeLiteral<?> type = e.getKey().getTypeLiteral();
        if (type.getRawType() == DynamicItem.class) {
            ParameterizedType t = (ParameterizedType) type.getType();
            dynamicItemTypes.add(TypeLiteral.get(t.getActualTypeArguments()[0]));
        } else if (type.getRawType() == DynamicSet.class || type.getRawType() == DynamicMap.class) {
            ParameterizedType t = (ParameterizedType) type.getType();
            dynamicTypes.add(TypeLiteral.get(t.getActualTypeArguments()[0]));
        }
    }
    final Map<Key<?>, Binding<?>> bindings = new LinkedHashMap<>();
    for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
        if (dynamicTypes.contains(e.getKey().getTypeLiteral()) && e.getKey().getAnnotation() != null) {
            // exported to plugins.
            continue;
        } else if (dynamicItemTypes.contains(e.getKey().getTypeLiteral())) {
            continue;
        } else if (shouldCopy(e.getKey())) {
            bindings.put(e.getKey(), e.getValue());
        }
    }
    bindings.remove(Key.get(Injector.class));
    bindings.remove(Key.get(java.util.logging.Logger.class));
    @Nullable final Binding<HttpServletRequest> requestBinding = src.getExistingBinding(Key.get(HttpServletRequest.class));
    @Nullable final Binding<HttpServletResponse> responseBinding = src.getExistingBinding(Key.get(HttpServletResponse.class));
    return new AbstractModule() {

        @SuppressWarnings("unchecked")
        @Override
        protected void configure() {
            for (Map.Entry<Key<?>, Binding<?>> e : bindings.entrySet()) {
                Key<Object> k = (Key<Object>) e.getKey();
                Binding<Object> b = (Binding<Object>) e.getValue();
                bind(k).toProvider(b.getProvider());
            }
            if (requestBinding != null) {
                bind(HttpServletRequest.class).annotatedWith(RootRelative.class).toProvider(requestBinding.getProvider());
            }
            if (responseBinding != null) {
                bind(HttpServletResponse.class).annotatedWith(RootRelative.class).toProvider(responseBinding.getProvider());
            }
        }
    };
}
Also used : Binding(com.google.inject.Binding) HttpServletResponse(javax.servlet.http.HttpServletResponse) LinkedHashMap(java.util.LinkedHashMap) AbstractModule(com.google.inject.AbstractModule) ParameterizedType(java.lang.reflect.ParameterizedType) HttpServletRequest(javax.servlet.http.HttpServletRequest) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) RootRelative(com.google.gerrit.extensions.annotations.RootRelative) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) Key(com.google.inject.Key) Nullable(com.google.gerrit.common.Nullable) HashSet(java.util.HashSet)

Example 52 with TypeLiteral

use of com.google.inject.TypeLiteral in project gerrit by GerritCodeReview.

the class PluginGuiceEnvironment method reattachMap.

private void reattachMap(ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> oldHandles, Map<TypeLiteral<?>, DynamicMap<?>> maps, @Nullable Injector src, Plugin newPlugin) {
    if (src == null || maps == null || maps.isEmpty()) {
        return;
    }
    for (Map.Entry<TypeLiteral<?>, DynamicMap<?>> e : maps.entrySet()) {
        @SuppressWarnings("unchecked") TypeLiteral<Object> type = (TypeLiteral<Object>) e.getKey();
        @SuppressWarnings("unchecked") PrivateInternals_DynamicMapImpl<Object> map = (PrivateInternals_DynamicMapImpl<Object>) e.getValue();
        Map<Annotation, ReloadableRegistrationHandle<?>> am = new HashMap<>();
        for (ReloadableRegistrationHandle<?> h : oldHandles.get(type)) {
            Annotation a = h.getKey().getAnnotation();
            if (a != null && !UNIQUE_ANNOTATION.isInstance(a)) {
                am.put(a, h);
            }
        }
        for (Binding<?> binding : bindings(src, e.getKey())) {
            @SuppressWarnings("unchecked") Binding<Object> b = (Binding<Object>) binding;
            Key<Object> key = b.getKey();
            if (key.getAnnotation() == null) {
                continue;
            }
            @SuppressWarnings("unchecked") ReloadableRegistrationHandle<Object> h = (ReloadableRegistrationHandle<Object>) am.remove(key.getAnnotation());
            if (h != null) {
                replace(newPlugin, h, b);
                oldHandles.remove(type, h);
            } else {
                newPlugin.add(map.put(newPlugin.getName(), b.getKey(), b.getProvider()));
            }
        }
    }
}
Also used : Binding(com.google.inject.Binding) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Annotation(java.lang.annotation.Annotation) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) TypeLiteral(com.google.inject.TypeLiteral) ReloadableRegistrationHandle(com.google.gerrit.extensions.registration.ReloadableRegistrationHandle) PrivateInternals_DynamicMapImpl(com.google.gerrit.extensions.registration.PrivateInternals_DynamicMapImpl) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap)

Example 53 with TypeLiteral

use of com.google.inject.TypeLiteral in project gerrit by GerritCodeReview.

the class SchemaUpdaterTest method update.

@Test
public void update() throws OrmException, FileNotFoundException, IOException {
    db.create();
    final Path site = Paths.get(UUID.randomUUID().toString());
    final SitePaths paths = new SitePaths(site);
    SchemaUpdater u = Guice.createInjector(new FactoryModule() {

        @Override
        protected void configure() {
            TypeLiteral<SchemaFactory<ReviewDb>> schemaFactory = new TypeLiteral<SchemaFactory<ReviewDb>>() {
            };
            bind(schemaFactory).to(NotesMigrationSchemaFactory.class);
            bind(Key.get(schemaFactory, ReviewDbFactory.class)).toInstance(db);
            bind(SitePaths.class).toInstance(paths);
            Config cfg = new Config();
            cfg.setString("user", null, "name", "Gerrit Code Review");
            cfg.setString("user", null, "email", "gerrit@localhost");
            //
            bind(Config.class).annotatedWith(//
            GerritServerConfig.class).toInstance(cfg);
            //
            bind(PersonIdent.class).annotatedWith(//
            GerritPersonIdent.class).toProvider(GerritPersonIdentProvider.class);
            bind(AllProjectsName.class).toInstance(new AllProjectsName("All-Projects"));
            bind(AllUsersName.class).toInstance(new AllUsersName("All-Users"));
            bind(GitRepositoryManager.class).toInstance(new InMemoryRepositoryManager());
            //
            bind(String.class).annotatedWith(//
            AnonymousCowardName.class).toProvider(AnonymousCowardNameProvider.class);
            bind(DataSourceType.class).to(InMemoryH2Type.class);
            bind(SystemGroupBackend.class);
            install(new ConfigNotesMigration.Module());
        }
    }).getInstance(SchemaUpdater.class);
    for (SchemaVersion s = u.getLatestSchemaVersion(); s.getVersionNbr() > 1; s = s.getPrior()) {
        try {
            assertThat(s.getPrior().getVersionNbr()).named("schema %s has prior version %s. Not true that", s.getVersionNbr(), s.getPrior().getVersionNbr()).isEqualTo(s.getVersionNbr() - 1);
        } catch (ProvisionException e) {
            // version.
            break;
        }
    }
    u.update(new UpdateUI() {

        @Override
        public void message(String msg) {
        }

        @Override
        public boolean yesno(boolean def, String msg) {
            return def;
        }

        @Override
        public boolean isBatch() {
            return true;
        }

        @Override
        public void pruneSchema(StatementExecutor e, List<String> pruneList) throws OrmException {
            for (String sql : pruneList) {
                e.execute(sql);
            }
        }
    });
    db.assertSchemaVersion();
    final SystemConfig sc = db.getSystemConfig();
    assertThat(sc.sitePath).isEqualTo(paths.site_path.toAbsolutePath().toString());
}
Also used : SystemConfig(com.google.gerrit.reviewdb.client.SystemConfig) InMemoryRepositoryManager(com.google.gerrit.testutil.InMemoryRepositoryManager) SystemConfig(com.google.gerrit.reviewdb.client.SystemConfig) Config(org.eclipse.jgit.lib.Config) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) SitePaths(com.google.gerrit.server.config.SitePaths) StatementExecutor(com.google.gwtorm.server.StatementExecutor) ProvisionException(com.google.inject.ProvisionException) TypeLiteral(com.google.inject.TypeLiteral) OrmException(com.google.gwtorm.server.OrmException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) Path(java.nio.file.Path) SchemaFactory(com.google.gwtorm.server.SchemaFactory) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) AnonymousCowardName(com.google.gerrit.server.config.AnonymousCowardName) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) FactoryModule(com.google.gerrit.extensions.config.FactoryModule) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) ConfigNotesMigration(com.google.gerrit.server.notedb.ConfigNotesMigration) AllUsersName(com.google.gerrit.server.config.AllUsersName) Test(org.junit.Test)

Example 54 with TypeLiteral

use of com.google.inject.TypeLiteral in project gerrit by GerritCodeReview.

the class AutoRegisterModules method makeSystemModule.

private Module makeSystemModule() {
    return new AbstractModule() {

        @Override
        protected void configure() {
            for (Class<?> clazz : sysSingletons) {
                bind(clazz).in(Scopes.SINGLETON);
            }
            for (Map.Entry<TypeLiteral<?>, Class<?>> e : sysListen.entries()) {
                @SuppressWarnings("unchecked") TypeLiteral<Object> type = (TypeLiteral<Object>) e.getKey();
                @SuppressWarnings("unchecked") Class<Object> impl = (Class<Object>) e.getValue();
                Annotation n = calculateBindAnnotation(impl);
                bind(type).annotatedWith(n).to(impl);
            }
            if (initJs != null) {
                DynamicSet.bind(binder(), WebUiPlugin.class).toInstance(new JavaScriptPlugin(initJs));
            }
        }
    };
}
Also used : JavaScriptPlugin(com.google.gerrit.extensions.webui.JavaScriptPlugin) AutoRegisterUtil.calculateBindAnnotation(com.google.gerrit.server.plugins.AutoRegisterUtil.calculateBindAnnotation) Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) TypeLiteral(com.google.inject.TypeLiteral) WebUiPlugin(com.google.gerrit.extensions.webui.WebUiPlugin) Map(java.util.Map)

Example 55 with TypeLiteral

use of com.google.inject.TypeLiteral in project gerrit by GerritCodeReview.

the class BaseInit method createSiteInit.

private SiteInit createSiteInit() {
    final ConsoleUI ui = getConsoleUI();
    final Path sitePath = getSitePath();
    final List<Module> m = new ArrayList<>();
    final SecureStoreInitData secureStoreInitData = discoverSecureStoreClass();
    final String currentSecureStoreClassName = getConfiguredSecureStoreClass();
    if (secureStoreInitData != null && currentSecureStoreClassName != null && !currentSecureStoreClassName.equals(secureStoreInitData.className)) {
        String err = String.format("Different secure store was previously configured: %s. " + "Use SwitchSecureStore program to switch between implementations.", currentSecureStoreClassName);
        throw die(err);
    }
    m.add(new GerritServerConfigModule());
    m.add(new InitModule(standalone, initDb));
    m.add(new AbstractModule() {

        @Override
        protected void configure() {
            bind(ConsoleUI.class).toInstance(ui);
            bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath);
            List<String> plugins = MoreObjects.firstNonNull(getInstallPlugins(), new ArrayList<String>());
            bind(new TypeLiteral<List<String>>() {
            }).annotatedWith(InstallPlugins.class).toInstance(plugins);
            bind(new TypeLiteral<Boolean>() {
            }).annotatedWith(InstallAllPlugins.class).toInstance(installAllPlugins());
            bind(PluginsDistribution.class).toInstance(pluginsDistribution);
            String secureStoreClassName;
            if (secureStoreInitData != null) {
                secureStoreClassName = secureStoreInitData.className;
            } else {
                secureStoreClassName = currentSecureStoreClassName;
            }
            if (secureStoreClassName != null) {
                ui.message("Using secure store: %s\n", secureStoreClassName);
            }
            bind(SecureStoreInitData.class).toProvider(Providers.of(secureStoreInitData));
            bind(String.class).annotatedWith(SecureStoreClassName.class).toProvider(Providers.of(secureStoreClassName));
            bind(SecureStore.class).toProvider(SecureStoreProvider.class).in(SINGLETON);
            bind(new TypeLiteral<List<String>>() {
            }).annotatedWith(LibraryDownload.class).toInstance(getSkippedDownloads());
            bind(Boolean.class).annotatedWith(LibraryDownload.class).toInstance(skipAllDownloads());
            bind(MetricMaker.class).to(DisabledMetricMaker.class);
        }
    });
    try {
        return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class);
    } catch (CreationException ce) {
        final Message first = ce.getErrorMessages().iterator().next();
        Throwable why = first.getCause();
        if (why instanceof Die) {
            throw (Die) why;
        }
        final StringBuilder buf = new StringBuilder(ce.getMessage());
        while (why != null) {
            buf.append("\n");
            buf.append(why.getMessage());
            why = why.getCause();
            if (why != null) {
                buf.append("\n  caused by ");
            }
        }
        throw die(buf.toString(), new RuntimeException("InitInjector failed", ce));
    }
}
Also used : Path(java.nio.file.Path) SitePath(com.google.gerrit.server.config.SitePath) Die(com.google.gerrit.common.Die) Message(com.google.inject.spi.Message) ArrayList(java.util.ArrayList) CreationException(com.google.inject.CreationException) SecureStore(com.google.gerrit.server.securestore.SecureStore) ConsoleUI(com.google.gerrit.pgm.init.api.ConsoleUI) AbstractModule(com.google.inject.AbstractModule) GerritServerConfigModule(com.google.gerrit.server.config.GerritServerConfigModule) TypeLiteral(com.google.inject.TypeLiteral) List(java.util.List) ArrayList(java.util.ArrayList) Module(com.google.inject.Module) GerritServerConfigModule(com.google.gerrit.server.config.GerritServerConfigModule) IndexModule(com.google.gerrit.server.index.IndexModule) AbstractModule(com.google.inject.AbstractModule) DisabledMetricMaker(com.google.gerrit.metrics.DisabledMetricMaker)

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