@Override
  protected void configureConnections(PrivateBinder binder) {
    binder.bind(QueryFactory.class).to(LdapQueryFactory.class);
    binder.bind(LdapTokenAttributeConversion.class);
    binder.bind(LdapSearchHandler.class);
    binder.bind(EntryPartialTokenConverter.class);
    binder.bind(EntryTokenConverter.class);
    binder.bind(LdapQueryBuilder.class);
    binder.bind(LdapQueryFactory.class);
    binder
        .bind(ConnectionConfig.class)
        .annotatedWith(Names.named(DataLayerConstants.EXTERNAL_CONFIG))
        .toProvider(ExternalConnectionConfigProvider.class);
    binder.bind(ConnectionFactoryProvider.class).to(LdapConnectionFactoryProvider.class);
    binder.bind(ConnectionFactory.class).toProvider(getConnectionFactoryProviderType());

    MapBinder<Class, EntryConverter> entryConverterBinder =
        MapBinder.newMapBinder(binder, Class.class, EntryConverter.class);
    entryConverterBinder.addBinding(String.class).to(EntryStringConverter.class);
    entryConverterBinder.addBinding(PartialToken.class).to(EntryPartialTokenConverter.class);
    entryConverterBinder.addBinding(Token.class).to(EntryTokenConverter.class);

    binder
        .bind(LdapDataLayerConfiguration.class)
        .to(getLdapConfigurationType())
        .in(Singleton.class);
    binder
        .bind(Key.get(LdapDataLayerConfiguration.class, DataLayer.Types.typed(connectionType)))
        .toProvider(binder.getProvider(LdapDataLayerConfiguration.class));
    binder.expose(Key.get(LdapDataLayerConfiguration.class, DataLayer.Types.typed(connectionType)));
  }
  private void doConnectionClosesTest(String url, TestBootstrapServer server) throws Exception {
    String responseData = "this is response data";
    int length = responseData.length();
    server.setResponseData(responseData);
    server.setResponse("HTTP/1.1 200 OK\r\nContent-Length: " + length);
    server.setAllowConnectionReuse(true);
    HttpGet get;
    LimeHttpClient client;

    get = new HttpGet(url);
    client = injector.getInstance(Key.get(LimeHttpClient.class));
    HttpResponse response = null;
    try {
      response = client.execute(get);
    } finally {
      client.releaseConnection(response);
    }

    Thread.sleep(1000 * 70);

    get = new HttpGet(url);
    client = injector.getInstance(Key.get(LimeHttpClient.class));
    try {
      response = client.execute(get);
    } finally {
      client.releaseConnection(response);
    }

    assertEquals("wrong connection attempts", 2, server.getConnectionAttempts());
    assertEquals("wrong request attempts", 2, server.getRequestAttempts());
  }
  public void testToString() {
    final Key<String> key1 = Key.get(String.class, Names.named("KEY"));
    final Key<String> key2 = Key.get(String.class, Names.named("BAD"));

    final Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(key1).toProvider(new ToStringProvider());
                bind(key2).toProvider(new BadToStringProvider());
              }
            });

    final Entry<Named, String> entry1 =
        new LazyBeanEntry<Named, String>(
            (Named) key1.getAnnotation(), injector.getBinding(key1), 0);
    final Entry<Named, String> entry2 =
        new LazyBeanEntry<Named, String>(
            (Named) key2.getAnnotation(), injector.getBinding(key2), 0);

    Exception error = null;
    try {
      injector.getInstance(key2);
    } catch (final Exception e) {
      error = e;
    }

    assertEquals('@' + javax.inject.Named.class.getName() + "(value=KEY)=VALUE", entry1.toString());
    assertEquals(
        '@' + javax.inject.Named.class.getName() + "(value=BAD)=" + error, entry2.toString());
  }
  public void testProviderMethodDependenciesAreExposed() throws Exception {
    Module module =
        new AbstractModule() {
          @Override
          protected void configure() {
            bind(Integer.class).toInstance(50);
            bindConstant().annotatedWith(Names.named("units")).to("Kg");
          }

          @Provides
          @Named("weight")
          String provideWeight(Integer count, @Named("units") String units) {
            return count + units;
          }
        };
    Injector injector = Guice.createInjector(module);

    ProviderInstanceBinding<?> binding =
        (ProviderInstanceBinding<?>)
            injector.getBinding(Key.get(String.class, Names.named("weight")));
    Method method =
        module.getClass().getDeclaredMethod("provideWeight", Integer.class, String.class);
    InjectionPoint point = new InjectionPoint(TypeLiteral.get(module.getClass()), method, false);
    assertEquals(
        ImmutableSet.<Dependency<?>>of(
            new Dependency<Integer>(point, Key.get(Integer.class), false, 0),
            new Dependency<String>(point, Key.get(String.class, Names.named("units")), false, 1)),
        binding.getDependencies());
  }
 @Singleton
 @Iso3166
 @Override
 public Map<String, Set<String>> get() {
   Builder<String, Set<String>> codes = ImmutableMap.<String, Set<String>>builder();
   for (String key : ImmutableSet.of(PROPERTY_REGION, PROPERTY_ZONE))
     try {
       String regionString = injector.getInstance(Key.get(String.class, named(key + "s")));
       for (String region : Splitter.on(',').split(regionString)) {
         try {
           codes.put(
               region,
               ImmutableSet.copyOf(
                   Splitter.on(',')
                       .split(
                           injector.getInstance(
                               Key.get(
                                   String.class,
                                   named(key + "." + region + "." + ISO3166_CODES))))));
         } catch (ConfigurationException e) {
           // this happens if regions property isn't set
           // services not run by AWS may not have regions, so this is ok.
         }
       }
     } catch (ConfigurationException e) {
       // this happens if regions property isn't set
       // services not run by AWS may not have regions, so this is ok.
     }
   return codes.build();
 }
 private void bindItem(final Binder binder, final SpaceIndexItem<Extension, ?> item)
     throws InstantiationException {
   switch (item.kind()) {
     case TYPE:
       {
         final Class impl = (Class) item.element();
         binder.bind(impl).in(Scopes.SINGLETON);
         bindHierarchy(binder, Key.get(impl));
         break;
       }
     case METHOD:
       {
         final Method method = (Method) item.element();
         final String name = method.getDeclaringClass().getName() + '.' + method.getName();
         final ExtensionQualifier qualifier = new ExtensionQualifierImpl(item.annotation(), name);
         bindProvider(binder, item, Key.get(method.getReturnType(), qualifier));
         break;
       }
     case FIELD:
       {
         final Field field = (Field) item.element();
         final String name = field.getDeclaringClass().getName() + '.' + field.getName();
         final ExtensionQualifier qualifier = new ExtensionQualifierImpl(item.annotation(), name);
         bindProvider(binder, item, Key.get(field.getType(), qualifier));
         break;
       }
     default:
       break;
   }
 }
示例#7
0
 /** Gets a key for the given type, member and annotations. */
 public static Key<?> getKey(
     TypeLiteral<?> type, Member member, Annotation[] annotations, Errors errors)
     throws ErrorsException {
   int numErrorsBefore = errors.size();
   Annotation found = findBindingAnnotation(errors, member, annotations);
   errors.throwIfNewErrors(numErrorsBefore);
   return found == null ? Key.get(type) : Key.get(type, found);
 }
  public void testDetails() {
    final Key<Bean> key1 = Key.get(Bean.class, Names.named("1"));
    final Key<Bean> key2 = Key.get(Bean.class, Names.named("2"));
    final Key<Bean> key3 = Key.get(Bean.class, Names.named("3"));
    final Key<Bean> key4 = Key.get(Bean.class, Names.named("4"));

    final Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(key1).to(DescribedBean.class).in(Scopes.SINGLETON);

                binder()
                    .withSource(
                        new BeanDescription() {
                          public String getDescription() {
                            return "Another test";
                          }
                        })
                    .bind(key2)
                    .toInstance(new BeanImpl());

                binder().withSource("where?").bind(key3).to(BeanImpl.class);

                bind(key4).toProvider(Providers.of(new BeanImpl()));
              }
            });

    final LazyBeanEntry<Annotation, Bean> bean1 =
        new LazyBeanEntry<Annotation, Bean>(key1.getAnnotation(), injector.getBinding(key1), 42);
    final LazyBeanEntry<Annotation, Bean> bean2 =
        new LazyBeanEntry<Annotation, Bean>(key2.getAnnotation(), injector.getBinding(key2), -24);
    final LazyBeanEntry<Annotation, Bean> bean3 =
        new LazyBeanEntry<Annotation, Bean>(key3.getAnnotation(), injector.getBinding(key3), 0);
    final LazyBeanEntry<Annotation, Bean> bean4 =
        new LazyBeanEntry<Annotation, Bean>(key4.getAnnotation(), injector.getBinding(key4), -1);

    assertEquals("This is a test", bean1.getDescription());
    assertTrue(bean1.getSource() instanceof StackTraceElement);
    assertEquals(DescribedBean.class, bean1.getImplementationClass());
    assertEquals(42, bean1.getRank());

    assertEquals("Another test", bean2.getDescription());
    assertTrue(bean2.getSource() instanceof BeanDescription);
    assertEquals(BeanImpl.class, bean2.getImplementationClass());
    assertEquals(-24, bean2.getRank());

    assertNull(bean3.getDescription());
    assertTrue(bean3.getSource() instanceof String);
    assertEquals(BeanImpl.class, bean3.getImplementationClass());
    assertEquals(0, bean3.getRank());

    assertNull(bean4.getDescription());
    assertTrue(bean4.getSource() instanceof StackTraceElement);
    assertEquals(null, bean4.getImplementationClass());
    assertEquals(-1, bean4.getRank());
  }
  @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);
    }
  }
 private AutoBindProvider getAutoBindProvider(Annotation annotation) {
   AutoBindProvider autoBindProvider = null;
   if (annotation.annotationType().isAnnotationPresent(AutoBind.class)) {
     ParameterizedType parameterizedType =
         Types.newParameterizedType(AutoBindProvider.class, annotation.annotationType());
     autoBindProvider =
         (AutoBindProvider<?>) injector.getInstance(Key.get(TypeLiteral.get(parameterizedType)));
   } else if (annotation.annotationType().isAssignableFrom(AutoBind.class)) {
     autoBindProvider =
         injector.getInstance(Key.get(new TypeLiteral<AutoBindProvider<AutoBind>>() {}));
   }
   return autoBindProvider;
 }
  @Override
  public void configure(Binder binder) {
    PolyBind.createChoice(
        binder, "druid.indexer.logs.type", Key.get(TaskLogs.class), Key.get(FileTaskLogs.class));
    JsonConfigProvider.bind(binder, "druid.indexer.logs", FileTaskLogsConfig.class);

    final MapBinder<String, TaskLogs> taskLogBinder = Binders.taskLogsBinder(binder);
    taskLogBinder.addBinding("noop").to(NoopTaskLogs.class).in(LazySingleton.class);
    taskLogBinder.addBinding("file").to(FileTaskLogs.class).in(LazySingleton.class);
    binder.bind(NoopTaskLogs.class).in(LazySingleton.class);
    binder.bind(FileTaskLogs.class).in(LazySingleton.class);

    binder.bind(TaskLogPusher.class).to(TaskLogs.class);
  }
  @Override
  public void configure(Binder binder) {
    // Instantiate eagerly so that we get everything registered and put into the Lifecycle
    // This makes the shutdown run pretty darn near last.

    try {
      // Reflection to try and allow non Log4j2 stuff to run. This acts as a gateway to stop errors
      // in the next few lines
      final Class<?> logManagerClazz = Class.forName("org.apache.logging.log4j.LogManager");

      final LoggerContextFactory contextFactory = LogManager.getFactory();
      if (!(contextFactory instanceof Log4jContextFactory)) {
        log.warn(
            "Expected [%s] found [%s]. Unknown class for context factory. Not logging shutdown",
            Log4jContextFactory.class.getCanonicalName(),
            contextFactory.getClass().getCanonicalName());
        return;
      }
      final ShutdownCallbackRegistry registry =
          ((Log4jContextFactory) contextFactory).getShutdownCallbackRegistry();
      if (!(registry instanceof Log4jShutdown)) {
        log.warn(
            "Shutdown callback registry expected class [%s] found [%s]. Skipping shutdown registry",
            Log4jShutdown.class.getCanonicalName(), registry.getClass().getCanonicalName());
        return;
      }
      binder.bind(Log4jShutdown.class).toInstance((Log4jShutdown) registry);
      binder
          .bind(Key.get(Log4jShutterDowner.class, Names.named("ForTheEagerness")))
          .to(Log4jShutterDowner.class)
          .asEagerSingleton();
    } catch (ClassNotFoundException | ClassCastException | LinkageError e) {
      log.warn(e, "Not registering log4j shutdown hooks. Not using log4j?");
    }
  }
  public void testApplyInputStreamDetails() throws UnknownHostException {
    InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json");

    UnwrapOnlyJsonValue<List<Image>> parser =
        i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<List<Image>>>() {}));
    List<Image> response =
        parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());

    assertEquals(response.get(0).getId(), 2);
    assertEquals(response.get(0).getName(), "CentOS 5.2");
    assertEquals(
        response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z"));
    assertEquals(response.get(0).getProgress(), null);
    assertEquals(response.get(0).getServerId(), null);
    assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE);
    assertEquals(
        response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));

    assertEquals(response.get(1).getId(), 743);
    assertEquals(response.get(1).getName(), "My Server Backup");
    assertEquals(
        response.get(1).getCreated(),
        dateService.iso8601SecondsDateParse("2009-07-07T09:56:16-05:00"));
    ;
    assertEquals(response.get(1).getProgress(), Integer.valueOf(80));
    assertEquals(response.get(1).getServerId(), Integer.valueOf(12));
    assertEquals(response.get(1).getStatus(), ImageStatus.SAVING);
    assertEquals(
        response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z"));
  }
 private <T> T getConfigurationValue(Class<T> type, String configurationKey) {
   try {
     return _injector.getInstance(Key.get(type, Names.named(configurationKey)));
   } catch (ConfigurationException e) {
     return null;
   }
 }
  @Test
  public void testGuice() throws Exception {
    Injector injector = Guice.createInjector(new MyModule());

    MyConfigurableRoute2 instance =
        injector.getInstance(Key.get(MyConfigurableRoute2.class, Names.named("foo")));
    assertNotNull("should have found a key for 'foo'", instance);

    log.info("Found instance: " + instance);

    // List<Binding<RouteBuilder>> list =
    // injector.findBindingsByType(TypeLiteral.get(RouteBuilder.class));
    Collection<RouteBuilder> list = Injectors.getInstancesOf(injector, RouteBuilder.class);
    log.info("RouteBuilder List: " + list);

    assertEquals("route builder list: " + list, 1, list.size());

    list = Injectors.getInstancesOf(injector, Matchers.subclassesOf(RouteBuilder.class));
    log.info("RouteBuilder List: " + list);

    assertEquals("route builder list: " + list, 1, list.size());
    /*
     * list = Injectors.getInstancesOf(injector,
     * Matchers.subclassesOf(RouteBuilder
     * .class).and(Matchers.annotatedWith(Names.named("foo"))));
     * log.info("RouteBuilder List: " + list);
     * assertEquals("route builder list: " + list, 1, list.size()); list =
     * Injectors.getInstancesOf(injector, Matchers.subclassesOf(RouteBuilder
     * .class).and(Matchers.annotatedWith(Names.named("bar"))));
     * log.info("RouteBuilder List: " + list);
     * assertEquals("route builder list: " + list, 0, list.size());
     */

    GuiceTest.assertCamelContextRunningThenCloseInjector(injector);
  }
  @Test
  public void testHttpSelectorAnnotation() {
    injector =
        Guice.createInjector(
            new ApplicationNameModule("test-application"),
            new ConfigurationModule(new ConfigurationFactory(ImmutableMap.<String, String>of())),
            new TestingNodeModule(),
            new TestingDiscoveryModule(),
            new TestingMBeanModule(),
            new ReportingModule(),
            new Module() {
              @Override
              public void configure(Binder binder) {
                discoveryBinder(binder).bindHttpSelector(serviceType("apple"));
              }
            });

    InMemoryDiscoveryClient discoveryClient = injector.getInstance(InMemoryDiscoveryClient.class);
    discoveryClient.announce(
        ImmutableSet.of(
            serviceAnnouncement("apple").addProperty("http", "fake://server-http").build()));

    HttpServiceSelector selector =
        injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple")));
    assertEquals(getOnlyElement(selector.selectHttpService()), URI.create("fake://server-http"));
  }
 @Test
 public void testGetEmitterViaRealGuice() {
   Injector injector =
       Guice.createInjector(
           new DruidGuiceExtensions(),
           new LifecycleModule(),
           new Module() {
             @Override
             public void configure(Binder binder) {
               Properties props = new Properties();
               props.put("druid.emitter.composing.emitters", "[\"" + testEmitterType + "\"]");
               binder.bind(Properties.class).toInstance(props);
               binder
                   .bind(Validator.class)
                   .toInstance(Validation.buildDefaultValidatorFactory().getValidator());
               binder
                   .bind(Emitter.class)
                   .annotatedWith(Names.named(testEmitterType))
                   .toInstance(emitter);
             }
           },
           new ComposingEmitterModule());
   injector.getInstance(Key.get(Emitter.class, Names.named("composing"))).start();
   EasyMock.verify(emitter);
 }
  public void testJsrNamed() {
    final Named guiceNamed = Names.named("TEST");

    final Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bindConstant().annotatedWith(guiceNamed).to("CONSTANT");
              }
            });

    @SuppressWarnings({"unchecked", "rawtypes"})
    final LazyBeanEntry<javax.inject.Named, String> entry =
        new LazyBeanEntry(guiceNamed, injector.getBinding(Key.get(String.class, guiceNamed)), 0);

    final javax.inject.Named jsrNamed = entry.getKey();

    assertTrue(jsrNamed.equals(jsrNamed));
    assertTrue(jsrNamed.equals(entry.getKey()));
    assertTrue(jsrNamed.equals(T.class.getAnnotation(javax.inject.Named.class)));
    assertTrue(jsrNamed.equals(guiceNamed));

    assertFalse(jsrNamed.equals(Names.named("")));
    assertFalse(jsrNamed.equals("TEST"));

    assertEquals(javax.inject.Named.class, jsrNamed.annotationType());

    assertEquals(T.class.getAnnotation(javax.inject.Named.class).hashCode(), jsrNamed.hashCode());
  }
  @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) {

    }
  }
示例#20
0
  public void testAssistedFactoryForTypeVariableParameters() {
    final TypeLiteral<InsuranceFactory<Camaro>> camaroInsuranceFactoryType =
        new TypeLiteral<InsuranceFactory<Camaro>>() {};

    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(Double.class).toInstance(50000.0d);
                bind(camaroInsuranceFactoryType)
                    .toProvider(
                        FactoryProvider.newFactory(
                            camaroInsuranceFactoryType,
                            new TypeLiteral<AutoInsurance<Camaro>>() {}));
              }
            });

    InsuranceFactory<Camaro> camaroInsuranceFactory =
        injector.getInstance(Key.get(camaroInsuranceFactoryType));

    Camaro camaro = new Camaro(3000, 1967, Color.BLUE);
    AutoInsurance camaroPolicy = (AutoInsurance) camaroInsuranceFactory.create(camaro, 800.0d);
    assertEquals(800.0d, camaroPolicy.premium);
    assertEquals(50000.0d, camaroPolicy.limit);
    assertEquals(camaro, camaroPolicy.car);
  }
示例#21
0
 /**
  * Declare a singleton {@code DynamicItem<T>} with a binder.
  *
  * <p>Items must be defined in a Guice module before they can be bound:
  *
  * <pre>
  *   DynamicSet.itemOf(binder(), new TypeLiteral&lt;Thing&lt;Foo&gt;&gt;() {});
  * </pre>
  *
  * @param binder a new binder created in the module.
  * @param member type of entry to store.
  */
 public static <T> void itemOf(Binder binder, TypeLiteral<T> member) {
   @SuppressWarnings("unchecked")
   Key<DynamicItem<T>> key =
       (Key<DynamicItem<T>>)
           Key.get(Types.newParameterizedType(DynamicItem.class, member.getType()));
   binder.bind(key).toProvider(new DynamicItemProvider<>(member, key)).in(Scopes.SINGLETON);
 }
 private void doUppercaseTest(String url, TestBootstrapServer server) throws Exception {
   // Make sure we can deal with strange info such as uppercase
   // HTTP stuff.
   HttpGet get = new HttpGet(url.toUpperCase());
   HttpClient client = injector.getInstance(Key.get(LimeHttpClient.class));
   client.execute(get);
   assertNotNull(server.getRequest());
 }
  @Override
  public synchronized void initPipeline(final ServletContext context) throws ServletException {
    if (servletContext == null && context != null) {
      servletContext = context;

      // register trigger to update definitions as FilterPipeline bindings come and go
      locator.watch(Key.get(FilterPipeline.class), new FilterPipelineMediator(), this);
    }
  }
示例#24
0
  @Test
  public void testSeed() {
    scope.enter();

    try {
      scope.scope(Key.get(SeedTarget.class), new ThrowingProvider<SeedTarget>()).get();
      // should throw exception
      assertTrue(false);
    } catch (OutOfScopeException e) {
      assertTrue(true);
    }

    scope.seed(SeedTarget.class, new SeedTarget());

    assertNotNull(scope.scope(Key.get(SeedTarget.class), new ThrowingProvider<SeedTarget>()).get());

    scope.exit();
  }
 public ComputeServiceContext buildComputeServiceContext() {
   // need the generic type information
   return (ComputeServiceContext)
       buildInjector()
           .getInstance(
               Key.get(
                   Types.newParameterizedType(
                       ComputeServiceContextImpl.class, syncClientType, asyncClientType)));
 }
  public void testSpi() throws Exception {
    Module m1 =
        new AbstractModule() {
          @Override
          protected void configure() {}

          @Provides
          @Named("foo")
          String provideFoo(Integer dep) {
            return "foo";
          }
        };
    Module m2 =
        new AbstractModule() {
          @Override
          protected void configure() {}

          @Provides
          Integer provideInt(@Named("foo") String dep) {
            return 42;
          }
        };
    Injector injector = Guice.createInjector(m1, m2);

    Binding<String> stringBinding = injector.getBinding(Key.get(String.class, Names.named("foo")));
    ProvidesMethodBinding<String> stringMethod =
        stringBinding.acceptTargetVisitor(new BindingCapturer<String>());
    assertEquals(m1, stringMethod.getEnclosingInstance());
    assertEquals(
        m1.getClass().getDeclaredMethod("provideFoo", Integer.class), stringMethod.getMethod());
    assertEquals(
        ((HasDependencies) stringBinding).getDependencies(), stringMethod.getDependencies());
    assertEquals(Key.get(String.class, Names.named("foo")), stringMethod.getKey());

    Binding<Integer> intBinding = injector.getBinding(Integer.class);
    ProvidesMethodBinding<Integer> intMethod =
        intBinding.acceptTargetVisitor(new BindingCapturer<Integer>());
    assertEquals(m2, intMethod.getEnclosingInstance());
    assertEquals(
        m2.getClass().getDeclaredMethod("provideInt", String.class), intMethod.getMethod());
    assertEquals(((HasDependencies) intBinding).getDependencies(), intMethod.getDependencies());
    assertEquals(Key.get(Integer.class), intMethod.getKey());
  }
 public void testTLStoNormalFails() throws Exception {
   // make sure execution fails if the server doesn't respond
   HttpClient client = injector.getInstance(Key.get(LimeHttpClient.class));
   HttpGet get = new HttpGet("tls://127.0.0.1:" + HTTP_PORT);
   try {
     client.execute(get);
     fail("should have thrown exception");
   } catch (IOException expected) {
   }
 }
  public void testApplyInputStreamDetails() throws UnknownHostException {
    InputStream is = getClass().getResourceAsStream("/test_list_backupschedule.json");

    UnwrapOnlyJsonValue<BackupSchedule> parser =
        i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<BackupSchedule>>() {}));
    BackupSchedule response =
        parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
    assertEquals(
        new BackupSchedule(WeeklyBackup.THURSDAY, DailyBackup.H_0400_0600, true), response);
  }
示例#29
0
  @Override
  protected void configure() {
    bind(Lifecycle.class).in(Singleton.class);

    bind(Key.get(ExceptionalCommand.class, StartupStage.class)).to(StartupRegistry.class);
    bind(StartupRegistry.class).in(Singleton.class);

    bind(ShutdownRegistry.class).to(ShutdownRegistryImpl.class);
    bind(Key.get(Command.class, ShutdownStage.class)).to(ShutdownRegistryImpl.class);
    bind(ShutdownRegistryImpl.class).in(Singleton.class);
    bindStartupAction(binder(), ShutdownHookRegistration.class);

    bind(LocalServiceRegistry.class).in(Singleton.class);

    // Ensure that there is at least an empty set for the service runners.
    runnerBinder(binder());

    bindStartupAction(binder(), LocalServiceLauncher.class);
  }
  private void doExecuteMethodRedirectingTest(String[] urls, TestBootstrapServer[] servers)
      throws Exception {
    HttpClient client = injector.getInstance(Key.get(LimeHttpClient.class));
    HttpGet get = new HttpGet(urls[0]);

    servers[0].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[1]);
    servers[1].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[2]);

    servers[2].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[3]);
    servers[3].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[4]);
    servers[4].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[5]);
    servers[5].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[6]);
    servers[6].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[7]);
    servers[7].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[8]);
    servers[8].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[9]);
    servers[9].setResponse("HTTP/1.1 303 Redirect\r\nLocation: " + urls[10]);

    try {
      client.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 1);
      client.execute(get);
      fail("Should have thrown redirect failure");
    } catch (ClientProtocolException he) {
      assertNotNull(servers[0].getRequest());
      assertNotNull(servers[1].getRequest());
      assertNull(servers[2].getRequest()); // should have stopped after 1 & 2 tried.
      // expected.
    }

    get = new HttpGet(urls[2]);
    client = injector.getInstance(Key.get(LimeHttpClient.class));
    client.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 8);
    client.execute(get);
    assertNotNull(servers[2].getRequest());
    assertNotNull(servers[3].getRequest());
    assertNotNull(servers[4].getRequest());
    assertNotNull(servers[5].getRequest());
    assertNotNull(servers[6].getRequest());
    assertNotNull(servers[7].getRequest());
    assertNotNull(servers[8].getRequest());
    assertNotNull(servers[9].getRequest());
    assertNotNull(servers[10].getRequest());
  }