Version 1.7.4
[gae.git] / java / src / main / com / google / appengine / tools / remoteapi / ThreadLocalDelegate.java
blob84344ee89e161a62385c19f076d51c7a9aaaf8fa
1 // Copyright 2011 Google. All Rights Reserved.
2 package com.google.appengine.tools.remoteapi;
4 import com.google.apphosting.api.ApiProxy;
5 import com.google.apphosting.api.ApiProxy.Delegate;
6 import com.google.apphosting.api.ApiProxy.Environment;
8 import java.util.List;
9 import java.util.concurrent.Future;
11 /**
12 * An {@link ApiProxy.Delegate} implementation that allows users to install
13 * another {@link ApiProxy.Delegate} that is only visible to the current
14 * thread. If there is nothing associated with the current thread, the global
15 * delegate provided as a constructor argument is used instead.
18 class ThreadLocalDelegate<E extends Environment> implements ApiProxy.Delegate<E> {
20 private final Delegate<E> globalDelegate;
22 private final ThreadLocal<Delegate<E>> threadLocalDelegate;
24 ThreadLocalDelegate(Delegate<E> globalDelegate, Delegate<E> threadDelegate) {
25 this.globalDelegate = globalDelegate;
26 this.threadLocalDelegate = new ThreadLocal<Delegate<E>>();
27 this.threadLocalDelegate.set(threadDelegate);
30 Delegate<E> getDelegate() {
31 ApiProxy.Delegate<E> result = threadLocalDelegate.get();
32 if (result == null) {
33 result = globalDelegate;
35 return result;
38 public byte[] makeSyncCall(E environment, String pkg, String method, byte[] bytes)
39 throws ApiProxy.ApiProxyException {
40 return getDelegate().makeSyncCall(environment, pkg, method, bytes);
43 public Future<byte[]> makeAsyncCall(E environment, String pkg, String method, byte[] bytes,
44 ApiProxy.ApiConfig apiConfig) {
45 return getDelegate().makeAsyncCall(environment, pkg, method, bytes, apiConfig);
48 public void log(E environment, ApiProxy.LogRecord logRecord) {
49 getDelegate().log(environment, logRecord);
52 @Override
53 public void flushLogs(E environment) {
54 getDelegate().flushLogs(environment);
57 @Override
58 public List<Thread> getRequestThreads(E environment) {
59 return getDelegate().getRequestThreads(environment);
62 Delegate<E> getDelegateForThread() {
63 return threadLocalDelegate.get();
66 void setDelegateForThread(Delegate<E> delegate) {
67 threadLocalDelegate.set(delegate);
70 void clearThreadDelegate() {
71 threadLocalDelegate.remove();
74 Delegate<E> getGlobalDelegate() {
75 return globalDelegate;