com.google.inject.util.Providers Java Examples
The following examples show how to use
com.google.inject.util.Providers.
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 check out the related API usage on the sidebar.
Example #1
Source File: BackupModule.java From presto with Apache License 2.0 | 6 votes |
@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
Source File: UpgradeManagerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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 #3
Source File: UpgradeManagerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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 #4
Source File: UpgradeManagerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@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 #5
Source File: CliModule.java From keywhiz with Apache License 2.0 | 6 votes |
@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 #6
Source File: AppServerConfigTest.java From riposte-microservice-template with Apache License 2.0 | 6 votes |
@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 #7
Source File: Formatter.java From gossip with MIT License | 6 votes |
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 #8
Source File: ToDoApplication.java From isis-app-todoapp with Apache License 2.0 | 6 votes |
@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 #9
Source File: ValidationJobSchedulerTest.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
@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 #10
Source File: PluginApplicationContextModule.java From pinpoint with Apache License 2.0 | 6 votes |
@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 File: TephraTransactionProvider.java From phoenix with Apache License 2.0 | 6 votes |
@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 File: EstatioApplication.java From estatio with Apache License 2.0 | 6 votes |
@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 File: ModuleTester.java From mail-importer with Apache License 2.0 | 5 votes |
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 #14
Source File: ConfigBindingModule.java From dropwizard-guicey with MIT License | 5 votes |
@SuppressWarnings("unchecked") private void bindValue(final LinkedBindingBuilder binding, final Object value) { if (value != null) { binding.toInstance(value); } else { binding.toProvider(Providers.of(null)); } }
Example #15
Source File: CryptoModule.java From seed with Mozilla Public License 2.0 | 5 votes |
@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 #16
Source File: ApplicationGuiceModule.java From eagle with Apache License 2.0 | 5 votes |
@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 #17
Source File: ShiroKerberosPermissiveAuthenticationFilterTest.java From attic-aurora with Apache License 2.0 | 5 votes |
@Before public void setUp() { mockServlet = createMock(HttpServlet.class); filter = new ShiroKerberosPermissiveAuthenticationFilter(Providers.of(createMock(Subject.class))); }
Example #18
Source File: ShiroKerberosAuthenticationFilterTest.java From attic-aurora with Apache License 2.0 | 5 votes |
@Before public void setUp() { subject = createMock(Subject.class); mockServlet = createMock(HttpServlet.class); filter = new ShiroKerberosAuthenticationFilter(Providers.of(subject)); }
Example #19
Source File: MarathonGuiceModule.java From marathonv5 with Apache License 2.0 | 5 votes |
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 #20
Source File: OutputManagerTest.java From ffwd with Apache License 2.0 | 5 votes |
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 File: RaptureWebResourceBundleTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@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 #22
Source File: SettingsManagerTest.java From emodb with Apache License 2.0 | 5 votes |
@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 #23
Source File: EvaluateStatementTest.java From yql-plus with Apache License 2.0 | 5 votes |
@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 #24
Source File: ValidationJobSchedulerTest.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@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 #25
Source File: InjectedApplication.java From android-arscblamer with Apache License 2.0 | 5 votes |
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 #26
Source File: TestMergingDatabaseDataSetConsumer.java From morf with Apache License 2.0 | 5 votes |
/** * 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 #27
Source File: OrientKeyStoreStorageManagerTest.java From nexus-public with Eclipse Public License 1.0 | 4 votes |
@Before public void setUp() { when(db.acquire()).thenReturn(tx); storageManager = new OrientKeyStoreStorageManager(Providers.of(db), entityAdapter, eventManager); }
Example #28
Source File: DeviceBrokerModule.java From android-test with Apache License 2.0 | 4 votes |
@Override public void configure() { bindConstant() .annotatedWith(ResourceDexdumpName.class) .to("/com/google/android/apps/common/testing/broker/dexdump_annotations"); bindConstant() .annotatedWith(TestServicesApkResourceName.class) .to( "/services/test_services.apk"); bindConstant() .annotatedWith(OdoApkResourceName.class) .to( "/runner/android_test_orchestrator/stubapp/stubapp.apk"); bind(AdbController.AdbControllerFactory.class).to(AdbController.FullControlAdbControllerFactory.class); bind(String.class) .annotatedWith(ExecutorLocation.class) .toProvider( new ResourceProvider( Providers.of("/com/google/android/apps/common/testing/broker/executor.sh"))) .in(Scopes.SINGLETON); bind(String.class).annotatedWith(OdoApkLocation.class).toProvider( new ResourceProvider(getProvider(Key.get(String.class, OdoApkResourceName.class)))) .in(Scopes.SINGLETON); bind(String.class) .annotatedWith(TestServicesApkLocation.class) .toProvider( new ResourceProvider( getProvider(Key.get(String.class, TestServicesApkResourceName.class)))) .in(Scopes.SINGLETON); bind(String.class).annotatedWith(ResourceDexdumpPath.class).toProvider( new ResourceProvider(getProvider(Key.get(String.class, ResourceDexdumpName.class)))) .in(Scopes.SINGLETON); Multibinder.newSetBinder(binder(), DeviceBrokerDecorator.class); MapBinder.newMapBinder(binder(), DeviceBrokerType.class, DeviceBroker.class); MapBinder<String, String> adbEnv = MapBinder.newMapBinder(binder(), String.class, String.class, AdbEnvironment.class); adbEnv.addBinding(ENVIRONMENT_KEY_ANDROID_ADB).to(Key.get(String.class, AdbPath.class)); }
Example #29
Source File: TestDatabaseDataSetConsumer.java From morf with Apache License 2.0 | 4 votes |
/** * Tests that blob fields are added to the the prepared insert statement in correct decoded form. * * @throws SQLException not really thrown */ @Test public void testBlobInsertion() throws SQLException { // Mock all the resources - we're only interested in the PreparedStatement // for this test. final ConnectionResources connectionResources = Mockito.mock(ConnectionResources.class); final DataSource dataSource = Mockito.mock(DataSource.class); final Connection connection = Mockito.mock(Connection.class); final SqlDialect dialect = Mockito.mock(SqlDialect.class); final PreparedStatement statement = Mockito.mock(PreparedStatement.class); final java.sql.Blob blob = Mockito.mock(java.sql.Blob.class); Mockito.when(statement.getConnection()).thenReturn(connection); Mockito.when(connection.createBlob()).thenReturn(blob); Mockito.when(blob.setBytes(eq(1L), any(byte[].class))).thenAnswer(invocation -> ((byte[]) invocation.getArguments()[1]).length); Mockito.when(connectionResources.getDataSource()).thenReturn(dataSource); Mockito.when(dataSource.getConnection()).thenReturn(connection); Mockito.when(connectionResources.sqlDialect()).thenReturn(dialect); Mockito.when(dialect.convertStatementToSQL(Mockito.any(InsertStatement.class), Mockito.any(Schema.class))).thenReturn("Foo :id :version :blob"); Mockito.when(connection.prepareStatement(Mockito.anyString())).thenReturn(statement); // Create our consumer final DatabaseDataSetConsumer consumer = new DatabaseDataSetConsumer(connectionResources, new SqlScriptExecutorProvider(dataSource, Providers.of(dialect))); consumer.open(); // Create a mock schema and records final Table table = table("DatabaseTest") .columns( idColumn(), versionColumn(), column("blob", DataType.BLOB) ); final List<Record> records = new ArrayList<>(); records.add(record().setInteger(idColumn().getName(), 1).setInteger(versionColumn().getName(), 2).setString("blob", "QUJD")); // consume the records consumer.table(table, records); // Verify dialect is requested to write the values to the statement Mockito.verify(dialect).prepareStatementParameters(any(NamedParameterPreparedStatement.class), parametersCaptor.capture(), valuesCaptor.capture()); assertThat(FluentIterable.from(parametersCaptor.getValue()).transform(SqlParameter::getImpliedName), contains( idColumn().getName(), versionColumn().getName(), "blob") ); assertThat(valuesCaptor.getValue().getInteger(idColumn().getName()), equalTo(1)); assertThat(valuesCaptor.getValue().getInteger(versionColumn().getName()), equalTo(2)); assertThat(valuesCaptor.getValue().getString("blob"), equalTo("QUJD")); }
Example #30
Source File: SqlScriptExecutorProvider.java From morf with Apache License 2.0 | 4 votes |
/** * @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); }