下面列出了com.google.inject.spi.DefaultElementVisitor#com.google.inject.util.Providers 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void setup(Binder binder)
{
configBinder(binder).bindConfig(BackupConfig.class);
String provider = buildConfigObject(BackupConfig.class).getProvider();
if (provider == null) {
binder.bind(BackupStore.class).toProvider(Providers.of(null));
}
else {
Module module = providers.get(provider);
if (module == null) {
binder.addError("Unknown backup provider: %s", provider);
}
else if (module instanceof ConfigurationAwareModule) {
install(module);
}
else {
binder.install(module);
}
}
binder.bind(BackupService.class).to(BackupServiceManager.class).in(Scopes.SINGLETON);
}
@Test public void testOutgoingReferencesToAnotherResourceWithBuilderStateNoAffection() {
String exportedName = "exportedName";
String importedName = "importedName";
testMe.setBuilderStateProvider(Providers.<IResourceDescriptions>of(new MyBuilderState(exportedName)));
documentResource.importedName = importedName;
documentURI = URI.createURI("document");
targetURI = URI.createURI("target");
ReferenceDescriptionImpl reference = (ReferenceDescriptionImpl) BuilderStateFactory.eINSTANCE.createReferenceDescription();
reference.setTargetEObjectUri(URI.createURI("anothertarget"));
referenceDescriptions.add(reference);
noDocumentDescription = false;
announceDirtyStateChanged();
validationScheduled = false;
testMe.scheduleInitialValidation(document);
assertFalse(validationScheduled);
}
Formatter(final String pattern) {
final List<String> patterns = Splitter.on(VAR_BEGIN).omitEmptyStrings().splitToList(pattern);
patterns.forEach(pt -> {
if (!pt.contains(VAR_END)) {
appenderList.add(Providers.of(pt));
} else {
StringTokenizer token = new StringTokenizer(pt, VAR_END);
String guiceKey = token.nextToken();
String rawString = null;
if (token.hasMoreTokens()) {
rawString = token.nextToken();
}
final KeyResolver resolver = new KeyResolver(guiceKey);
appenderList.add(resolver);
resolvers.add(resolver);
appenderList.add(Providers.of(rawString));
}
});
}
@Test
public void constructor_does_not_blow_up_if_metricsListener_is_null() {
// given
AppServerConfig asc = new AppServerConfig(configForTesting) {
@Override
protected List<Module> getAppGuiceModules(Config appConfig) {
return Arrays.asList(
Modules.override(new AppGuiceModule(appConfig)).with(
binder -> binder
.bind(new TypeLiteral<CodahaleMetricsListener>() {})
.toProvider(Providers.of(null))),
new BackstopperRiposteConfigGuiceModule()
);
}
};
// expect
assertThat(asc.metricsListener()).isNull();
}
@Test
public void testPrivateUpgrades() {
List<Checkpoint> checkpoints = ImmutableList.of(
new org.sonatype.nexus.upgrade.example.CheckpointFoo()
);
List<Upgrade> upgrades = ImmutableList.of(
new org.sonatype.nexus.upgrade.example.UpgradePrivateModel_1_1(Providers.of(mock(DatabaseInstance.class)))
);
UpgradeManager upgradeManager = createUpgradeManager(checkpoints, upgrades);
List<Upgrade> plan = upgradeManager.selectUpgrades(ImmutableMap.of(), false);
assertThat(plan, contains(
instanceOf(org.sonatype.nexus.upgrade.example.UpgradePrivateModel_1_1.class)
));
}
@Test
public void testPrivateUpgradesWithMissingCheckpointDependenciesAreIllegal() {
List<Checkpoint> checkpoints = ImmutableList.of(
new org.sonatype.nexus.upgrade.example.CheckpointFoo()
);
List<Upgrade> upgrades = ImmutableList.of(
new org.sonatype.nexus.upgrade.bad.UpgradePrivateModel_1_2(Providers.of(mock(DatabaseInstance.class)))
);
UpgradeManager upgradeManager = createUpgradeManager(checkpoints, upgrades);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Found 2 problem(s) with upgrades:" + lineSeparator()
+ "Upgrade step org.sonatype.nexus.upgrade.bad.UpgradePrivateModel_1_2 "
+ "has undeclared model dependencies: [foo]" + lineSeparator()
+ "Upgrade step org.sonatype.nexus.upgrade.bad.UpgradePrivateModel_1_2 "
+ "does not trigger a checkpoint");
upgradeManager.selectUpgrades(ImmutableMap.of(), false);
}
@Test
public void testPrivateUpgradesWithoutAnyCheckpointsAreIllegal() {
List<Checkpoint> checkpoints = ImmutableList.of(
new org.sonatype.nexus.upgrade.example.CheckpointFoo()
);
List<Upgrade> upgrades = ImmutableList.of(
new org.sonatype.nexus.upgrade.bad.UpgradePrivateModel_1_3(Providers.of(mock(DatabaseInstance.class)))
);
UpgradeManager upgradeManager = createUpgradeManager(checkpoints, upgrades);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Found 1 problem(s) with upgrades:" + lineSeparator()
+ "Upgrade step org.sonatype.nexus.upgrade.bad.UpgradePrivateModel_1_3 "
+ "does not trigger a checkpoint");
upgradeManager.selectUpgrades(ImmutableMap.of(), false);
}
@Override protected void configure() {
bind(CliConfiguration.class).toInstance(config);
bind(JCommander.class).annotatedWith(Names.named("ParentCommander"))
.toInstance(parentCommander);
if (commander == null) {
bind(JCommander.class).annotatedWith(Names.named("Commander"))
.toProvider(Providers.of((JCommander) null));
bind(String.class).annotatedWith(Names.named("Command"))
.toProvider(Providers.of((String) null));
} else {
bind(JCommander.class).annotatedWith(Names.named("Commander")).toInstance(commander);
bindConstant().annotatedWith(Names.named("Command")).to(command);
}
bind(Map.class).annotatedWith(Names.named("CommandMap")).toInstance(commands);
}
@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);
}
@Override
protected void configure() {
logger.info("configure {}", this.getClass().getSimpleName());
final DataSender spanDataSender = newUdpSpanDataSender();
logger.debug("spanDataSender:{}", spanDataSender);
bind(DataSender.class).annotatedWith(SpanDataSender.class).toInstance(spanDataSender);
final DataSender statDataSender = newUdpStatDataSender();
logger.debug("statDataSender:{}", statDataSender);
bind(DataSender.class).annotatedWith(StatDataSender.class).toInstance(statDataSender);
bind(StorageFactory.class).to(TestSpanStorageFactory.class);
bind(PinpointClientFactory.class).toProvider(Providers.of((PinpointClientFactory)null));
EnhancedDataSender<Object> enhancedDataSender = newTcpDataSender();
logger.debug("enhancedDataSender:{}", enhancedDataSender);
TypeLiteral<EnhancedDataSender<Object>> dataSenderTypeLiteral = new TypeLiteral<EnhancedDataSender<Object>>() {};
bind(dataSenderTypeLiteral).toInstance(enhancedDataSender);
ServerMetaDataRegistryService serverMetaDataRegistryService = newServerMetaDataRegistryService();
bind(ServerMetaDataRegistryService.class).toInstance(serverMetaDataRegistryService);
bind(ApiMetaDataService.class).toProvider(MockApiMetaDataServiceProvider.class).in(Scopes.SINGLETON);
}
@Override
public PhoenixTransactionService getTransactionService(Configuration config, ConnectionInfo connInfo, int port) {
config.setInt(TxConstants.Service.CFG_DATA_TX_BIND_PORT, port);
int retryTimeOut = config.getInt(TxConstants.Service.CFG_DATA_TX_CLIENT_DISCOVERY_TIMEOUT_SEC,
TxConstants.Service.DEFAULT_DATA_TX_CLIENT_DISCOVERY_TIMEOUT_SEC);
ZKClientService zkClient = ZKClientServices.delegate(
ZKClients.reWatchOnExpire(
ZKClients.retryOnFailure(
ZKClientService.Builder.of(connInfo.getZookeeperConnectionString())
.setSessionTimeout(config.getInt(HConstants.ZK_SESSION_TIMEOUT,
HConstants.DEFAULT_ZK_SESSION_TIMEOUT))
.build(),
RetryStrategies.exponentialDelay(500, retryTimeOut, TimeUnit.MILLISECONDS)
)
)
);
DiscoveryService discovery = new ZKDiscoveryService(zkClient);
TransactionManager txManager = new TransactionManager(config, new HDFSTransactionStateStorage(config,
new SnapshotCodecProvider(config), new TxMetricsCollector()), new TxMetricsCollector());
TransactionService txService = new TransactionService(config, zkClient, discovery, Providers.of(txManager));
TephraTransactionService service = new TephraTransactionService(zkClient, txService);
service.start();
return service;
}
@Override
protected Module newIsisWicketModule() {
final Module isisDefaults = super.newIsisWicketModule();
final Module estatioOverrides = new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("applicationName")).toInstance("Estatio");
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("welcomeMessage")).toInstance("This is Estatio - an open source property management system implemented using Apache Isis.");
bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("Estatio");
bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
// if uncommented, overrides isis.properties
// bind(AppManifest.class).toInstance(new EstatioAppManifest());
}
};
return Modules.override(isisDefaults).with(estatioOverrides);
}
protected void bindPanels() {
bind(AbstractGroupsPanel.class).annotatedWith(SuitesPanel.class).toInstance(new BlurbGroupsPanel(GroupType.SUITE));
bind(AbstractGroupsPanel.class).annotatedWith(FeaturesPanel.class).toInstance(new BlurbGroupsPanel(GroupType.FEATURE));
bind(AbstractGroupsPanel.class).annotatedWith(StoriesPanel.class).toInstance(new BlurbGroupsPanel(GroupType.STORY));
bind(AbstractGroupsPanel.class).annotatedWith(IssuesPanel.class).toInstance(new BlurbGroupsPanel(GroupType.ISSUE));
bind(IGroupTabPane.class).toProvider(Providers.of(null));
}
/**
* Verifies that merging two extracts containing both overlapping and non-overlapping records results in having the overlapping records
* overwrite the already-present ones and the non-overlapping to be inserted.
*/
@Test
@Parameters(method = "mergeParameters")
public void testMergeTwoExtracts(File controlExtract, File initialDataset, File datasetToMerge) throws IOException {
// GIVEN
// ... a control extract (provided)
// ... a database with some data
SqlScriptExecutorProvider sqlScriptExecutorProvider = new SqlScriptExecutorProvider(connectionResources.getDataSource(), Providers.of(connectionResources.sqlDialect()));
log.info("Creating the initial DataSet");
DataSetConsumer firstDatabaseDataSetConsumer = new SchemaModificationAdapter(new DatabaseDataSetConsumer(connectionResources, sqlScriptExecutorProvider));
new DataSetConnector(toDataSetProducer(initialDataset), firstDatabaseDataSetConsumer).connect();
log.info("Initial DataSet creation complete");
// WHEN
// ... we merge a datasource having both overlapping and non-overlapping tables and records into it
DataSetConsumer mergingDatabaseDatasetConsumer = new MergingDatabaseDataSetConsumer(connectionResources, sqlScriptExecutorProvider);
new DataSetConnector(toDataSetProducer(datasetToMerge), mergingDatabaseDatasetConsumer).connect();
// ... and we pipe the result into a zip file
log.info("Creating an XML extract from the merged database tables.");
File mergedExtractsAsFile = getDatabaseAsFile();
log.info("Merged XML file creation complete.");
// THEN
// ... the resulting dataset matches the control one
assertThat("the merged dataset should match the control one", mergedExtractsAsFile, sameXmlFileAndLengths(controlExtract));
}
private <T, U extends T> void bindAnnotation(Binder binder, Class<T> type, @Nullable U object,
Annotation annotation) {
if (object != null && !type.isInstance(object)) {
throw new RuntimeException("Impossible state while binding flag annotations.");
}
binder.bind(type).annotatedWith(annotation).toProvider(Providers.of(object));
}
@Test public void testOutgoingReferencesToAnotherResourceWithBuilderState() {
String exportedName = "exportedName";
testMe.setBuilderStateProvider(Providers.<IResourceDescriptions>of(new MyBuilderState(exportedName)));
documentResource.importedName = exportedName;
documentURI = URI.createURI("document");
targetURI = URI.createURI("target");
ReferenceDescriptionImpl reference = (ReferenceDescriptionImpl) BuilderStateFactory.eINSTANCE.createReferenceDescription();
reference.setTargetEObjectUri(URI.createURI("anothertarget"));
referenceDescriptions.add(reference);
noDocumentDescription = false;
announceDirtyStateChanged();
validationScheduled = false;
testMe.scheduleInitialValidation(document);
assertTrue(validationScheduled);
}
@Override
public ModuleType findModule(Location location, ContextPlanner planner, List<String> modulePath) {
String name = Joiner.on(".").join(modulePath);
if("test".equals(name)) {
Provider<Exports> moduleProvider = Providers.of(new TestModule());
ExportUnitGenerator adapter = new ExportUnitGenerator(planner.getGambitScope());
return adapter.apply(modulePath, moduleProvider);
}
return super.findModule(location, planner, modulePath);
}
@BeforeMethod
public void setUp() {
_dataStore = new InMemoryDataStore(new MetricRegistry());
_cacheRegistry = mock(CacheRegistry.class);
_cacheHandle = mock(CacheHandle.class);
when(_cacheRegistry.register(eq("settings"), any(Cache.class), eq(true))).thenReturn(_cacheHandle);
_settingsManager = new SettingsManager(Providers.of(_dataStore), "__system:settings",
"app_global:sys", _cacheRegistry);
}
@Before
public void setup() {
BaseUrlHolder.set("http://baseurl/");
when(httpServletRequest.getParameter("debug")).thenReturn("false");
underTest =
new RaptureWebResourceBundle(applicationVersion, Providers.of(httpServletRequest), Providers.of(stateComponent),
templateHelper, asList(new UiPluginDescriptorImpl()),
asList(new ExtJsUiPluginDescriptorImpl("test-1"), new ExtJsUiPluginDescriptorImpl("test-2")));
}
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);
}
@Override
protected void configure() {
bind(ApplicationProviderService.class).toProvider(Providers.of(appProviderInst));
bind(ApplicationDescService.class).toProvider(Providers.of(appProviderInst));
bind(ApplicationManagementService.class).to(ApplicationManagementServiceImpl.class).in(Singleton.class);
bind(ApplicationStatusUpdateService.class).to(ApplicationStatusUpdateServiceImpl.class).in(Singleton.class);
bind(ApplicationHealthCheckService.class).to(ApplicationHealthCheckServiceImpl.class).in(Singleton.class);
}
public void assertAllDependenciesDeclared() {
List<Key> requiredKeys = new ArrayList<>();
List<Element> elements = Elements.getElements(module);
for (Element element : elements) {
element.acceptVisitor(new DefaultElementVisitor<Void>() {
@Override
public <T> Void visit(ProviderLookup<T> providerLookup) {
// Required keys are the only ones with null injection points.
if (providerLookup.getDependency().getInjectionPoint() == null) {
requiredKeys.add(providerLookup.getKey());
}
return null;
}
});
}
Injector injector = Guice.createInjector(module,
new AbstractModule() {
@Override
@SuppressWarnings("unchecked")
protected void configure() {
binder().disableCircularProxies();
binder().requireAtInjectOnConstructors();
binder().requireExactBindingAnnotations();
for (Key<?> key : requiredKeys) {
bind((Key) key).toProvider(Providers.of(null));
}
}
});
injector.getAllBindings();
}
@SuppressWarnings("unchecked")
private void bindValue(final LinkedBindingBuilder binding, final Object value) {
if (value != null) {
binding.toInstance(value);
} else {
binding.toProvider(Providers.of(null));
}
}
@Override
protected void configure() {
// Truststore
OptionalBinder.newOptionalBinder(binder(), Key.get(KeyStore.class, Names.named(TRUSTSTORE)));
if (trustStore != null) {
bind(KeyStore.class).annotatedWith(Names.named(TRUSTSTORE)).toInstance(trustStore);
}
// Keystore(s)
for (Entry<String, KeyStore> keyStoreEntry : this.keyStores.entrySet()) {
bind(Key.get(KeyStore.class, Names.named(keyStoreEntry.getKey()))).toInstance(keyStoreEntry.getValue());
}
// Encryption service(s)
for (Entry<Key<EncryptionService>, EncryptionService> entry : this.encryptionServices.entrySet()) {
bind(entry.getKey()).toInstance(entry.getValue());
}
// Hashing service
bind(HashingService.class).to(PBKDF2HashingService.class);
// SSL context
OptionalBinder.newOptionalBinder(binder(), SSLContext.class);
if (sslContext != null) {
bind(SSLContext.class).toInstance(sslContext);
}
// Bind custom X509KeyManager if any
if (keyManagerClass != null) {
bind(X509KeyManager.class).to(keyManagerClass);
} else {
bind(X509KeyManager.class).toProvider(Providers.of(null));
}
// KeyManager adapters should be injectable
keyManagerAdapters.forEach(this::requestInjection);
}
@Before
public void setUp() {
mockServlet = createMock(HttpServlet.class);
filter =
new ShiroKerberosPermissiveAuthenticationFilter(Providers.of(createMock(Subject.class)));
}
@Before
public void setUp() {
subject = createMock(Subject.class);
mockServlet = createMock(HttpServlet.class);
filter = new ShiroKerberosAuthenticationFilter(Providers.of(subject));
}
@Provides
@Singleton
ContextService getContextService(
Provider<ClusterCoordinator> clusterCoordinator,
Provider<GroupResourceInformation> resourceInformation,
Provider<WorkStats> workStats,
Provider<LegacyKVStoreProvider> kvStoreProvider,
Provider<FabricService> fabricService,
Provider<ConduitServer> conduitServer,
Provider<UserServer> userServer,
Provider<MaterializationDescriptorProvider> materializationDescriptorProvider,
Provider<QueryObserverFactory> queryObserverFactory,
Provider<AccelerationManager> accelerationManager,
Provider<AccelerationListManager> accelerationListManager,
Provider<NamespaceService.Factory> namespaceServiceFactory,
Provider<DatasetListingService> datasetListingService,
Provider<UserService> userService,
Provider<CatalogService> catalogService,
Provider<ConduitProvider> conduitProvider,
Provider<SpillService> spillService,
Provider<ConnectionReader> connectionReader,
Provider<OptionManager> optionManagerProvider,
Provider<SystemOptionManager> systemOptionManagerProvider,
Provider<OptionValidatorListing> optionValidatorListingProvider
) {
return new ContextService(
bootstrap,
clusterCoordinator,
resourceInformation,
workStats,
kvStoreProvider,
fabricService,
conduitServer,
userServer,
materializationDescriptorProvider,
queryObserverFactory,
accelerationManager,
accelerationListManager,
namespaceServiceFactory,
datasetListingService,
userService,
catalogService,
conduitProvider,
Providers.of(null),
spillService,
connectionReader,
CredentialsService::new,
() -> JobResultInfoProvider.NOOP,
optionManagerProvider,
systemOptionManagerProvider,
Providers.of(null),
Providers.of(null),
optionValidatorListingProvider,
allRoles
);
}
@Override
public void bootstrap(final Runnable shutdownHook, final SingletonRegistry bootstrapRegistry, ScanResult scanResult, DACConfig dacConfig, boolean isMaster) {
final DremioConfig config = dacConfig.getConfig();
final boolean embeddedZookeeper = config.getBoolean(DremioConfig.EMBEDDED_MASTER_ZK_ENABLED_BOOL);
final BootStrapContext bootStrapContext = new BootStrapContext(config, scanResult, bootstrapRegistry);
boolean isMasterless = config.isMasterlessEnabled();
bootstrapRegistry.bindSelf(bootStrapContext);
bootstrapRegistry.bind(BufferAllocator.class, bootStrapContext.getAllocator());
// Start cluster coordinator before all other services so that non master nodes can poll for master status
if (dacConfig.getClusterMode() == ClusterMode.LOCAL) {
bootstrapRegistry.bind(ClusterCoordinator.class, new LocalClusterCoordinator());
} else if (config.getBoolean(DremioConfig.NO_OP_CLUSTER_COORDINATOR_ENABLED)) {
isMasterless = true;
Preconditions.checkState(!isMaster);
bootstrapRegistry.bind(ClusterCoordinator.class, new NoOpClusterCoordinator());
} else {
// ClusterCoordinator has a runtime dependency on ZooKeeper. If no ZooKeeper server
// is present, ClusterCoordinator won't start, so this service should be initialized first.
final Provider<Integer> portProvider;
if (isMaster && embeddedZookeeper) {
ZkServer zkServer = new ZkServer(
config.getString(DremioConfig.EMBEDDED_MASTER_ZK_ENABLED_PATH_STRING),
config.getInt(DremioConfig.EMBEDDED_MASTER_ZK_ENABLED_PORT_INT),
dacConfig.autoPort);
bootstrapRegistry.bindSelf(zkServer);
portProvider = dacConfig.autoPort ? new Provider<Integer>(){
@Override
public Integer get() {
return bootstrapRegistry.lookup(ZkServer.class).getPort();
}} : null;
} else {
portProvider = null;
}
final ZKClusterCoordinator coord;
try {
coord = new ZKClusterCoordinator(config.getSabotConfig(), portProvider);
} catch (IOException e) {
throw new RuntimeException("Cannot instantiate the ZooKeeper cluster coordinator", e);
}
bootstrapRegistry.bind(ClusterCoordinator.class, coord);
}
// Start master election
if (isMaster && !config.getBoolean(DremioConfig.DEBUG_DISABLE_MASTER_ELECTION_SERVICE_BOOL)) {
bootstrapRegistry.bindSelf(new MasterElectionService(bootstrapRegistry.provider(ClusterCoordinator.class)));
}
final MasterStatusListener masterStatusListener;
if (!isMasterless) {
masterStatusListener = new MasterStatusListener(bootstrapRegistry.provider(ClusterCoordinator.class), config.getSabotConfig(), isMaster);
} else {
masterStatusListener =
new MasterlessStatusListener(bootstrapRegistry.provider(ClusterCoordinator.class), isMaster);
}
// start master status listener
bootstrapRegistry.bind(MasterStatusListener.class, masterStatusListener);
bootstrapRegistry.bindProvider(EngineId.class, Providers.of(null));
bootstrapRegistry.bindProvider(SubEngineId.class, Providers.of(null));
}
@Override
public TableLoaderBuilder withDialect(SqlDialect sqlDialect) {
this.sqlDialect = Providers.of(sqlDialect);
return this;
}
/**
* @param dataSource The database connection source to use
* @param sqlDialect The dialect to use for the dataSource
*/
public SqlScriptExecutorProvider(final DataSource dataSource, SqlDialect sqlDialect) {
super();
this.dataSource = dataSource;
this.sqlDialect = Providers.<SqlDialect>of(sqlDialect);
}