Skip to content

Commit

Permalink
fix: set Thread Context ClassLoader correctly when invoking handler c…
Browse files Browse the repository at this point in the history
…onstructor (#239)
  • Loading branch information
garethgeorge authored Sep 28, 2023
1 parent 6dfc3c7 commit 9f7155b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,16 @@ public static HttpFunctionExecutor forClass(Class<?> functionClass) {
+ HttpFunction.class.getName());
}
Class<? extends HttpFunction> httpFunctionClass = functionClass.asSubclass(HttpFunction.class);
ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(httpFunctionClass.getClassLoader());
HttpFunction httpFunction = httpFunctionClass.getConstructor().newInstance();
return new HttpFunctionExecutor(httpFunction);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(
"Could not construct an instance of " + functionClass.getName() + ": " + e, e);
} finally {
Thread.currentThread().setContextClassLoader(oldContextLoader);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.google.cloud.functions.invoker;

import static com.google.common.truth.Truth.assertThat;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class HttpFunctionExecutorTest {
private static ClassLoader customClassLoader =
new ClassLoader(ClassLoader.getSystemClassLoader()) {};

public static class ClassLoaderVerifier implements HttpFunction {
public ClassLoaderVerifier() {
assertThat(Thread.currentThread().getContextClassLoader())
.isNotSameInstanceAs(customClassLoader);
}

@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
throw new UnsupportedOperationException("Not implemented");
}
}

@Test
public void usesCorrectClassLoaderOverride() {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(customClassLoader);
HttpFunctionExecutor.forClass(ClassLoaderVerifier.class);
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}

0 comments on commit 9f7155b

Please sign in to comment.