Java Code Examples for com.google.inject.Injector

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project components-ness-hbase, under directory /src/test/java/com/nesscomputing/hbase/.

Source file: TestHBaseModule.java

  19 
vote

@Test public void testBasicConfig(){
  final Config config=Config.getFixedConfig("ness.hbase.zookeeper.quorum","host1,host2,host3","ness.hbase.zookeeper.path","/foobar");
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,new ConfigModule(config),new HBaseModule());
  final HBaseConfig hbc=inj.getInstance(HBaseConfig.class);
  Assert.assertEquals("host1,host2,host3",hbc.getHBaseZookeeperQuorum());
  Assert.assertEquals("/foobar",hbc.getHBaseZookeeperPath());
}
 

Example 2

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/view/.

Source file: TouchPane.java

  18 
vote

private void initialize(Context context){
  Context applicationContext=context.getApplicationContext();
  Injector injector=AirCastingApplication.class.cast(applicationContext).getInjector();
  injector.injectMembers(this);
  gestureDetector.setOnDoubleTapListener(this);
}
 

Example 3

From project airlift, under directory /bootstrap/src/test/java/io/airlift/bootstrap/.

Source file: TestLifeCycleManager.java

  18 
vote

@Test public void testImmediateStarts() throws Exception {
  Module module=new Module(){
    @Override public void configure(    Binder binder){
      binder.bind(InstanceThatRequiresStart.class).in(Scopes.SINGLETON);
      binder.bind(InstanceThatUsesInstanceThatRequiresStart.class).in(Scopes.SINGLETON);
    }
  }
;
  Injector injector=Guice.createInjector(Stage.PRODUCTION,new LifeCycleModule(),module);
  LifeCycleManager lifeCycleManager=injector.getInstance(LifeCycleManager.class);
  lifeCycleManager.start();
  Assert.assertEquals(stateLog,Arrays.asList("InstanceThatUsesInstanceThatRequiresStart:OK"));
}
 

Example 4

From project android-rackspacecloud, under directory /extensions/log4j/src/test/java/org/jclouds/logging/log4j/config/.

Source file: Log4JLoggingModuleTest.java

  18 
vote

@Test public void testConfigure(){
  Injector i=Guice.createInjector(new Log4JLoggingModule());
  A a=i.getInstance(A.class);
  assertEquals(a.logger.getClass(),Log4JLogger.class);
  assertEquals(a.logger.getCategory(),getClass().getName() + "$A");
}
 

Example 5

From project androidannotations, under directory /AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/roboguice/.

Source file: InjectedTestRunner.java

  18 
vote

@Override public void prepareTest(Object test){
  SampleRoboApplication application=(SampleRoboApplication)Robolectric.application;
  Injector injector=application.getInjector();
  ContextScope scope=injector.getInstance(ContextScope.class);
  scope.enter(application);
  injector.injectMembers(test);
}
 

Example 6

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/.

Source file: AreciboAggregatorServer.java

  18 
vote

public static void main(String[] args) throws Exception {
  Injector injector=Guice.createInjector(Stage.PRODUCTION,new LifecycleModule(),new RMIModule(),new AbstractModule(){
    @Override protected void configure(){
      bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
    }
  }
,new EventPublisherModule(EventSenderType.SERVER),new EmbeddedJettyJerseyModule(),new RESTEventReceiverModule(EventProcessorImpl.class,"arecibo.aggregator:name=EventProcessor"),new UDPEventReceiverModule(),new EsperStatsModule(),new MonitoringPluginModule(),new KeyedExecutorModule(),new AggregatorModule());
  AggregatorServer server=injector.getInstance(AggregatorServer.class);
  server.run();
}
 

Example 7

From project atunit, under directory /atunit-guice/src/main/java/atunit/guice/.

Source file: GuiceContainer.java

  18 
vote

public Object createTest(Class<?> testClass,Map<Field,Object> fieldValues) throws Exception {
  FieldModule fields=new FieldModule(fieldValues);
  Injector injector;
  if (Module.class.isAssignableFrom(testClass)) {
    injector=Guice.createInjector(fields,(Module)testClass.newInstance());
  }
 else {
    injector=Guice.createInjector(fields);
  }
  return injector.getInstance(testClass);
}
 

Example 8

From project atunit_1, under directory /src/atunit/guice/.

Source file: GuiceContainer.java

  18 
vote

public Object createTest(Class<?> testClass,Map<Field,Object> fieldValues) throws Exception {
  FieldModule fields=new FieldModule(fieldValues);
  Injector injector;
  if (Module.class.isAssignableFrom(testClass)) {
    injector=Guice.createInjector(fields,(Module)testClass.newInstance());
  }
 else {
    injector=Guice.createInjector(fields);
  }
  return injector.getInstance(testClass);
}
 

Example 9

From project candlepin, under directory /src/test/java/org/candlepin/pinsetter/tasks/.

Source file: ImportRecordJobTest.java

  18 
vote

@Before public void init(){
  CandlepinCommonTestingModule testingModule=new CandlepinCommonTestingModule();
  Injector injector=Guice.createInjector(testingModule,new CandlepinNonServletEnvironmentTestingModule());
  this.ownerCurator=injector.getInstance(OwnerCurator.class);
  this.importRecordCurator=injector.getInstance(ImportRecordCurator.class);
  this.job=injector.getInstance(ImportRecordJob.class);
}
 

Example 10

From project cdk, under directory /commons/src/test/java/org/richfaces/cdk/.

Source file: CdkTestRunner.java

  18 
vote

private Object createTest(Class<?> testClass,Map<Field,Binding> fieldValues) throws Exception {
  FieldModule fields=new FieldModule(fieldValues);
  Injector injector;
  Object test=super.createTest();
  if (Module.class.isAssignableFrom(testClass)) {
    injector=Guice.createInjector(fields,(Module)testClass.newInstance());
  }
 else {
    injector=Guice.createInjector(fields);
  }
  injector.injectMembers(test);
  return test;
}
 

Example 11

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: Main.java

  18 
vote

public static void main(String[] args) throws Exception {
  Bootstrap app=new Bootstrap(new NodeModule(),new DiscoveryModule(),new HttpServerModule(),new JsonModule(),new JaxrsModule(),new MBeanModule(),new JmxModule(),new JmxHttpRpcModule(),new LogJmxModule(),new TraceTokenModule(),new NullEventModule(),ConditionalModule.installIfPropertyEquals(new InventoryClientModule(),"cloud-management.manager","Inventory"),ConditionalModule.installIfPropertyEquals(new InMemoryManagerModule(),"cloud-management.manager","InMemory"),new MainModule());
  try {
    Injector injector=app.strictConfig().initialize();
    injector.getInstance(Announcer.class).start();
  }
 catch (  Throwable e) {
    log.error(e);
    System.exit(1);
  }
}
 

Example 12

From project components-ness-config, under directory /src/test/java/com/nesscomputing/config/.

Source file: ConfigProviderTest.java

  18 
vote

@Test public void testConfigBeansSingleton(){
  Injector injector=Guice.createInjector(new AbstractModule(){
    @Override protected void configure(){
      install(ConfigModule.forTesting());
      bind(TestConfig.class).toProvider(ConfigProvider.of(TestConfig.class));
    }
  }
);
  TestConfig first=injector.getInstance(TestConfig.class);
  TestConfig second=injector.getInstance(TestConfig.class);
  Assert.assertSame("not bound as singleton,",first,second);
}
 

Example 13

From project components-ness-httpclient, under directory /client/src/test/java/com/nesscomputing/httpclient/guice/.

Source file: TestGuiceModule.java

  18 
vote

@Test public void testMultiple(){
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,ConfigModule.forTesting(),ENFORCEMENT_MODULE,new LifecycleModule(),new HttpClientModule("testing"),new HttpClientModule("running"));
  final HttpClient testingHttpClient=injector.getInstance(Key.get(HttpClient.class,Names.named("testing")));
  final HttpClient runningHttpClient=injector.getInstance(Key.get(HttpClient.class,Names.named("running")));
  Assert.assertNotNull(testingHttpClient);
  Assert.assertNotNull(runningHttpClient);
  Assert.assertFalse(testingHttpClient == runningHttpClient);
}
 

Example 14

From project components-ness-httpserver_1, under directory /src/main/java/com/nesscomputing/httpserver/standalone/.

Source file: StandaloneServer.java

  18 
vote

public final Injector getInjector(){
  final Config config=getConfig();
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,getPlumbingModules(config),getMainModule(config),new Module(){
    @Override public void configure(    final Binder binder){
      binder.requireExplicitBindings();
      binder.disableCircularProxies();
    }
  }
);
  return injector;
}
 

Example 15

From project components-ness-integration-testing, under directory /src/main/java/com/nesscomputing/testing/.

Source file: IntegrationTestRule.java

  18 
vote

/** 
 * Setup the various injectors. This is run when the rule triggers so that other rules (such as database or lifecycle) can be ready by the time the injectors are created.
 */
private void setup(){
  for (  final Entry<String,Module> service : services.entrySet()) {
    final Injector injector=Guice.createInjector(Stage.PRODUCTION,new GuiceDisableModule(),service.getValue());
    serviceInjectors.put(service.getKey(),injector);
    final Binding<Lifecycle> lifecycleBinding=injector.getExistingBinding(Key.get(Lifecycle.class));
    if (lifecycleBinding != null) {
      lifecycles.add(injector.getInstance(Lifecycle.class));
    }
  }
  final Injector testInjector=Guice.createInjector(Stage.PRODUCTION,new GuiceDisableModule(),testCaseModule);
  testInjector.injectMembers(this);
  testInjector.injectMembers(testCaseItself);
}
 

Example 16

From project components-ness-jackson, under directory /src/test/java/com/nesscomputing/jackson/.

Source file: TestJacksonFormatObjectMapperProvider.java

  18 
vote

@Test public void testBasics(){
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,ConfigModule.forTesting(),new NessJacksonModule());
  injector.injectMembers(this);
  Assert.assertNotNull(defaultMapper);
  Assert.assertNotNull(smileMapper);
  Assert.assertNotNull(jsonMapper);
  Assert.assertNotSame(defaultMapper,jsonMapper);
  Assert.assertNotSame(defaultMapper,smileMapper);
  Assert.assertNotSame(smileMapper,jsonMapper);
}
 

Example 17

From project components-ness-jdbi, under directory /src/test/java/com/nesscomputing/jdbi/metrics/.

Source file: TestDatabaseMetricsModule.java

  18 
vote

@Test public void testSimple(){
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,new Module(){
    @Override public void configure(    final Binder binder){
      binder.requireExplicitBindings();
      binder.disableCircularProxies();
    }
  }
,new DatabaseMetricsModule(),new InstrumentationModule());
  inj.injectMembers(this);
  Assert.assertNotNull(tc);
  Assert.assertNull(durationUnit);
  Assert.assertNull(rateUnit);
}
 

Example 18

From project components-ness-jersey, under directory /jersey/src/test/java/com/nesscomputing/jersey/exceptions/.

Source file: TestGuiceProvisionExceptionMapper.java

  18 
vote

@Test public void testNullCauseMessage(){
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,new Module(){
    @Override public void configure(    final Binder binder){
      binder.bind(GuiceProvisionExceptionMapper.class).asEagerSingleton();
    }
  }
);
  final GuiceProvisionExceptionMapper mapper=injector.getInstance(GuiceProvisionExceptionMapper.class);
  final Throwable cause=new NullPointerException();
  final ProvisionException pe=new ProvisionException("hello, world",cause);
  final Response response=mapper.toResponse(pe);
  Assert.assertNotNull(response);
}
 

Example 19

From project components-ness-jmx, under directory /src/test/java/com/nesscomputing/jmx/starter/guice/.

Source file: TestJmxExporterConfigProvider.java

  18 
vote

private void prepareGuice(final Config config,final Module... modules){
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,new ConfigModule(config),new JmxStarterModule(config),new Module(){
    @Override public void configure(    final Binder binder){
      binder.disableCircularProxies();
      binder.requireExplicitBindings();
      binder.bind(MBeanServer.class).to(TestingMBeanServer.class).in(Scopes.SINGLETON);
      for (      final Module module : modules) {
        binder.install(module);
      }
    }
  }
);
  inj.injectMembers(this);
}
 

Example 20

From project components-ness-lifecycle, under directory /src/test/java/com/nesscomputing/lifecycle/guice/.

Source file: TestLifecycleAnnotations.java

  18 
vote

@Test(expected=ProvisionException.class) public void testLifecycleAnnotationsAfterStartFails(){
  Injector injector=Guice.createInjector(new AbstractModule(){
    @Override protected void configure(){
      binder().requireExplicitBindings();
      binder().disableCircularProxies();
      install(new LifecycleModule());
      bind(LifecycleTest.class);
      requestInjection(TestLifecycleAnnotations.this);
    }
  }
);
  lifecycle.executeTo(LifecycleStage.START_STAGE);
  injector.getInstance(LifecycleTest.class);
}
 

Example 21

From project components-ness-tracking, under directory /src/test/java/com/nesscomputing/tracking/.

Source file: AbstractTrackingTestCase.java

  18 
vote

@Before public void setUpTracking() throws Exception {
  mockSupport=new EasyMockSupport();
  final Config config=getConfig();
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,new ThreadDelegatedScopeModule(),new TrackingModule(),getTestModule(),new AbstractModule(){
    @Override public void configure(){
      binder().requireExplicitBindings();
      binder().disableCircularProxies();
      bind(Config.class).toInstance(config);
      bind(GuiceFilter.class).in(Scopes.SINGLETON);
    }
  }
);
  injector.injectMembers(this);
}
 

Example 22

From project dimdwarf, under directory /dimdwarf-core/src/test/java/net/orfjackal/dimdwarf/tasks/.

Source file: RetryableExceptionsSpec.java

  18 
vote

public void create() throws Exception {
  server=new TestServer(new CommonModules());
  server.changeLoggingLevel(TransactionFilter.class,Level.WARNING);
  server.changeLoggingLevel(RetryingTaskExecutor.class,Level.WARNING);
  Injector injector=server.getInjector();
  taskContext=injector.getInstance(RetryingTaskExecutor.class);
  entities=injector.getProvider(EntityDao.class);
}
 

Example 23

From project eclipse-task-editor, under directory /plugins/de.sebastianbenz.task/src/de/sebastianbenz/task/generator/.

Source file: Main.java

  18 
vote

public static void main(String[] args){
  if (args.length == 0) {
    System.err.println("Aborting: no path to EMF resource provided!");
    return;
  }
  Injector injector=new de.sebastianbenz.task.TaskStandaloneSetup().createInjectorAndDoEMFRegistration();
  Main main=injector.getInstance(Main.class);
  main.runGenerator(args[0]);
}
 

Example 24

From project edna-rcp, under directory /org.edna.datamodel.language/src/org/edna/datamodel/.

Source file: DatamodelStandaloneSetup.java

  18 
vote

public void setStandalone(boolean standalone){
  if (standalone) {
    Injector theInjector=createInjectorAndDoEMFRegistration();
    DatamodelInjector.injector.set(theInjector);
  }
}
 

Example 25

From project ElasticSearchExample, under directory /src/main/java/de/jetwick/ese/search/.

Source file: Feeding.java

  18 
vote

public void start(boolean fake){
  Module module=new DefaultModule();
  Injector injector=Guice.createInjector(module);
  MySearch tws=injector.getInstance(MySearch.class);
  Collection<MyTweet> tweets;
  if (fake)   tweets=createFake();
 else   tweets=createReal();
  logger.info("Now feeding");
  StopWatch sw=new StopWatch().start();
  tws.bulkUpdate(tweets,tws.getIndexName());
  long time=sw.stop().totalTime().seconds();
  if (time == 0)   time=1;
  logger.info("Feeded " + tweets.size() + " users => "+ tweets.size() / time + " users/sec");
}
 

Example 26

From project EMF-IncQuery, under directory /plugins/org.eclipse.viatra2.emf.incquery.runtime/src/org/eclipse/viatra2/emf/incquery/runtime/api/.

Source file: IncQueryEngine.java

  18 
vote

/** 
 * Provides a static default logger.
 */
public static Logger getDefaultLogger(){
  if (defaultRuntimeLogger == null) {
    final Injector injector=XtextInjectorProvider.INSTANCE.getInjector();
    if (injector == null)     throw new AssertionError("Configuration error: EMF-IncQuery injector not initialized.");
    Logger parentLogger=injector.getInstance(Logger.class);
    if (parentLogger == null)     throw new AssertionError("Configuration error: EMF-IncQuery logger not found.");
    defaultRuntimeLogger=Logger.getLogger(parentLogger.getName() + ".runtime");
    if (defaultRuntimeLogger == null)     throw new AssertionError("Configuration error: unable to create default EMF-IncQuery runtime logger.");
  }
  return defaultRuntimeLogger;
}
 

Example 27

From project event-collector, under directory /event-collector/src/main/java/com/proofpoint/event/collector/.

Source file: CollectorMain.java

  18 
vote

public static void main(String[] args) throws Exception {
  Bootstrap app=new Bootstrap(new NodeModule(),new DiscoveryModule(),new HttpServerModule(),new JsonModule(),new JaxrsModule(),new MBeanModule(),new JmxModule(),new JmxHttpModule(),new JmxHttpRpcModule(),new JsonEventModule(),new CollectorMainModule(),new EventTapModule(),new HttpClientModule(EventTap.class));
  try {
    Injector injector=app.strictConfig().initialize();
    injector.getInstance(Announcer.class).start();
  }
 catch (  Exception e) {
    log.error(e);
    System.exit(1);
  }
}
 

Example 28

From project eventtracker, under directory /scribe/src/test/java/com/ning/metrics/eventtracker/.

Source file: TestIntegration.java

  18 
vote

@Test(groups="slow",enabled=false) public void testGuiceThrift() throws Exception {
  System.setProperty("eventtracker.type","SCRIBE");
  System.setProperty("eventtracker.directory",tmpDir.getAbsolutePath());
  System.setProperty("eventtracker.scribe.host","127.0.0.1");
  System.setProperty("eventtracker.scribe.port","7911");
  final Injector injector=Guice.createInjector(new CollectorControllerModule());
  final CollectorController controller=injector.getInstance(CollectorController.class);
  final ScribeSender sender=(ScribeSender)injector.getInstance(EventSender.class);
  sender.createConnection();
  fireThriftEvents(controller);
  sender.close();
}
 

Example 29

From project exo-training, under directory /guice-hello/src/main/java/exoplatform/.

Source file: App.java

  18 
vote

public static void main(String[] args){
  Hello hello=new Hello();
  Injector injector=Guice.createInjector();
  injector.injectMembers(hello);
  hello.helloWorld.sayHelloWorld();
}
 

Example 30

From project gadget-server, under directory /gadget-core/src/test/java/org/overlord/gadgets/server/.

Source file: UserManagerTest.java

  18 
vote

@BeforeClass public static void setUp() throws Exception {
  Injector injector=Guice.createInjector(new CoreModule());
  userManager=injector.getInstance(UserManager.class);
  gadgetService=injector.getInstance(GadgetService.class);
  userManager.createUser(user);
  userManager.addPage(page,user);
}
 

Example 31

From project gibson, under directory /gibson-dashboard/app/org/ardverk/gibson/dashboard/.

Source file: Context.java

  18 
vote

public static Injector injector(){
  Injector injector=INJECTOR.get();
  if (injector == null) {
    throw new IllegalStateException();
  }
  return injector;
}
 

Example 32

From project grouperfish, under directory /service/src/main/java/com/mozilla/grouperfish/bootstrap/.

Source file: Grouperfish.java

  18 
vote

public Grouperfish(final Module... modules){
  SLF4JBridgeHandler.install();
  final Injector injector=Guice.createInjector(modules);
  final RestService rest=new JerseyGuiceRestService(injector,ResourceConfig.class);
  rest.start();
  log.info("Grouperfish started.");
  log.debug("Configured port: {}, default: {}",System.getProperty(JerseyGuiceRestService.PROPERTY_PORT),DEFAULT_PORT);
}
 

Example 33

From project BHT-FPA, under directory /patterns-codebeispiele/de.bht.fpa.examples.icashbox/src/de/bht/fpa/icashbox/.

Source file: ExecutableExtensionFactory.java

  17 
vote

@SuppressWarnings("rawtypes") @Override public Object create() throws CoreException {
  final Bundle bundle=Activator.getDefault().getBundle();
  final Injector injector=Activator.getDefault().getInjector();
  try {
    final Class<?> clazz=bundle.loadClass(clazzName);
    final Object result=injector.getInstance(clazz);
    if (result instanceof IExecutableExtension) {
      ((IExecutableExtension)result).setInitializationData(config,null,null);
    }
 else     if (result instanceof BasePresenter) {
      return ((BasePresenter)result).getView();
    }
    return result;
  }
 catch (  Exception e) {
    throw new CoreException(new Status(IStatus.ERROR,bundle.getSymbolicName(),e.getMessage(),e));
  }
}
 

Example 34

From project closure-templates, under directory /java/src/com/google/template/soy/.

Source file: SoyParseInfoGenerator.java

  17 
vote

private void execMain(String[] args) throws IOException, SoySyntaxException {
  CmdLineParser cmdLineParser=MainClassUtils.parseFlags(this,args,USAGE_PREFIX);
  if (arguments.size() == 0) {
    MainClassUtils.exitWithError("Must provide list of Soy files.",cmdLineParser,USAGE_PREFIX);
  }
  if (outputDirectory.length() == 0) {
    MainClassUtils.exitWithError("Must provide output directory.",cmdLineParser,USAGE_PREFIX);
  }
  if (javaPackage.length() == 0) {
    MainClassUtils.exitWithError("Must provide Java package.",cmdLineParser,USAGE_PREFIX);
  }
  if (javaClassNameSource.length() == 0) {
    MainClassUtils.exitWithError("Must provide Java class name source.",cmdLineParser,USAGE_PREFIX);
  }
  Injector injector=Guice.createInjector(new SoyModule());
  SoyFileSet.Builder sfsBuilder=injector.getInstance(SoyFileSet.Builder.class);
  String inputPrefixStr=inputPrefix;
  for (  String arg : ImmutableSet.copyOf(arguments)) {
    sfsBuilder.add(new File(inputPrefixStr + arg));
  }
  SoyFileSet sfs=sfsBuilder.build();
  Map<String,String> generatedFiles=sfs.generateParseInfo(javaPackage,javaClassNameSource);
  for (  Map.Entry<String,String> entry : generatedFiles.entrySet()) {
    File outputFile=new File(outputDirectory,entry.getKey());
    BaseUtils.ensureDirsExistInPath(outputFile.getPath());
    Files.write(entry.getValue(),outputFile,Charsets.UTF_8);
  }
}
 

Example 35

From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/torque/.

Source file: TorqueNodeManager.java

  17 
vote

public TorqueNodeManager(Configuration configuration){
  this.configuration=configuration;
  try {
    TorqueConfiguration torqueConfiguration=buildTorqueConfiguration();
    Injector injector=Guice.createInjector(new SSHModule());
    SSHClient sshClient=injector.getInstance(SSHClient.class);
    sshClient.setCredentials(torqueConfiguration.getSshCredentials());
    nodeDeployer=new TorqueJPPFNodeDeployer(buildTorqueConfiguration(),sshClient);
    executorService=MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(THREAD_POOL_SIZE));
  }
 catch (  ConfigurationValueMissingException ex) {
    logger.error("Configuration value is missing.",ex);
  }
catch (  SSHClientException ex) {
    logger.error("Could not start ssh client. Something is wrong with your private key or its path.",ex);
  }
}
 

Example 36

From project collector, under directory /src/main/java/com/ning/metrics/collector/.

Source file: StandaloneCollectorServer.java

  17 
vote

public static void main(final String... args) throws Exception {
  final long startTime=System.currentTimeMillis();
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,new ServerModule());
  final StandaloneCollectorServer server=injector.getInstance(StandaloneCollectorServer.class);
  Runtime.getRuntime().addShutdownHook(new Thread(){
    @Override public void run(){
      server.stop();
    }
  }
);
  server.start();
  final long secondsToStart=(System.currentTimeMillis() - startTime) / 1000;
  log.info(String.format("Collector initialized in %d:%02d",secondsToStart / 60,secondsToStart % 60));
  Thread.currentThread().join();
}
 

Example 37

From project cometd, under directory /cometd-java/cometd-java-annotations/src/test/java/org/cometd/annotation/guice/.

Source file: GuiceAnnotationTest.java

  17 
vote

@Test public void testGuiceWiringOfCometDServices() throws Exception {
  Injector injector=Guice.createInjector(new CometDModule());
  BayeuxServerImpl bayeuxServer=injector.getInstance(BayeuxServerImpl.class);
  if (Boolean.getBoolean("debugTests"))   bayeuxServer.setOption("logLevel","3");
  bayeuxServer.start();
  ServerAnnotationProcessor processor=new ServerAnnotationProcessor(bayeuxServer);
  GuiceBayeuxService service=injector.getInstance(GuiceBayeuxService.class);
  Assert.assertTrue(processor.process(service));
  Assert.assertNotNull(service);
  assertNotNull(service.dependency);
  assertNotNull(service.bayeuxServer);
  assertNotNull(service.serverSession);
  assertTrue(service.active);
  assertEquals(1,service.bayeuxServer.getChannel(GuiceBayeuxService.CHANNEL).getSubscribers().size());
  Assert.assertTrue(processor.deprocess(service));
  bayeuxServer.stop();
  assertFalse(service.active);
}
 

Example 38

From project components-ness-pg, under directory /pg/src/test/java/com/nesscomputing/db/.

Source file: TestPostgresPreparer.java

  17 
vote

@Test public void testGuice() throws Exception {
  final DatabasePreparer preparer=DatabasePreparers.forPostgres(Resources.getResource(TestPostgresPreparer.class,"/sql/").toURI());
  try {
    preparer.setupDatabase("simple");
    Assert.assertTrue(preparer.exists());
    final Module module=preparer.getGuiceModule("test");
    final Injector injector=Guice.createInjector(ConfigModule.forTesting(),new LifecycleModule(),module);
    injector.injectMembers(this);
    Assert.assertNotNull(lifecycle);
    lifecycle.executeTo(LifecycleStage.START_STAGE);
    Assert.assertNotNull(testDbi);
    testWithInjectedDbi();
    testMigratory();
    lifecycle.executeTo(LifecycleStage.STOP_STAGE);
  }
  finally {
    preparer.teardownDatabase();
  }
  Assert.assertFalse(preparer.exists());
}
 

Example 39

From project gengweibo, under directory /src/com/gengweibo/web/.

Source file: GuiceInit.java

  17 
vote

public void init(ServletConfig config) throws ServletException {
  Injector injector=Guice.createInjector(new Module(){
    public void configure(    Binder binder){
      binder.bind(AccountAcction.class).in(Singleton.class);
      binder.bind(WeiboDao.class).to(WeiboDaoJdbcImpl.class).in(Singleton.class);
      binder.bind(DataSource.class).toProvider(C3P0Provider.class).in(Singleton.class);
      Properties properties=new Properties();
      try {
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties"));
      }
 catch (      IOException e) {
        throw new ExceptionInInitializerError(e);
      }
      Names.bindProperties(binder,properties);
    }
  }
);
  config.getServletContext().setAttribute(Injector.class.getName(),injector);
}
 

Example 40

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/network/factories/.

Source file: LsPacketHandlerFactory.java

  15 
vote

/** 
 * @param loginServer
 */
public LsPacketHandlerFactory(Injector injector){
  this.injector=injector;
  addPacket(new CM_ACCOUNT_RECONNECT_KEY(0x03),State.AUTHED);
  addPacket(new CM_ACOUNT_AUTH_RESPONSE(0x01),State.AUTHED);
  addPacket(new CM_GS_AUTH_RESPONSE(0x00),State.CONNECTED);
  addPacket(new CM_REQUEST_KICK_ACCOUNT(0x02),State.AUTHED);
}
 

Example 41

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/.

Source file: Factory.java

  15 
vote

public Injector createInjector(SocketAddress address,Module... modules){
  List<Module> m=new ArrayList<>();
  m.add(new ArdverkModule(keySize,address));
  m.addAll(Arrays.asList(modules));
  return Guice.createInjector(m);
}
 

Example 42

From project Empire, under directory /core/src/com/clarkparsia/empire/.

Source file: Empire.java

  15 
vote

/** 
 * Return the Guice injector.
 * @return the Guice injector for Empire
 */
private static Injector injector(){
  if (injector == null) {
    injector=Guice.createInjector(new DefaultEmpireModule());
  }
  return injector;
}
 

Example 43

From project flatpack-java, under directory /core/src/main/java/com/getperka/flatpack/codexes/.

Source file: DefaultCodexMapper.java

  15 
vote

@Inject void inject(Injector injector){
  this.injector=injector;
  simpleCodexes.put(BigDecimal.class,(NumberCodex<?>)injector.getInstance(Key.get(createType(NumberCodex.class,BigDecimal.class))));
  simpleCodexes.put(BigInteger.class,(NumberCodex<?>)injector.getInstance(Key.get(createType(NumberCodex.class,BigInteger.class))));
  simpleCodexes.put(boolean.class,injector.getInstance(BooleanCodex.class));
  simpleCodexes.put(Boolean.class,injector.getInstance(BooleanCodex.class));
  simpleCodexes.put(char.class,injector.getInstance(CharacterCodex.class));
  simpleCodexes.put(Character.class,injector.getInstance(CharacterCodex.class));
  simpleCodexes.put(Class.class,injector.getInstance(HasUuidClassCodex.class));
  simpleCodexes.put(DateTimeZone.class,injector.getInstance(DateTimeZoneCodex.class));
  simpleCodexes.put(JsonElement.class,injector.getInstance(JsonElementCodex.class));
  simpleCodexes.put(String.class,injector.getInstance(StringCodex.class));
  simpleCodexes.put(TypeHint.class,injector.getInstance(TypeHintCodex.class));
  simpleCodexes.put(UUID.class,injector.getInstance(UUIDCodex.class));
  simpleCodexes.put(void.class,injector.getInstance(VoidCodex.class));
  simpleCodexes.put(Void.class,injector.getInstance(VoidCodex.class));
  for (  Class<?> clazz : BOXED_TYPES) {
    if (Number.class.isAssignableFrom(clazz)) {
      @SuppressWarnings("unchecked") Key<ValueCodex<?>> key=(Key<ValueCodex<?>>)Key.get(createType(NumberCodex.class,clazz));
      simpleCodexes.put(clazz,injector.getInstance(key));
    }
  }
  for (  Class<?> clazz : PRIMITIVE_TYPES) {
    Class<?> boxed=box(clazz);
    if (Number.class.isAssignableFrom(boxed)) {
      @SuppressWarnings("unchecked") Key<ValueCodex<?>> key=(Key<ValueCodex<?>>)Key.get(createType(NumberCodex.class,boxed));
      simpleCodexes.put(clazz,injector.getInstance(key));
    }
  }
}