Skip to content

Instantly share code, notes, and snippets.

@joakime
Created October 19, 2018 11:36
Show Gist options
  • Save joakime/15b48c9309a22066bddfb6a663040446 to your computer and use it in GitHub Desktop.
Save joakime/15b48c9309a22066bddfb6a663040446 to your computer and use it in GitHub Desktop.
package jetty;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.function.Function;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class AttributesDump
{
public static void main(String[] args) throws Exception
{
Server server = new Server(9090);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(AttrDumpServlet.class, "/dump");
context.addEventListener(new AttrDumpListener());
server.setHandler(context);
server.start();
try
{
dumpAttrs("server.attrs (post-start)", server.getAttributeNames(), (name) -> server.getAttribute(name));
HttpURLConnection http = (HttpURLConnection) new URL("http://localhost:9090/dump").openConnection();
System.out.println("Http.responseCode = " + http.getResponseCode());
}
finally
{
server.stop();
}
}
private static void dumpAttrs(String scope, Enumeration<String> enNames, Function<String, Object> funcGetValue)
{
List<String> names = Collections.list(enNames);
System.out.printf("[%s] count = %,d%n", scope, names.size());
names.stream().forEach((name) -> {
Object val = funcGetValue.apply(name);
if (val == null)
System.out.printf("[%s] [%s] = <null>%n", scope, name);
else
System.out.printf("[%s] [%s] = (%s)%s%n", scope, name, val.getClass().getName(), val.toString());
});
}
public static class AttrDumpListener implements ServletContextListener
{
@Override
public void contextInitialized(ServletContextEvent sce)
{
ServletContext context = sce.getServletContext();
dumpAttrs("context.attrs (post-initialized)", context.getAttributeNames(), (name) -> context.getAttribute(name));
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
}
}
public static class AttrDumpServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
ServletContext context = req.getServletContext();
dumpAttrs("context.attrs (doGet)", context.getAttributeNames(), (name) -> context.getAttribute(name));
dumpAttrs("request.attrs (doGet)", req.getAttributeNames(), (name) -> req.getAttribute(name));
resp.setStatus(200);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment