예제 #1
0
 @BeforeMethod
 private void setUpManager() {
   final Injector injector = Guice.createInjector(new WorkspaceTckModule());
   manager = injector.getInstance(EntityManager.class);
   workspaceDao = injector.getInstance(JpaWorkspaceDao.class);
   cleaner = injector.getInstance(H2JpaCleaner.class);
 }
 @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();
 }
예제 #3
0
  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());
  }
 @Override
 protected DockerApi create(Properties props, Iterable<Module> modules) {
   Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();
   adapter = injector.getInstance(DockerComputeServiceAdapter.class);
   templateBuilder = injector.getInstance(TemplateBuilder.class);
   return injector.getInstance(DockerApi.class);
 }
 public GovernatorHttpInterceptorSupport<I, O> finish(Injector injector) {
   if (!finished) {
     for (HttpInClassHolder<I, O> holder : inboundInterceptorClasses) {
       HttpInboundHolder<I, O> ins = new HttpInboundHolder<I, O>(holder.getKey());
       for (Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>
           interceptor : holder.getInterceptors()) {
         ins.addIn(injector.getInstance(interceptor));
       }
       inboundInterceptors.add(ins.buildHolder());
     }
     for (HttpOutClassHolder<I, O> holder : outboundInterceptorClasses) {
       HttpOutboundHolder<I, O> outs = new HttpOutboundHolder<I, O>(holder.getKey());
       for (Class<? extends OutboundInterceptor<HttpServerResponse<O>>> interceptor :
           holder.getInterceptors()) {
         outs.addOut(injector.getInstance(interceptor));
       }
       outboundInterceptors.add(outs.buildHolder());
     }
     _finish();
     finished = true;
     if (null != finishListener) {
       finishListener.call(this);
     }
   }
   return this;
 }
 private void f() {
   Properties props = new Properties();
   props.setProperty("occurrence.ws.url", "api.gbif.org/v1/");
   Injector inj = Guice.createInjector(new OccurrenceWsClientModule(props));
   OccurrenceService occService = inj.getInstance(OccurrenceService.class);
   OccurrenceSearchService searchService = inj.getInstance(OccurrenceSearchService.class);
 }
  public void register(Injector injector) {
    if (!EPackage.Registry.INSTANCE.containsKey(
        "http://www.bme.hu/mit/inf/gomrp/statemachine/dsl/text/StateMachineDSL")) {
      EPackage.Registry.INSTANCE.put(
          "http://www.bme.hu/mit/inf/gomrp/statemachine/dsl/text/StateMachineDSL",
          hu.bme
              .mit
              .inf
              .gomrp
              .statemachine
              .dsl
              .text
              .stateMachineDSL
              .StateMachineDSLPackage
              .eINSTANCE);
    }

    org.eclipse.xtext.resource.IResourceFactory resourceFactory =
        injector.getInstance(org.eclipse.xtext.resource.IResourceFactory.class);
    org.eclipse.xtext.resource.IResourceServiceProvider serviceProvider =
        injector.getInstance(org.eclipse.xtext.resource.IResourceServiceProvider.class);
    Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("smbm", resourceFactory);
    org.eclipse.xtext.resource.IResourceServiceProvider.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("smbm", serviceProvider);
  }
  public void testSimpleTransaction() {
    injector.getInstance(TransactionalObject.class).runOperationInTxn();

    EntityManager session = injector.getInstance(EntityManager.class);
    assertFalse(
        "EntityManager was not closed by transactional service",
        session.getTransaction().isActive());

    // test that the data has been stored
    session.getTransaction().begin();
    Object result =
        session
            .createQuery("from JpaTestEntity where text = :text")
            .setParameter("text", UNIQUE_TEXT)
            .getSingleResult();

    session.getTransaction().commit();

    assertTrue("odd result returned fatal", result instanceof JpaTestEntity);

    assertEquals(
        "queried entity did not match--did automatic txn fail?",
        UNIQUE_TEXT,
        (((JpaTestEntity) result).getText()));
  }
  public void testSimpleTransactionRollbackOnCheckedExcepting() {
    Exception ex = null;
    try {
      injector.getInstance(TransactionalObject3.class).runOperationInTxnThrowingCheckedExcepting();
      fail("Exception was not thrown by test txn-al method!");
    } catch (IOException e) {
      // ignored
    }

    EntityManager session = injector.getInstance(EntityManager.class);
    assertFalse(
        "Txn was not closed by transactional service (commit didnt happen?)",
        session.getTransaction().isActive());

    // test that the data has been stored
    session.getTransaction().begin();
    Object result =
        session
            .createQuery("from JpaTestEntity where text = :text")
            .setParameter("text", UNIQUE_TEXT_2)
            .getSingleResult();

    session.getTransaction().commit();

    assertNotNull("a result was not returned! rollback happened anyway (ignore failed)!!!", result);
  }
  @Test(groups = "requiresTempFile")
  public void testAliasedBindingBindsCorrectly() {
    final String prefix = "test";
    Map<String, String> properties =
        createDefaultConfigurationProperties(prefix, temporaryFile.getAbsolutePath());

    Injector injector =
        createInjector(
            properties,
            new H2EmbeddedDataSourceModule(prefix, MainBinding.class, AliasBinding.class),
            new Module() {
              @Override
              public void configure(Binder binder) {
                binder.bind(TwoObjectsHolder.class);
              }
            });

    ObjectHolder objectHolder = injector.getInstance(ObjectHolder.class);
    TwoObjectsHolder twoObjectsHolder = injector.getInstance(TwoObjectsHolder.class);

    // Held data source objects should all be of the correct type
    Assertions.assertInstanceOf(twoObjectsHolder.mainDataSource, H2EmbeddedDataSource.class);
    Assertions.assertInstanceOf(twoObjectsHolder.aliasedDataSource, H2EmbeddedDataSource.class);

    // And should all be references to the same object
    assertSame(objectHolder.dataSource, twoObjectsHolder.mainDataSource);
    assertSame(objectHolder.dataSource, twoObjectsHolder.aliasedDataSource);
  }
  public void register(Injector injector) {

    org.eclipse.xtext.resource.IResourceFactory resourceFactory =
        injector.getInstance(org.eclipse.xtext.resource.IResourceFactory.class);
    org.eclipse.xtext.resource.IResourceServiceProvider serviceProvider =
        injector.getInstance(org.eclipse.xtext.resource.IResourceServiceProvider.class);
    Resource.Factory.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("eobjectatoffsettestlanguage", resourceFactory);
    org.eclipse.xtext.resource.IResourceServiceProvider.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("eobjectatoffsettestlanguage", serviceProvider);

    if (!EPackage.Registry.INSTANCE.containsKey(
        "http://www.xtext.org/EObjectAtOffsetTestLanguage")) {
      EPackage.Registry.INSTANCE.put(
          "http://www.xtext.org/EObjectAtOffsetTestLanguage",
          org.eclipse
              .xtext
              .resource
              .eObjectAtOffsetTestLanguage
              .EObjectAtOffsetTestLanguagePackage
              .eINSTANCE);
    }
  }
  @Test
  public void testStatisticStatistics() throws Exception {
    File tempFile = File.createTempFile("ais-ab-stat-builder", "");
    String outputFilename = tempFile.getCanonicalPath();
    String inputDirectory = "src/test/resources";
    String inputFilenamePattern = "ais-sample-micro.txt.gz";
    String[] args =
        new String[] {
          "-inputDirectory",
          inputDirectory,
          "-input",
          inputFilenamePattern,
          "-output",
          outputFilename
        };

    Injector injector =
        Guice.createInjector(
            new AbnormalStatBuilderAppTestModule(
                tempFile.getCanonicalPath(), inputDirectory, inputFilenamePattern, false, 200.0));
    AbnormalStatBuilderApp.setInjector(injector);
    AbnormalStatBuilderApp app = injector.getInstance(AbnormalStatBuilderApp.class);

    AbnormalStatBuilderApp.userArguments = parseUserArguments(args);
    app.execute(new String[] {});

    AppStatisticsService appStatistics = injector.getInstance(AppStatisticsService.class);
    assertEquals(
        (Long) 8L,
        appStatistics.getStatisticStatistics("ShipTypeAndSizeStatistic", "Events processed"));
  }
 public void test() {
   InputStream is = getClass().getResourceAsStream("/firewallService.xml");
   Injector injector = Guice.createInjector(new SaxParserModule());
   Factory factory = injector.getInstance(ParseSax.Factory.class);
   FirewallService result =
       factory.create(injector.getInstance(FirewallServiceHandler.class)).parse(is);
   assertEquals(result.isEnabled(), false);
   assertEquals(
       result.getFirewallRules(),
       ImmutableSet.<FirewallRule>of(
           FirewallRule.builder()
               .firewallType("SERVER_TIER_FIREWALL")
               .isEnabled(false)
               .source("internet")
               .destination("VM Tier01")
               .port("22")
               .protocol("Tcp")
               .policy("allow")
               .description("Server Tier Firewall Rule")
               .isLogged(false)
               .build(),
           FirewallRule.builder()
               .firewallType("SERVER_TIER_FIREWALL")
               .isEnabled(true)
               .source("VM Tier03")
               .destination("VM Tier03")
               .protocol("Icmp-ping")
               .policy("allow")
               .description("Server Tier Firewall Rule")
               .isLogged(false)
               .build()));
 }
예제 #14
0
파일: Qarrot.java 프로젝트: viphe/qarrot
  private void scanBindings() throws IOException {
    for (Map.Entry<Key<?>, Binding<?>> e : globalInjector.getAllBindings().entrySet()) {
      Key<?> bindingKey = e.getKey();
      Binding<?> binding = e.getValue();
      TypeLiteral boundTypeLiteral = bindingKey.getTypeLiteral();
      Type boundType = boundTypeLiteral.getType();
      if (boundType instanceof Class) {
        final Class boundClass = (Class) boundType;
        for (Method method : boundClass.getMethods()) {
          if ((method.getModifiers() & Modifier.STATIC) == 0) {
            for (Annotation annotation : method.getAnnotations()) {
              if (annotation instanceof Path) {
                Path pathSpec = (Path) annotation;
                RouteSpec routeIn = Routes.parse(pathSpec.value(), true);
                endPointMethods.add(new EndPointMethod(routeIn, bindingKey, boundClass, method));
              }
            }
          }
        }

        if (MessageBodyReader.class.isAssignableFrom(boundClass)) {
          messageBodyReaders.add(0, (MessageBodyReader) globalInjector.getInstance(bindingKey));
        }
        if (MessageBodyWriter.class.isAssignableFrom(boundClass)) {
          messageBodyWriters.add(0, (MessageBodyWriter) globalInjector.getInstance(bindingKey));
        }
      }
    }
  }
  /** Transforms the {@link Statechart} model to a {@link ExecutionFlow} model */
  protected ExecutionFlow createExecutionFlow(Statechart statechart, GeneratorEntry entry) {
    Injector injector = getInjector(entry);
    ModelSequencer sequencer = injector.getInstance(ModelSequencer.class);
    ExecutionFlow flow = sequencer.transform(statechart);
    Assert.isNotNull(flow, "Error creation ExecutionFlow");

    FeatureConfiguration optimizeConfig = entry.getFeatureConfiguration(FUNCTION_INLINING_FEATURE);

    FlowOptimizer optimizer = injector.getInstance(FlowOptimizer.class);

    optimizer.inlineReactions(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_REACTIONS, true));
    optimizer.inlineExitActions(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_EXIT_ACTIONS, true));
    optimizer.inlineEntryActions(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_ENTRY_ACTIONS, true));
    optimizer.inlineEnterSequences(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_ENTER_SEQUENCES, true));
    optimizer.inlineExitSequences(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_EXIT_SEQUENCES, true));
    optimizer.inlineChoices(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_CHOICES, true));
    optimizer.inlineEntries(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_ENTRIES, true));
    optimizer.inlineEnterRegion(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_ENTER_REGION, true));
    optimizer.inlineExitRegion(
        getBoolValue(optimizeConfig, FUNCTION_INLINING_FEATURE_INLINE_EXIT_REGION, true));

    flow = optimizer.transform(flow);

    return flow;
  }
  @Test
  public void testSimpleCrossTxnWork() {
    Session session1 = injector.getInstance(SessionFactory.class).openSession();
    ManagedSessionContext.bind(session1);
    HibernateTestEntity entity =
        injector
            .getInstance(ManualLocalTransactionsWithCustomMatchersTest.TransactionalObject.class)
            .runOperationInTxn();
    injector
        .getInstance(ManualLocalTransactionsWithCustomMatchersTest.TransactionalObject.class)
        .runOperationInTxn2();

    assert injector.getInstance(Session.class).contains(entity)
        : "Session appears to have been closed across txns!";
    session1.close();

    // try to query them back out

    Session session = injector.getInstance(SessionFactory.class).openSession();
    assert null
        != session
            .createCriteria(HibernateTestEntity.class)
            .add(Expression.eq("text", UNIQUE_TEXT))
            .uniqueResult();
    assert null
        != session
            .createCriteria(HibernateTestEntity.class)
            .add(Expression.eq("text", UNIQUE_TEXT_2))
            .uniqueResult();
    session.close();
  }
  @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"));
  }
예제 #18
0
  public static MessageRouter startMessageRouter(Injector injector) throws Exception {
    String mapDesc =
        "{\n"
            + "    \"topic1\": {\n"
            + "        \"where\": [\n"
            + "            { \"sink\" : \"sink1\" },\n"
            + "            { \"sink\" : \"default\" }\n"
            + "        ]\n"
            + "    },\n"
            + "    \"topic2\": {\n"
            + "        \"where\": [\n"
            + "            { \"sink\" : \"sink1\" },\n"
            + "            { \"sink\" : \"sink2\",\n"
            + "              \"filter\" : {"
            + "                \"type\"  : \"regex\",\n"
            + "                \"regex\" : \"1\"\n"
            + "                }"
            + "            }\n"
            + "        ]\n"
            + "    }\n"
            + "}";

    RoutingMap routingMap = injector.getInstance(RoutingMap.class);
    ObjectMapper mapper = injector.getInstance(ObjectMapper.class);
    routingMap.set(getRoutingMap(mapper, mapDesc));
    return injector.getInstance(MessageRouter.class);
  }
예제 #19
0
  @Override
  protected Injector getInjector() {
    Properties properties = new Properties();
    try {
      properties.load(getClass().getClassLoader().getResourceAsStream("rideapp.properties"));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    try {
      module =
          Class.forName(properties.getProperty("module.class"))
              .asSubclass(BaseModule.class)
              .getDeclaredConstructor(Properties.class)
              .newInstance(properties);
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    Injector injector = Guice.createInjector(module);
    // Stupid Guice bugs 455/522
    com.yrek.rideapp.servlet.UserServlet.objectMapper =
        injector.getInstance(org.codehaus.jackson.map.ObjectMapper.class);
    com.yrek.rideapp.servlet.UserServlet.restAPI =
        injector.getInstance(com.yrek.rideapp.rest.RESTAPI.class);
    com.yrek.rideapp.servlet.UserServlet.db =
        injector.getInstance(com.yrek.rideapp.storage.DB.class);
    return injector;
  }
 @Before
 public void init() {
   introInjector = Guice.createInjector(new IntrospectionEfficientPairsModule(introCollection));
   simpleInjector = Guice.createInjector(new EfficientPairsModule());
   eps1 = introInjector.getInstance(EfficientPairs.class);
   eps2 = simpleInjector.getInstance(EfficientPairs.class);
 }
예제 #21
0
  @SuppressWarnings("deprecation")
  public void testWatchers() {
    assertTrue(CItem.initialized);

    assertEquals(4, namedItemWatcher.items.size());
    assertEquals(2, markedItemWatcher.items.size());
    assertEquals(5, annotatedItemWatcher.items.size());

    assertTrue(namedItemWatcher.items.get(AItem.class.getName()) instanceof AItem);
    assertTrue(namedItemWatcher.items.get(BItem.class.getName()) instanceof BItem);
    assertTrue(namedItemWatcher.items.get(CItem.class.getName()) instanceof CItem);
    assertTrue(namedItemWatcher.items.get(DItem.class.getName()) instanceof DItem);

    assertNotSame(
        namedItemWatcher.items.get(AItem.class.getName()), injector.getInstance(AItem.class));
    assertSame(
        namedItemWatcher.items.get(CItem.class.getName()), injector.getInstance(CItem.class));

    assertTrue(markedItemWatcher.items.get(Integer.valueOf(0)) instanceof BItem);
    assertTrue(markedItemWatcher.items.get(Integer.valueOf(1)) instanceof DItem);

    injector.getInstance(MutableBeanLocator.class).remove(injector);

    assertEquals(0, namedItemWatcher.items.size());
    assertEquals(0, markedItemWatcher.items.size());
    assertEquals(0, annotatedItemWatcher.items.size());
  }
  public void register(Injector injector) {
    if (!EPackage.Registry.INSTANCE.containsKey(
        "http://www.eclipse.org/2011/xtext/idea/ui/common/types/xtext/ui/Refactoring")) {
      EPackage.Registry.INSTANCE.put(
          "http://www.eclipse.org/2011/xtext/idea/ui/common/types/xtext/ui/Refactoring",
          org.eclipse
              .xtext
              .idea
              .common
              .types
              .refactoringTestLanguage
              .RefactoringTestLanguagePackage
              .eINSTANCE);
    }

    org.eclipse.xtext.resource.IResourceFactory resourceFactory =
        injector.getInstance(org.eclipse.xtext.resource.IResourceFactory.class);
    org.eclipse.xtext.resource.IResourceServiceProvider serviceProvider =
        injector.getInstance(org.eclipse.xtext.resource.IResourceServiceProvider.class);
    Resource.Factory.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("ideaTypesRefactoring", resourceFactory);
    org.eclipse.xtext.resource.IResourceServiceProvider.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("ideaTypesRefactoring", serviceProvider);
  }
예제 #23
0
  public void testWildcardProviderMethods() {
    final List<String> strings = ImmutableList.of("A", "B", "C");
    final List<Number> numbers = ImmutableList.<Number>of(1, 2, 3);

    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                @SuppressWarnings("unchecked")
                Key<List<? super Integer>> listOfSupertypesOfInteger =
                    (Key<List<? super Integer>>)
                        Key.get(Types.listOf(Types.supertypeOf(Integer.class)));
                bind(listOfSupertypesOfInteger).toInstance(numbers);
              }

              @Provides
              public List<? extends CharSequence> provideCharSequences() {
                return strings;
              }

              @Provides
              public Class<?> provideType() {
                return Float.class;
              }
            });

    assertSame(strings, injector.getInstance(HasWildcardInjection.class).charSequences);
    assertSame(numbers, injector.getInstance(HasWildcardInjection.class).numbers);
    assertSame(Float.class, injector.getInstance(HasWildcardInjection.class).type);
  }
예제 #24
0
  @Test(dataProvider = "builders")
  public void testUsingIn(LifecycleInjectorBuilder lifecycleInjectorBuilder) {
    Injector injector =
        lifecycleInjectorBuilder
            .withModules(
                new Module() {
                  @Override
                  public void configure(Binder binder) {
                    binder.bind(LazySingletonObject.class).in(LazySingletonScope.get());
                  }
                })
            .createInjector();

    Assert.assertEquals(LazySingletonObject.constructorCount.get(), 0);
    Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 0);

    LazySingletonObject instance = injector.getInstance(LazySingletonObject.class);
    Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1);
    Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1);

    LazySingletonObject instance2 = injector.getInstance(LazySingletonObject.class);
    Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1);
    Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1);

    Assert.assertSame(instance, instance2);
  }
    @Override
    public void setUp() throws Exception {
        networkManagerStub = new NetworkManagerStub();
        networkManagerStub.setPort(PORT);
        Injector injector = LimeTestUtils.createInjector(MyActivityCallback.class, new LimeTestUtils.NetworkManagerStubModule(networkManagerStub));
        super.setUp(injector);

        DownloadManagerImpl downloadManager = (DownloadManagerImpl)injector.getInstance(DownloadManager.class);
        callback = (MyActivityCallback) injector.getInstance(ActivityCallback.class);
        
        downloadManager.clearAllDownloads();
        
        //      Turn off by default, explicitly test elsewhere.
        networkManagerStub.setIncomingTLSEnabled(false);
        networkManagerStub.setOutgoingTLSEnabled(false);
        // duplicate queries are sent out each time, so avoid the DuplicateFilter
        Thread.sleep(2000);        

        // send a MessagesSupportedMessage
        testUP[0].send(injector.getInstance(MessagesSupportedVendorMessage.class));
        testUP[0].flush();
        
        // we expect to get a PushProxy request
        Message m;
        do {
            m = testUP[0].receive(TIMEOUT);
        } while (!(m instanceof PushProxyRequest));

        // we should answer the push proxy request
        PushProxyAcknowledgement ack = new PushProxyAcknowledgement(InetAddress
                .getLocalHost(), 6355, new GUID(m.getGUID()));
        testUP[0].send(ack);
        testUP[0].flush();
    }
예제 #26
0
  public RefControlTest() {
    systemConfig = SystemConfig.create();
    systemConfig.adminGroupId = admin;
    systemConfig.anonymousGroupId = anonymous;
    systemConfig.registeredGroupId = registered;
    systemConfig.ownerGroupId = owners;
    systemConfig.batchUsersGroupId = anonymous;
    try {
      byte[] bin = "abcdefghijklmnopqrstuvwxyz".getBytes("UTF-8");
      systemConfig.registerEmailPrivateKey = Base64.encodeBase64String(bin);
    } catch (UnsupportedEncodingException err) {
      throw new RuntimeException("Cannot encode key", err);
    }

    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(Config.class) //
                    .annotatedWith(GerritServerConfig.class) //
                    .toInstance(new Config());

                bind(SystemConfig.class).toInstance(systemConfig);
                bind(AuthConfig.class);
                bind(AnonymousUser.class);
              }
            });
    authConfig = injector.getInstance(AuthConfig.class);
    anonymousUser = injector.getInstance(AnonymousUser.class);
  }
  @BeforeClass
  public static void runServer() throws Exception {

    // Migrate database to the latest version
    Injector configManagerModuleInjector = Guice.createInjector(new ConfigManagerModule());
    CreateBaseline createBaseline = configManagerModuleInjector.getInstance(CreateBaseline.class);
    createBaseline.create();

    // Run service
    ringringServerApi = configManagerModuleInjector.getInstance(ringringServerApi.class);
    ringringServerApi.run();

    // Create direct db connection to the user repository
    Injector userRepositoryInjector = Guice.createInjector(new UserRepositoryModule());
    userRepository = userRepositoryInjector.getInstance(UserRepository.class);

    // Create config manager to direct access to the config
    configManager = new PropertiesConfigManagerImpl();

    // Start fake SMTP server
    wiser = new Wiser();
    wiser.setHostname(configManager.getSmtpHost());
    wiser.setPort(configManager.getSmtpPort());
    wiser.start();
  }
예제 #28
0
  /** Starts servers for connection with aion client and login server. */
  private void startServers() {
    NioServer nioServer = injector.getInstance(NioServer.class);
    LoginServer loginServer = injector.getInstance(LoginServer.class);

    // Nio must go first
    nioServer.connect();
    loginServer.connect();
  }
예제 #29
0
  public void testProvidesMethodVisibility() {
    Injector injector = Guice.createInjector(new VisibilityModule());

    assertEquals(42, injector.getInstance(Integer.class).intValue());
    assertEquals(42L, injector.getInstance(Long.class).longValue());
    assertEquals(42D, injector.getInstance(Double.class).doubleValue(), 0.0);
    assertEquals(42F, injector.getInstance(Float.class).floatValue(), 0.0f);
  }
 public static void main(String[] args) {
   Injector injector = Guice.createInjector(new StaffModule());
   Staff messenger = injector.getInstance(Messenger.class);
   Staff guard = injector.getInstance(Guard.class);
   WorkDispatcher dispatcher = injector.getInstance(WorkDispatcher.class);
   Librarian librarian = new Librarian(messenger, guard, dispatcher);
   librarian.work();
 }