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

The following are top voted examples for showing how to use com.google.inject.util.Modules. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: grpc-mate   File: ProductDaoTest.java   Source Code and License 8 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
  faker = new Faker();
  String ip = esContainer.getContainerIpAddress();
  Integer transportPort = esContainer.getMappedPort(9300);
  MapConfiguration memoryParams = new MapConfiguration(new HashMap<>());
  memoryParams.setProperty(CONFIG_ES_CLUSTER_HOST, ip);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_PORT, transportPort);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_NAME, "elasticsearch");
  injector = Guice.createInjector(
      Modules.override(new ElasticSearchModule())
          .with(binder -> {
            binder.bind(Configuration.class).toProvider(() -> memoryParams);
          })
  );
  productDao = injector.getInstance(ProductDao.class);
  esClient = injector.getInstance(TransportClient.class);
}
 
Example 2
Project: rotabuilder   File: DomainApplication.java   Source Code and License 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(ComponentFactoryRegistrar.class).to(MyComponentFactoryRegistrar.class);

            bind(String.class).annotatedWith(Names.named("applicationName")).toInstance("RotaBuilder");
            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(readLines(getClass(), "welcome.html"));
            bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("RotaBuilder");
            bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(
                    Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
            // if uncommented, then overrides isis.appManifest in config file.
            // bind(AppManifest.class).toInstance(new DomainAppAppManifest());
        }
    };

    return Modules.override(isisDefaults).with(overrides);
}
 
Example 3
Project: dragoman   File: MongoCannedDatasetsWriterTest.java   Source Code and License 6 votes vote down vote up
@BeforeEach
public void setUp() {
  Injector injector =
      Guice.createInjector(
          Modules.override(
                  new DatasetModule(), new CannedDatasetsModule(), new ConfigurationModule())
              .with(
                  new MongoOverrideModule(),
                  new AbstractModule() {
                    @Override
                    protected void configure() {
                      bind(CannedDatasetsLoader.class)
                          .toInstance(Mockito.mock(CannedDatasetsLoader.class));
                    }
                  }));
  injector.injectMembers(this);

  when(mongoProvider.provide()).thenReturn(getMongoClient());
}
 
Example 4
Project: grpc-mate   File: TransportClientProviderTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  String ip = esContainer.getContainerIpAddress();
  Integer transportPort = esContainer.getMappedPort(9300);
  MapConfiguration memoryParams = new MapConfiguration(new HashMap<>());
  memoryParams.setProperty(CONFIG_ES_CLUSTER_HOST, ip);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_PORT, transportPort);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_NAME, "elasticsearch");
  Injector injector = Guice.createInjector(
      Modules.override(new ElasticSearchModule()).with(
          binder -> {
            binder.bind(Configuration.class).toInstance(memoryParams);
          }
      )
  );
  transportClientProvider = injector.getInstance(TransportClientProvider.class);
}
 
Example 5
Project: grpc-mate   File: ProductUpdateServiceTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  faker = new Faker();
  productDao = mock(ProductDao.class);
  injector = Guice.createInjector(
      Modules.override(new ElasticSearchModule())
          .with(binder -> {
            binder.bind(ProductDao.class).toProvider(() -> productDao);
          })
  );

  productUpdateService = injector.getInstance(ProductUpdateService.class);
  grpcServerRule.getServiceRegistry().addService(productUpdateService);

  stub = ProductUpdateServiceGrpc.newStub(grpcServerRule.getChannel());
}
 
Example 6
Project: verify-hub   File: StateControllerFactoryTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup() {
    Injector injector = Guice.createInjector(
            Modules.override(new PolicyModule()
            ).with(new AbstractModule() {
                @Override
                protected void configure() {
                    bind(EventSinkProxy.class).toInstance(mock(EventSinkProxy.class));
                    bind(IdentityProvidersConfigProxy.class).toInstance(mock(IdentityProvidersConfigProxy.class));
                    bind(Client.class).toInstance(mock(Client.class));
                    bind(Environment.class).toInstance(mock(Environment.class));
                    bind(PolicyConfiguration.class).toInstance(aPolicyConfiguration().build());
                    InfinispanCacheManager infinispanCacheManager = anInfinispanCacheManager().build(InfinispanJunitRunner.EMBEDDED_CACHE_MANAGER);
                    bind(InfinispanCacheManager.class).toInstance(infinispanCacheManager);
                    bind(EventSinkHubEventLogger.class).toInstance(mock(EventSinkHubEventLogger.class));
                    bind(JsonClient.class).annotatedWith(Names.named("samlSoapProxyClient")).toInstance(mock(JsonClient.class));
                    bind(JsonClient.class).toInstance(mock(JsonClient.class));
                }
            })
    );

    factory = new StateControllerFactory(injector);
}
 
Example 7
Project: datarouter   File: ModuleFactory.java   Source Code and License 6 votes vote down vote up
@Override
public Module createModule(ITestContext context, Class<?> testClass){

	Module globalModule = new AbstractModule(){

		@Override
		protected void configure(){
			for(Module module : modules){
				install(module);
			}
		}

	};
	Iterable<? extends Module> overriders = getOverriders();
	return Modules.override(globalModule).with(overriders);
}
 
Example 8
Project: Proyecto2017Seguros   File: PacinetesApplication.java   Source Code and License 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("SiGeSe");
             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("brandLogoSignin")).toInstance("/about/images/login.png");
	bind(String.class).annotatedWith(Names.named("welcomeMessage")).toInstance(readLines(getClass(), "welcome.html"));
	bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("SiGeSe");
	bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
}
     };

     return Modules.override(isisDefaults).with(overrides);
 }
 
Example 9
Project: ice   File: ConfigSystem.java   Source Code and License 6 votes vote down vote up
private static <C> Module configModuleWithOverrides(final Class<C> configInterface, final Optional<Named> nameOpt, final Optional<OverrideConsumer<C>> overrideOpt)
{
    checkNotNull(configInterface);
    checkNotNull(nameOpt);
    checkNotNull(overrideOpt);

    if (overrideOpt.isPresent()) {
        return Modules.override(ConfigBuilder.configModule(configInterface, nameOpt))
            .with(new OverrideModule<C>(configInterface, nameOpt.map(n -> n.value()))
            {
                @Override
                protected void configure()
                {
                    overrideOpt.get().accept(this);
                }
            });
    }
    else {
        return ConfigBuilder.configModule(configInterface, nameOpt);
    }
}
 
Example 10
Project: ice   File: Example1Test.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 5000)
@SuppressWarnings("UnnecessaryUnboxing")
public void testExample1() throws Exception
{
    Injector injector = Guice.createInjector(Modules.override(
        ConfigConfigurator.standardModules(),
        Example1.module())
        .with(new AbstractModule()
        {
            @Override
            protected void configure()
            {
                bind(String.class).annotatedWith(named(FileDynamicConfigSource.FILENAME_NAME)).toInstance(getClass().getResource("Example1.config").getFile());
            }
        })
    );

    injector.injectMembers(this);

    assertNotNull(example);
    example.doStuff();

    assertEquals("testFoo", example.config.connectionString());
    assertEquals(123L, example.config.connectionTimeout().longValue());
    assertEquals(Duration.parse("P1DT2H32M18S"), example.config.delayTime());
}
 
Example 11
Project: ice   File: ProviderExampleTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup()
{
    final Named name = Names.named("provider-test");

    Module module = Modules.override(
        ConfigConfigurator.testModules(),
        ProviderExample.module(name)
    ).with(new AbstractModule()
    {
        @Override
        protected void configure()
        {
            install(ConfigSystem.overrideModule(ProviderExample.Config.class, name, om -> {
                om.override(om.id().connectionString()).withValue("foo bar");
                om.override(om.id().keyspaceName()).withValue("keyspace baz");
            }));
        }
    });

    Guice.createInjector(module).injectMembers(this);
}
 
Example 12
Project: Mastering-Mesos   File: DbModule.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a module that will prepare a private in-memory database, using a specific task store
 * implementation bound within the key factory and provided module.
 *
 * @param keyFactory Key factory to use.
 * @param taskStoreModule Module providing task store bindings.
 * @return A new database module for testing.
 */
@VisibleForTesting
public static Module testModuleWithWorkQueue(
    KeyFactory keyFactory,
    Optional<Module> taskStoreModule) {

  return Modules.combine(
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(GatedWorkQueue.class).annotatedWith(AsyncExecutor.class).toInstance(
              new GatedWorkQueue() {
                @Override
                public <T, E extends Exception> T closeDuring(
                    GatedOperation<T, E> operation) throws E {

                  return operation.doWithGateClosed();
                }
              });
        }
      },
      testModule(keyFactory, taskStoreModule)
  );
}
 
Example 13
Project: Mastering-Mesos   File: HttpSecurityIT.java   Source Code and License 6 votes vote down vote up
@Override
protected Module getChildServletModule() {
  return Modules.combine(
      new ApiModule(),
      new H2ConsoleModule(true),
      new HttpSecurityModule(
          new IniShiroRealmModule(ini),
          Key.get(Filter.class, SHIRO_AFTER_AUTH_FILTER_ANNOTATION)),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(Filter.class)
              .annotatedWith(SHIRO_AFTER_AUTH_FILTER_ANNOTATION)
              .toInstance(shiroAfterAuthFilter);
          MockDecoratedThrift.bindForwardedMock(binder(), auroraAdmin);
        }
      });
}
 
Example 14
Project: Mastering-Mesos   File: CronIT.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  stateManager = createMock(StateManager.class);
  storage = DbUtil.createStorage();
  auroraCronJob = createMock(AuroraCronJob.class);

  injector = Guice.createInjector(
      // Override to verify that Guice is actually used for construction of the AuroraCronJob.
      // TODO(ksweeney): Use the production class here.
      Modules.override(new CronModule()).with(new AbstractModule() {
        @Override
        protected void configure() {
          bind(AuroraCronJob.class).toInstance(auroraCronJob);
        }
      }), new AbstractModule() {
        @Override
        protected void configure() {
          bind(ConfigurationManager.class).toInstance(TaskTestUtil.CONFIGURATION_MANAGER);
          bind(Clock.class).toInstance(Clock.SYSTEM_CLOCK);
          bind(StateManager.class).toInstance(stateManager);
          bind(Storage.class).toInstance(storage);
        }
      });
}
 
Example 15
Project: walkaround   File: GuiceSetup.java   Source Code and License 6 votes vote down vote up
public static Module getRootModule(final String webinfRoot) {
  return Modules.combine(
      Modules.combine(extraModules),
      new WalkaroundServerModule(),
      new ConvStoreModule(),
      new UdwStoreModule(),
      new AbstractModule() {
        @Override public void configure() {
          bind(String.class).annotatedWith(Names.named("webinf root")).toInstance(webinfRoot);

          // TODO(ohler): Find a way to create these bindings in StoreModuleHelper; but note that
          // http://code.google.com/p/google-guice/wiki/Multibindings says something about
          // private modules not interacting well with multibindings.  I don't know if that
          // refers to our situation here.
          MapBinder<String, SlobFacilities> mapBinder =
              MapBinder.newMapBinder(binder(), String.class, SlobFacilities.class);
          for (Entry<String, Class<? extends Annotation>> entry
              : ImmutableMap.of(ConvStoreModule.ROOT_ENTITY_KIND, ConvStore.class,
                  UdwStoreModule.ROOT_ENTITY_KIND, UdwStore.class).entrySet()) {
            mapBinder.addBinding(entry.getKey())
                .to(Key.get(SlobFacilities.class, entry.getValue()));
          }
        }
      });
}
 
Example 16
Project: isis-agri   File: DomainApplication.java   Source Code and License 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("Food 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("welcomeMessage")).toInstance(readLines(getClass(), "welcome.html"));
            bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("Food App");
            bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(
                    Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
            // if uncommented, then overrides isis.appManifest in config file.
            // bind(AppManifest.class).toInstance(new DomainAppAppManifest());
        }
    };

    return Modules.override(isisDefaults).with(overrides);
}
 
Example 17
Project: riposte-microservice-template   File: AppServerConfigTest.java   Source Code and License 6 votes vote down vote up
@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 18
Project: ecpcrm   File: EcpCrmApplication.java   Source Code and License 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("ECP CRM");
                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/domainapp-logo-header.png");
//                bind(String.class).annotatedWith(Names.named("brandLogoSignin")).toInstance("/images/domainapp-logo-signin.png");
                bind(String.class).annotatedWith(Names.named("welcomeMessage")).toInstance(readLines(getClass(), "welcome.html"));
                bind(String.class).annotatedWith(Names.named("aboutMessage")).toInstance("ECP CRM");
                bind(InputStream.class).annotatedWith(Names.named("metaInfManifest")).toProvider(Providers.of(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")));
            }
        };

        return Modules.override(isisDefaults).with(overrides);
    }
 
Example 19
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestHandlerWithSyncCloseResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    writeResponse(out);
                    closeResponse(out);
                    return null;
                }
            });
}
 
Example 20
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestHandlerWithSyncWriteResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    writeResponse(out);
                    closeResponseInOtherThread(out);
                    return null;
                }
            });
}
 
Example 21
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestHandlerWithSyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    callInOtherThread(() -> {
                        writeResponse(out);
                        closeResponse(out);
                        return null;
                    });
                    return null;
                }
            });
}
 
Example 22
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestHandlerWithAsyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    respondWithContentInOtherThread(handler);
                    return null;
                }
            });
}
 
Example 23
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestExceptionWithSyncCloseResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    writeResponse(out);
                    closeResponse(out);
                    throw new ConformanceException();
                }
            });
}
 
Example 24
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestExceptionWithSyncWriteResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    writeResponse(out);
                    closeResponseInOtherThread(out);
                    throw new ConformanceException();
                }
            });
}
 
Example 25
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestNondeterministicExceptionWithSyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    callInOtherThread(() -> {
                        writeResponse(out);
                        closeResponse(out);
                        return null;
                    });
                    throw new ConformanceException();
                }
            });
}
 
Example 26
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestExceptionBeforeResponseWriteWithSyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    final Event exceptionHandledByFramework = new Event();
                    callInOtherThread(() -> {
                        exceptionHandledByFramework.await();
                        writeResponse(out);
                        closeResponse(out);
                        return null;
                    });
                    throw new ConformanceException(exceptionHandledByFramework);
                }
            });
}
 
Example 27
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestExceptionAfterResponseWriteWithSyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    callInOtherThread(() -> {
                        writeResponse(out);
                        closeResponse(out);
                        return null;
                    });
                    responseWritten.await();
                    throw new ConformanceException();
                }
            });
}
 
Example 28
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestExceptionAfterResponseCloseNoContentWithAsyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    callInOtherThread(() -> {
                        try {
                            respondNoContent(handler);
                        } catch (Throwable ignored) {

                        }
                        return null;
                    });
                    responseClosed.await();
                    throw new ConformanceException();
                }
            });
}
 
Example 29
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testRequestExceptionAfterResponseWriteWithAsyncHandleResponse(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(final Request request, final ResponseHandler handler) {
                    callInOtherThread(new Callable<Void>() {

                        @Override
                        public Void call() throws Exception {
                            final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                            writeResponse(out);
                            closeResponse(out);
                            return null;
                        }
                    });
                    responseWritten.await();
                    throw new ConformanceException();
                }
            });
}
 
Example 30
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testResponseWriteCompletionException(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(Request request, ResponseHandler handler) {
                    final ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    for (ByteBuffer buf : adapter.newResponseContent()) {
                        out.write(buf, EXCEPTION_COMPLETION_HANDLER);
                    }
                    closeResponse(out);
                    return null;
                }
            });
}
 
Example 31
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testResponseCloseCompletionException(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(Request request, ResponseHandler handler) {
                    ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    writeResponse(out);
                    out.close(EXCEPTION_COMPLETION_HANDLER);
                    return null;
                }
            });
}
 
Example 32
Project: vespa   File: ServerProviderConformanceTest.java   Source Code and License 6 votes vote down vote up
private <T extends ServerProvider, U, V> void testResponseCloseCompletionExceptionNoContent(
        final Adapter<T, U, V> adapter,
        final Module... config)
        throws Throwable {
    runTest(adapter,
            Modules.combine(config),
            RequestType.WITHOUT_CONTENT,
            new TestRequestHandler() {

                @Override
                public ContentChannel handle(Request request, ResponseHandler handler) {
                    ContentChannel out = handler.handleResponse(new Response(Response.Status.OK));
                    out.close(EXCEPTION_COMPLETION_HANDLER);
                    return null;
                }
            });
}
 
Example 33
Project: vespa   File: HttpServerConformanceTest.java   Source Code and License 6 votes vote down vote up
@Override
public Module newConfigModule() {
    return Modules.combine(
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(FilterBindings.class)
                            .toInstance(new FilterBindings(
                                    new BindingRepository<>(),
                                    new BindingRepository<>()));
                    bind(ServerConfig.class)
                            .toInstance(new ServerConfig(new ServerConfig.Builder()));
                    bind(ServletPathsConfig.class)
                            .toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
                }
            },
            new ConnectorFactoryRegistryModule());
}
 
Example 34
Project: vespa   File: FilterTestCase.java   Source Code and License 6 votes vote down vote up
private static com.google.inject.Module newFilterModule(
        final BindingRepository<RequestFilter> requestFilters,
        final BindingRepository<ResponseFilter> responseFilters) {
    return Modules.combine(
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(FilterBindings.class).toInstance(
                            new FilterBindings(
                                    requestFilters != null ? requestFilters : EMPTY_REQUEST_FILTER_REPOSITORY,
                                    responseFilters != null ? responseFilters : EMPTY_RESPONSE_FILTER_REPOSITORY));
                    bind(ServerConfig.class).toInstance(new ServerConfig(new ServerConfig.Builder()));
                    bind(ConnectorConfig.class).toInstance(new ConnectorConfig(new ConnectorConfig.Builder()));
                    bind(ServletPathsConfig.class).toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
                }
            },
            new ConnectorFactoryRegistryModule());
}
 
Example 35
Project: vespa   File: TestDrivers.java   Source Code and License 6 votes vote down vote up
public static TestDriver newInstanceWithSsl(final RequestHandler requestHandler,
                                            final Module... guiceModules) throws IOException {
    return TestDriver.newInstance(
            JettyHttpServer.class,
            requestHandler,
            newConfigModule(
                    new ServerConfig.Builder(),
                    new ConnectorConfig.Builder()
                            .ssl(new ConnectorConfig.Ssl.Builder()
                                         .enabled(true)
                                         .keyDbKey("dummy-key-for-StaticKeyDbConnectorFactory.getPasswordFromKeydb")
                                         .keyStorePath(KEY_STORE)
                                         .trustStorePath(KEY_STORE)),
                    Modules.combine(new AbstractModule() {

                        @Override
                        protected void configure() {
                            bind(String.class).annotatedWith(named("keyStorePassword"))
                                    .toInstance(KEY_STORE_PASSWORD);
                        }
                    }, Modules.combine(guiceModules))
            ));
}
 
Example 36
Project: vespa   File: TestDrivers.java   Source Code and License 6 votes vote down vote up
private static Module newConfigModule(
        final ServerConfig.Builder serverConfig,
        final ConnectorConfig.Builder connectorConfigBuilder,
        final Module... guiceModules) {
    return Modules.combine(
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(ServletPathsConfig.class).toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
                    bind(ServerConfig.class).toInstance(new ServerConfig(serverConfig));
                    bind(ConnectorConfig.class).toInstance(new ConnectorConfig(connectorConfigBuilder));
                    bind(FilterBindings.class).toInstance(
                            new FilterBindings(
                                    new BindingRepository<RequestFilter>(),
                                    new BindingRepository<ResponseFilter>()));
                }
            },
            new ConnectorFactoryRegistryModule(connectorConfigBuilder),
            new ServletModule(),
            Modules.combine(guiceModules));
}
 
Example 37
Project: gstrap   File: GuiceExtension.java   Source Code and License 6 votes vote down vote up
@Override
public void beforeEach(final ExtensionContext context) throws Exception {
	final GuicyTest testInstance = (GuicyTest)context.getTestInstance().get();
	final Module module = testInstance.module();

	final RequestScope requestScope = new RequestScope();

	final AbstractModule basicTestModule = new AbstractModule() {
		@Override
		protected void configure() {
			this.bindScope(RequestScoped.class, requestScope);
			this.bind(RequestScope.class).toInstance(requestScope);

			this.bind(HttpServletRequest.class).to(FakeHttpServletRequest.class);
			this.bind(HttpServletResponse.class).to(FakeHttpServletResponse.class);
		}
	};

	final Injector injector = Guice.createInjector(Modules.override(basicTestModule).with(module));
	context.getStore(NAMESPACE).put(Injector.class, injector);

	final ScopeRequestFilter scopeFilter = injector.getInstance(ScopeRequestFilter.class);
	injector.getInstance(Requestor.class).addFilter(scopeFilter);
}
 
Example 38
Project: dsl-devkit   File: OverridingGuiceModule.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(final Binder binder) {
  Stream.of(Platform.getExtensionRegistry().getConfigurationElementsFor(OVERRIDING_GUICE_MODULE_EXTENSION_POINT)).sorted((a, b) -> {
    int aPriority = Integer.parseInt(a.getAttribute(OVERRIDING_GUICE_MODULE_EXTENSION_PRIORITY));
    int bPriority = Integer.parseInt(b.getAttribute(OVERRIDING_GUICE_MODULE_EXTENSION_PRIORITY));
    return aPriority - bPriority;
  }).map(element -> {
    try {
      return (Module) element.createExecutableExtension(OVERRIDING_GUICE_MODULE_EXTENSION_CLASS);
    } catch (CoreException e) {
      LOGGER.log(Level.ERROR, "Overriding guice module from " + element.getContributor() + " could not be instatiated and has been skipped.", e); //$NON-NLS-1$ //$NON-NLS-2$
      return null;
    }
  }).filter(Objects::nonNull).reduce((dummy) -> {}, (previous, next) -> {
    LOGGER.log(Level.DEBUG, "Overriding guice module with " + next.getClass().getName()); //$NON-NLS-1$
    return Modules.override(previous).with(next);
  }).configure(binder);
}
 
Example 39
Project: ratpack-eureka   File: EurekaFactory.java   Source Code and License 6 votes vote down vote up
public Module buildModule(ServerConfig serverConfig) {
    if (enabled) {

        Preconditions.checkNotNull(name);
        Preconditions.checkNotNull(defaultServiceUrl);
        Preconditions.checkNotNull(healthCheckUrl);
        Preconditions.checkNotNull(dataCenter);

        Properties properties = new Properties();

        properties.setProperty("eureka.name", name);
        properties.setProperty("eureka.serviceUrl.default", defaultServiceUrl.toString());
        properties.setProperty("eureka.healthCheckUrl", healthCheckUrl);
        properties.setProperty("eureka.datacenter", dataCenter == DataCenter.LOCAL ? "local" : "cloud");

        properties.setProperty("eureka.port", String.valueOf(serverConfig.getPort()));
        properties.setProperty("eureka.vipAddress", vipAddress != null ? vipAddress : name);
        properties.setProperty("eureka.statusPageUrl", healthCheckUrl);

        return new EurekaModule(properties);
    }
    return Modules.EMPTY_MODULE;
}
 
Example 40
Project: incubator-tephra   File: TransactionExecutorTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {
  final Configuration conf = new Configuration();
  conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV4.class.getName());
  conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());
  Injector injector = Guice.createInjector(
    new ConfigModule(conf),
    new DiscoveryModules().getInMemoryModules(),
    Modules.override(
      new TransactionModules("clientB").getInMemoryModules()).with(new AbstractModule() {
      @Override
      protected void configure() {
        TransactionManager txManager = new TransactionManager(conf);
        txManager.startAndWait();
        bind(TransactionManager.class).toInstance(txManager);
        bind(TransactionSystemClient.class).to(DummyTxClient.class).in(Singleton.class);
      }
    }));

  txClient = (DummyTxClient) injector.getInstance(TransactionSystemClient.class);
  factory = injector.getInstance(TransactionExecutorFactory.class);
}