Java Code Examples for com.google.inject.Scope

The following are top voted examples for showing how to use com.google.inject.Scope. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: guiceberry   File: ModuleWriter.java   Source Code and License 6 votes vote down vote up
protected void applyScoping(Binding<?> binding, final ScopedBindingBuilder scopedBindingBuilder) {
  binding.acceptScopingVisitor(new BindingScopingVisitor<Void>() {
    public Void visitEagerSingleton() {
      if (scopedBindingBuilder != null) {
        scopedBindingBuilder.asEagerSingleton();
      }
      return null;
    }

    public Void visitScope(Scope scope) {
      scopedBindingBuilder.in(scope);
      return null;
    }

    public Void visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
      scopedBindingBuilder.in(scopeAnnotation);
      return null;
    }

    public Void visitNoScoping() {
      // do nothing
      return null;
    }
  });
}
 
Example 2
Project: guiceberry   File: ModuleWriter.java   Source Code and License 6 votes vote down vote up
protected void applyScoping(Binding<?> binding, final ScopedBindingBuilder scopedBindingBuilder) {
  binding.acceptScopingVisitor(new BindingScopingVisitor<Void>() {
    public Void visitEagerSingleton() {
      if (scopedBindingBuilder != null) {
        scopedBindingBuilder.asEagerSingleton();
      }
      return null;
    }

    public Void visitScope(Scope scope) {
      scopedBindingBuilder.in(scope);
      return null;
    }

    public Void visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
      scopedBindingBuilder.in(scopeAnnotation);
      return null;
    }

    public Void visitNoScoping() {
      // do nothing
      return null;
    }
  });
}
 
Example 3
Project: deguicifier   File: Generators.java   Source Code and License 6 votes vote down vote up
private static String scoped(final Binding<?> binding, final String statement) {
  return binding.acceptScopingVisitor(new BindingScopingVisitor<String>() {
    @Override
    public String visitEagerSingleton() {
      if (binding instanceof InstanceBinding<?>) {
        return statement;
      }
      throw new DeguicifierException();
    }

    @Override
    public String visitScope(Scope scope) {
      return scopeFieldName(scope) + ".scope(null, " + guicify(statement) + ")";
    }

    @Override
    public String visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
      throw new DeguicifierException();
    }

    @Override
    public String visitNoScoping() {
      return statement;
    }
  });
}
 
Example 4
Project: guice-old   File: ScopeBindingProcessor.java   Source Code and License 6 votes vote down vote up
@Override public Boolean visit(ScopeBinding command) {
  Scope scope = command.getScope();
  Class<? extends Annotation> annotationType = command.getAnnotationType();

  if (!Annotations.isScopeAnnotation(annotationType)) {
    errors.missingScopeAnnotation(annotationType);
    // Go ahead and bind anyway so we don't get collateral errors.
  }

  if (!Annotations.isRetainedAtRuntime(annotationType)) {
    errors.missingRuntimeRetention(annotationType);
    // Go ahead and bind anyway so we don't get collateral errors.
  }

  ScopeBinding existing = injector.state.getScopeBinding(checkNotNull(annotationType, "annotation type"));
  if (existing != null) {
    errors.duplicateScopes(existing, annotationType, scope);
  } else {
    checkNotNull(scope, "scope");
    injector.state.putScopeBinding(annotationType, command);
  }

  return true;
}
 
Example 5
Project: guice-old   File: Scoping.java   Source Code and License 6 votes vote down vote up
public static Scoping forInstance(final Scope scope) {
  if (scope == Scopes.SINGLETON) {
    return SINGLETON_INSTANCE;
  }

  return new Scoping() {
    @Override public <V> V acceptVisitor(BindingScopingVisitor<V> visitor) {
      return visitor.visitScope(scope);
    }

    @Override public Scope getScopeInstance() {
      return scope;
    }

    @Override public String toString() {
      return scope.toString();
    }

    @Override public void applyTo(ScopedBindingBuilder scopedBindingBuilder) {
      scopedBindingBuilder.in(scope);
    }
  };
}
 
Example 6
Project: guice-old   File: OverrideModuleTest.java   Source Code and License 6 votes vote down vote up
public void testOverrideScopeAnnotation() {
  final Scope scope = new Scope() {
    public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
      throw new AssertionError("Should not be called");
    }
  };

  final SingleUseScope replacementScope = new SingleUseScope();

  Module original = new AbstractModule() {
    @Override protected void configure() {
      bindScope(TestScopeAnnotation.class, scope);
      bind(Date.class).in(TestScopeAnnotation.class);
    }
  };

  Module replacements = new AbstractModule() {
    @Override protected void configure() {
      bindScope(TestScopeAnnotation.class, replacementScope);
    }
  };

  Injector injector = createInjector(Modules.override(original).with(replacements));
  injector.getInstance(Date.class);
  assertTrue(replacementScope.used);
}
 
Example 7
Project: google-guice   File: ScopeBindingProcessor.java   Source Code and License 6 votes vote down vote up
@Override public Boolean visit(ScopeBinding command) {
  Scope scope = command.getScope();
  Class<? extends Annotation> annotationType = command.getAnnotationType();

  if (!Annotations.isScopeAnnotation(annotationType)) {
    errors.withSource(annotationType).missingScopeAnnotation();
    // Go ahead and bind anyway so we don't get collateral errors.
  }

  if (!Annotations.isRetainedAtRuntime(annotationType)) {
    errors.withSource(annotationType)
        .missingRuntimeRetention(command.getSource());
    // Go ahead and bind anyway so we don't get collateral errors.
  }

  Scope existing = injector.state.getScope(checkNotNull(annotationType, "annotation type"));
  if (existing != null) {
    errors.duplicateScopes(existing, annotationType, scope);
  } else {
    injector.state.putAnnotation(annotationType, checkNotNull(scope, "scope"));
  }

  return true;
}
 
Example 8
Project: google-guice   File: Scoping.java   Source Code and License 6 votes vote down vote up
public static Scoping forInstance(final Scope scope) {
  if (scope == Scopes.SINGLETON) {
    return SINGLETON_INSTANCE;
  }

  return new Scoping() {
    public <V> V acceptVisitor(BindingScopingVisitor<V> visitor) {
      return visitor.visitScope(scope);
    }

    @Override public Scope getScopeInstance() {
      return scope;
    }

    @Override public String toString() {
      return scope.toString();
    }

    public void applyTo(ScopedBindingBuilder scopedBindingBuilder) {
      scopedBindingBuilder.in(scope);
    }
  };
}
 
Example 9
Project: parabuild-ci   File: OutOfScopeException.java   Source Code and License 5 votes vote down vote up
public OutOfScopeException(Scope scope, Key<?> key, Throwable cause) 
{
    super(String.format(
        "Not in scope %s for key %s: caused by %s",
        scope, key, cause
    ), cause);
}
 
Example 10
Project: dwr   File: OutOfScopeException.java   Source Code and License 5 votes vote down vote up
public OutOfScopeException(Scope scope, Key<?> key, Throwable cause)
{
    super(String.format(
        "Not in scope %s for key %s: caused by %s",
        scope, key, cause
    ), cause);
}
 
Example 11
Project: wava   File: Scopes.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public static void bindScopeInstance(Binder binder, Scope scope, Class<? extends Annotation> annotationType)
{
    requireNonNull(scope);
    binder.bindScope(annotationType, scope);
    binder.bind((Class) scope.getClass()).toInstance(scope);
}
 
Example 12
Project: Camel   File: Injectors.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the scope annotation for the given binding or null if there is no
 * scope
 */
public static Class<? extends Annotation> getScopeAnnotation(
        Binding<?> binding) {
    Class<? extends Annotation> scopeAnnotation = null;
    if (binding instanceof BindingImpl) {
        BindingImpl bindingImpl = (BindingImpl) binding;
        Scoping scoping = bindingImpl.getScoping();
        if (scoping != null) {
            scopeAnnotation = scoping.getScopeAnnotation();

            // TODO not sure why we need this hack???
            if (scopeAnnotation == null) {
                Scope scope = scoping.getScopeInstance();
                if (scope instanceof HasScopeAnnotation) {
                    HasScopeAnnotation hasScopeAnnotation = (HasScopeAnnotation) scope;
                    scopeAnnotation = hasScopeAnnotation
                            .getScopeAnnotation();
                }

                if (scopeAnnotation == null
                        && (scoping == Scoping.EAGER_SINGLETON
                                || scoping == Scoping.SINGLETON_ANNOTATION || scoping == Scoping.SINGLETON_INSTANCE)) {
                    scopeAnnotation = Singleton.class;
                }
            }
        }
    }
    return scopeAnnotation;
}
 
Example 13
Project: gerrit   File: RequestScopePropagator.java   Source Code and License 5 votes vote down vote up
protected RequestScopePropagator(
    Scope scope,
    ThreadLocalRequestContext local,
    Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
  this.scope = scope;
  this.local = local;
  this.dbProviderProvider = dbProviderProvider;
}
 
Example 14
Project: gerrit   File: ThreadLocalRequestScopePropagator.java   Source Code and License 5 votes vote down vote up
protected ThreadLocalRequestScopePropagator(
    Scope scope,
    ThreadLocal<C> threadLocal,
    ThreadLocalRequestContext local,
    Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
  super(scope, local, dbProviderProvider);
  this.threadLocal = threadLocal;
}
 
Example 15
Project: dropwizardry   File: GuiceContainer.java   Source Code and License 5 votes vote down vote up
@Override
public Map<Scope, ComponentScope> createScopeMap() {
    Map<Scope, ComponentScope> m = super.createScopeMap();

    m.put(ServletScopes.REQUEST, ComponentScope.PerRequest);
    return m;
}
 
Example 16
Project: deguicifier   File: Generators.java   Source Code and License 5 votes vote down vote up
private static String scopeInstance(Scope scope) {
  if (scope == Scopes.SINGLETON) {
    return Scopes.class.getCanonicalName() + ".SINGLETON";
  } else {
    return "new " + scope.getClass().getCanonicalName() + "()";
  }
}
 
Example 17
Project: guice   File: CheckedProviderTest.java   Source Code and License 5 votes vote down vote up
public void testProvisionExceptionOnDependenciesOfCxtor() throws Exception {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              ThrowingProviderBinder.create(binder())
                  .bind(RemoteProvider.class, Foo.class)
                  .providing(ProvisionExceptionFoo.class);
              bindScope(
                  BadScope.class,
                  new Scope() {
                    @Override
                    public <T> Provider<T> scope(final Key<T> key, Provider<T> unscoped) {
                      return new Provider<T>() {
                        @Override
                        public T get() {
                          throw new OutOfScopeException("failure: " + key.toString());
                        }
                      };
                    }
                  });
            }
          });

  try {
    injector.getInstance(Key.get(remoteProviderOfFoo)).get();
    fail();
  } catch (ProvisionException pe) {
    Message message = Iterables.getOnlyElement(pe.getErrorMessages());
    assertEquals(
        "Error in custom provider, com.google.inject.OutOfScopeException: failure: "
            + Key.get(Unscoped1.class),
        message.getMessage());
  }
}
 
Example 18
Project: guice   File: ScopeBindingProcessor.java   Source Code and License 5 votes vote down vote up
@Override
public Boolean visit(ScopeBinding command) {
  Scope scope = checkNotNull(command.getScope(), "scope");
  Class<? extends Annotation> annotationType =
      checkNotNull(command.getAnnotationType(), "annotation type");

  if (!Annotations.isScopeAnnotation(annotationType)) {
    errors.missingScopeAnnotation(annotationType);
    // Go ahead and bind anyway so we don't get collateral errors.
  }

  if (!Annotations.isRetainedAtRuntime(annotationType)) {
    errors.missingRuntimeRetention(annotationType);
    // Go ahead and bind anyway so we don't get collateral errors.
  }

  ScopeBinding existing = injector.state.getScopeBinding(annotationType);
  if (existing != null) {
    if (!scope.equals(existing.getScope())) {
      errors.duplicateScopes(existing, annotationType, scope);
    }
  } else {
    injector.state.putScopeBinding(annotationType, command);
  }

  return true;
}
 
Example 19
Project: guice   File: InheritingState.java   Source Code and License 5 votes vote down vote up
@Override
public Map<Class<? extends Annotation>, Scope> getScopes() {
  ImmutableMap.Builder<Class<? extends Annotation>, Scope> builder = ImmutableMap.builder();
  for (Map.Entry<Class<? extends Annotation>, ScopeBinding> entry : scopes.entrySet()) {
    builder.put(entry.getKey(), entry.getValue().getScope());
  }
  return builder.build();
}
 
Example 20
Project: guice   File: Scoping.java   Source Code and License 5 votes vote down vote up
public static Scoping forInstance(final Scope scope) {
  if (scope == Scopes.SINGLETON) {
    return SINGLETON_INSTANCE;
  } else if (scope == Scopes.NO_SCOPE) {
    return EXPLICITLY_UNSCOPED;
  }

  return new Scoping() {
    @Override
    public <V> V acceptVisitor(BindingScopingVisitor<V> visitor) {
      return visitor.visitScope(scope);
    }

    @Override
    public Scope getScopeInstance() {
      return scope;
    }

    @Override
    public String toString() {
      return scope.toString();
    }

    @Override
    public void applyTo(ScopedBindingBuilder scopedBindingBuilder) {
      scopedBindingBuilder.in(scope);
    }
  };
}
 
Example 21
Project: guice   File: Modules.java   Source Code and License 5 votes vote down vote up
private Scope getScopeInstanceOrNull(Binding<?> binding) {
  return binding.acceptScopingVisitor(
      new DefaultBindingScopingVisitor<Scope>() {
        @Override
        public Scope visitScope(Scope scope) {
          return scope;
        }
      });
}
 
Example 22
Project: guice   File: OverrideModuleTest.java   Source Code and License 5 votes vote down vote up
public void testOverrideScopeAnnotation() {
  final Scope scope =
      new Scope() {
        @Override
        public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
          throw new AssertionError("Should not be called");
        }
      };

  final SingleUseScope replacementScope = new SingleUseScope();

  Module original =
      new AbstractModule() {
        @Override
        protected void configure() {
          bindScope(TestScopeAnnotation.class, scope);
          bind(Date.class).in(TestScopeAnnotation.class);
        }
      };

  Module replacements =
      new AbstractModule() {
        @Override
        protected void configure() {
          bindScope(TestScopeAnnotation.class, replacementScope);
        }
      };

  Injector injector = createInjector(Modules.override(original).with(replacements));
  injector.getInstance(Date.class);
  assertTrue(replacementScope.used);
}
 
Example 23
Project: papaya   File: GuiceDependencyGraph.java   Source Code and License 5 votes vote down vote up
public static ServiceDependencyManager buildServiceDependencyManager(
        final Injector injector,
        Iterable<Key<? extends BaseService<?>>> serviceKeys
) {
  final Multimap<ResolvedBinding<BaseService<?>>, ResolvedBinding<? extends BaseService<?>>> graph = computeInterdependencies(
          serviceKeys,
          injector);
  for (ResolvedBinding<? extends BaseService<?>> binding : graph.values()) {
    checkArgument(binding.getBinding().acceptScopingVisitor(new BindingScopingVisitor<Boolean>() {
      public Boolean visitEagerSingleton() { return true; }

      public Boolean visitScope(Scope scope) { return scope == Scopes.SINGLETON; }

      public Boolean visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
        return scopeAnnotation.equals(Singleton.class);
      }

      public Boolean visitNoScoping() { return false; }
    }), "Managed service must be bound as Singleton", binding);
  }

  return ServiceDependencyManager.buildServicesWithDependencies(
          ResolvedBinding.<BaseService<?>>resolver(injector)
                         .andThen(ResolvedBinding::get)
                         .transform(serviceKeys)
                         .toList(),
          Functional.funPairs(graph.entries())
                  .mapKeys(ResolvedBinding::get)
                  .mapValues((F<ResolvedBinding<? extends BaseService<?>>, BaseService<?>>) binding -> binding.get())
                  .toList()
  );
}
 
Example 24
Project: guice-old   File: CheckedProviderTest.java   Source Code and License 5 votes vote down vote up
public void testProvisionExceptionOnDependenciesOfCxtor() throws Exception {
  Injector injector = Guice.createInjector(new AbstractModule() {
      @Override
      protected void configure() {
        ThrowingProviderBinder.create(binder())
            .bind(RemoteProvider.class, Foo.class)
            .providing(ProvisionExceptionFoo.class);
        bindScope(BadScope.class, new Scope() {
          @Override
          public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
            return new Provider<T>() {
              @Override
              public T get() {
                throw new OutOfScopeException("failure");
              }
            };
          }
        });
      }
    });
  
  try {
    injector.getInstance(Key.get(remoteProviderOfFoo)).get();
    fail();
  } catch(ProvisionException pe) {
    assertEquals(2, pe.getErrorMessages().size());
    List<Message> messages = Lists.newArrayList(pe.getErrorMessages());
    assertEquals("Error in custom provider, com.google.inject.OutOfScopeException: failure",
        messages.get(0).getMessage());
    assertEquals("Error in custom provider, com.google.inject.OutOfScopeException: failure",
        messages.get(1).getMessage());
  }
}
 
Example 25
Project: guice-old   File: InheritingState.java   Source Code and License 5 votes vote down vote up
public Map<Class<? extends Annotation>, Scope> getScopes() {
  ImmutableMap.Builder<Class<? extends Annotation>, Scope> builder = ImmutableMap.builder();
  for (Map.Entry<Class<? extends Annotation>, ScopeBinding> entry : scopes.entrySet()) {
    builder.put(entry.getKey(), entry.getValue().getScope());
  }
  return builder.build();
}
 
Example 26
Project: guice-old   File: Modules.java   Source Code and License 5 votes vote down vote up
private Scope getScopeInstanceOrNull(Binding<?> binding) {
  return binding.acceptScopingVisitor(new DefaultBindingScopingVisitor<Scope>() {
    @Override public Scope visitScope(Scope scope) {
      return scope;
    }
  });
}
 
Example 27
Project: jfunk   File: JFunkBaseModule.java   Source Code and License 5 votes vote down vote up
private <T extends Scope> void bindScope(final Class<T> scopeClass, final T scope,
		final Class<? extends Annotation> scopeAnnotation) {
	// We need a custom thread scope for things related to test runs, because each test runs in
	// its own thread. This gives us thread-local Guice singletons.
	bindScope(scopeAnnotation, scope);

	// We also need to get a hold of the ThreadScope instance via Guice in order to be able to
	// call its cleanUp method after a thread is done. We need to do a clean-up in order to
	// avoid memory leaks.
	bind(scopeClass).toInstance(scope);
}
 
Example 28
Project: google-guice   File: CheckedProviderTest.java   Source Code and License 5 votes vote down vote up
public void testProvisionExceptionOnDependenciesOfCxtor() throws Exception {
  Injector injector = Guice.createInjector(new AbstractModule() {
      @Override
      protected void configure() {
        ThrowingProviderBinder.create(binder())
            .bind(RemoteProvider.class, Foo.class)
            .providing(ProvisionExceptionFoo.class);
        bindScope(BadScope.class, new Scope() {
          @Override
          public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
            return new Provider<T>() {
              @Override
              public T get() {
                throw new OutOfScopeException("failure");
              }
            };
          }
        });
      }
    });
  
  try {
    injector.getInstance(Key.get(remoteProviderOfFoo)).get();
    fail();
  } catch(ProvisionException pe) {
    assertEquals(2, pe.getErrorMessages().size());
    List<Message> messages = Lists.newArrayList(pe.getErrorMessages());
    assertEquals("Error in custom provider, com.google.inject.OutOfScopeException: failure",
        messages.get(0).getMessage());
    assertEquals("Error in custom provider, com.google.inject.OutOfScopeException: failure",
        messages.get(1).getMessage());
  }
}
 
Example 29
Project: google-guice   File: Scoping.java   Source Code and License 5 votes vote down vote up
/**
 * Replaces annotation scopes with instance scopes using the Injector's annotation-to-instance
 * map. If the scope annotation has no corresponding instance, an error will be added and unscoped
 * will be retuned.
 */
static Scoping makeInjectable(Scoping scoping, InjectorImpl injector, Errors errors) {
  Class<? extends Annotation> scopeAnnotation = scoping.getScopeAnnotation();
  if (scopeAnnotation == null) {
    return scoping;
  }

  Scope scope = injector.state.getScope(scopeAnnotation);
  if (scope != null) {
    return forInstance(scope);
  }

  errors.scopeNotFound(scopeAnnotation);
  return UNSCOPED;
}
 
Example 30
Project: beadledom   File: DelegatingInjector.java   Source Code and License 4 votes vote down vote up
@Override
public Map<Class<? extends Annotation>, Scope> getScopeBindings() {
  return injector.getScopeBindings();
}
 
Example 31
Project: ProjectAres   File: AbstractBindingBuilder.java   Source Code and License 4 votes vote down vote up
@Override
public void in(Scope scope) {
    applyScoping(Scoping.forInstance(scope));
}
 
Example 32
Project: violet   File: ForwardingBinder.java   Source Code and License 4 votes vote down vote up
@Override
default void bindScope(final Class<? extends Annotation> annotationType, final Scope scope) {
  this.binder().bindScope(annotationType, scope);
}
 
Example 33
Project: violet   File: ForwardingLinkedBindingBuilder.java   Source Code and License 4 votes vote down vote up
@Override
default void in(final Scope scope) {
  this.builder().in(scope);
}
 
Example 34
Project: wava   File: ScopeListeners.java   Source Code and License 4 votes vote down vote up
@Override
public void onEnter(Class<? extends Scope> scopeClass)
{
}
 
Example 35
Project: wava   File: ScopeListeners.java   Source Code and License 4 votes vote down vote up
@Override
public void onExit(Class<? extends Scope> scopeClass)
{
}
 
Example 36
Project: wava   File: ScopeListeners.java   Source Code and License 4 votes vote down vote up
@Override
public void onEnter(Class<? extends Scope> scopeClass)
{
    injector.getInstance(key);
}
 
Example 37
Project: wava   File: ScopeListeners.java   Source Code and License 4 votes vote down vote up
public static void bindScopeListeners(Binder binder, Class<? extends Scope> scopeCls)
{
    binder.bind(Key.get(Types.newParameterizedType(ScopeListeners.class, scopeCls))).asEagerSingleton();
}
 
Example 38
Project: guice-scoped-proxy-extension   File: ScopedProxyBinder.java   Source Code and License 4 votes vote down vote up
@Override
public void in(Scope scope) {
    this.bindRewritten().in(scope);
}
 
Example 39
Project: salta   File: ScopedBindingBuilderImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void in(Scope scope) {
    delegate.in(new ScopeImpl(new GuiceScopeAdapter(scope)));
}
 
Example 40
Project: salta   File: BinderImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void bindScope(Class<? extends Annotation> annotationType,
        Scope scope) {
    delegate.bindScope(annotationType,
            new ScopeImpl(new GuiceScopeAdapter(scope)));
}