Search in sources :

Example 21 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project JMRI by JMRI.

the class WebServer method registerResource.

/**
     * Register a URL pattern to return resources from the file system. The
     * filePath may start with any of the following:
     * <ol>
     * <li>{@link jmri.util.FileUtil#PREFERENCES}
     * <li>{@link jmri.util.FileUtil#PROFILE}
     * <li>{@link jmri.util.FileUtil#SETTINGS}
     * <li>{@link jmri.util.FileUtil#PROGRAM}
     * </ol>
     * Note that the filePath can be overridden by an otherwise identical
     * filePath starting with any of the portable paths above it in the
     * preceding list.
     *
     * @param urlPattern the pattern to get resources for
     * @param filePath   the portable path for the resources
     * @throws IllegalArgumentException if urlPattern is already registered to
     *                                  deny access or for a servlet or if
     *                                  filePath is not allowed
     */
public void registerResource(String urlPattern, String filePath) throws IllegalArgumentException {
    if (this.registeredUrls.get(urlPattern) != null) {
        throw new IllegalArgumentException("urlPattern \"" + urlPattern + "\" is already registered.");
    }
    this.registeredUrls.put(urlPattern, Registration.RESOURCE);
    ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
    servletContext.setContextPath(urlPattern);
    HandlerList handlers = new HandlerList();
    if (filePath.startsWith(FileUtil.PROGRAM) && !filePath.equals(FileUtil.PROGRAM)) {
        // make it possible to override anything under program: with an identical path under preference:, profile:, or settings:
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PREFERENCES)));
        ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
        ResourceHandler settingsHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.SETTINGS)));
        ResourceHandler programHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
        handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, settingsHandler, programHandler, new DefaultHandler() });
    } else if (filePath.startsWith(FileUtil.SETTINGS) && !filePath.equals(FileUtil.SETTINGS)) {
        // make it possible to override anything under settings: with an identical path under preference: or profile:
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.SETTINGS, FileUtil.PREFERENCES)));
        ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
        ResourceHandler settingsHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
        handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, settingsHandler, new DefaultHandler() });
    } else if (filePath.startsWith(FileUtil.PROFILE) && !filePath.equals(FileUtil.PROFILE)) {
        // make it possible to override anything under profile: with an identical path under preference:
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.SETTINGS, FileUtil.PREFERENCES)));
        ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
        handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, new DefaultHandler() });
    } else if (FileUtil.isPortableFilename(filePath)) {
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler handler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
        handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });
    } else if (URIforPortablePath(filePath) == null) {
        throw new IllegalArgumentException("\"" + filePath + "\" is not allowed.");
    }
    ContextHandler handlerContext = new ContextHandler();
    handlerContext.setContextPath(urlPattern);
    handlerContext.setHandler(handlers);
    ((ContextHandlerCollection) this.server.getHandler()).addHandler(handlerContext);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) DirectoryHandler(jmri.web.servlet.directory.DirectoryHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) DirectoryHandler(jmri.web.servlet.directory.DirectoryHandler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler)

Example 22 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project blade by biezhi.

the class EmbedJettyServer method startup.

@Override
public void startup(int port, String contextPath, String webRoot) throws EmbedServerException {
    this.port = port;
    Config config = Blade.$().config();
    int minThreads = config.getInt("server.jetty.min-threads", 8);
    int maxThreads = config.getInt("server.jetty.max-threads", 200);
    String poolName = config.get("server.jetty.pool-name", "blade-pool");
    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(minThreads);
    threadPool.setMaxThreads(maxThreads);
    threadPool.setName(poolName);
    this.server = new org.eclipse.jetty.server.Server(threadPool);
    this.webAppContext = new WebAppContext();
    this.webAppContext.setContextPath(contextPath);
    this.webAppContext.setResourceBase("");
    int securePort = config.getInt("server.jetty.http.secure-port", 9443);
    int outputBufferSize = config.getInt("server.jetty.http.output-buffersize", 32 * 1024);
    int requestHeaderSize = config.getInt("server.jetty.http.request-headersize", 8 * 1024);
    int responseHeaderSize = config.getInt("server.jetty.http.response-headersize", 8 * 1024);
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecurePort(securePort);
    http_config.setOutputBufferSize(outputBufferSize);
    http_config.setRequestHeaderSize(requestHeaderSize);
    http_config.setResponseHeaderSize(responseHeaderSize);
    long idleTimeout = config.getLong("server.jetty.http.idle-timeout", 30000L);
    String host = config.get("server.host", "0.0.0.0");
    ServerConnector serverConnector = new ServerConnector(server, new HttpConnectionFactory(http_config));
    serverConnector.setHost(host);
    serverConnector.setPort(this.port);
    serverConnector.setIdleTimeout(idleTimeout);
    server.setConnectors(new Connector[] { serverConnector });
    boolean isAsync = config.getBoolean("server.async", false);
    Class<? extends Servlet> servlet = isAsync ? AsyncDispatcherServlet.class : DispatcherServlet.class;
    ServletHolder servletHolder = new ServletHolder(servlet);
    servletHolder.setAsyncSupported(isAsync);
    servletHolder.setInitOrder(1);
    webAppContext.addEventListener(new BladeInitListener());
    Set<String> statics = Blade.$().bConfig().getStatics();
    defaultHolder = new ServletHolder(DefaultServlet.class);
    defaultHolder.setInitOrder(0);
    if (StringKit.isNotBlank(classPath)) {
        LOGGER.info("add classpath : {}", classPath);
        defaultHolder.setInitParameter("resourceBase", classPath);
    }
    statics.forEach(s -> {
        if (s.indexOf(".") != -1) {
            webAppContext.addServlet(defaultHolder, s);
        } else {
            s = s.endsWith("/") ? s + '*' : s + "/*";
            webAppContext.addServlet(defaultHolder, s);
        }
    });
    webAppContext.addServlet(defaultHolder, "/favicon.ico");
    webAppContext.addServlet(servletHolder, "/");
    try {
        this.loadServlets(webAppContext);
        this.loadFilters(webAppContext);
        HandlerList handlerList = new HandlerList();
        handlerList.setHandlers(new Handler[] { webAppContext, new DefaultHandler() });
        server.setHandler(handlerList);
        server.setStopAtShutdown(true);
        server.start();
        LOGGER.info("Blade Server Listen on {}:{}", host, this.port);
        server.join();
    } catch (Exception e) {
        throw new EmbedServerException(e);
    }
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) org.eclipse.jetty.server(org.eclipse.jetty.server) EmbedServerException(com.blade.exception.EmbedServerException) Config(com.blade.kit.base.Config) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) BladeInitListener(com.blade.mvc.context.BladeInitListener) EmbedServerException(com.blade.exception.EmbedServerException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) DefaultServlet(org.eclipse.jetty.servlet.DefaultServlet)

Example 23 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project jetty.project by eclipse.

the class FastFileServer method main.

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { new FastFileHandler(new File(System.getProperty("user.dir"))), new DefaultHandler() });
    server.setHandler(handlers);
    server.start();
    server.join();
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) Server(org.eclipse.jetty.server.Server) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler)

Example 24 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project jetty.project by eclipse.

the class WebAppContextTest method testContextWhiteList.

/**
     * tests that the servlet context white list works
     *
     * @throws Exception on test failure
     */
@Test
public void testContextWhiteList() throws Exception {
    Server server = new Server(0);
    HandlerList handlers = new HandlerList();
    WebAppContext contextA = new WebAppContext(".", "/A");
    contextA.addServlet(ServletA.class, "/s");
    handlers.addHandler(contextA);
    WebAppContext contextB = new WebAppContext(".", "/B");
    contextB.addServlet(ServletB.class, "/s");
    contextB.setContextWhiteList(new String[] { "/doesnotexist", "/B/s" });
    handlers.addHandler(contextB);
    server.setHandler(handlers);
    server.start();
    // context A should be able to get both A and B servlet contexts
    Assert.assertNotNull(contextA.getServletHandler().getServletContext().getContext("/A/s"));
    Assert.assertNotNull(contextA.getServletHandler().getServletContext().getContext("/B/s"));
    // context B has a contextWhiteList set and should only be able to get ones that are approved
    Assert.assertNull(contextB.getServletHandler().getServletContext().getContext("/A/s"));
    Assert.assertNotNull(contextB.getServletHandler().getServletContext().getContext("/B/s"));
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) Server(org.eclipse.jetty.server.Server) Test(org.junit.Test)

Example 25 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project jetty.project by eclipse.

the class AliasedConstraintTest method startServer.

@BeforeClass
public static void startServer() throws Exception {
    server = new Server();
    connector = new LocalConnector(server);
    server.setConnectors(new Connector[] { connector });
    ContextHandler context = new ContextHandler();
    SessionHandler session = new SessionHandler();
    TestLoginService loginService = new TestLoginService(TEST_REALM);
    loginService.putUser("user0", new Password("password"), new String[] {});
    loginService.putUser("user", new Password("password"), new String[] { "user" });
    loginService.putUser("user2", new Password("password"), new String[] { "user" });
    loginService.putUser("admin", new Password("password"), new String[] { "user", "administrator" });
    loginService.putUser("user3", new Password("password"), new String[] { "foo" });
    context.setContextPath("/ctx");
    context.setResourceBase(MavenTestingUtils.getTestResourceDir("docroot").getAbsolutePath());
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
    server.setHandler(handlers);
    context.setHandler(session);
    // context.addAliasCheck(new AllowSymLinkAliasChecker());
    server.addBean(loginService);
    security = new ConstraintSecurityHandler();
    session.setHandler(security);
    ResourceHandler handler = new ResourceHandler();
    security.setHandler(handler);
    List<ConstraintMapping> constraints = new ArrayList<>();
    Constraint constraint0 = new Constraint();
    constraint0.setAuthenticate(true);
    constraint0.setName("forbid");
    ConstraintMapping mapping0 = new ConstraintMapping();
    mapping0.setPathSpec("/forbid/*");
    mapping0.setConstraint(constraint0);
    constraints.add(mapping0);
    Set<String> knownRoles = new HashSet<>();
    knownRoles.add("user");
    knownRoles.add("administrator");
    security.setConstraintMappings(constraints, knownRoles);
    server.start();
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HandlerList(org.eclipse.jetty.server.handler.HandlerList) Server(org.eclipse.jetty.server.Server) Constraint(org.eclipse.jetty.util.security.Constraint) LocalConnector(org.eclipse.jetty.server.LocalConnector) ArrayList(java.util.ArrayList) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) Matchers.containsString(org.hamcrest.Matchers.containsString) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Password(org.eclipse.jetty.util.security.Password) HashSet(java.util.HashSet) BeforeClass(org.junit.BeforeClass)

Aggregations

HandlerList (org.eclipse.jetty.server.handler.HandlerList)35 Server (org.eclipse.jetty.server.Server)19 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)17 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)13 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)11 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)8 Handler (org.eclipse.jetty.server.Handler)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 ServerConnector (org.eclipse.jetty.server.ServerConnector)5 DefaultServlet (org.eclipse.jetty.servlet.DefaultServlet)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 File (java.io.File)3 URI (java.net.URI)3 ArrayList (java.util.ArrayList)3 ServletException (javax.servlet.ServletException)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)3 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)3