package example;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.util.Objects;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.FilterInfo;
import static io.undertow.servlet.Servlets.defaultContainer;
import static io.undertow.servlet.Servlets.deployment;
import static io.undertow.servlet.Servlets.filter;
import static io.undertow.servlet.Servlets.servlet;
public class UndertowRequestAttributeLost {
public static void main(final String[] args) throws MalformedURLException, IOException {
try {
FilterInfo filter = filter(TestFilter.class);
DeploymentInfo servletBuilder = deployment()
.setClassLoader(UndertowRequestAttributeLost.class.getClassLoader()).setContextPath("/")
.setDeploymentName("test.war").addFilter(filter)
.addServlets(servlet("TestServlet", TestServlet.class).addMapping("/*"))
.addFilterUrlMapping(filter.getName(), "/*", DispatcherType.REQUEST);
DeploymentManager manager = defaultContainer().addDeployment(servletBuilder);
manager.deploy();
HttpHandler servletHandler = manager.start();
Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(servletHandler).build();
server.start();
Socket socket = new Socket();
socket.connect(new InetSocketAddress("localhost", 8080));
OutputStream output = socket.getOutputStream();
output.write("GET / HTTP/1.1\nHost: localhost:8080\n\n".getBytes());
output.flush();
socket.getInputStream().read();
socket.close();
manager.stop();
server.stop();
}
catch (ServletException e) {
throw new RuntimeException(e);
}
}
public static class TestFilter implements Filter {
private static final String ATTRIBUTE_NAME = TestFilter.class.getName();
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setAttribute(ATTRIBUTE_NAME, new Object());
try {
chain.doFilter(request, response);
}
finally {
Objects.requireNonNull(request.getAttribute(ATTRIBUTE_NAME));
}
}
}
public static class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
while (true) {
resp.getOutputStream().write(1);
}
}
}
}