Java Code Examples for com.google.inject.util.Providers

The following examples show how to use com.google.inject.util.Providers. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: presto   Source File: BackupModule.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
@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);
}
 
Example 3
Source Project: gossip   Source File: Formatter.java    License: MIT License 6 votes vote down vote up
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));
        }
    });
}
 
Example 4
@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();
}
 
Example 5
Source Project: nexus-public   Source File: UpgradeManagerTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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)
  ));
}
 
Example 6
Source Project: nexus-public   Source File: UpgradeManagerTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example 7
Source Project: nexus-public   Source File: UpgradeManagerTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example 8
Source Project: keywhiz   Source File: CliModule.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 9
Source Project: isis-app-todoapp   Source File: ToDoApplication.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 10
Source Project: pinpoint   Source File: PluginApplicationContextModule.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 11
Source Project: phoenix   Source File: TephraTransactionProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 12
Source Project: estatio   Source File: EstatioApplication.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 13
Source Project: marathonv5   Source File: MarathonGuiceModule.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 14
Source Project: morf   Source File: TestMergingDatabaseDataSetConsumer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 15
Source Project: android-arscblamer   Source File: InjectedApplication.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 16
@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);
}
 
Example 17
Source Project: yql-plus   Source File: EvaluateStatementTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 18
Source Project: emodb   Source File: SettingsManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 19
@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")));
}
 
Example 20
Source Project: ffwd   Source File: OutputManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 21
Source Project: eagle   Source File: ApplicationGuiceModule.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 22
Source Project: mail-importer   Source File: ModuleTester.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 23
Source Project: dropwizard-guicey   Source File: ConfigBindingModule.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void bindValue(final LinkedBindingBuilder binding, final Object value) {
    if (value != null) {
        binding.toInstance(value);
    } else {
        binding.toProvider(Providers.of(null));
    }
}
 
Example 24
Source Project: seed   Source File: CryptoModule.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@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);
}
 
Example 25
@Before
public void setUp() {
  mockServlet = createMock(HttpServlet.class);

  filter =
      new ShiroKerberosPermissiveAuthenticationFilter(Providers.of(createMock(Subject.class)));
}
 
Example 26
@Before
public void setUp() {
  subject = createMock(Subject.class);
  mockServlet = createMock(HttpServlet.class);

  filter = new ShiroKerberosAuthenticationFilter(Providers.of(subject));
}
 
Example 27
Source Project: dremio-oss   Source File: SabotNode.java    License: Apache License 2.0 4 votes vote down vote up
@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
  );
}
 
Example 28
Source Project: dremio-oss   Source File: DACDaemonModule.java    License: Apache License 2.0 4 votes vote down vote up
@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));
}
 
Example 29
Source Project: morf   Source File: TableLoaderBuilder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public TableLoaderBuilder withDialect(SqlDialect sqlDialect) {
  this.sqlDialect = Providers.of(sqlDialect);
  return this;
}
 
Example 30
Source Project: morf   Source File: SqlScriptExecutorProvider.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @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);
}