@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"));
  }
  @Test(dataProvider = "builders")
  public void testUsingInWithProvider(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);

    InjectedProvider injectedProvider = injector.getInstance(InjectedProvider.class);
    Assert.assertEquals(LazySingletonObject.constructorCount.get(), 0);
    Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 0);

    LazySingletonObject instance = injectedProvider.provider.get();
    Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1);
    Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1);

    LazySingletonObject instance2 = injectedProvider.provider.get();
    Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1);
    Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1);

    Assert.assertSame(instance, instance2);
  }
  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);
  }
  public void testModuleBindings() throws Exception {
    Module module =
        new AbstractModule() {
          @Override
          protected void configure() {}

          @Provides
          Integer fail() {
            return 1;
          }
        };
    // sanity check that the injector works
    Injector injector = Guice.createInjector(module);
    assertEquals(1, injector.getInstance(Integer.class).intValue());
    ProviderInstanceBinding injectorBinding =
        (ProviderInstanceBinding) injector.getBinding(Integer.class);
    assertEquals(1, injectorBinding.getUserSuppliedProvider().get());

    ProviderInstanceBinding moduleBinding =
        (ProviderInstanceBinding) Iterables.getOnlyElement(Elements.getElements(module));
    try {
      moduleBinding.getUserSuppliedProvider().get();
      fail();
    } catch (IllegalStateException ise) {
      assertEquals(
          "This Provider cannot be used until the Injector has been created.", ise.getMessage());
    }
  }
  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());
  }
  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());
  }
    @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();
    }
  /** 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;
  }
Example #9
0
  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));
        }
      }
    }
  }
  @Test
  public void testShippingHierarchy() {
    Injector injector = Guice.createInjector(new DbModule());
    PersistedClassDao persistedClassDao = injector.getInstance(PersistedClassDao.class);

    ShipsTo shippingFrom = new ShipsTo("USA");
    ShipsTo shippingToPak = new ShipsTo("Pakistan", 5L, 35.00);
    ShipsTo shippingToEngland = new ShipsTo("England", 2L, 20.00);
    ShipsTo shippingToGermany = new ShipsTo("Germany", 1L, 15.00);

    Set<ShipsTo> shippingTo = new HashSet<ShipsTo>();
    shippingTo.add(shippingToPak);
    shippingTo.add(shippingToEngland);
    shippingTo.add(shippingToGermany);

    shippingFrom.setShippingTo(shippingTo);

    persistedClassDao.saveInNewTransaction(shippingFrom);

    ShipsTo retrievedShipping =
        persistedClassDao.getEntityManager().find(ShipsTo.class, shippingFrom.getId());
    Assert.assertNotNull(retrievedShipping.getId());

    Set<ShipsTo> shippingsFrom = (Set<ShipsTo>) retrievedShipping.getShippingTo();
    Iterator<ShipsTo> ite = shippingsFrom.iterator();
    while (ite.hasNext()) {
      ShipsTo shipping = ite.next();
      Assert.assertNotNull(shipping.getId());
    }
  }
  /**
   * Initializes the application; in particular, bootstrapping the Isis backend, and initializing
   * the {@link ComponentFactoryRegistry} to be used for rendering.
   */
  @Override
  protected void init() {
    super.init();

    // 6.0.0 rather than overriding getRequestCycleSettings
    // TODO: reinstate REDIRECT_TO_RENDER once WICKET-4773 implemented (Wicket 6.1.0)
    getRequestCycleSettings().setRenderStrategy(RenderStrategy.REDIRECT_TO_BUFFER);
    // 6.0.0 instead of subclassing newRequestCycle
    getRequestCycleListeners().add(new WebRequestCycleForIsis());

    getResourceSettings().setParentFolderPlaceholder("$up$");
    final DeploymentType deploymentType = determineDeploymentType();

    final IsisConfigurationBuilder isisConfigurationBuilder =
        createConfigBuilder(getServletContext());

    final IsisInjectModule isisModule =
        new IsisInjectModule(deploymentType, isisConfigurationBuilder);
    final Injector injector = Guice.createInjector(isisModule, newIsisWicketModule());
    injector.injectMembers(this);

    this.bookmarkedPagesModel = new BookmarkedPagesModel();

    initWicketComponentInjection(injector);
  }
  @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();
  }
Example #13
0
	@Test
	public void testShutDown() throws Exception {
		final Injector injector = Guice.createInjector(new TextExtractorModule());
		final QueueListener __ = injector.getInstance(QueueListener.class);
		final String fn = "/tmp/img-test-large.jpg";
		Commons.copyStreamIntoFile(Commons.loadInputStreamFromSourceName("/rec02.jpg"), fn);
		for (int i = 0; i < 2; i++) {
			final String id = "test_msg_id_" + i;
			//			final String msg = "{\"receipt\":{\"id\":\"" + id + "\",\"url\":\"file://" + fn + "\"}}";
			final String msg = "{\"receipt\":{\"extracted_store_name_raw_json\":null,\"img_updated_at\":\"2011-03-31T22:36:26Z\",\"img_file_size\":4816,\"extracted_store_name\":null,\"created_at\":\"2011-03-31T22:36:26Z\",\"updated_at\":\"2011-03-31T22:36:26Z\",\"url\":\"https://s3.amazonaws.com/recipitor_receipts_prod/imgs/170/medium/screenshot2.png?AWSAccessKeyId=AKIAJ77AXDKGDKTJEOMQ&Expires=1301697386&Signature=gHsq%2BuhElgDCU9RzaoK%2BqngTH2o%3D\",\"id\":"
					+ "\""
					+ id
					+ "\""
					+ ",\"user_id\":3,\"img_file_name\":\"screenshot2.png\",\"description\":null,\"img_content_type\":\"image/png\"}}";
			__.REQ.sendMessage(msg);
		}
		final Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					__.listen();
				} catch (final Exception e) {
					e.printStackTrace();
					Assert.fail();
				}
			}
		});
		t.start();
		Thread.sleep(3000);
		//		__.onShutDown();
	}
  @Test
  public void methodToMethod() throws Exception {

    ShapeHelperWrapper shapeHelperWrapper = Mockito.mock(ShapeHelperWrapper.class);
    UnoRuntimeWrapper unoRuntimeWrapper = Mockito.mock(UnoRuntimeWrapper.class);

    XShape method1 = Mockito.mock(XShape.class);

    XShape method2 = Mockito.mock(XShape.class);
    Mockito.when(shapeHelperWrapper.getNodeType(method2)).thenReturn(Node.NodeType.MethodOfProcess);

    XConnectorShape link = Mockito.mock(XConnectorShape.class);
    XPropertySet linkPropertySet = Mockito.mock(XPropertySet.class);

    Mockito.when(shapeHelperWrapper.isConnectorShape(link)).thenReturn(true);

    Mockito.when(linkPropertySet.getPropertyValue(ConnectedShapes.START_SHAPE)).thenReturn(method2);
    Mockito.when(linkPropertySet.getPropertyValue(ConnectedShapes.END_SHAPE)).thenReturn(method1);

    Mockito.when(unoRuntimeWrapper.queryInterface(XPropertySet.class, link))
        .thenReturn(linkPropertySet);

    Injector injector = Guice.createInjector(new TestModule(shapeHelperWrapper, unoRuntimeWrapper));

    DiagramWalker diagramWalker = injector.getInstance(DiagramWalker.class);

    //        diagramWalker.walk(Sets.newHashSet());
  }
  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);
  }
Example #16
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);
  }
  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());
  }
 @BeforeClass(groups = "slow")
 protected void beforeClass() throws Exception {
   final Injector injector =
       Guice.createInjector(
           Stage.PRODUCTION, new TestEntitlementModuleWithEmbeddedDB(configSource));
   injector.injectMembers(this);
 }
  /** @param args */
  public static void main(String[] args) {

    Injector injector = Guice.createInjector(new OperationsModule());
    InstructionsProcessor opsController = injector.getInstance(InstructionsProcessor.class);
    setupInstructionList();
    opsController.processInstructions(instructionList);
  }
Example #20
0
  public final ServerStarter start(Stage stage, Consumer<ServerBuilder> consumer) {
    notNull(consumer, "Null ServerBuilder consumer");

    /* Create a new injector and set up the module */
    final Injector injector =
        Guice.createInjector(stage, (binder) -> consumer.accept(new ServerBuilder(binder)));

    /* Get a hold on our HttpServer instance */
    final HttpServer server = injector.getInstance(HttpServer.class);
    final String serverName = server.getServerConfiguration().getName();

    /* Attempt to start our server */
    try {
      log.info("Starting server %s", serverName);
      server.start();
    } catch (IOException exception) {
      log.error(exception, "Exception starting server %s", serverName);
      System.exit(1);
    }

    /* Add a shutdown hook terminating the server on exit */
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                log.info("Shutting down server %s", serverName);
                server.shutdown();
              }
            });

    /* Return self for chaining */
    this.server = server;
    return this;
  }
  public void testNullability() throws Exception {
    Module module =
        new AbstractModule() {
          @Override
          protected void configure() {
            bind(String.class).toProvider(Providers.<String>of(null));
          }

          @SuppressWarnings("unused")
          @Provides
          Integer fail(String foo) {
            return 1;
          }

          @SuppressWarnings("unused")
          @Provides
          Long succeed(@Nullable String foo) {
            return 2L;
          }
        };
    Injector injector = Guice.createInjector(module);
    InjectionPoint fooPoint =
        InjectionPoint.forMethod(
            module.getClass().getDeclaredMethod("fail", String.class),
            TypeLiteral.get(module.getClass()));
    Dependency<?> fooDependency = Iterables.getOnlyElement(fooPoint.getDependencies());

    runNullableTest(injector, fooDependency, module);

    injector.getInstance(Long.class);
  }
  @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) {

    }
  }
  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);
  }
  public RestTransportServer(RestContact contact, final AppServerHandler appServerHandler) {
    this.contact = contact;

    server = new Server(contact.getPort());
    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/");

    // servletContextHandler.addServlet(new ServletHolder(new
    // RestTransportServlet(appServerHandler)), "/*");
    servletContextHandler.addServlet(new ServletHolder(new NotFoundServlet()), "/*");

    final Injector injector =
        Guice.createInjector(
            new ReefyServletModule(),
            new AbstractModule() {
              @Override
              protected void configure() {
                binder().requireExplicitBindings();
                bind(GuiceFilter.class);
                bind(new TypeLiteral<AppServerHandler<RestContact>>() {})
                    .toInstance(appServerHandler);
              }
            });

    final FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
    servletContextHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    server.setHandler(servletContextHandler);
  }
  /** Ensures that transactions are rolled back when a runtime exception occurs. */
  public void testTransactionRolledBackOnRuntimeException() {
    /*
     * Create mock entity manager factory which returns a mock
     * entity manager when asked.
     */
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager em = mock(EntityManager.class);
    when(emf.create()).thenReturn(em);
    EntityTransaction tx = mock(EntityTransaction.class);
    when(em.getTransaction()).thenReturn(tx);

    Injector injector = Guice.createInjector(new TestModule(emf, true));
    OuterTransactedClass outer = injector.getInstance(OuterTransactedClass.class);
    try {
      outer.doSomethingInATransaction();
      fail("A runtime exception should have been thrown");
    } catch (RuntimeException ignored) {
    }

    // emf.create should only have been called once.
    verify(emf).create();
    verify(tx).begin();
    verify(tx).rollback();
    verify(em).close();
  }
 /** Test setup */
 @Before
 public void setUp() throws Exception {
   Injector injector = Guice.createInjector(new ShindigIntegratorTestsGuiceModule());
   personService = injector.getInstance(ShindigIntegratorPersonService.class);
   ((ShindigIntegratorPersonService) personService)
       .setPersistenceAdapter(new ShindigIntegratorPersistenceAdapter());
 }
Example #27
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());
  }
Example #28
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;
  }
 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()));
 }
 @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);
 }