下面列出了org.junit.runners.model.InitializationError#com.google.inject.Injector 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String getMultipleSingletonStatusString(Multimap<Class<?>, Injector> singletonInstances,
Map<Injector, String> injectors) {
// sort to preserve output order
List<Class<?>> sortedByClassName = new ArrayList<>(singletonInstances.keySet());
Comparator<Class<?>> comparatorByClassName = new Comparator<>() {
@Override
public int compare(Class<?> c1, Class<?> c2) {
return c1.getName().compareTo(c2.getName());
}
};
Collections.sort(sortedByClassName, comparatorByClassName);
String status = "";
int multipleInstancesCount = 0;
for (Class<?> singleton : sortedByClassName) {
String outputForInstance = printInjectorsForInstances(singleton, injectors);
if (outputForInstance.length() > 0) {
status += outputForInstance;
multipleInstancesCount++;
}
}
status = "Found multiple instances for " + multipleInstancesCount + " singleton classes:\n" + status;
return status;
}
@Before
public void setUpEditor() throws Exception {
IResourceServiceProvider rsp = IResourceServiceProvider.Registry.INSTANCE
.getResourceServiceProvider(URI.createURI("dummy.testlanguage"));
rsp.get(Injector.class).injectMembers(this);
IFile file = IResourcesSetupUtil.createFile("test/foo.testlanguage", "stuff foo");
editor = openEditor(file);
syncUtil.yieldToQueuedDisplayJobs(new NullProgressMonitor());
editor.getSite().getPage().activate(editor);
syncUtil.yieldToQueuedDisplayJobs(new NullProgressMonitor());
events = new ArrayList<>();
editor.getDirtyStateEditorSupport().getDirtyStateManager().addListener(e -> events.add(e));
myDisplay = editor.getSite().getShell().getDisplay();
myDisplay.getShells()[0].forceActive();
syncUtil.yieldToQueuedDisplayJobs(new NullProgressMonitor());
styledText = editor.getInternalSourceViewer().getTextWidget();
styledText.setCaretOffset(9);
styledText.setFocus();
syncUtil.waitForReconciler(editor);
syncUtil.yieldToQueuedDisplayJobs(new NullProgressMonitor());
Thread.sleep(20);
Assert.assertTrue(events.isEmpty());
}
@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)));
}
private static XtextResource doGetResource(Injector injector,
InputStream in, URI uri) throws Exception {
XtextResourceSet rs = injector.getInstance(XtextResourceSet.class);
rs.setClasspathURIContext(DotEditorUtils.class);
XtextResource resource = (XtextResource) injector
.getInstance(IResourceFactory.class).createResource(uri);
rs.getResources().add(resource);
resource.load(in, null);
if (resource instanceof LazyLinkingResource) {
((LazyLinkingResource) resource)
.resolveLazyCrossReferences(CancelIndicator.NullImpl);
} else {
EcoreUtil.resolveAll(resource);
}
return resource;
}
@Override
public void install(final AbstractBinder binder, final Injector injector, final Class<Object> type) {
final boolean hkExtension = isJerseyExtension(type);
final boolean forceSingleton = isForceSingleton(type, hkExtension);
// since jersey 2.26 internal hk Factory class replaced by java 8 Supplier
if (is(type, Supplier.class)) {
// register factory directly (without wrapping)
bindFactory(binder, injector, type, hkExtension, forceSingleton);
} else {
// support multiple extension interfaces on one type
final Set<Class<?>> extensions = Sets.intersection(EXTENSION_TYPES,
GenericsResolver.resolve(type).getGenericsInfo().getComposingTypes());
if (!extensions.isEmpty()) {
for (Class<?> ext : extensions) {
bindSpecificComponent(binder, injector, type, ext, hkExtension, forceSingleton);
}
} else {
// no known extension found
bindComponent(binder, injector, type, hkExtension, forceSingleton);
}
}
}
@Override
public boolean configure(FeatureContext context) {
InjectionManager injectionManager = InjectionManagerProvider.getInjectionManager(context);
ServiceLocator locator;
if (injectionManager instanceof ImmediateHk2InjectionManager) {
locator = ((ImmediateHk2InjectionManager) injectionManager).getServiceLocator();
} else if (injectionManager instanceof DelayedHk2InjectionManager) {
locator = ((DelayedHk2InjectionManager) injectionManager).getServiceLocator();
} else {
throw new IllegalStateException("expected an hk2 injection manager");
}
GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
// register all your modules, here
Injector injector = Guice.createInjector(new GreetingModule());
GuiceIntoHK2Bridge guiceBridge = locator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);
return true;
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MavenModule(), new MavenCommandOptionsModule(), new XmlModule());
OptionalArgs optionalArgs = injector.getInstance(OptionalArgs.class);
JCommander jCommander = JCommander.newBuilder().addObject(optionalArgs).build();
jCommander.setProgramName("mvnUploader");
jCommander.parse(args);
if (optionalArgs.isHelp()){
jCommander.usage();
} else {
logger.info("Welcome To Maven Artifacts Uploader");
Uploader uploader = injector.getInstance(Uploader.class);
uploader.uploadToRepository(Paths.get(optionalArgs.getPathToArtifacts()));
logger.info("Done uploading all the artifacts!");
}
}
/**
* Parse single guice element.
*
* @param injector injector instance
* @param element element to analyze
* @return parsed descriptor or null if element is not supported (or intentionally skipped)
*/
public static BindingDeclaration parseElement(final Injector injector, final Element element) {
final BindingDeclaration dec = element.acceptVisitor(ELEMENT_VISITOR);
if (dec != null) {
fillDeclaration(dec, injector);
fillSource(dec, element);
dec.setModule(BindingUtils.getModules(element).get(0));
if (dec.getKey() != null) {
final Class ann = dec.getKey().getAnnotationType();
if (ann != null) {
if (ann.getName().equals("com.google.inject.internal.Element")) {
dec.setSpecial(Collections.singletonList("multibinding"));
}
if (ann.getName().startsWith("com.google.inject.internal.RealOptionalBinder")) {
dec.setSpecial(Collections.singletonList("optional binding"));
}
}
}
}
return dec;
}
@Override
public void init( ServiceInfo info ) {
super.init(info);
smf = getApplicationContext().getBean(ServiceManagerFactory.class);
emf = getApplicationContext().getBean(EntityManagerFactory.class);
Properties props = (Properties)getApplicationContext().getBean("properties");
metricsService = getApplicationContext().getBean(Injector.class).getInstance(MetricsFactory.class);
postMeter = metricsService.getMeter(NotificationsService.class, "collection.post_requests");
postTimer = metricsService.getTimer(this.getClass(), "collection.post_requests");
JobScheduler jobScheduler = new JobScheduler(sm,em);
String name = ApplicationQueueManagerImpl.getQueueNames( props );
LegacyQueueScope queueScope = new LegacyQueueScopeImpl( name, LegacyQueueScope.RegionImplementation.LOCAL);
queueManagerFactory = getApplicationContext().getBean( Injector.class ).getInstance(LegacyQueueManagerFactory.class);
LegacyQueueManager legacyQueueManager = queueManagerFactory.getQueueManager(queueScope);
applicationQueueManagerCache = getApplicationContext().getBean(Injector.class).getInstance(ApplicationQueueManagerCache.class);
notificationQueueManager = applicationQueueManagerCache
.getApplicationQueueManager(em, legacyQueueManager, jobScheduler, metricsService ,props);
gracePeriod = JobScheduler.SCHEDULER_GRACE_PERIOD;
}
@Test
public void testSetGcdParticipantIdInRoutingTableCalledOnlyForGcdDiscoveryEntry() throws Exception {
Set<DiscoveryEntry> discoveryEntries = createDiscoveryEntries("io.joynr",
GlobalCapabilitiesDirectory.INTERFACE_NAME,
GlobalDomainAccessController.INTERFACE_NAME);
final String serializedDiscoveryEntries = objectMapper.writeValueAsString(discoveryEntries);
Injector injector = createInjectorForJsonValue(serializedDiscoveryEntries);
injector.getInstance(CapabilitiesProvisioning.class);
ArgumentCaptor<String> gcdParticipantIdCaptor = ArgumentCaptor.forClass(String.class);
verify(routingTable, times(1)).setGcdParticipantId(gcdParticipantIdCaptor.capture());
String gcdParticpantId = gcdParticipantIdCaptor.getValue();
assertTrue(gcdParticpantId.contains(GlobalCapabilitiesDirectory.INTERFACE_NAME));
}
public static IProject createPluginProject(String name) throws CoreException {
Injector injector = XbaseActivator.getInstance().getInjector("org.eclipse.xtext.xbase.Xbase");
PluginProjectFactory projectFactory = injector.getInstance(PluginProjectFactory.class);
projectFactory.setProjectName(name);
projectFactory.setBreeToUse(JREContainerProvider.PREFERRED_BREE);
projectFactory.addFolders(Collections.singletonList("src"));
projectFactory.addBuilderIds(
JavaCore.BUILDER_ID,
"org.eclipse.pde.ManifestBuilder",
"org.eclipse.pde.SchemaBuilder",
XtextProjectHelper.BUILDER_ID);
projectFactory.addProjectNatures(JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature", XtextProjectHelper.NATURE_ID);
projectFactory.addRequiredBundles(Collections.singletonList("org.eclipse.xtext.xbase.lib"));
IProject result = projectFactory.createProject(new NullProgressMonitor(), null);
JavaProjectSetupUtil.makeJava8Compliant(JavaCore.create(result));
JavaProjectSetupUtil.setUnixLineEndings(result);
return result;
}
public static void create(AtomicReference<Injector> injector, final Properties properties, Module... modules) throws Exception {
// Create the injector
injector.set(LifecycleInjector.builder()
.withBootstrapModule(
new BootstrapModule() {
@Override
public void configure(BootstrapBinder binder) {
binder.bindConfigurationProvider().toInstance(
new PropertiesConfigurationProvider(properties));
}
}
)
.withModules(
new RoutingPlugin(),
new ServerSinkPlugin(),
new SuroInputPlugin(),
new SuroDynamicPropertyModule(),
new SuroModule(),
StatusServer.createJerseyServletModule()
)
.withAdditionalModules(modules)
.build().createInjector());
}
@Test
public void testConvertDelayParameter() {
Injector injector = StartupListener.INJECTOR;
QueueResource queueResource = injector.getInstance( QueueResource.class );
Assert.assertEquals( 0L, queueResource.convertDelayParameter( "" ).longValue() );
Assert.assertEquals( 0L, queueResource.convertDelayParameter( "0" ).longValue() );
Assert.assertEquals( 0L, queueResource.convertDelayParameter( "NONE" ).longValue() );
Assert.assertEquals( 5L, queueResource.convertDelayParameter( "5" ).longValue() );
try {
queueResource.convertDelayParameter( "bogus value" );
fail("Expected exception on bad value");
} catch ( IllegalArgumentException expected ) {
// pass
}
}
public void testParseMultipleClassesAndPackages() throws Exception {
Injector injector = Guice.createInjector(new ConfigModule(new String[]{
"-cp", "not/default/path",
"com.google.FirstClass",
"com.google.second.package",
"com.google.third.package"}, outStream, errStream));
CommandLineConfig commandLineConfig = injector.getInstance(CommandLineConfig.class);
assertEquals("", err.toString());
assertEquals("not/default/path", commandLineConfig.cp);
List<String> expectedArgs = new ArrayList<String>();
expectedArgs.add("com.google.FirstClass");
expectedArgs.add("com.google.second.package");
expectedArgs.add("com.google.third.package");
assertNotNull(commandLineConfig.entryList);
assertEquals(expectedArgs, commandLineConfig.entryList);
}
public Injector getInjector(String language) {
synchronized (injectors) {
Injector injector = injectors.get(language);
if (injector == null) {
injectors.put(language, injector = createInjector(language));
}
return injector;
}
}
@Override
public Injector createInjectorAndDoEMFRegistration() {
TerminalsStandaloneSetup.doSetup();
Injector injector = createInjector();
register(injector);
return injector;
}
public static <T> Injector testPage(Class<? extends View> page, Class<T> api,
T impl, Map<String,String> params, Module... modules) {
Injector injector = createMockInjector(api, impl, modules);
View view = injector.getInstance(page);
if(params != null) {
for(Map.Entry<String, String> entry: params.entrySet()) {
view.set(entry.getKey(), entry.getValue());
}
}
view.render();
flushOutput(injector);
return injector;
}
@Test
public void testArgumentMissAlpha() throws Exception {
Injector injector = Guice.createInjector(new JavaTestModule());
YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
String errorMessage = null;
try {
CompiledProgram program = compiler.compile("" +
"PROGRAM (@a int32);" +
"SELECT * FROM innersource WHERE iid = a OUTPUT AS b1;");
} catch (ProgramCompileException e) {
errorMessage = e.getMessage();
}
Assert.assertTrue(errorMessage.contains("L1:57"));
}
public NullContext(FileObject location, IProject project, ILanguageImpl language, Injector injector) {
this.identifier = new ContextIdentifier(location, project, language);
this.location = location;
this.project = project;
this.language = language;
this.injector = injector;
}
@Override
protected void createLeftColumnControls(Composite parent) {
Label lblExpression = getToolkit().createLabel(parent, "Expression: ");
GridDataFactory.fillDefaults().span(2, 1).applyTo(lblExpression);
Injector injector = getInjector(Transition.class.getName());
if (injector != null) {
textControl = new StyledText(parent, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP);
((StyledText) textControl).setAlwaysShowScrollBars(false);
createHelpWidget(parent, textControl, HelpContextIds.SC_PROPERTIES_TRANSITION_EXPRESSION);
} else {
textControl = getToolkit().createText(parent, "", SWT.MULTI);
}
GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize()).applyTo(textControl);
}
public XtextFakeResourceContext(Injector injector, IProject activeProject) {
this.activeProject = activeProject;
injector.injectMembers(this);
// create resource set
createXtextFakeResourceSet();
// initialize fake resource (which was injected and thus does not has to
// be created)
initXtextFakeResource();
// initialize the resource set (the fake resource has to be added)
initXtextFakeResourceSet();
}
@Test
void shouldThrowWhenInjectorIsMissing() {
Optional<AnnotatedElement> optional = Optional.of(annotatedElement);
when(context.getElement()).thenReturn(optional);
when(store.getOrComputeIfAbsent(any(), any(), eq(Injector.class)))
.thenThrow(NoSuchElementException.class);
when(context.getStore(namespace)).thenReturn(store);
assertThrows(NoSuchElementException.class,
() -> InjectorUtils.retrieveInjectorFromStore(context, namespace));
}
/**
* Creates a new resource instance given with the resource class.
*
* @param clazz
* the class to instantiate.
* @return the new instance of the class.
*/
public BaseResource createResource(final Class<? extends BaseResource> clazz) {
try {
BaseResource resource = clazz.getConstructor().newInstance();
Injector injector = injectedInjector;
injector.injectMembers(resource);
return resource;
} catch (final Exception e) {
LOGGER.error("Error while creating resource for class: " + clazz + ";", e);
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
private void initializeLoadBalancerFactory(Injector localInjector) {
ServiceDiscoveryProvider provider = localInjector.getInstance(ServiceDiscoveryProvider.class);
if (provider != null) {
LoadBalancerFactory lbFactory = localInjector.getInstance(LoadBalancerFactory.class);
lbFactory.initialize(provider);
}
}
@Override
public Injector getInjector() {
if (injector == null) {
stateBeforeInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
this.injector = internalCreateInjector();
stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
}
return injector;
}
public void setUp() throws Exception {
System.setProperty("archaius.deployment.applicationId", "middletier");
System.setProperty("archaius.deployment.environment", "ci");
Injector injector = LifecycleInjector.builder().withModules(new RSSModule()).createInjector();
LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class);
lifecycleManager.start();
middleTierServer = injector.getInstance(MiddleTierServer.class);
middleTierServer.start();
}
public void register(Injector injector) {
IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("bug289524testlanguage", resourceFactory);
IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("bug289524testlanguage", serviceProvider);
if (!EPackage.Registry.INSTANCE.containsKey("http://eclipse.org/xtext/Bug289524TestLanguage")) {
EPackage.Registry.INSTANCE.put("http://eclipse.org/xtext/Bug289524TestLanguage", Bug289524TestPackage.eINSTANCE);
}
}
@Override
public Injector getInjector() {
if (injector == null) {
this.injector = internalCreateInjector();
stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
}
return injector;
}
/**
* Convenience method to get the table description supplier.
*
* @param inj
* @return
*/
public static KinesisTableDescriptionSupplier getTableDescSupplier(Injector inj)
{
requireNonNull(inj, "Injector is missing in getTableDescSupplier");
Supplier<Map<SchemaTableName, KinesisStreamDescription>> supplier =
inj.getInstance(Key.get(new TypeLiteral<Supplier<Map<SchemaTableName, KinesisStreamDescription>>>() {}));
requireNonNull(inj, "Injector cannot find any table description supplier");
return (KinesisTableDescriptionSupplier) supplier;
}
public OutputManager createOutputManager() {
final List<Module> modules = Lists.newArrayList();
modules.add(new AbstractModule() {
@Override
protected void configure() {
bind(new TypeLiteral<List<PluginSink>>() {
}).toInstance(ImmutableList.of(sink));
bind(AsyncFramework.class).toInstance(async);
bind(new TypeLiteral<Map<String, String>>() {
}).annotatedWith(Names.named("tags")).toInstance(tags);
bind(new TypeLiteral<Map<String, String>>() {
}).annotatedWith(Names.named("tagsToResource")).toInstance(tagsToResource);
bind(new TypeLiteral<Map<String, String>>() {
}).annotatedWith(Names.named("resource")).toInstance(resource);
bind(new TypeLiteral<Set<String>>() {
}).annotatedWith(Names.named("riemannTags")).toInstance(riemannTags);
bind(new TypeLiteral<Set<String>>() {
}).annotatedWith(Names.named("skipTagsForKeys")).toInstance(skipTagsForKeys);
bind(Boolean.class)
.annotatedWith(Names.named("automaticHostTag"))
.toInstance(automaticHostTag);
bind(String.class).annotatedWith(Names.named("host")).toInstance(host);
bind(long.class).annotatedWith(Names.named("ttl")).toInstance(ttl);
bind(Integer.class).annotatedWith(Names.named("rateLimit")).toProvider(Providers.of(rateLimit));
bind(DebugServer.class).toInstance(debugServer);
bind(OutputManagerStatistics.class).toInstance(statistics);
bind(Filter.class).toInstance(filter);
bind(OutputManager.class).to(CoreOutputManager.class);
bind(Long.class).annotatedWith(Names.named("cardinalityLimit")).toProvider(Providers.of(cardinalityLimit));
bind(Long.class).annotatedWith(Names.named("hyperLogLogPlusSwapPeriodMS")).toProvider(Providers.of(
hyperLogLogPlusSwapPeriodMS));
}
});
final Injector injector = Guice.createInjector(modules);
return injector.getInstance(OutputManager.class);
}