Java Code Examples for com.google.inject.OutOfScopeException

The following are top voted examples for showing how to use com.google.inject.OutOfScopeException. 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: ProjectAres   File: DataDogClient.java   Source Code and License 6 votes vote down vote up
String[] renderedTags() {
    final StringBuilder sb = new StringBuilder();
    boolean some = false;
    for(Provider<Tagger> provider : taggers.get()) {
        final Tagger tagger;
        try {
            tagger = Injection.unwrappingExceptions(OutOfScopeException.class, provider);
        } catch(OutOfScopeException e) {
            // If the tagger is out of scope, just omit its tags,
            // but log a warning in case this hides an unexpected exception.
            logger.warning("Ignoring out-of-scope tagger (" + e.toString() + ")");
            continue;
        }

        final ImmutableSet<Tag> tags = tagger.tags();
        if(!tags.isEmpty()) {
            if(some) sb.append(',');
            some = true;
            sb.append(tagSetCache.getUnchecked(tags));
        }
    }
    return some ? new String[] {sb.toString()} : EMPTY;
}
 
Example 2
Project: biomedicus   File: BiomedicusScopes.java   Source Code and License 6 votes vote down vote up
@Override
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
  return () -> {
    Context context = contextRef.get();
    if (null != context) {
      @SuppressWarnings("unchecked")
      T t = (T) context.objectsMap.get(key);

      if (t == null) {
        t = unscoped.get();
        if (!Scopes.isCircularProxy(t)) {
          context.objectsMap.put(key, t);
        }
      }
      return t;
    } else {
      throw new OutOfScopeException("Not currently in a document scope");
    }
  };
}
 
Example 3
Project: nexus-public   File: ClientInfoProviderImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public ClientInfo getCurrentThreadClientInfo() {
  try {
    HttpServletRequest request = httpRequestProvider.get();
    return new ClientInfo(
        UserIdHelper.get(),
        request.getRemoteAddr(),
        request.getHeader(HttpHeaders.USER_AGENT)
    );
  }
  catch (ProvisionException | OutOfScopeException e) {
    // ignore; this happens when called out of scope of http request
    return null;
  }
}
 
Example 4
Project: gerrit   File: InProcessProtocol.java   Source Code and License 6 votes vote down vote up
static Module module() {
  return new AbstractModule() {
    @Override
    public void configure() {
      install(new GerritRequestModule());
      bind(RequestScopePropagator.class).to(Propagator.class);
      bindScope(RequestScoped.class, InProcessProtocol.REQUEST);
    }

    @Provides
    @RemotePeer
    SocketAddress getSocketAddress() {
      // TODO(dborowitz): Could potentially fake this with thread ID or
      // something.
      throw new OutOfScopeException("No remote peer in acceptance tests");
    }
  };
}
 
Example 5
Project: gerrit   File: InProcessProtocol.java   Source Code and License 6 votes vote down vote up
@Override
public <T> Provider<T> scope(Key<T> key, Provider<T> creator) {
  return new Provider<T>() {
    @Override
    public T get() {
      Context ctx = current.get();
      if (ctx == null) {
        throw new OutOfScopeException("Not in TestProtocol scope");
      }
      return ctx.get(key, creator);
    }

    @Override
    public String toString() {
      return String.format("%s[%s]", creator, REQUEST);
    }
  };
}
 
Example 6
Project: gerrit   File: IdentifiedUser.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a materialized copy of the user with all dependencies.
 *
 * <p>Invoke all providers and factories of dependent objects and store the references to a copy
 * of the current identified user.
 *
 * @return copy of the identified user
 */
public IdentifiedUser materializedCopy() {
  Provider<SocketAddress> remotePeer;
  try {
    remotePeer = Providers.of(remotePeerProvider.get());
  } catch (OutOfScopeException | ProvisionException e) {
    remotePeer =
        new Provider<SocketAddress>() {
          @Override
          public SocketAddress get() {
            throw e;
          }
        };
  }
  return new IdentifiedUser(
      authConfig,
      realm,
      anonymousCowardName,
      Providers.of(canonicalUrl.get()),
      accountCache,
      groupBackend,
      disableReverseDnsLookup,
      remotePeer,
      state,
      realUser);
}
 
Example 7
Project: gerrit   File: IdentifiedUser.java   Source Code and License 6 votes vote down vote up
private String guessHost() {
  String host = null;
  SocketAddress remotePeer = null;
  try {
    remotePeer = remotePeerProvider.get();
  } catch (OutOfScopeException | ProvisionException e) {
    // Leave null.
  }
  if (remotePeer instanceof InetSocketAddress) {
    InetSocketAddress sa = (InetSocketAddress) remotePeer;
    InetAddress in = sa.getAddress();
    host = in != null ? getHost(in) : sa.getHostName();
  }
  if (Strings.isNullOrEmpty(host)) {
    return "unknown";
  }
  return host;
}
 
Example 8
Project: closure-templates   File: GuiceSimpleScope.java   Source Code and License 6 votes vote down vote up
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscopedProvider) {

  return new Provider<T>() {
    @Override
    public T get() {
      ArrayDeque<HashMap<Key<?>, Object>> arrayDeque = scopedValuesTl.get();
      if (arrayDeque == null || arrayDeque.isEmpty()) {
        throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
      }
      Map<Key<?>, Object> scopedValues = arrayDeque.peek();
      Object value = scopedValues.get(key);
      if (value == null) {
        value = unscopedProvider.get();
        scopedValues.put(key, value == null ? NULL_SENTINEL : value);
      }
      @SuppressWarnings("unchecked")
      T typedValue = value == NULL_SENTINEL ? null : (T) value;
      return typedValue;
    }
  };
}
 
Example 9
Project: guice   File: ScopeRequestIntegrationTest.java   Source Code and License 6 votes vote down vote up
public final void testNullReplacement() throws Exception {
  Injector injector =
      Guice.createInjector(
          new ServletModule() {
            @Override
            protected void configureServlets() {
              bindConstant().annotatedWith(Names.named(SomeObject.INVALID)).to(SHOULDNEVERBESEEN);
              bind(SomeObject.class).in(RequestScoped.class);
            }
          });

  Callable<SomeObject> callable = injector.getInstance(Caller.class);
  try {
    assertNotNull(callable.call());
    fail();
  } catch (ProvisionException pe) {
    assertTrue(pe.getCause() instanceof OutOfScopeException);
  }

  // Validate that an actual null entry in the map results in a null injected object.
  Map<Key<?>, Object> map = Maps.newHashMap();
  map.put(Key.get(SomeObject.class), null);
  callable = ServletScopes.scopeRequest(injector.getInstance(Caller.class), map);
  assertNull(callable.call());
}
 
Example 10
Project: guice-old   File: ScopeRequestIntegrationTest.java   Source Code and License 6 votes vote down vote up
public final void testNullReplacement() throws Exception {
  Injector injector = Guice.createInjector(new ServletModule() {
    @Override protected void configureServlets() {
      bindConstant().annotatedWith(Names.named(SomeObject.INVALID)).to(SHOULDNEVERBESEEN);
      bind(SomeObject.class).in(RequestScoped.class);
    }
  });

  Callable<SomeObject> callable = injector.getInstance(Caller.class);
  try {
    assertNotNull(callable.call());
    fail();
  } catch(ProvisionException pe) {
    assertTrue(pe.getCause() instanceof OutOfScopeException);
  }

  // Validate that an actual null entry in the map results in a null injected object.
  Map<Key<?>, Object> map = Maps.newHashMap();
  map.put(Key.get(SomeObject.class), null);
  callable = ServletScopes.scopeRequest(injector.getInstance(Caller.class), map);
  assertNull(callable.call());
}
 
Example 11
Project: google-guice   File: ScopeRequestIntegrationTest.java   Source Code and License 6 votes vote down vote up
public final void testNullReplacement() throws Exception {
  Injector injector = Guice.createInjector(new ServletModule() {
    @Override protected void configureServlets() {
      bindConstant().annotatedWith(Names.named(SomeObject.INVALID)).to(SHOULDNEVERBESEEN);
      bind(SomeObject.class).in(RequestScoped.class);
    }
  });

  Callable<SomeObject> callable = injector.getInstance(Caller.class);
  try {
    assertNotNull(callable.call());
    fail();
  } catch(ProvisionException pe) {
    assertTrue(pe.getCause() instanceof OutOfScopeException);
  }

  // Validate that an actual null entry in the map results in a null injected object.
  Map<Key<?>, Object> map = Maps.newHashMap();
  map.put(Key.get(SomeObject.class), null);
  callable = ServletScopes.scopeRequest(injector.getInstance(Caller.class), map);
  assertNull(callable.call());
}
 
Example 12
Project: js-dossier   File: ExplicitScope.java   Source Code and License 6 votes vote down vote up
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
  return () -> {
    if (scope == null) {
      throw new OutOfScopeException("Not in scope");
    }

    Object value = scope.get(key);
    if (value == null) {
      T provided = unscoped.get();
      if (provided instanceof CircularDependencyProxy) {
        return provided;
      }
      value = (provided == null) ? NULL_SENTINEL : provided;
      scope.put(key, value);
    }

    @SuppressWarnings("unchecked")
    T result = (value != NULL_SENTINEL) ? (T) value : null;
    return result;
  };
}
 
Example 13
Project: ProjectAres   File: InjectionScope.java   Source Code and License 5 votes vote down vote up
@Override
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
    return () -> {
        final InjectionStore<A> store = currentStore(key).orElseThrow(
            () -> new OutOfScopeException("Cannot provide " + key + " outside of " + annotation.getSimpleName() + " scope")
        );

        // If the current store already contains the key, return its value.
        // Otherwise, provision an unscoped value and add it to the store.
        // If the key is of the store itself, just use the store we have.
        return store.provide(key, () -> storeKey.equals(key) ? (T) store : unscoped.get());
    };
}
 
Example 14
Project: wava   File: SimpleScope.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public <T> T getScopedObject(Key<T> key)
{
    Storage storage = threadLocalStoragePolicy.get().getStorage();
    if (storage == null) {
        throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
    }
    return (T) requireNonNull(storage.get(key));
}
 
Example 15
Project: yql-plus   File: ExecutionScoper.java   Source Code and License 5 votes vote down vote up
public ScopedObjects getScope() {
    Stack<ScopedObjects> scope = scopeLocal.get();
    if (scope == null) {
        throw new OutOfScopeException("Not inside an ExecutionScope");
    }
    return scope.peek();
}
 
Example 16
Project: aet   File: TestSuiteScope.java   Source Code and License 5 votes vote down vote up
private <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
  Map<Key<?>, Object> scopedObjects = values.get();
  if (scopedObjects == null) {
    throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
  }
  return scopedObjects;
}
 
Example 17
Project: gstrap   File: SimpleScope.java   Source Code and License 5 votes vote down vote up
private <T> Map<Key<?>, Object> getScopedObjects(Key<T> key) {
	Map<Key<?>, Object> actualValues = this.values.get();
	if (actualValues == null) {
		throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
	}
	return actualValues;
}
 
Example 18
Project: gerrit   File: AcceptanceTestRequestScope.java   Source Code and License 5 votes vote down vote up
private static Context requireContext() {
  final Context ctx = current.get();
  if (ctx == null) {
    throw new OutOfScopeException("Not in command/request");
  }
  return ctx;
}
 
Example 19
Project: gerrit   File: SshScope.java   Source Code and License 5 votes vote down vote up
private static Context requireContext() {
  final Context ctx = current.get();
  if (ctx == null) {
    throw new OutOfScopeException("Not in command/request");
  }
  return ctx;
}
 
Example 20
Project: gerrit   File: HttpCanonicalWebUrlProvider.java   Source Code and License 5 votes vote down vote up
@Override
public String get() {
  String canonicalUrl = super.get();
  if (canonicalUrl != null) {
    return canonicalUrl;
  }

  if (requestProvider != null) {
    // No canonical URL configured? Maybe we can get a reasonable
    // guess from the incoming HTTP request, if we are currently
    // inside of an HTTP request scope.
    //
    final HttpServletRequest req;
    try {
      req = requestProvider.get();
    } catch (ProvisionException noWeb) {
      if (noWeb.getCause() instanceof OutOfScopeException) {
        // We can't obtain the request as we are not inside of
        // an HTTP request scope. Callers must handle null.
        //
        return null;
      }
      throw noWeb;
    }
    return CanonicalWebUrl.computeFromRequest(req);
  }

  // We have no way of guessing our HTTP url.
  //
  return null;
}
 
Example 21
Project: gerrit   File: PerThreadRequestScope.java   Source Code and License 5 votes vote down vote up
private static Context requireContext() {
  final Context ctx = current.get();
  if (ctx == null) {
    throw new OutOfScopeException("Not in command/request");
  }
  return ctx;
}
 
Example 22
Project: gerrit   File: EmailMerge.java   Source Code and License 5 votes vote down vote up
@Override
public CurrentUser getUser() {
  if (submitter != null) {
    return identifiedUserFactory.create(submitter).getRealUser();
  }
  throw new OutOfScopeException("No user on email thread");
}
 
Example 23
Project: gerrit   File: ThreadLocalRequestScopePropagator.java   Source Code and License 5 votes vote down vote up
private C requireContext() {
  C context = threadLocal.get();
  if (context == null) {
    throw new OutOfScopeException("Cannot access scoped object");
  }
  return context;
}
 
Example 24
Project: github-v2   File: AccountScope.java   Source Code and License 5 votes vote down vote up
@Override
protected <T> Map<Key<?>, Object> getScopedObjectMap(final Key<T> key) {
    GitHubAccount account = currentAccount.get();
    if (account == null)
        throw new OutOfScopeException("Cannot access " + key
                + " outside of a scoping block");

    Map<Key<?>, Object> scopeMap = repoScopeMaps.get(account);
    if (scopeMap == null) {
        scopeMap = new ConcurrentHashMap<Key<?>, Object>();
        scopeMap.put(GITHUB_ACCOUNT_KEY, account);
        repoScopeMaps.put(account, scopeMap);
    }
    return scopeMap;
}
 
Example 25
Project: ninja_chic-   File: RepositoryScope.java   Source Code and License 5 votes vote down vote up
@Override
protected <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
    File gitdir = currentRepoGitdir.get();
    if (gitdir == null) {
        throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
    }
    return repoScopeMaps.get(gitdir);
}
 
Example 26
Project: ninja_chic-   File: OperationScope.java   Source Code and License 5 votes vote down vote up
@Override
protected <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
    Map<Key<?>, Object> map = threadLocalMap.get();
    if (map == null) {
        throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
    }
    return map;
}
 
Example 27
Project: guice   File: GuiceFilter.java   Source Code and License 5 votes vote down vote up
private static Context getContext(Key<?> key) {
  Context context = localContext.get();
  if (context == null) {
    throw new OutOfScopeException(
        "Cannot access scoped ["
            + Errors.convert(key)
            + "]. Either we are not currently inside an HTTP Servlet request, or you may"
            + " have forgotten to apply "
            + GuiceFilter.class.getName()
            + " as a servlet filter for this request.");
  }
  return context;
}
 
Example 28
Project: guice   File: ServletScopes.java   Source Code and License 5 votes vote down vote up
private static RequestScoper transferHttpRequest() {
  final GuiceFilter.Context context = GuiceFilter.localContext.get();
  if (context == null) {
    throw new OutOfScopeException("Not in a request scope");
  }
  return context;
}
 
Example 29
Project: guice   File: ServletScopes.java   Source Code and License 5 votes vote down vote up
private static RequestScoper transferNonHttpRequest() {
  final Context context = requestScopeContext.get();
  if (context == null) {
    throw new OutOfScopeException("Not in a request scope");
  }
  return context;
}
 
Example 30
Project: guice   File: TransferRequestIntegrationTest.java   Source Code and License 5 votes vote down vote up
public void testTransferHttp_outOfScope() {
  try {
    ServletScopes.transferRequest(FALSE_CALLABLE);
    fail();
  } catch (OutOfScopeException expected) {
  }
}
 
Example 31
Project: guice   File: TransferRequestIntegrationTest.java   Source Code and License 5 votes vote down vote up
public void testTransferNonHttp_outOfScope() {
  try {
    ServletScopes.transferRequest(FALSE_CALLABLE);
    fail();
  } catch (OutOfScopeException expected) {
  }
}
 
Example 32
Project: guice   File: TransferRequestIntegrationTest.java   Source Code and License 5 votes vote down vote up
public void testTransferNonHttp_outOfScope_closeable() {
  try {
    ServletScopes.transferRequest();
    fail();
  } catch (OutOfScopeException expected) {
  }
}
 
Example 33
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 34
Project: acai   File: TestScope.java   Source Code and License 5 votes vote down vote up
private <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
  Map<Key<?>, Object> scopedObjects = values.get();
  if (scopedObjects == null) {
    throw new OutOfScopeException("Attempt to inject @TestScoped binding outside test: " + key);
  }
  return scopedObjects;
}
 
Example 35
Project: guice-old   File: GuiceFilter.java   Source Code and License 5 votes vote down vote up
private static Context getContext(Key<?> key) {
  Context context = localContext.get();
  if (context == null) {
    throw new OutOfScopeException("Cannot access scoped [" + Errors.convert(key) 
        + "]. Either we are not currently inside an HTTP Servlet request, or you may"
        + " have forgotten to apply " + GuiceFilter.class.getName()
        + " as a servlet filter for this request.");
  }
  return context;
}
 
Example 36
Project: guice-old   File: ServletScopes.java   Source Code and License 5 votes vote down vote up
private static <T> Callable<T> transferHttpRequest(final Callable<T> callable) {
  final GuiceFilter.Context context = GuiceFilter.localContext.get();
  if (context == null) {
    throw new OutOfScopeException("Not in a request scope");
  }
  return new Callable<T>() {
    public T call() throws Exception {
      return context.call(callable);
    }
  };
}
 
Example 37
Project: guice-old   File: ServletScopes.java   Source Code and License 5 votes vote down vote up
private static <T> Callable<T> transferNonHttpRequest(final Callable<T> callable) {
  final Context context = requestScopeContext.get();
  if (context == null) {
    throw new OutOfScopeException("Not in a request scope");
  }
  return new Callable<T>() {
    public T call() throws Exception {
      return context.call(callable);
    }
  };
}
 
Example 38
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 39
Project: jooby   File: RequestScope.java   Source Code and License 5 votes vote down vote up
private <T> Map<Object, Object> getScopedObjectMap(final Key<T> key) {
  Map<Object, Object> scopedObjects = scope.get();
  if (scopedObjects == null) {
    throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
  }
  return scopedObjects;
}
 
Example 40
Project: jooby   File: RequestScopeTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unchecked" })
@Test(expected = OutOfScopeException.class)
public void outOfScope() throws Exception {
  RequestScope requestScope = new RequestScope();
  Key<Object> key = Key.get(Object.class);
  Object value = new Object();
  new MockUnit(Provider.class, Map.class)
      .run(unit -> {
        Object result = requestScope.<Object> scope(key, unit.get(Provider.class)).get();
        assertEquals(value, result);
      });
}