Skip to content

Commit 9f7155b

Browse files
authored
fix: set Thread Context ClassLoader correctly when invoking handler constructor (#239)
1 parent 6dfc3c7 commit 9f7155b

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

invoker/core/src/main/java/com/google/cloud/functions/invoker/HttpFunctionExecutor.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,16 @@ public static HttpFunctionExecutor forClass(Class<?> functionClass) {
4848
+ HttpFunction.class.getName());
4949
}
5050
Class<? extends HttpFunction> httpFunctionClass = functionClass.asSubclass(HttpFunction.class);
51+
ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
5152
try {
53+
Thread.currentThread().setContextClassLoader(httpFunctionClass.getClassLoader());
5254
HttpFunction httpFunction = httpFunctionClass.getConstructor().newInstance();
5355
return new HttpFunctionExecutor(httpFunction);
5456
} catch (ReflectiveOperationException e) {
5557
throw new RuntimeException(
5658
"Could not construct an instance of " + functionClass.getName() + ": " + e, e);
59+
} finally {
60+
Thread.currentThread().setContextClassLoader(oldContextLoader);
5761
}
5862
}
5963

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.google.cloud.functions.invoker;
2+
3+
import static com.google.common.truth.Truth.assertThat;
4+
5+
import com.google.cloud.functions.HttpFunction;
6+
import com.google.cloud.functions.HttpRequest;
7+
import com.google.cloud.functions.HttpResponse;
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
import org.junit.runners.JUnit4;
11+
12+
@RunWith(JUnit4.class)
13+
public class HttpFunctionExecutorTest {
14+
private static ClassLoader customClassLoader =
15+
new ClassLoader(ClassLoader.getSystemClassLoader()) {};
16+
17+
public static class ClassLoaderVerifier implements HttpFunction {
18+
public ClassLoaderVerifier() {
19+
assertThat(Thread.currentThread().getContextClassLoader())
20+
.isNotSameInstanceAs(customClassLoader);
21+
}
22+
23+
@Override
24+
public void service(HttpRequest request, HttpResponse response) throws Exception {
25+
throw new UnsupportedOperationException("Not implemented");
26+
}
27+
}
28+
29+
@Test
30+
public void usesCorrectClassLoaderOverride() {
31+
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
32+
Thread.currentThread().setContextClassLoader(customClassLoader);
33+
HttpFunctionExecutor.forClass(ClassLoaderVerifier.class);
34+
Thread.currentThread().setContextClassLoader(oldClassLoader);
35+
}
36+
}

0 commit comments

Comments
 (0)