Search in sources :

Example 96 with TypeLiteral

use of com.google.inject.TypeLiteral in project graylog2-server by Graylog2.

the class JournalDecode method runCommand.

@Override
protected void runCommand() {
    Range<Long> range;
    try {
        final List<String> offsets = Splitter.on("..").limit(2).splitToList(rangeArg);
        if (offsets.size() == 1) {
            range = Range.singleton(Long.valueOf(offsets.get(0)));
        } else if (offsets.size() == 2) {
            final String first = offsets.get(0);
            final String second = offsets.get(1);
            if (first.isEmpty()) {
                range = Range.atMost(Long.valueOf(second));
            } else if (second.isEmpty()) {
                range = Range.atLeast(Long.valueOf(first));
            } else {
                range = Range.closed(Long.valueOf(first), Long.valueOf(second));
            }
        } else {
            throw new RuntimeException();
        }
    } catch (Exception e) {
        System.err.println("Malformed offset range: " + rangeArg);
        return;
    }
    final Map<String, Codec.Factory<? extends Codec>> codecFactory = injector.getInstance(Key.get(new TypeLiteral<Map<String, Codec.Factory<? extends Codec>>>() {
    }));
    final Long readOffset = range.lowerEndpoint();
    final long count = range.upperEndpoint() - range.lowerEndpoint() + 1;
    final List<Journal.JournalReadEntry> entries = journal.read(readOffset, count);
    for (final Journal.JournalReadEntry entry : entries) {
        final RawMessage raw = RawMessage.decode(entry.getPayload(), entry.getOffset());
        if (raw == null) {
            System.err.println(MessageFormatter.format("Journal entry at offset {} failed to decode", entry.getOffset()));
            continue;
        }
        final Codec codec = codecFactory.get(raw.getCodecName()).create(raw.getCodecConfig());
        final Message message = codec.decode(raw);
        if (message == null) {
            System.err.println(MessageFormatter.format("Could not use codec {} to decode raw message id {} at offset {}", new Object[] { raw.getCodecName(), raw.getId(), entry.getOffset() }));
        } else {
            message.setJournalOffset(raw.getJournalOffset());
        }
        final ResolvableInetSocketAddress remoteAddress = raw.getRemoteAddress();
        final String remote = remoteAddress == null ? "unknown address" : remoteAddress.getInetSocketAddress().toString();
        final StringBuffer sb = new StringBuffer();
        sb.append("Message ").append(raw.getId()).append('\n').append(" at ").append(raw.getTimestamp()).append('\n').append(" in format ").append(raw.getCodecName()).append('\n').append(" at offset ").append(raw.getJournalOffset()).append('\n').append(" received from remote address ").append(remote).append('\n').append(" (source field: ").append(message == null ? "unparsed" : message.getSource()).append(')').append('\n');
        if (message != null) {
            sb.append(" contains ").append(message.getFieldNames().size()).append(" fields.");
        } else {
            sb.append("The message could not be parse by the given codec.");
        }
        System.out.println(sb);
    }
}
Also used : RawMessage(org.graylog2.plugin.journal.RawMessage) Message(org.graylog2.plugin.Message) Journal(org.graylog2.shared.journal.Journal) Codec(org.graylog2.plugin.inputs.codecs.Codec) ResolvableInetSocketAddress(org.graylog2.plugin.ResolvableInetSocketAddress) TypeLiteral(com.google.inject.TypeLiteral) RawMessage(org.graylog2.plugin.journal.RawMessage)

Example 97 with TypeLiteral

use of com.google.inject.TypeLiteral in project OpenAM by OpenRock.

the class CoreGuiceModule method configure.

@Override
protected void configure() {
    bind(new AdminTokenType()).toProvider(new AdminTokenProvider()).in(Singleton.class);
    bind(ServiceManagementDAO.class).to(ServiceManagementDAOWrapper.class).in(Singleton.class);
    bind(DNWrapper.class).in(Singleton.class);
    bind(URLValidator.class).toInstance(URLValidator.getInstance());
    bind(new TypeLiteral<TokenAdapter<JsonValue>>() {
    }).annotatedWith(Names.named(OAuth2Constants.CoreTokenParams.OAUTH_TOKEN_ADAPTER)).to(OAuthAdapter.class);
    bind(DSConfigMgr.class).toProvider(new Provider<DSConfigMgr>() {

        public DSConfigMgr get() {
            try {
                return DSConfigMgr.getDSConfigMgr();
            } catch (LDAPServiceException e) {
                throw new IllegalStateException(e);
            }
        }
    }).in(Singleton.class);
    bind(SSOTokenManager.class).toProvider(new Provider<SSOTokenManager>() {

        public SSOTokenManager get() {
            try {
                return SSOTokenManager.getInstance();
            } catch (SSOException e) {
                throw new IllegalStateException(e);
            }
        }
    }).in(Singleton.class);
    /**
         * Core Token Service bindings are divided into a number of logical groups.
         */
    // CTS General
    bind(CTSPersistentStore.class).to(CTSPersistentStoreImpl.class);
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_REAPER_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_REAPER_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_ASYNC_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_ASYNC_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_MONITOR_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_MONITOR_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(DataLayerConstants.DATA_LAYER_DEBUG)).toInstance(Debug.getInstance(DataLayerConstants.DATA_LAYER_DEBUG));
    bind(Debug.class).annotatedWith(Names.named("amSMS")).toInstance(Debug.getInstance("amSMS"));
    bind(Debug.class).annotatedWith(Names.named(PolicyMonitor.POLICY_MONITOR_DEBUG)).toInstance(Debug.getInstance(PolicyMonitor.POLICY_MONITOR_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(OAuth2Constants.DEBUG_LOG_NAME)).toInstance(Debug.getInstance(OAuth2Constants.DEBUG_LOG_NAME));
    bind(CoreTokenConstants.class).in(Singleton.class);
    bind(CoreTokenConfig.class).in(Singleton.class);
    // CTS Connection Management
    bind(String.class).annotatedWith(Names.named(DataLayerConstants.ROOT_DN_SUFFIX)).toProvider(new Provider<String>() {

        public String get() {
            return SMSEntry.getRootSuffix();
        }
    }).in(Singleton.class);
    bind(ConfigurationObserver.class).toProvider(new Provider<ConfigurationObserver>() {

        public ConfigurationObserver get() {
            return ConfigurationObserver.getInstance();
        }
    }).in(Singleton.class);
    // CTS Monitoring
    bind(CTSOperationsMonitoringStore.class).to(CTSMonitoringStoreImpl.class);
    bind(CTSReaperMonitoringStore.class).to(CTSMonitoringStoreImpl.class);
    bind(CTSConnectionMonitoringStore.class).to(CTSMonitoringStoreImpl.class);
    // Enable monitoring of all CTS operations
    bind(ResultHandlerFactory.class).to(MonitoredResultHandlerFactory.class);
    // CTS Reaper configuration
    bind(ReaperQuery.class).to(ReaperConnection.class);
    // Policy Monitoring
    bind(PolicyMonitor.class).to(PolicyMonitorImpl.class);
    // SAML2 token repository dependencies
    bind(new TypeLiteral<TokenAdapter<SAMLToken>>() {
    }).to(SAMLAdapter.class);
    /**
         * Session related dependencies.
         */
    bind(SessionOperationStrategy.class).to(ServerSessionOperationStrategy.class);
    // TODO: Investigate whether or not this lazy-loading "Config<SessionService>" wrapper is still needed
    bind(new TypeLiteral<Config<SessionService>>() {
    }).toInstance(new Config<SessionService>() {

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

        @Override
        public SessionService get() {
            return InjectorHolder.getInstance(SessionService.class);
        }
    });
    bind(Debug.class).annotatedWith(Names.named(SessionConstants.SESSION_DEBUG)).toInstance(Debug.getInstance(SessionConstants.SESSION_DEBUG));
    bind(new TypeLiteral<Function<String, String, NeverThrowsException>>() {
    }).annotatedWith(Names.named("tagSwapFunc")).toInstance(new Function<String, String, NeverThrowsException>() {

        @Override
        public String apply(String text) {
            return ServicesDefaultValues.tagSwap(text, true);
        }
    });
    install(new FactoryModuleBuilder().implement(AMIdentityRepository.class, AMIdentityRepository.class).build(AMIdentityRepositoryFactory.class));
    install(new FactoryModuleBuilder().implement(SMSAuditor.class, SMSAuditor.class).build(ConfigAuditorFactory.class));
    Multibinder.newSetBinder(binder(), SMSAuditFilter.class);
    Multibinder.newSetBinder(binder(), IdRepoCreationListener.class);
    bind(Stats.class).annotatedWith(Names.named(SessionConstants.STATS_MASTER_TABLE)).toInstance(Stats.getInstance(SessionConstants.STATS_MASTER_TABLE));
    bind(SessionCache.class).toInstance(SessionCache.getInstance());
    bind(SessionPollerPool.class).toInstance(SessionPollerPool.getInstance());
    /*
         * Must use a provider to ensure initialisation happens after SystemProperties have been set.
         */
    bind(SessionCookies.class).toProvider(new Provider<SessionCookies>() {

        @Override
        public SessionCookies get() {
            return SessionCookies.getInstance();
        }
    });
    /*
         * Must use a provider to ensure initialisation happens after SystemProperties have been set.
         */
    bind(SessionURL.class).toProvider(new Provider<SessionURL>() {

        @Override
        public SessionURL get() {
            return SessionURL.getInstance();
        }
    });
    bind(SessionServiceURLService.class).toInstance(SessionServiceURLService.getInstance());
    bind(ConsoleConfigHandler.class).to(ConsoleConfigHandlerImpl.class);
}
Also used : ServiceManagementDAOWrapper(com.sun.identity.sm.ServiceManagementDAOWrapper) FactoryModuleBuilder(com.google.inject.assistedinject.FactoryModuleBuilder) SessionURL(org.forgerock.openam.session.SessionURL) SSOException(com.iplanet.sso.SSOException) PolicyMonitor(org.forgerock.openam.entitlement.monitoring.PolicyMonitor) CTSOperationsMonitoringStore(org.forgerock.openam.cts.monitoring.CTSOperationsMonitoringStore) CTSPersistentStore(org.forgerock.openam.cts.CTSPersistentStore) Function(org.forgerock.util.Function) SessionCookies(org.forgerock.openam.session.SessionCookies) TypeLiteral(com.google.inject.TypeLiteral) URLValidator(com.sun.identity.shared.validation.URLValidator) ConfigAuditorFactory(com.sun.identity.sm.ldap.ConfigAuditorFactory) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) CTSConnectionMonitoringStore(org.forgerock.openam.cts.monitoring.CTSConnectionMonitoringStore) ServerSessionOperationStrategy(com.iplanet.dpro.session.operations.ServerSessionOperationStrategy) SessionOperationStrategy(com.iplanet.dpro.session.operations.SessionOperationStrategy) SessionPollerPool(org.forgerock.openam.session.SessionPollerPool) CTSReaperMonitoringStore(org.forgerock.openam.cts.monitoring.CTSReaperMonitoringStore) ConsoleConfigHandler(org.forgerock.openam.sm.config.ConsoleConfigHandler) AMIdentityRepositoryFactory(org.forgerock.openam.identity.idm.AMIdentityRepositoryFactory) SAMLToken(org.forgerock.openam.cts.api.tokens.SAMLToken) SessionServiceURLService(org.forgerock.openam.session.SessionServiceURLService) Provider(com.google.inject.Provider) ReaperQuery(org.forgerock.openam.cts.impl.query.reaper.ReaperQuery) CoreTokenConfig(org.forgerock.openam.cts.CoreTokenConfig) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) SessionService(com.iplanet.dpro.session.service.SessionService) CoreTokenConstants(org.forgerock.openam.cts.api.CoreTokenConstants) TokenAdapter(org.forgerock.openam.cts.adapters.TokenAdapter) MonitoredResultHandlerFactory(org.forgerock.openam.cts.monitoring.impl.queue.MonitoredResultHandlerFactory) ResultHandlerFactory(org.forgerock.openam.cts.impl.queue.ResultHandlerFactory) SessionCache(org.forgerock.openam.session.SessionCache)

Example 98 with TypeLiteral

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

the class HttpAutoRegisterModuleGenerator method configureServlets.

@Override
protected void configureServlets() {
    for (Map.Entry<String, Class<HttpServlet>> e : serve.entrySet()) {
        bind(e.getValue()).in(Scopes.SINGLETON);
        serve(e.getKey()).with(e.getValue());
    }
    for (Map.Entry<TypeLiteral<?>, Class<?>> e : listeners.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);
    }
}
Also used : TypeLiteral(com.google.inject.TypeLiteral) HashMap(java.util.HashMap) Map(java.util.Map) AutoRegisterUtil.calculateBindAnnotation(com.google.gerrit.server.plugins.AutoRegisterUtil.calculateBindAnnotation) Annotation(java.lang.annotation.Annotation)

Example 99 with TypeLiteral

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

the class PrivateInternals_DynamicTypes method dynamicMapsOf.

public static Map<TypeLiteral<?>, DynamicMap<?>> dynamicMapsOf(Injector src) {
    Map<TypeLiteral<?>, DynamicMap<?>> m = new HashMap<>();
    for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
        TypeLiteral<?> type = e.getKey().getTypeLiteral();
        if (type.getRawType() == DynamicMap.class) {
            ParameterizedType p = (ParameterizedType) type.getType();
            m.put(TypeLiteral.get(p.getActualTypeArguments()[0]), (DynamicMap<?>) e.getValue().getProvider().get());
        }
    }
    if (m.isEmpty()) {
        return Collections.emptyMap();
    }
    return Collections.unmodifiableMap(m);
}
Also used : Binding(com.google.inject.Binding) ParameterizedType(java.lang.reflect.ParameterizedType) TypeLiteral(com.google.inject.TypeLiteral) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) Key(com.google.inject.Key)

Example 100 with TypeLiteral

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

the class PrivateInternals_DynamicTypes method dynamicSetsOf.

public static Map<TypeLiteral<?>, DynamicSet<?>> dynamicSetsOf(Injector src) {
    Map<TypeLiteral<?>, DynamicSet<?>> m = new HashMap<>();
    for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) {
        TypeLiteral<?> type = e.getKey().getTypeLiteral();
        if (type.getRawType() == DynamicSet.class) {
            ParameterizedType p = (ParameterizedType) type.getType();
            m.put(TypeLiteral.get(p.getActualTypeArguments()[0]), (DynamicSet<?>) e.getValue().getProvider().get());
        }
    }
    if (m.isEmpty()) {
        return Collections.emptyMap();
    }
    return Collections.unmodifiableMap(m);
}
Also used : Binding(com.google.inject.Binding) ParameterizedType(java.lang.reflect.ParameterizedType) TypeLiteral(com.google.inject.TypeLiteral) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) Key(com.google.inject.Key)

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