Skip to content

Commit

Permalink
Merge pull request #42 from Unknow0/41-servlet-failed-to-find-servlet…
Browse files Browse the repository at this point in the history
…containerinitializer

gh-41 servlet: use runtime class loader instead of system one to load…
  • Loading branch information
Unknow0 authored Jun 24, 2024
2 parents f7a9c04 + adf7ac2 commit f1d324f
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public abstract class Builder {
public static interface BuilderContext {
ClassOrInterfaceDeclaration self();

ClassLoader classLoader();

Descriptor descriptor();

TypeCache type();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ public ClassOrInterfaceDeclaration self() {
return cl;
}

@Override
public ClassLoader classLoader() {
return classLoader;
}

@Override
public Descriptor descriptor() {
return descriptor;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.github.javaparser.ast.stmt.BlockStmt;

import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletException;
import unknow.server.maven.Utils;
import unknow.server.maven.servlet.Builder;

Expand All @@ -34,7 +35,7 @@ public class LoadInitializer extends Builder {
public void add(BuilderContext ctx) {
List<String> clazz = new ArrayList<>(ctx.descriptor().initializer);
try {
Enumeration<URL> e = ClassLoader.getSystemResources("/META-INF/services/" + ServletContainerInitializer.class.getName());
Enumeration<URL> e = ctx.classLoader().getResources("META-INF/services/" + ServletContainerInitializer.class.getName());
while (e.hasMoreElements()) {
URL nextElement = e.nextElement();
try (BufferedReader br = new BufferedReader(new InputStreamReader(nextElement.openStream()))) {
Expand All @@ -46,7 +47,8 @@ public void add(BuilderContext ctx) {
} catch (Exception ex) {
logger.warn("Failed to process ServletContainerInitializer", ex);
}
BlockStmt b = ctx.self().addMethod("loadInitializer", Keyword.PROTECTED, Keyword.FINAL).addMarkerAnnotation(Override.class).createBody();
BlockStmt b = ctx.self().addMethod("loadInitializer", Keyword.PROTECTED, Keyword.FINAL).addThrownException(ctx.type().getClass(ServletException.class))
.addMarkerAnnotation(Override.class).createBody();
for (String s : clazz)
b.addStatement(new MethodCallExpr(new ObjectCreationExpr(null, ctx.type().getClass(s), Utils.list()), "onStartup",
Utils.list(new NullLiteralExpr(), new NameExpr("ctx"))));
Expand Down

0 comments on commit f1d324f

Please sign in to comment.