org.eclipse.jetty.server.Handler Java Examples

The following examples show how to use org.eclipse.jetty.server.Handler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArmeriaServerFactory.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void addDefaultHandlers(Server server, Environment environment, MetricRegistry metrics) {
    final JerseyEnvironment jersey = environment.jersey();
    final Handler applicationHandler = createAppServlet(
            server,
            jersey,
            environment.getObjectMapper(),
            environment.getValidator(),
            environment.getApplicationContext(),
            environment.getJerseyServletContainer(),
            metrics);
    final Handler adminHandler = createAdminServlet(server, environment.getAdminContext(),
                                                    metrics, environment.healthChecks());
    final ContextRoutingHandler routingHandler = new ContextRoutingHandler(
            ImmutableMap.of(applicationContextPath, applicationHandler, adminContextPath, adminHandler));
    final Handler gzipHandler = buildGzipHandler(routingHandler);
    server.setHandler(addStatsHandler(addRequestLog(server, gzipHandler, environment.getName())));
}
 
Example #2
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void invalidateAllSession(HttpSession preferredSession, HttpSession localSession) {
    Server server = ((Session)preferredSession).getSessionHandler().getServer();
    final Handler[] handlers = server.getChildHandlersByClass(SessionHandler.class);
    List<String> invalidatedSessions = new ArrayList<>();
    if (handlers!=null) {
        for (Handler h: handlers) {
            Session session = ((SessionHandler)h).getSession(preferredSession.getId());
            if (session!=null) {
                invalidatedSessions.add(session.getId());
                session.invalidate();
            }
        }
    }
    if(!invalidatedSessions.contains(localSession.getId())){
        localSession.invalidate();
    }
}
 
Example #3
Source File: Main.java    From quark with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates the Handler for use by the Avatica (Jetty) server.
 *
 * @param service The Avatica Service implementation
 * @param handlerFactory Factory used for creating a Handler
 * @return The Handler to use.
 */
Handler getHandler(Service service, HandlerFactory handlerFactory) {
  String serializationName = "PROTOBUF";
  Driver.Serialization serialization;
  try {
    serialization = Driver.Serialization.valueOf(serializationName);
  } catch (Exception e) {
    LOG.error("Unknown message serialization type for " + serializationName);
    throw e;
  }

  Handler handler = handlerFactory.getHandler(service, serialization);
  LOG.info("Instantiated " + handler.getClass() + " for Quark Server");

  return handler;
}
 
Example #4
Source File: Jetty9Server.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    server.addEventListener(mbeans());
    server.addConnector(plainConnector());

    ContextHandlerCollection handlers = new ContextHandlerCollection();
    deploymentManager.setContexts(handlers);

    createWebAppContext();

    JettyCustomErrorPageHandler errorHandler = new JettyCustomErrorPageHandler();
    webAppContext.setErrorHandler(errorHandler);
    webAppContext.setGzipHandler(gzipHandler());
    server.addBean(errorHandler);
    server.addBean(deploymentManager);

    HandlerCollection serverLevelHandlers = new HandlerCollection();
    serverLevelHandlers.setHandlers(new Handler[]{handlers});
    server.setHandler(serverLevelHandlers);

    performCustomConfiguration();
    server.setStopAtShutdown(true);
}
 
Example #5
Source File: WebServerTestCase.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Starts the web server on the default {@link #PORT}.
 * The given resourceBase is used to be the ROOT directory that serves the default context.
 * <p><b>Don't forget to stop the returned HttpServer after the test</b>
 *
 * @param resourceBase the base of resources for the default context
 * @throws Exception if the test fails
 */
protected void startWebServer(final String resourceBase) throws Exception {
    if (server_ != null) {
        throw new IllegalStateException("startWebServer() can not be called twice");
    }
    final Server server = buildServer(PORT);

    final WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setResourceBase(resourceBase);

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(resourceBase);
    final MimeTypes mimeTypes = new MimeTypes();
    mimeTypes.addMimeMapping("js", MimeType.APPLICATION_JAVASCRIPT);
    resourceHandler.setMimeTypes(mimeTypes);

    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resourceHandler, context});
    server.setHandler(handlers);
    server.setHandler(resourceHandler);

    tryStart(PORT, server);
    server_ = server;
}
 
Example #6
Source File: PlayerRequestJettyEntrance.java    From PeonyFramwork with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    sessionService = BeanHelper.getServiceBean(SessionService.class);
    requestService = BeanHelper.getServiceBean(RequestService.class);
    accountSysService = BeanHelper.getServiceBean(AccountSysService.class);

    Handler entranceHandler = new AbstractHandler(){
        @Override
        public void handle(String target, Request baseRequest,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
            fire(request,response,"EntranceJetty");
        }
    };

    server = new Server(this.port);
    server.setHandler(entranceHandler);
    server.start();
}
 
Example #7
Source File: JAXRSClientServerWebSocketSpringWebAppNoAtmosphereTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected static void startServers(String port) throws Exception {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(port));

    WebAppContext webappcontext = new WebAppContext();
    String contextPath = null;
    try {
        contextPath = JAXRSClientServerWebSocketSpringWebAppTest.class
            .getResource("/jaxrs_websocket").toURI().getPath();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    webappcontext.setContextPath("/webapp");

    webappcontext.setWar(contextPath);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
}
 
Example #8
Source File: WebContainerAccessLogAutoConfiguration.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer accessWebServerFactoryCustomizer() {
    return factory -> {
        if (factory instanceof JettyServletWebServerFactory) {
            ((JettyServletWebServerFactory) factory).addServerCustomizers((JettyServerCustomizer) server -> {
                HandlerCollection handlers = new HandlerCollection();
                for (Handler handler : server.getHandlers()) {
                    handlers.addHandler(handler);
                }
                RequestLogHandler reqLogs = new RequestLogHandler();
                Slf4jRequestLog requestLog = new Slf4jRequestLog();
                requestLog.setLoggerName("access-log");
                requestLog.setLogLatency(false);

                reqLogs.setRequestLog(requestLog);
                handlers.addHandler(reqLogs);
                server.setHandler(handlers);
            });
        }
    };
}
 
Example #9
Source File: ResolverTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void startServer() throws Throwable {
    Server server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/resolver");
    webappcontext.setBaseResource(Resource.newClassPathResource("/resolver"));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
    Throwable e = webappcontext.getUnavailableException();
    if (e != null) {
        throw e;
    }
    server.stop();
}
 
Example #10
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public MultiSessionAttributeAdapter resetExpiration() {
    // force all sessions with this ID to be marked used so they are not expired
    // (if _any_ session with this ID is expired, then they all are, even if another
    // with the same ID is in use or has a later expiry)
    Integer maxInativeInterval = MAX_INACTIVE_INTERVAL.getDefaultValue();
    if(this.mgmt != null){
        maxInativeInterval = mgmt.getConfig().getConfig(MAX_INACTIVE_INTERVAL);
    }
    Handler[] hh = getSessionHandlers();
    if (hh!=null) {
        for (Handler h: hh) {
            Session ss = ((SessionHandler)h).getSession(getId());
            if (ss!=null) {
                ss.setMaxInactiveInterval(maxInativeInterval);
            }
        }
    }
    return this;
}
 
Example #11
Source File: JettyServerModule.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
private static Handler getRewriteHandler(Handler wrapped) {
  RewriteHandler rewrites = new RewriteHandler();
  rewrites.setOriginalPathAttribute(ORIGINAL_PATH_ATTRIBUTE_NAME);
  rewrites.setRewriteRequestURI(true);
  rewrites.setRewritePathInfo(true);

  for (Map.Entry<String, String> entry : REGEX_REWRITE_RULES.entrySet()) {
    RewriteRegexRule rule = new RewriteRegexRule();
    rule.setRegex(entry.getKey());
    rule.setReplacement(entry.getValue());
    rewrites.addRule(rule);
  }

  rewrites.setHandler(wrapped);

  return rewrites;
}
 
Example #12
Source File: TlsCertificateAuthorityService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
    Server server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setIncludeProtocols("TLSv1.2");
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(keyPassword);

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(port);

    server.addConnector(sslConnector);
    server.setHandler(handler);

    return server;
}
 
Example #13
Source File: JettyAutoConfiguration.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<JettyServletWebServerFactory> jsfJettyFactoryCustomizer() {
	return factory -> factory.addServerCustomizers(new JettyServerCustomizer() {
		@Override
		@SneakyThrows(IOException.class)
		public void customize(Server server) {
			Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
			final WebAppContext webAppContext = (WebAppContext) childHandlersByClass[0];

			String classPathResourceString = JettyAutoConfiguration.this.jettyProperties.getClassPathResource();

			webAppContext.setBaseResource(new ResourceCollection(
				Resource.newResource(new ClassPathResource(classPathResourceString).getURI()),
				webAppContext.getBaseResource()));

			log.info("Setting Jetty classLoader to {} directory", classPathResourceString);
		}
	});
}
 
Example #14
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void removeAttribute(String name) {
    if (setAllKnownSessions) {
        Handler[] hh = getSessionHandlers();
        if (hh!=null) {
            for (Handler h: hh) {
                Session ss = ((SessionHandler)h).getSession(localSession.getId());
                if (ss!=null) {
                    ss.removeAttribute(name);
                }
            }
            return;
        } else {
            if (!setLocalValuesAlso) {
                // can't do all, but at least to local
                configureWhetherToSetLocalValuesAlso(true);
            }
        }
    }
    preferredSession.removeAttribute(name);
    if (setLocalValuesAlso) {
        localSession.removeAttribute(name);
    }
}
 
Example #15
Source File: WebServer.java    From sparkler with Apache License 2.0 6 votes vote down vote up
public WebServer(int port, String resRoot){
    super(port);
    LOG.info("Port:{}, Resources Root:{}", port, resRoot);
    ResourceHandler rh0 = new ResourceHandler();
    ContextHandler context0 = new ContextHandler();
    context0.setContextPath("/res/*");
    context0.setResourceBase(resRoot);
    context0.setHandler(rh0);

    //ServletHandler context1 = new ServletHandler();
    //this.setHandler(context1);

    ServletContextHandler context1 =  new ServletContextHandler();
    context1.addServlet(TestSlaveServlet.class, "/slavesite/*");

    // Create a ContextHandlerCollection and set the context handlers to it.
    // This will let jetty process urls against the declared contexts in
    // order to match up content.
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { context1, context0});

    this.setHandler(contexts);
}
 
Example #16
Source File: Application.java    From vk-java-sdk with MIT License 6 votes vote down vote up
private static void initServer(Properties properties) throws Exception {
    Integer port = Integer.valueOf(properties.getProperty("server.port"));
    String host = properties.getProperty("server.host");

    Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
    String clientSecret = properties.getProperty("client.secret");

    HandlerCollection handlers = new HandlerCollection();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());

    VkApiClient vk = new VkApiClient(new HttpTransportClient());
    handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();
    server.join();
}
 
Example #17
Source File: SimpleMmiDemo.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The main method.
 * 
 * @param args
 *            Command line arguments. None expected.
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {
    LOGGER.info("Starting 'simple mmi' demo for JVoiceXML...");
    LOGGER.info("(c) 2014 by JVoiceXML group - "
            + "http://jvoicexml.sourceforge.net/");

    // Start the web server
    final Server server = new Server(9092);
    final SimpleMmiDemo demo = new SimpleMmiDemo();
    final Handler handler = new MmiHandler(demo);
    server.setHandler(handler);
    server.start();

    demo.call();

    // Wait for the end of the session
    demo.waitSessionEnd();
    server.stop();
}
 
Example #18
Source File: EmbeddedServer.java    From jaxrs with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	URI baseUri = UriBuilder.fromUri("http://localhost").port(SERVER_PORT)
			.build();
	ResourceConfig config = new ResourceConfig(Calculator.class);
	Server server = JettyHttpContainerFactory.createServer(baseUri, config,
			false);

	ContextHandler contextHandler = new ContextHandler("/rest");
	contextHandler.setHandler(server.getHandler());
	
	ProtectionDomain protectionDomain = EmbeddedServer.class
			.getProtectionDomain();
	URL location = protectionDomain.getCodeSource().getLocation();
	
	ResourceHandler resourceHandler = new ResourceHandler();
	resourceHandler.setWelcomeFiles(new String[] { "index.html" });
	resourceHandler.setResourceBase(location.toExternalForm());
	System.out.println(location.toExternalForm());
	HandlerCollection handlerCollection = new HandlerCollection();
	handlerCollection.setHandlers(new Handler[] { resourceHandler,
			contextHandler, new DefaultHandler() });
	server.setHandler(handlerCollection);
	server.start();
	server.join();
}
 
Example #19
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Jetty context handler that can be used to expose static files.
 *
 * Note that an invocation of this method will not register the handler (and thus make the related functionality
 * available to the end user). Instead, the created handler is returned by this method, and will need to be
 * registered with the embedded Jetty webserver by the caller.
 *
 * @return A Jetty context handler, or null when the static content could not be accessed.
 */
protected Handler createStaticContentHandler()
{
    final File spankDirectory = new File( JiveGlobals.getHomeDirectory() + File.separator + "resources" + File.separator + "spank" );
    if ( spankDirectory.exists() )
    {
        if ( spankDirectory.canRead() )
        {
            final WebAppContext context = new WebAppContext( null, spankDirectory.getPath(), "/" );
            context.setWelcomeFiles( new String[] { "index.html" } );

            return context;
        }
        else
        {
            Log.warn( "Openfire cannot read the directory: " + spankDirectory );
        }
    }
    return null;
}
 
Example #20
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void customWar(String simpleName, byte[] bytes) throws Exception {
	File war = new File(Config.dir_custom(true), simpleName + ".war");
	File dir = new File(Config.dir_servers_applicationServer_work(), simpleName);
	FileUtils.writeByteArrayToFile(war, bytes, false);
	if (Servers.applicationServerIsRunning()) {
		GzipHandler gzipHandler = (GzipHandler) Servers.applicationServer.getHandler();
		HandlerList hanlderList = (HandlerList) gzipHandler.getHandler();
		for (Handler handler : hanlderList.getHandlers()) {
			if (QuickStartWebApp.class.isAssignableFrom(handler.getClass())) {
				QuickStartWebApp app = (QuickStartWebApp) handler;
				if (StringUtils.equals("/" + simpleName, app.getContextPath())) {
					app.stop();
					this.modified(bytes, war, dir);
					app.start();
				}
			}
		}
	}
}
 
Example #21
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void customJar(String simpleName, byte[] bytes) throws Exception {
	File jar = new File(Config.dir_custom_jars(true), simpleName + ".jar");
	FileUtils.writeByteArrayToFile(jar, bytes, false);
	List<String> contexts = new ArrayList<>();
	for (String s : Config.dir_custom().list(new WildcardFileFilter("*.war"))) {
		contexts.add("/" + FilenameUtils.getBaseName(s));
	}
	if (Servers.applicationServerIsRunning()) {
		GzipHandler gzipHandler = (GzipHandler) Servers.applicationServer.getHandler();
		HandlerList hanlderList = (HandlerList) gzipHandler.getHandler();
		for (Handler handler : hanlderList.getHandlers()) {
			if (QuickStartWebApp.class.isAssignableFrom(handler.getClass())) {
				QuickStartWebApp app = (QuickStartWebApp) handler;
				if (contexts.contains(app.getContextPath())) {
					app.stop();
					Thread.sleep(2000);
					app.start();
				}
			}
		}
	}
}
 
Example #22
Source File: OAuthServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {

        server = new org.eclipse.jetty.server.Server(PORT);

        WebAppContext webappcontext = new WebAppContext();
        String contextPath = null;
        try {
            contextPath = getClass().getResource(RESOURCE_PATH).toURI().getPath();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        webappcontext.setContextPath("/");

        webappcontext.setWar(contextPath);

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});

        server.setHandler(handlers);
        try {
            server.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example #23
Source File: HttpMain.java    From graphql-java-http-example with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    //
    // This example uses Jetty as an embedded HTTP server
    Server server = new Server(PORT);
    //
    // In Jetty, handlers are how your get called backed on a request
    HttpMain main_handler = new HttpMain();

    // this allows us to server our index.html and GraphIQL JS code
    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(false);
    resource_handler.setWelcomeFiles(new String[]{"index.html"});
    resource_handler.setResourceBase("./src/main/resources/httpmain");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, main_handler});
    server.setHandler(handlers);

    server.start();

    server.join();
}
 
Example #24
Source File: EmbeddedServer.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Server server = new Server( 8080 );

    WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );

    ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
    webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );

    server.setHandler( handlers );


    server.start();
    server.join();
}
 
Example #25
Source File: RunnerRun.java    From stagen with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final File baseDir) throws IOException, ExecutorException {
    // Generate site:
    clean.run(baseDir);
    gen.run(baseDir);
    
    // Start monitoring service:
    startMonitoring(baseDir);
    
    // Start server:
    try {
        LOG.log(Level.INFO, "Starting HTTP server at port: {0}", cmd.port);
        Server server = new Server(cmd.port);
        
        ResourceHandler rh = new ResourceHandler();
        rh.setDirectoriesListed(true);
        rh.setWelcomeFiles(new String[]{"index.html"});
        rh.setResourceBase(Constants.getOutDir(baseDir).getPath());
        
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]{rh, new DefaultHandler()});
        server.setHandler(handlers);
        
        server.start();
        server.join();
    }
    catch(Exception ex) {
        throw new ExecutorException(ex);
    }
}
 
Example #26
Source File: VRaptorServer.java    From mamute with Apache License 2.0 5 votes vote down vote up
private void reloadContexts(String webappDirLocation, String webXmlLocation) {
	WebAppContext context = loadContext(webappDirLocation, webXmlLocation);
	if ("development".equals(getEnv())) {
		contexts.setHandlers(new Handler[]{context, systemRestart()});
	} else {
		contexts.setHandlers(new Handler[]{context});
	}

}
 
Example #27
Source File: Main.java    From tp_java_2015_02 with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    int port = 8080;
    if (args.length == 1) {
        String portString = args[0];
        port = Integer.valueOf(portString);
    }

    System.out.append("Starting at port: ").append(String.valueOf(port)).append('\n');

    AccountService accountService = new AccountService();

    Servlet signin = new SignInServlet(accountService);
    Servlet signUp = new SignUpServlet(accountService);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(signin), "/api/v1/auth/signin");
    context.addServlet(new ServletHolder(signUp), "/api/v1/auth/signup");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setResourceBase("public_html");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, context});

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();
    server.join();
}
 
Example #28
Source File: TestServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
public void clearHandlers() {
    HandlerCollection hc = (HandlerCollection) jetty.getHandler();
    Handler[] ha = hc.getHandlers();
    if (ha != null) {
        for (Handler h : ha) {
            hc.removeHandler(h);
        }
    }
}
 
Example #29
Source File: MockConsoleFactory.java    From knox with Apache License 2.0 5 votes vote down vote up
public static Handler create() {
  ServletHolder consoleHolder = new ServletHolder( "console", MockServlet.class );
  consoleHolder.setInitParameter( "contentType", "text/html" );
  consoleHolder.setInitParameter( "content", "<html>Console UI goes here.</html>" );

  ServletContextHandler consoleContext = new ServletContextHandler( ServletContextHandler.SESSIONS );
  consoleContext.setContextPath( "/console" );
  consoleContext.setResourceBase( "target/classes" );
  consoleContext.addServlet( consoleHolder, "/*" );

  return consoleContext;
}
 
Example #30
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Jetty context handler that can be used to expose Websocket functionality.
 *
 * Note that an invocation of this method will not register the handler (and thus make the related functionality
 * available to the end user). Instead, the created handler is returned by this method, and will need to be
 * registered with the embedded Jetty webserver by the caller.
 *
 * @return A Jetty context handler (never null).
 */
protected Handler createWebsocketHandler()
{
    final ServletContextHandler context = new ServletContextHandler( null, "/ws", ServletContextHandler.SESSIONS );
    context.setAllowNullPathInfo(true);
    // Add the functionality-providers.
    context.addServlet( new ServletHolder( new OpenfireWebSocketServlet() ), "/*" );

    return context;
}