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; }
@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"); } }; }
@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; } }
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"); } }; }
@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); } }; }
/** * 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); }
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; }
@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; } }; }
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()); }
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()); }
@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; }; }
@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()); }; }
@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)); }
public ScopedObjects getScope() { Stack<ScopedObjects> scope = scopeLocal.get(); if (scope == null) { throw new OutOfScopeException("Not inside an ExecutionScope"); } return scope.peek(); }
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; }
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; }
private static Context requireContext() { final Context ctx = current.get(); if (ctx == null) { throw new OutOfScopeException("Not in command/request"); } return ctx; }
@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; }
@Override public CurrentUser getUser() { if (submitter != null) { return identifiedUserFactory.create(submitter).getRealUser(); } throw new OutOfScopeException("No user on email thread"); }
private C requireContext() { C context = threadLocal.get(); if (context == null) { throw new OutOfScopeException("Cannot access scoped object"); } return context; }
@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; }
@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); }
@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; }
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; }
private static RequestScoper transferHttpRequest() { final GuiceFilter.Context context = GuiceFilter.localContext.get(); if (context == null) { throw new OutOfScopeException("Not in a request scope"); } return context; }
private static RequestScoper transferNonHttpRequest() { final Context context = requestScopeContext.get(); if (context == null) { throw new OutOfScopeException("Not in a request scope"); } return context; }
public void testTransferHttp_outOfScope() { try { ServletScopes.transferRequest(FALSE_CALLABLE); fail(); } catch (OutOfScopeException expected) { } }
public void testTransferNonHttp_outOfScope() { try { ServletScopes.transferRequest(FALSE_CALLABLE); fail(); } catch (OutOfScopeException expected) { } }
public void testTransferNonHttp_outOfScope_closeable() { try { ServletScopes.transferRequest(); fail(); } catch (OutOfScopeException expected) { } }
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()); } }
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; }
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; }
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); } }; }
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); } }; }
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()); } }
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; }
@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); }); }