Search in sources :

Example 21 with DefaultHandler

use of org.eclipse.jetty.server.handler.DefaultHandler 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 DefaultHandler

use of org.eclipse.jetty.server.handler.DefaultHandler 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 DefaultHandler

use of org.eclipse.jetty.server.handler.DefaultHandler in project metrics by dropwizard.

the class InstrumentedHandlerTest method setUp.

@Before
public void setUp() throws Exception {
    handler.setName("handler");
    handler.setHandler(new DefaultHandler());
    server.addConnector(connector);
    server.setHandler(handler);
    server.start();
    client.start();
}
Also used : DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) Before(org.junit.Before)

Example 24 with DefaultHandler

use of org.eclipse.jetty.server.handler.DefaultHandler 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 25 with DefaultHandler

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

the class LikeJettyXml method main.

public static void main(String[] args) throws Exception {
    // Path to as-built jetty-distribution directory
    String jettyHomeBuild = "../../jetty-distribution/target/distribution";
    // Find jetty home and base directories
    String homePath = System.getProperty("jetty.home", jettyHomeBuild);
    File start_jar = new File(homePath, "start.jar");
    if (!start_jar.exists()) {
        homePath = jettyHomeBuild = "jetty-distribution/target/distribution";
        start_jar = new File(homePath, "start.jar");
        if (!start_jar.exists())
            throw new FileNotFoundException(start_jar.toString());
    }
    File homeDir = new File(homePath);
    String basePath = System.getProperty("jetty.base", homeDir + "/demo-base");
    File baseDir = new File(basePath);
    if (!baseDir.exists()) {
        throw new FileNotFoundException(baseDir.getAbsolutePath());
    }
    // Configure jetty.home and jetty.base system properties
    String jetty_home = homeDir.getAbsolutePath();
    String jetty_base = baseDir.getAbsolutePath();
    System.setProperty("jetty.home", jetty_home);
    System.setProperty("jetty.base", jetty_base);
    // === jetty.xml ===
    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(500);
    // Server
    Server server = new Server(threadPool);
    // Scheduler
    server.addBean(new ScheduledExecutorScheduler());
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);
    http_config.setRequestHeaderSize(8192);
    http_config.setResponseHeaderSize(8192);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);
    // httpConfig.addCustomizer(new ForwardedRequestCustomizer());
    // Handler Structure
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() });
    server.setHandler(handlers);
    // Extra options
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    // === jetty-jmx.xml ===
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);
    // === jetty-http.xml ===
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(8080);
    http.setIdleTimeout(30000);
    server.addConnector(http);
    // === jetty-https.xml ===
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(jetty_home + "/../../../jetty-server/src/test/config/etc/keystore");
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    sslContextFactory.setTrustStorePath(jetty_home + "/../../../jetty-server/src/test/config/etc/keystore");
    sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
    // SSL HTTP Configuration
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
    sslConnector.setPort(8443);
    server.addConnector(sslConnector);
    // === jetty-deploy.xml ===
    DeploymentManager deployer = new DeploymentManager();
    DebugListener debug = new DebugListener(System.err, true, true, true);
    server.addBean(debug);
    deployer.addLifeCycleBinding(new DebugListenerBinding(debug));
    deployer.setContexts(contexts);
    deployer.setContextAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/servlet-api-[^/]*\\.jar$");
    WebAppProvider webapp_provider = new WebAppProvider();
    webapp_provider.setMonitoredDirName(jetty_base + "/webapps");
    webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml");
    webapp_provider.setScanInterval(1);
    webapp_provider.setExtractWars(true);
    webapp_provider.setConfigurationManager(new PropertiesConfigurationManager());
    deployer.addAppProvider(webapp_provider);
    server.addBean(deployer);
    // === setup jetty plus ==
    Configuration.ClassList.setServerDefault(server).addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
    // === jetty-stats.xml ===
    StatisticsHandler stats = new StatisticsHandler();
    stats.setHandler(server.getHandler());
    server.setHandler(stats);
    ServerConnectionStatistics.addToAllConnectors(server);
    // === Rewrite Handler
    RewriteHandler rewrite = new RewriteHandler();
    rewrite.setHandler(server.getHandler());
    server.setHandler(rewrite);
    // === jetty-requestlog.xml ===
    NCSARequestLog requestLog = new NCSARequestLog();
    requestLog.setFilename(jetty_home + "/logs/yyyy_mm_dd.request.log");
    requestLog.setFilenameDateFormat("yyyy_MM_dd");
    requestLog.setRetainDays(90);
    requestLog.setAppend(true);
    requestLog.setExtended(true);
    requestLog.setLogCookies(false);
    requestLog.setLogTimeZone("GMT");
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setRequestLog(requestLog);
    handlers.addHandler(requestLogHandler);
    // === jetty-lowresources.xml ===
    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(server);
    lowResourcesMonitor.setPeriod(1000);
    lowResourcesMonitor.setLowResourcesIdleTimeout(200);
    lowResourcesMonitor.setMonitorThreads(true);
    lowResourcesMonitor.setMaxConnections(0);
    lowResourcesMonitor.setMaxMemory(0);
    lowResourcesMonitor.setMaxLowResourcesTime(5000);
    server.addBean(lowResourcesMonitor);
    // === test-realm.xml ===
    HashLoginService login = new HashLoginService();
    login.setName("Test Realm");
    login.setConfig(jetty_base + "/etc/realm.properties");
    login.setHotReload(false);
    server.addBean(login);
    // Start the server
    server.start();
    server.join();
}
Also used : Server(org.eclipse.jetty.server.Server) DeploymentManager(org.eclipse.jetty.deploy.DeploymentManager) FileNotFoundException(java.io.FileNotFoundException) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HashLoginService(org.eclipse.jetty.security.HashLoginService) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) DebugListenerBinding(org.eclipse.jetty.deploy.bindings.DebugListenerBinding) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) PropertiesConfigurationManager(org.eclipse.jetty.deploy.PropertiesConfigurationManager) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) RewriteHandler(org.eclipse.jetty.rewrite.handler.RewriteHandler) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) DebugListener(org.eclipse.jetty.server.DebugListener) WebAppProvider(org.eclipse.jetty.deploy.providers.WebAppProvider) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) LowResourceMonitor(org.eclipse.jetty.server.LowResourceMonitor) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) File(java.io.File)

Aggregations

DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)40 Server (org.eclipse.jetty.server.Server)25 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)22 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)18 ServerConnector (org.eclipse.jetty.server.ServerConnector)16 HandlerList (org.eclipse.jetty.server.handler.HandlerList)16 RequestLogHandler (org.eclipse.jetty.server.handler.RequestLogHandler)15 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)11 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)10 Handler (org.eclipse.jetty.server.Handler)9 URI (java.net.URI)7 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)7 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)7 Test (org.junit.Test)7 File (java.io.File)6 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)6 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)6 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)6 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)6 SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)5