Line data Source code
1 : // Copyright (C) 2012 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.util; 16 : 17 : import com.google.common.base.MoreObjects; 18 : import com.google.gerrit.common.Nullable; 19 : import com.google.gerrit.exceptions.NotSignedInException; 20 : import com.google.gerrit.server.CurrentUser; 21 : import com.google.gerrit.server.IdentifiedUser; 22 : import com.google.inject.AbstractModule; 23 : import com.google.inject.Inject; 24 : import com.google.inject.Module; 25 : import com.google.inject.Provides; 26 : import com.google.inject.ProvisionException; 27 : import com.google.inject.name.Named; 28 : import com.google.inject.name.Names; 29 : 30 : /** 31 : * ThreadLocalRequestContext manages the current RequestContext using a ThreadLocal. When the 32 : * context is set, the fields exposed by the context are considered in scope. Otherwise, the 33 : * FallbackRequestContext is used. 34 : */ 35 : public class ThreadLocalRequestContext { 36 : private static final String FALLBACK = "FALLBACK"; 37 : 38 : public static Module module() { 39 152 : return new AbstractModule() { 40 : @Override 41 : protected void configure() { 42 152 : bind(ThreadLocalRequestContext.class); 43 152 : bind(RequestContext.class) 44 152 : .annotatedWith(Names.named(FALLBACK)) 45 152 : .to(FallbackRequestContext.class); 46 152 : } 47 : 48 : @Provides 49 : RequestContext provideRequestContext(@Named(FALLBACK) RequestContext fallback) { 50 150 : return MoreObjects.firstNonNull(local.get(), fallback); 51 : } 52 : 53 : @Provides 54 : CurrentUser provideCurrentUser(RequestContext ctx) { 55 150 : return ctx.getUser(); 56 : } 57 : 58 : @Provides 59 : IdentifiedUser provideCurrentUser(CurrentUser user) { 60 149 : if (user.isIdentifiedUser()) { 61 149 : return user.asIdentifiedUser(); 62 : } 63 0 : throw new ProvisionException(NotSignedInException.MESSAGE, new NotSignedInException()); 64 : } 65 : }; 66 : } 67 : 68 152 : private static final ThreadLocal<RequestContext> local = new ThreadLocal<>(); 69 : 70 : @Inject 71 152 : ThreadLocalRequestContext() {} 72 : 73 : public RequestContext setContext(@Nullable RequestContext ctx) { 74 151 : RequestContext old = getContext(); 75 151 : local.set(ctx); 76 151 : return old; 77 : } 78 : 79 : @Nullable 80 : public RequestContext getContext() { 81 151 : return local.get(); 82 : } 83 : }