Search in sources :

Example 81 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project killbill by killbill.

the class HttpServer method createServletContextHandler.

private ServletContextHandler createServletContextHandler(final String resourceBase, final Iterable<EventListener> eventListeners, final Map<FilterHolder, String> filterHolders) {
    final ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");
    if (resourceBase != null) {
        // Required if you want a webapp directory. See ContextHandler#getResource and http://docs.codehaus.org/display/JETTY/Embedding+Jetty
        final String webapp = this.getClass().getClassLoader().getResource(resourceBase).toExternalForm();
        context.setResourceBase(webapp);
    }
    // Jersey insists on using java.util.logging (JUL)
    final EventListener listener = new JULServletContextListener();
    context.addEventListener(listener);
    for (final EventListener eventListener : eventListeners) {
        context.addEventListener(eventListener);
    }
    for (final FilterHolder filterHolder : filterHolders.keySet()) {
        context.addFilter(filterHolder, filterHolders.get(filterHolder), EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
    }
    // Make sure Guice filter all requests
    final FilterHolder filterHolder = new FilterHolder(GuiceFilter.class);
    context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
    // Backend servlet for Guice - never used
    final ServletHolder sh = new ServletHolder(DefaultServlet.class);
    context.addServlet(sh, "/*");
    return context;
}
Also used : JULServletContextListener(org.killbill.commons.skeleton.listeners.JULServletContextListener) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) EventListener(java.util.EventListener) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 82 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project hbase by apache.

the class HBaseRESTTestingUtility method startServletContainer.

public void startServletContainer(Configuration conf) throws Exception {
    if (server != null) {
        LOG.error("ServletContainer already running");
        return;
    }
    // Inject the conf for the test by being first to make singleton
    RESTServlet.getInstance(conf, UserProvider.instantiate(conf));
    // set up the Jersey servlet container for Jetty
    ResourceConfig app = new ResourceConfig().packages("org.apache.hadoop.hbase.rest").register(Jackson1Feature.class);
    ServletHolder sh = new ServletHolder(new ServletContainer(app));
    // set up Jetty and run the embedded server
    server = new Server(0);
    LOG.info("configured " + ServletContainer.class.getName());
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSendDateHeader(false);
    httpConfig.setSendServerVersion(false);
    ServerConnector serverConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    serverConnector.setPort(testServletPort);
    server.addConnector(serverConnector);
    // set up context
    ServletContextHandler ctxHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    ctxHandler.addServlet(sh, "/*");
    // Load filters specified from configuration.
    String[] filterClasses = conf.getStrings(Constants.FILTER_CLASSES, ArrayUtils.EMPTY_STRING_ARRAY);
    for (String filter : filterClasses) {
        filter = filter.trim();
        ctxHandler.addFilter(filter, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
    LOG.info("Loaded filter classes :" + filterClasses);
    conf.set(RESTServer.REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY, ".*");
    RESTServer.addCSRFFilter(ctxHandler, conf);
    HttpServerUtil.constrainHttpMethods(ctxHandler);
    // start the server
    server.start();
    // get the port
    testServletPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
    LOG.info("started " + server.getClass().getName() + " on port " + testServletPort);
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 83 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project kafka by apache.

the class RestServer method start.

public void start(Herder herder) {
    log.info("Starting REST server");
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(new JacksonJsonProvider());
    resourceConfig.register(RootResource.class);
    resourceConfig.register(new ConnectorsResource(herder));
    resourceConfig.register(new ConnectorPluginsResource(herder));
    resourceConfig.register(ConnectExceptionMapper.class);
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
        FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
        filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler(), requestLogHandler });
    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);
    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new ConnectException("Unable to start REST server", e);
    }
    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}
Also used : Slf4jRequestLog(org.eclipse.jetty.server.Slf4jRequestLog) ConnectorsResource(org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ConnectorPluginsResource(org.apache.kafka.connect.runtime.rest.resources.ConnectorPluginsResource) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) ConnectRestException(org.apache.kafka.connect.runtime.rest.errors.ConnectRestException) IOException(java.io.IOException) ConnectException(org.apache.kafka.connect.errors.ConnectException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ConnectException(org.apache.kafka.connect.errors.ConnectException)

Example 84 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project hadoop by apache.

the class NotificationTestCase method startHttpServer.

private void startHttpServer() throws Exception {
    // Create the webServer
    if (webServer != null) {
        webServer.stop();
        webServer = null;
    }
    webServer = new Server(0);
    ServletContextHandler context = new ServletContextHandler(webServer, contextPath);
    // create servlet handler
    context.addServlet(new ServletHolder(new NotificationServlet()), servletPath);
    // Start webServer
    webServer.start();
    port = ((ServerConnector) webServer.getConnectors()[0]).getLocalPort();
}
Also used : Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 85 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project hadoop by apache.

the class TestWebDelegationToken method testKerberosDelegationTokenAuthenticator.

private void testKerberosDelegationTokenAuthenticator(final boolean doAs) throws Exception {
    final String doAsUser = doAs ? OK_USER : null;
    // setting hadoop security to kerberos
    org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
    conf.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(conf);
    File testDir = new File("target/" + UUID.randomUUID().toString());
    Assert.assertTrue(testDir.mkdirs());
    MiniKdc kdc = new MiniKdc(MiniKdc.createConf(), testDir);
    final Server jetty = createJettyServer();
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/foo");
    jetty.setHandler(context);
    context.addFilter(new FilterHolder(KDTAFilter.class), "/*", EnumSet.of(DispatcherType.REQUEST));
    context.addServlet(new ServletHolder(UserServlet.class), "/bar");
    try {
        kdc.start();
        File keytabFile = new File(testDir, "test.keytab");
        kdc.createPrincipal(keytabFile, "client", "HTTP/localhost");
        KDTAFilter.keytabFile = keytabFile.getAbsolutePath();
        jetty.start();
        final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
        final DelegationTokenAuthenticatedURL aUrl = new DelegationTokenAuthenticatedURL();
        final URL url = new URL(getJettyURL() + "/foo/bar");
        try {
            aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
            Assert.fail();
        } catch (AuthenticationException ex) {
            Assert.assertTrue(ex.getMessage().contains("GSSException"));
        }
        doAsKerberosUser("client", keytabFile.getAbsolutePath(), new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                aUrl.getDelegationToken(url, token, doAs ? doAsUser : "client", doAsUser);
                Assert.assertNotNull(token.getDelegationToken());
                Assert.assertEquals(new Text("token-kind"), token.getDelegationToken().getKind());
                // Make sure the token belongs to the right owner
                ByteArrayInputStream buf = new ByteArrayInputStream(token.getDelegationToken().getIdentifier());
                DataInputStream dis = new DataInputStream(buf);
                DelegationTokenIdentifier id = new DelegationTokenIdentifier(new Text("token-kind"));
                id.readFields(dis);
                dis.close();
                Assert.assertEquals(doAs ? new Text(OK_USER) : new Text("client"), id.getOwner());
                if (doAs) {
                    Assert.assertEquals(new Text("client"), id.getRealUser());
                }
                aUrl.renewDelegationToken(url, token, doAsUser);
                Assert.assertNotNull(token.getDelegationToken());
                aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
                Assert.assertNotNull(token.getDelegationToken());
                try {
                    aUrl.renewDelegationToken(url, token, doAsUser);
                    Assert.fail();
                } catch (Exception ex) {
                    Assert.assertTrue(ex.getMessage().contains("403"));
                }
                aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
                aUrl.cancelDelegationToken(url, token, doAsUser);
                Assert.assertNull(token.getDelegationToken());
                return null;
            }
        });
    } finally {
        jetty.stop();
        kdc.stop();
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Configuration(javax.security.auth.login.Configuration) Server(org.eclipse.jetty.server.Server) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) URL(java.net.URL) MiniKdc(org.apache.hadoop.minikdc.MiniKdc) Text(org.apache.hadoop.io.Text) DataInputStream(java.io.DataInputStream) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File)

Aggregations

ServletHolder (org.eclipse.jetty.servlet.ServletHolder)287 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)158 Server (org.eclipse.jetty.server.Server)111 Test (org.junit.Test)77 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)46 ServerConnector (org.eclipse.jetty.server.ServerConnector)45 HttpServletRequest (javax.servlet.http.HttpServletRequest)38 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)25 HttpClient (org.eclipse.jetty.client.HttpClient)23 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)23 IOException (java.io.IOException)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)22 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)19 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)18 DefaultServlet (org.eclipse.jetty.servlet.DefaultServlet)18 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 BeforeClass (org.junit.BeforeClass)17 File (java.io.File)15 ServletException (javax.servlet.ServletException)15