下面列出了org.junit.jupiter.api.extension.ExtendWith#com.google.inject.Key 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Node lookupOrCreateGlobalComponent(Node node, Injector fallbackInjector, Class<?> clazz, Key<?> key) {
Optional<Node> component = lookupGlobalComponent(key);
if (component.isEmpty()) {
Object instance;
try {
log.log(Level.FINE, "Trying the fallback injector to create" + messageForNoGlobalComponent(clazz, node));
instance = fallbackInjector.getInstance(key);
} catch (ConfigurationException e) {
throw removeStackTrace(new IllegalStateException(
(messageForMultipleClassLoaders(clazz).isEmpty()) ? "No global" + messageForNoGlobalComponent(clazz, node)
: messageForMultipleClassLoaders(clazz)));
}
component = Optional.of(matchingGuiceNode(key, instance).orElseGet(() -> {
GuiceNode guiceNode = new GuiceNode(instance, key.getAnnotation());
add(guiceNode);
return guiceNode;
}));
}
return component.get();
}
int execute(String cliCommand, CliContext cliContext, Map<String, String> kernelParameters) throws Exception {
if (launched.compareAndSet(false, true)) {
KernelConfiguration kernelConfiguration = NuunCore.newKernelConfiguration();
for (Map.Entry<String, String> kernelParameter : kernelParameters.entrySet()) {
kernelConfiguration.param(kernelParameter.getKey(), kernelParameter.getValue());
}
kernel = Seed.createKernel(cliContext, kernelConfiguration, true);
CommandLineHandler cliHandler;
try {
cliHandler = kernel.objectGraph()
.as(Injector.class)
.getInstance(Key.get(CommandLineHandler.class, Names.named(cliCommand)));
LOGGER.info("Executing CLI command {}, handled by {}",
cliCommand,
cliHandler.getClass().getCanonicalName());
} catch (ConfigurationException e) {
throw SeedException.wrap(e, CliErrorCode.COMMAND_LINE_HANDLER_NOT_FOUND)
.put("commandLineHandler", cliCommand);
}
return cliHandler.call();
} else {
throw SeedException.createNew(CliErrorCode.COMMAND_LINE_HANDLER_ALREADY_RUN);
}
}
@Test
public void testInsecureAuthenticatorHttpsOnly()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.allow-insecure-over-http", "false")
.build())
.build()) {
server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl());
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
assertAuthenticationDisabled(httpServerInfo.getHttpUri());
assertInsecureAuthentication(httpServerInfo.getHttpsUri());
}
}
@SuppressWarnings({"unchecked"})
@Test
public void testGetRepositoryTypeOfOfTString(final @Mocked Repository<AggregateRoot<Long>, Long> repository1) {
DomainRegistry domainRegistry = createDomainRegistry();
new Expectations() {
{
injector.getInstance((Key<Repository<AggregateRoot<Long>, Long>>) any);
result = repository1;
}
};
Repository<AggregateRoot<Long>, Long> repository2 = domainRegistry.getRepository(
new TypeLiteral<Repository<AggregateRoot<Long>, Long>>() {}.getType(), "dummyAnnotation");
assertThat(repository2).isEqualTo(repository1);
}
@Test
public void testFixedManagerAuthenticatorHttpInsecureEnabledOnly()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "password")
.put("http-server.authentication.allow-insecure-over-http", "true")
.put("management.user", MANAGEMENT_USER)
.build())
.build()) {
server.getInstance(Key.get(PasswordAuthenticatorManager.class)).setAuthenticator(TestResourceSecurity::authenticate);
server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl());
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
assertFixedManagementUser(httpServerInfo.getHttpUri(), true);
assertPasswordAuthentication(httpServerInfo.getHttpsUri());
}
}
@Test
public void testFixedAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("web-ui.authentication.type", "fixed")
.put("web-ui.user", "test-user")
.build())
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testAlwaysAuthorized(httpServerInfo.getHttpUri(), client, nodeId);
testAlwaysAuthorized(httpServerInfo.getHttpsUri(), client, nodeId);
testFixedAuthenticator(httpServerInfo.getHttpUri());
testFixedAuthenticator(httpServerInfo.getHttpsUri());
}
}
@SuppressWarnings({"unchecked"})
@Test
public void testGetServiceTypeOfOfTString(final @Mocked MockedServiceParameterized<Long> service1) {
DomainRegistry domainRegistry = createDomainRegistry();
new Expectations() {
{
injector.getInstance((Key<MockedServiceParameterized<Long>>) any);
result = service1;
}
};
MockedServiceParameterized<Long> service2 = domainRegistry.getService(
new TypeLiteral<MockedServiceParameterized<Long>>() {}.getType(), "dummyAnnotation");
assertThat(service2).isEqualTo(service1);
}
@Test
public void testBindings() throws Exception {
Injector injector = createInjector(new AsyncModule(new AsyncModule.Options()));
control.replay();
Set<Service> services = injector.getInstance(
Key.get(new TypeLiteral<Set<Service>>() { }, AppStartup.class));
for (Service service : services) {
service.startAsync().awaitRunning();
}
injector.getBindings();
assertEquals(
ImmutableMap.of(
RegisterGauges.TIMEOUT_QUEUE_GAUGE, 0,
RegisterGauges.ASYNC_TASKS_GAUGE, 0L),
statsProvider.getAllValues()
);
}
@SuppressWarnings("unchecked")
protected <T> T get(Key<T> key, Provider<T> unscoped) {
T t = (T) objectsMap.get(key);
if (t == null) {
synchronized (lock) {
t = (T) objectsMap.get(key);
if (t == null) {
t = unscoped.get();
if (!Scopes.isCircularProxy(t)) {
objectsMap.put(key, t);
}
}
}
}
return t;
}
@Override
protected void configure(Binder binder) {
binder
.bind(new Key<Set<GroovyDriverPlugin>>() {})
.toInstance(getPlugins());
binder.bind(InMemoryPlatformMessageBus.class).in(Singleton.class);
binder.bind(InMemoryProtocolMessageBus.class).in(Singleton.class);
binder.bind(PlatformMessageBus.class).to(InMemoryPlatformMessageBus.class);
binder.bind(ProtocolMessageBus.class).to(InMemoryProtocolMessageBus.class);
Multibinder.newSetBinder(binder, CompilationCustomizer.class)
.addBinding()
.to(DriverCompilationCustomizer.class);
binder
.bind(Scheduler.class)
.toInstance(new ExecutorScheduler(Executors.newScheduledThreadPool(1)))
;
}
@BeforeClass
public static void setup() throws Throwable {
final Injector injector = Guice.createInjector().createChildInjector(new SPIModule());
Globals.set(Injector.class, injector);
final Set<String> moduleNames = SPILoader.spiNames(Module.class);
if (!CollectionUtils.isEmpty(moduleNames)) {
final List<Module> loadedModules = Lists.newArrayList();
for (final String moduleName : moduleNames) {
final Module module = injector.getInstance(Key.get(Module.class, Names.named(moduleName)));
module.config(config);
loadedModules.addAll(module.load());
}
Globals.set(Injector.class, injector.createChildInjector(loadedModules));
}
}
@Test
public void testNativeUnitModule(@Mocked final CryptoModule module, @Mocked final SSLContext sslContext,
@Mocked final KeyStore trustStore, @Mocked final KeyManagerAdapter keyManagerAdapter) {
final Map<Key<EncryptionService>, EncryptionService> encryptionServices = new HashMap<>();
final Map<String, KeyStore> keyStores = new HashMap<>();
final CryptoPlugin underTest = new CryptoPlugin();
Deencapsulation.setField(underTest, "encryptionServices", encryptionServices);
Deencapsulation.setField(underTest, "keyStores", keyStores);
Deencapsulation.setField(underTest, "sslContext", sslContext);
Deencapsulation.setField(underTest, "trustStore", trustStore);
List<KeyManagerAdapter> keyManagerAdapters = Lists.newArrayList(keyManagerAdapter);
Deencapsulation.setField(underTest, "keyManagerAdapters", keyManagerAdapters);
underTest.nativeUnitModule();
new Verifications() {{
new CryptoModule(encryptionServices, keyStores, trustStore, sslContext, keyManagerAdapters, null);
times = 1;
}};
}
@Override
protected void configure() {
bind(Integer.class).annotatedWith(NumRefPartitions.class).toInstance(REF_PARTITIONS);
bind(RateLimitedLogFactory.class).to(DefaultRateLimitedLogFactory.class).asEagerSingleton();
bind(String.class).annotatedWith(TableEventRegistrationId.class).to(Key.get(String.class, MegabusApplicationId.class));
bind(Service.class).annotatedWith(MegabusRefResolverService.class).to(ResilientMegabusRefResolver.class).asEagerSingleton();
bind(Service.class).annotatedWith(MissingRefDelayService.class).to(ResilientMissingRefDelayProcessor.class).asEagerSingleton();
bind(Service.class).annotatedWith(TableEventRegistrationService.class).to(TableEventRegistrar.class).asEagerSingleton();
bind(Service.class).annotatedWith(TableEventProcessorService.class).to(TableEventProcessorManager.class).asEagerSingleton();
bind(MegabusRefProducerManager.class).asEagerSingleton();
bind(MegabusBootWorkflowManager.class).asEagerSingleton();
bind(MegabusRefSubscriptionMonitorManager.class).asEagerSingleton();
bind(MegabusSource.class).to(DefaultMegabusSource.class).asEagerSingleton();
expose(MegabusSource.class);
bind(MegabusRefSubscriptionMonitorManager.class).asEagerSingleton();
}
@BeforeClass
public static void setup() throws Throwable {
PropertiesLoader.load("/cluster-scheduler-context.properties", true);
final Injector injector = Guice.createInjector().createChildInjector(new SPIModule());
Globals.set(Injector.class, injector);
final Set<String> moduleNames = SPILoader.spiNames(Module.class);
if (!CollectionUtils.isEmpty(moduleNames)) {
final List<Module> loadedModules = Lists.newArrayList();
for (final String moduleName : moduleNames) {
final Module module = injector.getInstance(Key.get(Module.class, Names.named(moduleName)));
module.config(config);
loadedModules.addAll(module.load());
}
Globals.set(Injector.class, injector.createChildInjector(loadedModules));
}
}
public TypeMapBinder(Binder binder, @Nullable TypeLiteral<K> keyType, @Nullable TypeLiteral<V> valueType) {
this.keyType = keyType != null ? keyType : new ResolvableType<K>(){}.in(getClass());
this.valueType = valueType != null ? valueType : new ResolvableType<V>(){}.in(getClass());
final TypeArgument<K> keyTypeArg = new TypeArgument<K>(this.keyType){};
final TypeArgument<V> valueTypeArg = new TypeArgument<V>(this.valueType){};
this.collectionKey = Key.get(new ResolvableType<TypeMap<K, V>>(){}.with(keyTypeArg, valueTypeArg));
this.backingCollectionKey = Key.get(new ResolvableType<Map<TypeToken<? extends K>, Set<V>>>(){}.with(keyTypeArg, valueTypeArg));
this.backingCollectionBinder = MapBinder.newMapBinder(
binder,
new ResolvableType<TypeToken<? extends K>>(){}.with(keyTypeArg),
this.valueType
).permitDuplicates();
binder.install(new KeyedManifest.Impl(collectionKey) {
@Override
public void configure() {
final Provider<Map<TypeToken<? extends K>, Set<V>>> backingCollectionProvider = getProvider(backingCollectionKey);
bind(collectionType()).toProvider(() -> ImmutableTypeMap.copyOf(backingCollectionProvider.get()));
}
});
}
@Test
public void testChildInjector() {
Injector parentInjector = Guice.createInjector();
Injector injector = parentInjector.createChildInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.bind(CharSequence.class).to(String.class);
}
});
Assert.assertNotNull(injector.getExistingBinding(Key.get(CharSequence.class)));
// Parent allows JIT bindings and those are always created in the ancestor
Assert.assertNotNull(injector.getExistingBinding(Key.get(String.class)));
CharSequence emptyString = injector.getInstance(CharSequence.class);
Assert.assertEquals("", emptyString);
Assert.assertNotNull(injector.getExistingBinding(Key.get(String.class)));
Assert.assertNotNull(parentInjector.getExistingBinding(Key.get(String.class)));
}
@SuppressWarnings("unchecked")
public ApplicationBindingBuilder addProviderInstance(Object object)
{
Key<Object> key = Key.get((Class<Object>) object.getClass(), UniqueAnnotations.create());
binder.bind(key).toInstance(object);
initializer.addProvider(key);
return this;
}
@Test(expected = ConfigurationException.class)
public void testEmptyChildInjectorNoJIT() {
Injector injector = Guice.createInjector().createChildInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.requireExplicitBindings();
}
});
Assert.assertNull(injector.getExistingBinding(Key.get(String.class)));
injector.getInstance(String.class);
}
@Override
protected void configure() {
for (Map.Entry<Key<?>, Class<?>> binding : bindings.entrySet()) {
LOGGER.trace("Overriding {} with {}", binding.getKey(), binding.getValue()
.getSimpleName());
bind(binding.getKey()).to(Classes.cast(binding.getValue()));
}
}
@SuppressWarnings("unchecked")
public <T> ApplicationBindingBuilder addResources(Class<T> annotatedClass, Provider<? extends T> resourceProvider)
{
Key<T> key = Key.get(annotatedClass, UniqueAnnotations.create());
binder.bind(key).toProvider(resourceProvider);
initializer.addResource((Key<Object>) key, annotatedClass);
return this;
}
@Test
public void testCertAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "certificate")
.put("http-server.https.truststore.path", LOCALHOST_KEYSTORE)
.put("http-server.https.truststore.key", "")
.build())
.build()) {
server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl());
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
assertAuthenticationDisabled(httpServerInfo.getHttpUri());
OkHttpClient.Builder clientBuilder = client.newBuilder();
setupSsl(
clientBuilder,
Optional.of(LOCALHOST_KEYSTORE),
Optional.empty(),
Optional.of(LOCALHOST_KEYSTORE),
Optional.empty());
OkHttpClient clientWithCert = clientBuilder.build();
assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithCert);
}
}
@Override
protected void configure() {
bind( MapManagerFactory.class ).to( MapManagerFactoryImpl.class );
bind( MapSerialization.class ).to( MapSerializationImpl.class );
Multibinder<Migration> migrationBinding = Multibinder.newSetBinder( binder(), Migration.class );
migrationBinding.addBinding().to( Key.get( MapSerialization.class ) );
}
@Override
protected void configure() {
bind(DatabusConfiguration.class).toInstance(_configuration.getDatabusConfiguration());
// Used by the databus resource to support long polling
bind(DatabusResourcePoller.class).asEagerSingleton();
bind(OwnerDatabusAuthorizer.class).asEagerSingleton();
// Bind the suppressed event condition setting as the supplier
bind(new TypeLiteral<Supplier<Condition>>(){}).annotatedWith(DefaultJoinFilter.class)
.to(Key.get(new TypeLiteral<Setting<Condition>>(){}, DefaultJoinFilter.class));
bind(DatabusDefaultJoinFilterConditionAdminTask.class).asEagerSingleton();
install(new DatabusModule(_serviceMode, _environment.metrics()));
}
/** Constructor.
*/
public SARLProjectConfigurator() {
final Injector injector = SARLEclipseExecutableExtensionFactory.getSARLInjector();
final String fileExtension = injector.getInstance(
Key.get(String.class, Names.named(Constants.FILE_EXTENSIONS)));
if (Strings.isNullOrEmpty(fileExtension)) {
this.fileExtension = null;
} else {
this.fileExtension = "." + fileExtension; //$NON-NLS-1$
}
injector.injectMembers(this);
this.candidates = new ArrayList<>();
this.candidates.addAll(Arrays.asList(BundleUtil.SRC_FOLDERS));
this.candidates.add(SARLConfig.FOLDER_TEST_SOURCE_SARL);
}
/**
* Adds an attribute value.
*/
@SuppressWarnings("unchecked")
public <T> void addAttribute(Key<List<T>> key, T value) {
List<T> list = getAttribute(key);
if (list == null) {
list = Lists.newArrayList();
putAttribute(key, list);
}
list.add(value);
}
@Test
public void testJwtAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "jwt")
.put("http-server.authentication.jwt.key-file", HMAC_KEY)
.build())
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testLogIn(httpServerInfo.getHttpUri(), false);
testNeverAuthorized(httpServerInfo.getHttpsUri(), client);
String hmac = Files.readString(Paths.get(HMAC_KEY));
String token = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, hmac)
.setSubject("test-user")
.setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()))
.compact();
OkHttpClient clientWithJwt = client.newBuilder()
.authenticator((route, response) -> response.request().newBuilder()
.header(AUTHORIZATION, "Bearer " + token)
.build())
.build();
testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithJwt, nodeId);
}
}
@SuppressWarnings("unchecked")
@Test
public void testGetFactoryClassOfT(final @Mocked Factory<?> factory) {
DomainRegistry domainRegistry = createDomainRegistry();
new Expectations() {
{
injector.getInstance((Key<Factory<AggregateRoot<Long>>>) any);
result = factory;
}
};
assertThat(domainRegistry.getFactory(AggregateRoot.class)).isEqualTo(factory);
}
@SuppressWarnings("unchecked")
@Test
public void testGetServiceClassOfTClassOfQextendsAnnotation(final @Mocked MockedService service) {
DomainRegistry domainRegistry = createDomainRegistry();
new Expectations() {
{
injector.getInstance((Key<MockedService>) any);
result = service;
}
};
assertThat(domainRegistry.getService(MockedService.class, MockedAnnotation.class)).isEqualTo(service);
}
private boolean isPinpointBinding(Key<?> key) {
TypeLiteral<?> typeLiteral = key.getTypeLiteral();
if (typeLiteral != null && typeLiteral.toString().startsWith(PINPOINT_PACKAGE_PREFIX)) {
return true;
}
Class<? extends Annotation> annotationType = key.getAnnotationType();
if (annotationType != null) {
return annotationType.getName().startsWith(PINPOINT_PACKAGE_PREFIX);
}
return false;
}
@Override
public final void graph(Injector injector, Set<Key<?>> root)
throws IOException {
reset();
Iterable<Binding<?>> bindings = getBindings(injector, root);
Map<NodeId, NodeId> aliases = resolveAliases(aliasCreator
.createAliases(bindings));
createNodes(nodeCreator.getNodes(bindings), aliases);
createEdges(edgeCreator.getEdges(bindings), aliases);
postProcess();
}