@Test
  public void confirmBindingSingletonOrder() throws Exception {
    final TypeLiteral<List<Integer>> listTypeLiteral = new TypeLiteral<List<Integer>>() {};
    final List<Integer> actual = Lists.newArrayList();
    final List<Module> modules =
        Lists.<Module>newArrayList(new ModuleA1(), new ModuleA2(), new ModuleA3(), new ModuleA4());
    BootstrapModule bootstrap =
        new BootstrapModule() {
          @Override
          public void configure(BootstrapBinder binder) {
            binder.bind(listTypeLiteral).toInstance(actual);
          }
        };

    // Confirm that singletons are created in binding order
    final List<Integer> expected = Lists.newArrayList(1, 2, 3, 4);
    {
      actual.clear();
      Injector injector =
          LifecycleInjector.builder()
              .withModules(modules)
              .withBootstrapModule(bootstrap)
              .build()
              .createInjector();
      List<Integer> integers = injector.getInstance(Key.get(listTypeLiteral));
      Assert.assertEquals(integers, expected);
    }

    // Reverse the order of modules in the list to confirm that singletons
    // are now created in reverse order
    {
      actual.clear();
      Injector injector =
          LifecycleInjector.builder()
              .withModules(Lists.reverse(modules))
              .withBootstrapModule(bootstrap)
              .build()
              .createInjector();
      List<Integer> integers = injector.getInstance(Key.get(listTypeLiteral));
      Assert.assertEquals(integers, Lists.reverse(expected));
    }

    // Now add the modules using module dependency order and confirm singletons are
    // created in the proper order
    {
      actual.clear();
      Injector injector =
          LifecycleInjector.builder()
              .withBootstrapModule(bootstrap)
              .withRootModule(ModuleA4.class)
              .build()
              .createInjector();
      List<Integer> integers = injector.getInstance(Key.get(listTypeLiteral));
      Assert.assertEquals(integers, expected);
    }
  }
  @Test
  public void shouldUseOverrideModule() {
    Injector injector =
        LifecycleInjector.builder()
            .withRootModule(ConcurrencyModule.class)
            .withBootstrapModule(
                new BootstrapModule() {
                  @Override
                  public void configure(BootstrapBinder binder) {
                    binder
                        .bind(ConcurrencyModule.class)
                        .toInstance(
                            new ConcurrencyModule() {
                              @Override
                              protected void configure() {}
                            });
                  }
                })
            .build()
            .createInjector();

    try {
      ScheduledExecutorService service =
          injector.getInstance(Key.get(ScheduledExecutorService.class, Background.class));
      Assert.fail("Binding shouldn't exist");
    } catch (ConfigurationException e) {

    }
  }
  @Test
  public void backgroundShouldBeInjectable() {
    Injector injector =
        LifecycleInjector.builder()
            .withRootModule(ConcurrencyModule.class)
            .build()
            .createInjector();

    ScheduledExecutorService service =
        injector.getInstance(Key.get(ScheduledExecutorService.class, Background.class));
  }
  public static void main(String[] args) throws Exception {
    // Always get the Guice injector from Governator
    LifecycleInjector lifecycleInjector =
        LifecycleInjector.builder().withModules(new ExampleModule()).build();
    Injector injector = lifecycleInjector.createInjector();

    LifecycleManager manager = injector.getInstance(LifecycleManager.class);

    // Always start the Lifecycle Manager
    manager.start();

    long objectsToCreate = 10000;

    // Test creating objects without @JsonProperty annotations
    ExamplePojoWithoutAnnotationsFactory factory2 =
        injector.getInstance(ExamplePojoWithoutAnnotationsFactory.class);
    long start = System.currentTimeMillis();

    for (int i = 0; i < objectsToCreate; i++) {
      factory2.create();
    }

    long end = System.currentTimeMillis();
    System.out.println("Created " + objectsToCreate + " objects in " + (end - start) + "ms");

    // Test creating objects with @JsonProperty annotations
    ExamplePojoWithAnnotationsFactory factory1 =
        injector.getInstance(ExamplePojoWithAnnotationsFactory.class);
    start = System.currentTimeMillis();

    for (int i = 0; i < objectsToCreate; i++) {
      factory1.create();
    }

    end = System.currentTimeMillis();
    System.out.println(
        "Created " + objectsToCreate + " objects with annotations in " + (end - start) + "ms");

    // Always close the Lifecycle Manager at app end
    manager.close();
  }
Exemplo n.º 5
0
  private Injector createInjector(final Properties properties) {
    injector =
        LifecycleInjector.builder()
            .withBootstrapModule(
                new BootstrapModule() {
                  @Override
                  public void configure(BootstrapBinder binder) {
                    binder
                        .bindConfigurationProvider()
                        .toInstance(new PropertiesConfigurationProvider(properties));
                  }
                })
            .withModules(new SuroClientModule())
            .createInjector();
    LifecycleManager manager = injector.getInstance(LifecycleManager.class);

    try {
      manager.start();
    } catch (Exception e) {
      throw new RuntimeException(
          "LifecycleManager cannot start with an exception: " + e.getMessage(), e);
    }
    return injector;
  }
Exemplo n.º 6
0
  @Test
  public void testOutPool() throws Exception {
    props.put(ClientConfig.LB_SERVER, "localhost:8900");
    props.setProperty(ClientConfig.MINIMUM_RECONNECT_TIME_INTERVAL, "0");
    props.setProperty(ClientConfig.RECONNECT_INTERVAL, "0");
    props.setProperty(ClientConfig.RECONNECT_TIME_INTERVAL, "0");

    servers = TestConnectionPool.startServers(1, 8900);

    injector =
        LifecycleInjector.builder()
            .withBootstrapModule(
                new BootstrapModule() {
                  @Override
                  public void configure(BootstrapBinder binder) {
                    binder
                        .bindConfigurationProvider()
                        .toInstance(new PropertiesConfigurationProvider(props));
                    binder.bind(ILoadBalancer.class).to(StaticLoadBalancer.class);
                  }
                })
            .build()
            .createInjector();
    injector.getInstance(LifecycleManager.class).start();

    final ConnectionPool pool = injector.getInstance(ConnectionPool.class);
    assertEquals(pool.getPoolSize(), 1);

    ExecutorService executors = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; ++i) {
      executors.execute(
          new Runnable() {
            @Override
            public void run() {
              for (int i = 0; i < 5; ++i) {
                try {
                  ConnectionPool.SuroConnection client = pool.chooseConnection();
                  assertEquals(
                      client.send(TestConnectionPool.createMessageSet(100)).getResultCode(),
                      ResultCode.OK);
                  pool.endConnection(client);
                } catch (TException e) {
                  fail(e.getMessage());
                }
              }
            }
          });
    }
    executors.shutdown();
    executors.awaitTermination(10, TimeUnit.SECONDS);

    assertTrue(pool.getOutPoolSize() > 0);
    try {
      Thread.sleep(1000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    TestConnectionPool.checkMessageSetCount(servers, 50, false);

    TestConnectionPool.shutdownServers(servers);
  }
Exemplo n.º 7
0
  @Test
  public void test() throws Exception {
    final Properties properties = new Properties();
    properties.setProperty(ServerConfig.MESSAGE_ROUTER_THREADS, "1");

    Injector injector =
        LifecycleInjector.builder()
            .withModules(
                new SuroPlugin() {
                  @Override
                  protected void configure() {
                    bind(ObjectMapper.class).to(DefaultObjectMapper.class);
                    this.addSinkType("TestSink", TestSink.class);
                  }
                },
                new RoutingPlugin())
            .withBootstrapModule(
                new BootstrapModule() {
                  @Override
                  public void configure(BootstrapBinder binder) {
                    binder
                        .bindConfigurationProvider()
                        .toInstance(new PropertiesConfigurationProvider(properties));
                  }
                })
            .createInjector();

    SinkManager sinkManager = startSinkMakager(injector);

    startMessageRouter(injector);

    MessageSetProcessor queue = injector.getInstance(MessageSetProcessor.class);
    queue.start();

    MessageSetBuilder builder = new MessageSetBuilder(new ClientConfig());

    for (int i = 0; i < 10; ++i) {
      builder.withMessage("topic1", Integer.toString(i).getBytes());
    }
    // sink1: 10
    // default: 10
    queue.process(builder.build());

    for (int i = 0; i < 5; ++i) {
      builder.withMessage("topic2", Integer.toString(i).getBytes());
    }
    // sink1: 5
    queue.process(builder.build());

    for (int i = 0; i < 20; ++i) {
      builder.withMessage("topic3", Integer.toString(i).getBytes());
    }
    // default: 20
    queue.process(builder.build());

    // total sink1: 15, default: 30
    int count = 10;
    while (!answer() && count > 0) {
      Thread.sleep(1000);
      --count;
    }
    assertTrue(count > 0);

    queue.shutdown();
    sinkManager.shutdown();
  }
 @Test
 public void testModuleDepdency() throws Exception {
   Injector injector =
       LifecycleInjector.builder().withRootModule(ModuleB.class).build().createInjector();
 }
  /**
   * Starts the container and hence the embedded jetty server.
   *
   * @throws Exception if there is an issue while starting the server
   */
  @PostConstruct
  public void init() throws Exception {
    try {
      if (alreadyInited.compareAndSet(false, true)) {
        initAdminContainerConfigIfNeeded();
        initAdminRegistryIfNeeded();

        if (!adminContainerConfig.shouldEnable()) {
          return;
        }

        if (adminContainerConfig.shouldScanClassPathForPluginDiscovery()) {
          adminPageRegistry.registerAdminPagesWithClasspathScan();
        }

        Injector adminResourceInjector;
        if (shouldShareResourcesWithParentInjector()) {
          adminResourceInjector = appInjector.createChildInjector(buildAdminPluginsGuiceModules());
        } else {
          adminResourceInjector =
              LifecycleInjector.builder()
                  .inStage(Stage.DEVELOPMENT)
                  .usingBasePackages("com.netflix.explorers")
                  .withModules(buildAdminPluginsGuiceModules())
                  .build()
                  .createInjector();
          adminResourceInjector.getInstance(LifecycleManager.class).start();
        }

        server = new Server(adminContainerConfig.listenPort());

        // redirect filter based on configurable RedirectRules
        final Context rootHandler = new Context();
        rootHandler.setContextPath("/");
        rootHandler.addFilter(
            new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)),
            "/*",
            Handler.DEFAULT);
        rootHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

        // admin page template resources
        AdminResourcesFilter arfTemplatesResources =
            adminResourceInjector.getInstance(AdminResourcesFilter.class);
        arfTemplatesResources.setPackages(adminContainerConfig.jerseyViewableResourcePkgList());

        final Context adminTemplatesResHandler = new Context();
        adminTemplatesResHandler.setContextPath(adminContainerConfig.templateResourceContext());
        adminTemplatesResHandler.setSessionHandler(new SessionHandler());
        adminTemplatesResHandler.addFilter(LoggingFilter.class, "/*", Handler.DEFAULT);
        adminTemplatesResHandler.addFilter(
            new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)),
            "/*",
            Handler.DEFAULT);
        adminTemplatesResHandler.addFilter(
            new FilterHolder(arfTemplatesResources), "/*", Handler.DEFAULT);
        adminTemplatesResHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

        // admin page data resources
        final String jerseyPkgListForAjaxResources =
            appendCoreJerseyPackages(adminPageRegistry.buildJerseyResourcePkgListForAdminPages());
        AdminResourcesFilter arfDataResources =
            adminResourceInjector.getInstance(AdminResourcesFilter.class);
        arfDataResources.setPackages(jerseyPkgListForAjaxResources);

        final Context adminDataResHandler = new Context();
        adminDataResHandler.setContextPath(adminContainerConfig.ajaxDataResourceContext());
        adminDataResHandler.addFilter(
            new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)),
            "/*",
            Handler.DEFAULT);
        adminDataResHandler.addFilter(new FilterHolder(arfDataResources), "/*", Handler.DEFAULT);
        adminDataResHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setDaemon(true);
        server.setThreadPool(threadPool);

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(
            new Handler[] {adminTemplatesResHandler, adminDataResHandler, rootHandler});
        server.setHandler(handlers);

        server.start();

        final Connector connector = server.getConnectors()[0];
        serverPort = connector.getLocalPort();
      }
    } catch (Exception e) {
      logger.error("Exception in building AdminResourcesContainer ", e);
    }
  }