下面列出了怎么用com.google.inject.util.Modules的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Builds and returns a Guice module containing the custom configuration for the kernel
* application, including additions and overrides by the user.
*
* @return The custom configuration module.
*/
private static Module customConfigurationModule() {
List<KernelInjectionModule> defaultModules
= Arrays.asList(new DefaultKernelInjectionModule(),
new DefaultDispatcherModule(),
new DefaultRouterModule(),
new DefaultSchedulerModule(),
new DefaultRecoveryEvaluatorModule());
ConfigurationBindingProvider bindingProvider = configurationBindingProvider();
for (KernelInjectionModule defaultModule : defaultModules) {
defaultModule.setConfigBindingProvider(bindingProvider);
}
return Modules.override(defaultModules)
.with(findRegisteredModules(bindingProvider));
}
@Override
protected Module newIsisWicketModule() {
final Module isisDefaults = super.newIsisWicketModule();
final Module overrides = new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("applicationName")).toInstance("ToDo App");
bind(String.class).annotatedWith(Names.named("applicationCss")).toInstance("css/application.css");
bind(String.class).annotatedWith(Names.named("applicationJs")).toInstance("scripts/application.js");
bind(String.class).annotatedWith(Names.named("brandLogoHeader")).toInstance("/images/todoapp-logo-header.png");
bind(String.class).annotatedWith(Names.named("brandLogoSignin")).toInstance("/images/todoapp-logo-signin.png");
bind(String.class).annotatedWith(Names.named("welcomeMessage")).toInstance(readLines(getClass(), "welcome.html"));
bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("ToDo App");
bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
}
};
return Modules.override(isisDefaults).with(overrides);
}
private JoynrRuntime createClusterController(Properties webSocketConfig) {
Properties ccConfig = new Properties();
ccConfig.putAll(webSocketConfig);
ccConfig.putAll(baseTestConfig);
ccConfig.setProperty(ConfigurableMessagingSettings.PROPERTY_CC_CONNECTION_TYPE, "WEBSOCKET");
injectorCC = new JoynrInjectorFactory(ccConfig,
Modules.override(new CCWebSocketRuntimeModule())
.with(new MqttPahoModule(), new AbstractModule() {
@Override
protected void configure() {
bind(Boolean.class).annotatedWith(Names.named(WebSocketMessagingSkeleton.WEBSOCKET_IS_MAIN_TRANSPORT))
.toInstance(Boolean.TRUE);
}
})).getInjector();
return injectorCC.getInstance(JoynrRuntime.class);
}
@BeforeClass
public static void setup() throws IOException {
final Configuration conf = new Configuration();
conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV4.class.getName());
conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());
Injector injector = Guice.createInjector(
new ConfigModule(conf),
new DiscoveryModules().getInMemoryModules(),
Modules.override(
new TransactionModules("clientB").getInMemoryModules()).with(new AbstractModule() {
@Override
protected void configure() {
TransactionManager txManager = new TransactionManager(conf);
txManager.startAndWait();
bind(TransactionManager.class).toInstance(txManager);
bind(TransactionSystemClient.class).to(DummyTxClient.class).in(Singleton.class);
}
}));
txClient = (DummyTxClient) injector.getInstance(TransactionSystemClient.class);
factory = injector.getInstance(TransactionExecutorFactory.class);
}
@BeforeClass
public static void setup() throws IOException {
final Configuration conf = new Configuration();
conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV4.class.getName());
conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());
Injector injector = Guice.createInjector(
new ConfigModule(conf),
new DiscoveryModules().getInMemoryModules(),
Modules.override(
new TransactionModules("clientA").getInMemoryModules()).with(new AbstractModule() {
@Override
protected void configure() {
TransactionManager txManager = new TransactionManager(conf);
txManager.startAndWait();
bind(TransactionManager.class).toInstance(txManager);
bind(TransactionSystemClient.class).to(DummyTxClient.class).in(Singleton.class);
}
}));
txClient = (DummyTxClient) injector.getInstance(TransactionSystemClient.class);
}
/**
* Returns the {@code TestEnvironment} for the module, creating it if this is the first time it
* has been requested.
*/
private static TestEnvironment getOrCreateTestEnvironment(Class<? extends Module> module) {
if (environments.containsKey(module)) {
return environments.get(module);
}
// Use modules override to configure TearDownAccepter and GuiceberryCompatibilityModule.
// This allows reuse of modules which install GuiceBerryModule by overriding its bindings
// with equivalent ones from Acai.
Injector injector =
Guice.createInjector(
Modules.override(instantiateModule(module), new TestScopeModule())
.with(new TearDownAccepterModule(), new GuiceberryCompatibilityModule()));
TestEnvironment testEnvironment =
new TestEnvironment(
injector,
Dependencies.inOrder(injector.getInstance(TESTING_SERVICES_KEY))
.stream()
.map(TestingServiceManager::new)
.collect(Collectors.toList()));
environments.put(module, testEnvironment);
return testEnvironment;
}
public static final void main(String... args) {
logger.info("Starting consumer ...");
Properties joynrProperties = new Properties();
joynrProperties.setProperty(MessagingPropertyKeys.PERSISTENCE_FILE, "consumer-joynr.properties");
joynrProperties.setProperty(PROPERTY_JOYNR_DOMAIN_LOCAL, "message_persistence_consumer_local_domain");
joynrProperties.setProperty(MqttModule.PROPERTY_KEY_MQTT_MAX_MSGS_INFLIGHT, "100");
Module runtimeModule = Modules.combine(new CCInProcessRuntimeModule(), new MqttPahoModule());
JoynrInjectorFactory joynrInjectorFactory = new JoynrInjectorFactory(joynrProperties, runtimeModule);
JoynrApplication application = joynrInjectorFactory.createApplication(ConsumerApplication.class);
logger.info("Application created.");
application.run();
logger.info("Application finished. Shutting down.");
application.shutdown();
}
private JoynrRuntime createRuntime() {
Properties properties = new Properties();
properties.put(MqttModule.PROPERTY_MQTT_BROKER_URIS, "tcp://localhost:1883");
properties.put(MessagingPropertyKeys.PROPERTY_MESSAGING_PRIMARYGLOBALTRANSPORT, "mqtt");
Module module = Modules.override(new CCInProcessRuntimeModule()).with(new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named(ClusterControllerRuntimeModule.PROPERTY_ACCESSCONTROL_ENABLE))
.to(true);
}
}, new MqttPahoModule());
DummyJoynrApplication app = (DummyJoynrApplication) new JoynrInjectorFactory(properties,
module).createApplication(DummyJoynrApplication.class);
return app.getRuntime();
}
public Injector getMainModuleInjector() {
//TODO: Synchronise this with e.g. synchronized (ZeroCodePackageRunner.class) {}
final TargetEnv envAnnotation = testClass.getAnnotation(TargetEnv.class);
String serverEnv = envAnnotation != null ? envAnnotation.value() : "config_hosts.properties";
serverEnv = getEnvSpecificConfigFile(serverEnv, testClass);
Class<? extends BasicHttpClient> runtimeHttpClient = createCustomHttpClientOrDefault();
Class<? extends BasicKafkaClient> runtimeKafkaClient = createCustomKafkaClientOrDefault();
return createInjector(Modules.override(new ApplicationMainModule(serverEnv))
.with(
new RuntimeHttpClientModule(runtimeHttpClient),
new RuntimeKafkaClientModule(runtimeKafkaClient)
));
}
public static final void main(String... args) {
Bootstrap.logger.info("Starting consumer ...");
Properties joynrProperties = new Properties();
joynrProperties.put("joynr.messaging.mqtt.brokerUri", "tcp://mqttbroker:1883");
joynrProperties.put(MessagingPropertyKeys.PROPERTY_MESSAGING_PRIMARYGLOBALTRANSPORT, "mqtt");
joynrProperties.setProperty(MessagingPropertyKeys.PERSISTENCE_FILE, "consumer-joynr.properties");
joynrProperties.setProperty(PROPERTY_JOYNR_DOMAIN_LOCAL, "stateless_async_consumer_local_domain");
Module runtimeModule = Modules.combine(new CCInProcessRuntimeModule(), new MqttPahoModule());
JoynrInjectorFactory joynrInjectorFactory = new JoynrInjectorFactory(joynrProperties, runtimeModule);
JoynrApplication application = joynrInjectorFactory.createApplication(ConsumerApplication.class);
Bootstrap.logger.info("Application created.");
application.run();
Bootstrap.logger.info("Application finished. Shutting down.");
application.shutdown();
}
private static Module commonModules(Session session, CassandraTypesProvider typesProvider,
CassandraMessageId.Factory messageIdFactory,
CassandraConfiguration configuration) {
return Modules.combine(
binder -> binder.bind(MessageId.Factory.class).toInstance(messageIdFactory),
binder -> binder.bind(BlobId.Factory.class).toInstance(new HashBlobId.Factory()),
binder -> binder.bind(BlobStore.class).to(CassandraBlobStore.class),
binder -> binder.bind(CassandraDumbBlobStore.class).in(SINGLETON),
binder -> binder.bind(BucketName.class)
.annotatedWith(Names.named(CassandraDumbBlobStore.DEFAULT_BUCKET))
.toInstance(BucketName.DEFAULT),
binder -> binder.bind(Session.class).toInstance(session),
binder -> binder.bind(CassandraTypesProvider.class).toInstance(typesProvider),
binder -> binder.bind(CassandraConfiguration.class).toInstance(configuration),
binder -> binder.bind(CassandraConsistenciesConfiguration.class)
.toInstance(CassandraConsistenciesConfiguration.fromConfiguration(configuration)));
}
private <T extends ServerProvider, U, V> void testRequestHandlerWithSyncCloseResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
writeResponse(out);
closeResponse(out);
return null;
}
});
}
public static final void main(String... args) {
logger.info("Starting consumer ...");
Properties joynrProperties = new Properties();
joynrProperties.put("joynr.messaging.mqtt.brokerUri", "tcp://mqttbroker:1883");
joynrProperties.put(MessagingPropertyKeys.PROPERTY_MESSAGING_PRIMARYGLOBALTRANSPORT, "mqtt");
joynrProperties.setProperty(MessagingPropertyKeys.PERSISTENCE_FILE, "consumer-joynr.properties");
joynrProperties.setProperty(PROPERTY_JOYNR_DOMAIN_LOCAL, "gracefulshutdown_consumer_local_domain");
Module runtimeModule = Modules.combine(new CCInProcessRuntimeModule(), new HivemqMqttClientModule());
JoynrInjectorFactory joynrInjectorFactory = new JoynrInjectorFactory(joynrProperties, runtimeModule);
JoynrApplication application = joynrInjectorFactory.createApplication(ConsumerApplication.class);
logger.info("Application created.");
application.run();
logger.info("Application finished. Shutting down.");
application.shutdown();
}
private <T extends ServerProvider, U, V> void testRequestExceptionWithSyncCloseResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
writeResponse(out);
closeResponse(out);
throw new ConformanceException();
}
});
}
private <T extends ServerProvider, U, V> void testRequestExceptionWithSyncWriteResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
writeResponse(out);
closeResponseInOtherThread(out);
throw new ConformanceException();
}
});
}
private <T extends ServerProvider, U, V> void testRequestNondeterministicExceptionWithSyncHandleResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
callInOtherThread(() -> {
writeResponse(out);
closeResponse(out);
return null;
});
throw new ConformanceException();
}
});
}
private <T extends ServerProvider, U, V> void testRequestExceptionBeforeResponseWriteWithSyncHandleResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
final Event exceptionHandledByFramework = new Event();
callInOtherThread(() -> {
exceptionHandledByFramework.await();
writeResponse(out);
closeResponse(out);
return null;
});
throw new ConformanceException(exceptionHandledByFramework);
}
});
}
private <T extends ServerProvider, U, V> void testRequestExceptionAfterResponseWriteWithSyncHandleResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
callInOtherThread(() -> {
writeResponse(out);
closeResponse(out);
return null;
});
responseWritten.await();
throw new ConformanceException();
}
});
}
private <T extends ServerProvider, U, V> void testRequestExceptionAfterResponseCloseNoContentWithAsyncHandleResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
callInOtherThread(() -> {
try {
respondNoContent(handler);
} catch (Throwable ignored) {
}
return null;
});
responseClosed.await();
throw new ConformanceException();
}
});
}
private <T extends ServerProvider, U, V> void testRequestExceptionAfterResponseWriteWithAsyncHandleResponse(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(final Request request, final ResponseHandler handler) {
callInOtherThread(new Callable<Void>() {
@Override
public Void call() throws Exception {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
writeResponse(out);
closeResponse(out);
return null;
}
});
responseWritten.await();
throw new ConformanceException();
}
});
}
private <T extends ServerProvider, U, V> void testResponseWriteCompletionException(
final Adapter<T, U, V> adapter,
final Module... config)
throws Throwable {
runTest(adapter,
Modules.combine(config),
RequestType.WITHOUT_CONTENT,
new TestRequestHandler() {
@Override
public ContentChannel handle(Request request, ResponseHandler handler) {
final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
for (ByteBuffer buf : adapter.newResponseContent()) {
out.write(buf, EXCEPTION_COMPLETION_HANDLER);
}
closeResponse(out);
return null;
}
});
}
@Override
protected List<Module> getModules() {
// based on logic that getServletModule() is called BEFORE getModules() in the
// EverrestGuiceContextListener
modules.add(new InitModule(PostConstruct.class));
modules.add(new DestroyModule(PreDestroy.class, LOG_HANDLER));
modules.add(new URIConverter());
modules.add(new URLConverter());
modules.add(new FileConverter());
modules.add(new PathConverter());
modules.add(new StringArrayConverter());
modules.add(new PairConverter());
modules.add(new PairArrayConverter());
modules.addAll(ModuleScanner.findModules());
Map<String, Set<String>> aliases = readConfigurationAliases();
Module firstConfigurationPermutation =
Modules.override(new WebInfConfiguration(aliases)).with(new ExtConfiguration(aliases));
Module secondConfigurationPermutation =
Modules.override(firstConfigurationPermutation)
.with(new CheSystemPropertiesConfigurationModule(aliases));
Module lastConfigurationPermutation =
Modules.override(secondConfigurationPermutation)
.with(new CheEnvironmentVariablesConfigurationModule(aliases));
modules.add(lastConfigurationPermutation);
return modules;
}
/**
* Static method that creates a cluster controller {@link JoynrRuntime} for Android developers with default configurations.
* ATTENTION: This method shouldn't be called by joynr app developers as the cluster controller is usually running in another app/process.
*
* @param context The Application context
* @param brokerUri The mqtt broker uri
* @param properties Extra properties that can configure joynr runtime.
* @param modules Extra modules that can configure joynr runtime.
* @return A {@link JoynrRuntime} object
*/
public static JoynrRuntime initClusterController(Context context, String brokerUri, Properties properties, Module... modules) {
// set default joynr properties
final Properties config = getDefaultJoynrProperties(context);
// override with possible developer specified properties
config.putAll(properties);
config.put("joynr.messaging.mqtt.brokerUris", brokerUri);
Module runtimeModule = new CCBinderRuntimeModule(context);
final Module backendTransportModules = new HivemqMqttClientModule();
runtimeModule = Modules.override(runtimeModule).with(backendTransportModules);
for (Module module : modules) {
runtimeModule = Modules.override(runtimeModule).with(module);
}
injector = new JoynrInjectorFactory(config, runtimeModule).getInjector();
runtime = injector.getInstance(JoynrRuntime.class);
logger.debug("Started Android CC runtime...");
return runtime;
}
@Override
public Module getModule() {
return Modules.combine(
binder -> binder.bind(BlobExportImplChoice.class)
.toInstance(BlobExportImplChoice.LINSHARE),
binder -> {
try {
binder.bind(LinshareConfiguration.class)
.toInstance(linshareExtension.configurationWithBasicAuthFor(
new LinshareFixture.Credential(
linshareExtension.getTechnicalAccountUUID().toString(),
LinshareFixture.TECHNICAL_ACCOUNT.getPassword()))
);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
);
}
@Override
public Module newConfigModule() {
return Modules.combine(
new AbstractModule() {
@Override
protected void configure() {
bind(FilterBindings.class)
.toInstance(new FilterBindings(
new BindingRepository<>(),
new BindingRepository<>()));
bind(ServerConfig.class)
.toInstance(new ServerConfig(new ServerConfig.Builder()));
bind(ServletPathsConfig.class)
.toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
}
},
new ConnectorFactoryRegistryModule());
}
private static com.google.inject.Module newFilterModule(
final BindingRepository<RequestFilter> requestFilters,
final BindingRepository<ResponseFilter> responseFilters) {
return Modules.combine(
new AbstractModule() {
@Override
protected void configure() {
bind(FilterBindings.class).toInstance(
new FilterBindings(
requestFilters != null ? requestFilters : EMPTY_REQUEST_FILTER_REPOSITORY,
responseFilters != null ? responseFilters : EMPTY_RESPONSE_FILTER_REPOSITORY));
bind(ServerConfig.class).toInstance(new ServerConfig(new ServerConfig.Builder()));
bind(ConnectorConfig.class).toInstance(new ConnectorConfig(new ConnectorConfig.Builder()));
bind(ServletPathsConfig.class).toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
}
},
new ConnectorFactoryRegistryModule());
}
private static Module getRuntimeModule(String transport, String host, int port, Properties joynrConfig) {
Module runtimeModule;
if (transport != null) {
if (transport.contains("websocketcc")) {
configureWebSocket(host, port, joynrConfig);
runtimeModule = new CCWebSocketRuntimeModule();
} else if (transport.contains("websocket")) {
configureWebSocket(host, port, joynrConfig);
runtimeModule = new LibjoynrWebSocketRuntimeModule();
} else {
runtimeModule = new CCInProcessRuntimeModule();
}
Module backendTransportModules = Modules.EMPTY_MODULE;
if (transport.contains("http")) {
backendTransportModules = Modules.combine(backendTransportModules, new AtmosphereMessagingModule());
}
if (transport.contains("mqtt")) {
configureMqtt(joynrConfig);
backendTransportModules = Modules.combine(backendTransportModules, new HivemqMqttClientModule());
}
return Modules.override(runtimeModule).with(backendTransportModules);
}
return Modules.override(new CCInProcessRuntimeModule()).with(new HivemqMqttClientModule());
}
@Override
public void configure(final Binder binder) {
Stream.of(Platform.getExtensionRegistry().getConfigurationElementsFor(OVERRIDING_GUICE_MODULE_EXTENSION_POINT)).sorted((a, b) -> {
int aPriority = Integer.parseInt(a.getAttribute(OVERRIDING_GUICE_MODULE_EXTENSION_PRIORITY));
int bPriority = Integer.parseInt(b.getAttribute(OVERRIDING_GUICE_MODULE_EXTENSION_PRIORITY));
return aPriority - bPriority;
}).map(element -> {
try {
return (Module) element.createExecutableExtension(OVERRIDING_GUICE_MODULE_EXTENSION_CLASS);
} catch (CoreException e) {
LOGGER.log(Level.ERROR, "Overriding guice module from " + element.getContributor() + " could not be instatiated and has been skipped.", e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}).filter(Objects::nonNull).reduce((dummy) -> {}, (previous, next) -> {
LOGGER.log(Level.DEBUG, "Overriding guice module with " + next.getClass().getName()); //$NON-NLS-1$
return Modules.override(previous).with(next);
}).configure(binder);
}
public static Module authenticatorModule(String name, Class<? extends Authenticator> clazz, Module module)
{
checkArgument(name.toLowerCase(ENGLISH).equals(name), "name is not lower case: %s", name);
Module authModule = binder -> authenticatorBinder(binder).addBinding(name).to(clazz).in(Scopes.SINGLETON);
return installModuleIf(
SecurityConfig.class,
config -> authenticationTypes(config).contains(name),
Modules.combine(module, authModule));
}
public static Module webUiAuthenticator(String name, Class<? extends Authenticator> clazz, Module module)
{
checkArgument(name.toLowerCase(ENGLISH).equals(name), "name is not lower case: %s", name);
Module authModule = binder -> {
binder.install(new FormUiAuthenticatorModule(false));
newOptionalBinder(binder, Key.get(Authenticator.class, ForWebUi.class)).setBinding().to(clazz).in(SINGLETON);
};
return webUiAuthenticator(name, Modules.combine(module, authModule));
}