Java Code Examples for javax.inject.Singleton

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 xwiki-commons, under directory /xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-default/src/main/java/org/xwiki/component/annotation/.

Source file: ComponentDescriptorFactory.java

  21 
vote

/** 
 * @param componentClass the component class from which to extract the component instantiation strategy
 * @return the component instantiation strategy to use
 */
private ComponentInstantiationStrategy createComponentInstantiationStrategy(Class<?> componentClass){
  ComponentInstantiationStrategy strategy;
  Singleton singleton=componentClass.getAnnotation(Singleton.class);
  if (singleton != null) {
    strategy=ComponentInstantiationStrategy.SINGLETON;
  }
 else {
    InstantiationStrategy instantiationStrategy=componentClass.getAnnotation(InstantiationStrategy.class);
    if (instantiationStrategy != null) {
      strategy=instantiationStrategy.value();
    }
 else {
      strategy=ComponentInstantiationStrategy.SINGLETON;
    }
  }
  return strategy;
}
 

Example 2

From project aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/impl/.

Source file: AetherModule.java

  20 
vote

@Override protected void configure(){
  bind(RepositorySystem.class).to(DefaultRepositorySystem.class).in(Singleton.class);
  bind(ArtifactResolver.class).to(DefaultArtifactResolver.class).in(Singleton.class);
  bind(DependencyCollector.class).to(DefaultDependencyCollector.class).in(Singleton.class);
  bind(Deployer.class).to(DefaultDeployer.class).in(Singleton.class);
  bind(Installer.class).to(DefaultInstaller.class).in(Singleton.class);
  bind(MetadataResolver.class).to(DefaultMetadataResolver.class).in(Singleton.class);
  bind(RepositoryConnectorProvider.class).to(DefaultRepositoryConnectorProvider.class).in(Singleton.class);
  bind(RemoteRepositoryManager.class).to(DefaultRemoteRepositoryManager.class).in(Singleton.class);
  bind(UpdateCheckManager.class).to(DefaultUpdateCheckManager.class).in(Singleton.class);
  bind(UpdatePolicyAnalyzer.class).to(DefaultUpdatePolicyAnalyzer.class).in(Singleton.class);
  bind(FileProcessor.class).to(DefaultFileProcessor.class).in(Singleton.class);
  bind(SyncContextFactory.class).to(DefaultSyncContextFactory.class).in(Singleton.class);
  bind(RepositoryEventDispatcher.class).to(DefaultRepositoryEventDispatcher.class).in(Singleton.class);
  bind(LocalRepositoryProvider.class).to(DefaultLocalRepositoryProvider.class).in(Singleton.class);
  bind(LocalRepositoryManagerFactory.class).annotatedWith(Names.named("simple")).to(SimpleLocalRepositoryManagerFactory.class).in(Singleton.class);
  bind(LocalRepositoryManagerFactory.class).annotatedWith(Names.named("enhanced")).to(EnhancedLocalRepositoryManagerFactory.class).in(Singleton.class);
  if (Slf4jLoggerFactory.isSlf4jAvailable()) {
    bindSlf4j();
  }
 else {
    bind(LoggerFactory.class).toInstance(NullLoggerFactory.INSTANCE);
  }
}
 

Example 3

From project aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/impl/.

Source file: AetherModule.java

  20 
vote

@Provides @Singleton Set<LocalRepositoryManagerFactory> provideLocalRepositoryManagerFactories(@Named("simple") LocalRepositoryManagerFactory simple,@Named("enhanced") LocalRepositoryManagerFactory enhanced){
  Set<LocalRepositoryManagerFactory> factories=new HashSet<LocalRepositoryManagerFactory>();
  factories.add(simple);
  factories.add(enhanced);
  return Collections.unmodifiableSet(factories);
}
 

Example 4

From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/config/.

Source file: ApacheHCHttpCommandExecutorServiceModule.java

  19 
vote

@Singleton @Provides HttpParams newBasicHttpParams(HttpUtils utils){
  BasicHttpParams params=new BasicHttpParams();
  params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,8 * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true).setParameter(CoreProtocolPNames.ORIGIN_SERVER,"jclouds/1.0");
  if (utils.getConnectionTimeout() > 0) {
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,utils.getConnectionTimeout());
  }
  if (utils.getSocketOpenTimeout() > 0) {
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,utils.getSocketOpenTimeout());
  }
  if (utils.getMaxConnections() > 0)   ConnManagerParams.setMaxTotalConnections(params,utils.getMaxConnections());
  if (utils.getMaxConnectionsPerHost() > 0) {
    ConnPerRoute connectionsPerRoute=new ConnPerRouteBean(utils.getMaxConnectionsPerHost());
    ConnManagerParams.setMaxConnectionsPerRoute(params,connectionsPerRoute);
  }
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  return params;
}
 

Example 5

From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/config/.

Source file: ApacheHCHttpCommandExecutorServiceModule.java

  19 
vote

@Singleton @Provides ClientConnectionManager newClientConnectionManager(HttpParams params,X509HostnameVerifier verifier,Closer closer) throws NoSuchAlgorithmException, KeyManagementException {
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  Scheme http=new Scheme("http",PlainSocketFactory.getSocketFactory(),80);
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(null,null,null);
  SSLSocketFactory sf=new SSLSocketFactory(context);
  sf.setHostnameVerifier(verifier);
  Scheme https=new Scheme("https",sf,443);
  SchemeRegistry sr=new SchemeRegistry();
  sr.register(http);
  sr.register(https);
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  final ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  closer.addToClose(new Closeable(){
    @Override public void close() throws IOException {
      cm.shutdown();
    }
  }
);
  return cm;
}
 

Example 6

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

Source file: MongoModule.java

  19 
vote

@Provides @Singleton Datastore getDatastore(Configuration configuration) throws IOException {
  MongoURI uri=parseURI(configuration.getString(URI_KEY),Gibson.URI);
  String database=uri.getDatabase();
  if (database == null) {
    throw new IOException("Database missing: " + uri);
  }
  if (LOG.isInfoEnabled()) {
    LOG.info("Connecting: uri=" + uri);
  }
  Mongo mongo=new Mongo(uri);
  DatastoreFactory factory=new DatastoreFactory(mongo);
  return factory.createDatastore(database);
}
 

Example 7

From project guice-automatic-injection, under directory /core/src/main/java/de/devsurf/injection/guice/annotations/features/.

Source file: ImplementationBindingFeature.java

  19 
vote

@Override public void process(final Class<Object> annotatedClass,final Map<String,Annotation> annotations){
  final boolean asSingleton=(annotations.containsKey(com.google.inject.Singleton.class.getName()) || annotations.containsKey(javax.inject.Singleton.class.getName()));
  if (_logger.isLoggable(Level.FINE)) {
    _logger.fine(String.format("Binding Class %s. Singleton? %s ",annotatedClass,asSingleton));
  }
  bind(annotatedClass,null,(asSingleton ? Singleton.class : null));
}
 

Example 8

From project guice-jit-providers, under directory /core/test/com/googlecode/guice/.

Source file: Jsr330Test.java

  19 
vote

public void testSingleton(){
  Injector injector=Guice.createInjector(new AbstractModule(){
    protected void configure(){
      bind(B.class).in(Singleton.class);
    }
  }
);
  B b=injector.getInstance(B.class);
  assertSame(b,injector.getInstance(B.class));
  assertSame(b,injector.getInstance(B.class));
  J j=injector.getInstance(J.class);
  assertSame(j,injector.getInstance(J.class));
  assertSame(j,injector.getInstance(J.class));
}
 

Example 9

From project guice-jit-providers, under directory /core/test/com/googlecode/guice/.

Source file: Jsr330Test.java

  19 
vote

public void testEagerSingleton(){
  Guice.createInjector(Stage.PRODUCTION,new AbstractModule(){
    protected void configure(){
      bind(J.class);
      bind(K.class).in(Singleton.class);
    }
  }
);
  assertEquals(1,J.nextInstanceId);
  assertEquals(1,K.nextInstanceId);
}
 

Example 10

From project incubator-deltaspike, under directory /deltaspike/cdictrl/impl-owb/src/main/java/org/apache/deltaspike/cdise/owb/.

Source file: OpenWebBeansContextControl.java

  19 
vote

private void startSingletonScope(){
  ContextsService contextsService=getContextsService();
  Object mockServletContext=null;
  if (isServletApiAvailable()) {
    mockServletContext=OwbHelper.getMockServletContext();
  }
  contextsService.startContext(Singleton.class,mockServletContext);
}
 

Example 11

From project incubator-deltaspike, under directory /deltaspike/cdictrl/impl-owb/src/main/java/org/apache/deltaspike/cdise/owb/.

Source file: OpenWebBeansContextControl.java

  19 
vote

private void stopSingletonScope(){
  ContextsService contextsService=getContextsService();
  Object mockServletContext=null;
  if (isServletApiAvailable()) {
    mockServletContext=OwbHelper.getMockServletContext();
  }
  contextsService.endContext(Singleton.class,mockServletContext);
}
 

Example 12

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.

Source file: BaseChefRestClientModule.java

  19 
vote

@Provides @Singleton @Validator public Optional<String> provideValidatorName(Injector injector){
  Key<String> key=Key.get(String.class,Names.named(CHEF_VALIDATOR_NAME));
  try {
    return Optional.<String>of(injector.getInstance(key));
  }
 catch (  ConfigurationException ex) {
    return Optional.<String>absent();
  }
}
 

Example 13

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.

Source file: BaseChefRestClientModule.java

  19 
vote

@Provides @Singleton @Validator public Optional<PrivateKey> provideValidatorCredential(Crypto crypto,Injector injector) throws InvalidKeySpecException, IOException {
  Key<String> key=Key.get(String.class,Names.named(CHEF_VALIDATOR_CREDENTIAL));
  try {
    String validatorCredential=injector.getInstance(key);
    PrivateKey validatorKey=crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(InputSuppliers.of(validatorCredential)));
    return Optional.<PrivateKey>of(validatorKey);
  }
 catch (  ConfigurationException ex) {
    return Optional.<PrivateKey>absent();
  }
}
 

Example 14

From project jclouds-ovh-compute, under directory /src/main/java/org/jclouds/ovh/compute/config/.

Source file: OVHComputeServiceContextModule.java

  19 
vote

@Provides @Singleton protected Supplier<SessionWithToken> sessionWithToken(final SessionHandler sessionHandler){
  return Suppliers.memoize(new Supplier<SessionWithToken>(){
    @Override public SessionWithToken get(){
      SessionWithToken session;
      try {
        session=sessionHandler.login(SessionParameters.getSessionParameters().getJcloudsLogin(),SessionParameters.getSessionParameters().getJcloudsPwd(),SessionParameters.CLOUD_LANG,null);
      }
 catch (      OvhWsException e) {
        session=new SessionWithToken();
        session.setSession(null);
        session.setToken(null);
      }
      return session;
    }
  }
);
}
 

Example 15

From project juzu, under directory /core/src/main/java/juzu/impl/inject/spi/cdi/.

Source file: ExtensionImpl.java

  19 
vote

void processBean(@Observes ProcessBean event,BeanManager beanManager){
  Bean bean=event.getBean();
  manager.beans.add(bean);
  if (bean.getScope() == Singleton.class) {
    singletons.add(bean);
  }
}
 

Example 16

From project juzu, under directory /core/src/main/java/juzu/impl/inject/spi/spring/.

Source file: ScopeMetadataResolverImpl.java

  19 
vote

@Override public ScopeMetadata resolveScopeMetadata(BeanDefinition definition){
  ScopeMetadata metadata=new ScopeMetadata();
  if (definition instanceof AnnotatedBeanDefinition) {
    AnnotatedBeanDefinition annDef=(AnnotatedBeanDefinition)definition;
    Set<String> annotationTypes=annDef.getMetadata().getAnnotationTypes();
    String scopeName;
    if (annotationTypes.contains(Singleton.class.getName())) {
      scopeName="singleton";
    }
 else {
      scopeName="prototype";
      for (      Scope scope : scopes) {
        if (annotationTypes.contains(scope.getAnnotationType().getName())) {
          scopeName=scope.name().toLowerCase();
          break;
        }
      }
    }
    metadata.setScopeName(scopeName);
    return metadata;
  }
 else {
    return super.resolveScopeMetadata(definition);
  }
}
 

Example 17

From project openwebbeans, under directory /webbeans-impl/src/main/java/org/apache/webbeans/context/.

Source file: ContextFactory.java

  19 
vote

public void initSingletonContext(Object parameter){
  try {
    ContextsService contextService=getContextsService();
    contextService.startContext(Singleton.class,parameter);
  }
 catch (  Exception e) {
    logger.log(Level.SEVERE,e.getMessage(),e);
  }
}
 

Example 18

From project openwebbeans, under directory /webbeans-impl/src/main/java/org/apache/webbeans/corespi/se/.

Source file: DefaultContextsService.java

  19 
vote

/** 
 * {@inheritDoc}
 */
@Override public Context getCurrentContext(Class<? extends Annotation> scopeType){
  if (scopeType.equals(RequestScoped.class)) {
    return getCurrentRequestContext();
  }
 else   if (scopeType.equals(SessionScoped.class)) {
    return getCurrentSessionContext();
  }
 else   if (scopeType.equals(ApplicationScoped.class)) {
    return getCurrentApplicationContext();
  }
 else   if (scopeType.equals(ConversationScoped.class)) {
    return getCurrentConversationContext();
  }
 else   if (scopeType.equals(Dependent.class)) {
    return getCurrentDependentContext();
  }
 else   if (scopeType.equals(Singleton.class)) {
    return getCurrentSingletonContext();
  }
  return null;
}
 

Example 19

From project recommenders, under directory /plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/.

Source file: RecommendersModule.java

  19 
vote

@Singleton @Provides protected IClasspathEntryInfoProvider configurePackageFragmentRootInfoProvider(final EventBus bus,IWorkspaceRoot workspace){
  Bundle bundle=FrameworkUtil.getBundle(getClass());
  File stateLocation=new File(Platform.getStateLocation(bundle).toFile(),"v0.5-package-root-infos.json");
  final IClasspathEntryInfoProvider cpeInfoProvider=new ClasspathEntryInfoProvider(stateLocation,workspace,bus);
  PlatformUI.getWorkbench().addWorkbenchListener(new IWorkbenchListener(){
    @Override public boolean preShutdown(    IWorkbench workbench,    boolean forced){
      try {
        ((Closeable)cpeInfoProvider).close();
      }
 catch (      Throwable e) {
        e.printStackTrace();
      }
      return true;
    }
    @Override public void postShutdown(    IWorkbench workbench){
    }
  }
);
  bus.register(cpeInfoProvider);
  return cpeInfoProvider;
}
 

Example 20

From project recommenders, under directory /plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/.

Source file: RecommendersModule.java

  19 
vote

@Singleton @Provides protected EventBus provideWorkspaceEventBus(){
  final int numberOfCores=Runtime.getRuntime().availableProcessors();
  final ExecutorService pool=coreThreadsTimoutExecutor(numberOfCores + 1,MIN_PRIORITY,"Recommenders-Bus-Thread-",1L,TimeUnit.MINUTES);
  final EventBus bus=new AsyncEventBus("Code Recommenders asychronous Workspace Event Bus",pool);
  return bus;
}
 

Example 21

From project security_1, under directory /security-system/src/main/java/org/sonatype/security/guice/.

Source file: SecurityModule.java

  19 
vote

@Override protected void configureShiro(){
  bindRealm().to(EmptyRealm.class);
  bind(SessionDAO.class).to(EnterpriseCacheSessionDAO.class).asEagerSingleton();
  bind(Authenticator.class).to(FirstSuccessfulModularRealmAuthenticator.class).in(Singleton.class);
  bind(Authorizer.class).to(ExceptionCatchingModularRealmAuthorizer.class).in(Singleton.class);
}
 

Example 22

From project security_1, under directory /security-web/src/main/java/org/sonatype/security/web/guice/.

Source file: SecurityWebModule.java

  19 
vote

@Override protected void configureShiroWeb(){
  bindRealm().to(EmptyRealm.class);
  bind(SessionDAO.class).to(EnterpriseCacheSessionDAO.class).asEagerSingleton();
  bind(Authenticator.class).to(FirstSuccessfulModularRealmAuthenticator.class).in(Singleton.class);
  bind(Authorizer.class).to(ExceptionCatchingModularRealmAuthorizer.class).in(Singleton.class);
  bind(ProtectedPathManager.class).to(SimpleProtectedPathManager.class).in(Singleton.class);
  if (useFilterChainManager) {
    bind(FilterChainResolver.class).toConstructor(ctor(PathMatchingFilterChainResolver.class)).asEagerSingleton();
    bind(FilterChainManager.class).toProvider(FilterChainManagerProvider.class).in(Singleton.class);
  }
  expose(ProtectedPathManager.class);
  expose(FilterChainResolver.class);
}
 

Example 23

From project sisu-guice, under directory /core/test/com/googlecode/guice/.

Source file: Jsr330Test.java

  19 
vote

public void testSingleton(){
  Injector injector=Guice.createInjector(new AbstractModule(){
    protected void configure(){
      bind(B.class).in(Singleton.class);
    }
  }
);
  B b=injector.getInstance(B.class);
  assertSame(b,injector.getInstance(B.class));
  assertSame(b,injector.getInstance(B.class));
  J j=injector.getInstance(J.class);
  assertSame(j,injector.getInstance(J.class));
  assertSame(j,injector.getInstance(J.class));
}
 

Example 24

From project sisu-guice, under directory /core/test/com/googlecode/guice/.

Source file: Jsr330Test.java

  19 
vote

public void testEagerSingleton(){
  Guice.createInjector(Stage.PRODUCTION,new AbstractModule(){
    protected void configure(){
      bind(J.class);
      bind(K.class).in(Singleton.class);
    }
  }
);
  assertEquals(1,J.nextInstanceId);
  assertEquals(1,K.nextInstanceId);
}