Java Code Examples for org.eclipse.jetty.server.Server#setHandler()

The following examples show how to use org.eclipse.jetty.server.Server#setHandler() . 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: WebIntegrationIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before
public void startJetty() throws Exception {
	Tracee.getBackend().clear();

	server = new Server(new InetSocketAddress("127.0.0.1", 0));
	ServletContextHandler context = new ServletContextHandler(null, "/", ServletContextHandler.NO_SECURITY);
	final DispatcherServlet dispatcherServlet = new DispatcherServlet();
	dispatcherServlet.setContextClass(AnnotationConfigWebApplicationContext.class);
	dispatcherServlet.setContextInitializerClasses(TraceeInterceptorSpringApplicationInitializer.class.getCanonicalName());
	dispatcherServlet.setContextConfigLocation(TraceeInterceptorSpringConfig.class.getName());
	context.addServlet(new ServletHolder(dispatcherServlet), "/");
	server.setHandler(context);
	server.start();
	ENDPOINT_URL = "http://" + server.getConnectors()[0].getName() + "/";

}
 
Example 2
Source File: EngineWebServer.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public EngineWebServer(final int port)
{
    // Configure Jetty to use java.util.logging, and don't announce that it's doing that
    System.setProperty("org.eclipse.jetty.util.log.announce", "false");
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");

    server = new Server(port);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(MainServlet.class, "/main/*");
    context.addServlet(DisconnectedServlet.class, "/disconnected/*");
    context.addServlet(GroupsServlet.class, "/groups/*");
    context.addServlet(GroupServlet.class, "/group/*");
    context.addServlet(ChannelServlet.class, "/channel/*");
    context.addServlet(RestartServlet.class, "/restart/*");
    context.addServlet(StopServlet.class, "/stop/*");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(EngineWebServer.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);
}
 
Example 3
Source File: ServerStarter.java    From jetty-web-sockets-jsr356 with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    Server server = new Server(8080);

    // Create the 'root' Spring application context
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new ContextLoaderListener());
    context.setInitParameter("contextClass",AnnotationConfigWebApplicationContext.class.getName());
    context.setInitParameter("contextConfigLocation",AppConfig.class.getName());

    // Create default servlet (servlet api required)
    // The name of DefaultServlet should be set to 'defualt'.
    final ServletHolder defaultHolder = new ServletHolder( "default", DefaultServlet.class );
    defaultHolder.setInitParameter( "resourceBase", System.getProperty("user.dir") );
    context.addServlet( defaultHolder, "/" );

    server.setHandler(context);
    WebSocketServerContainerInitializer.configureContext(context);

    server.start();
    server.join();	
}
 
Example 4
Source File: ApiIT.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    // Check if executed inside target directory or module directory
    String pathPrefix =new File(".").getCanonicalFile().getName().equals("target") ? "../" : "./";

    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(18080);
    connector.setHost("localhost");
    server.setConnectors(new Connector[]{connector});

    WebAppContext context = new WebAppContext();
    context.setDescriptor(pathPrefix + "src/main/webapp/WEB-INF/web.xml");
    context.setResourceBase(pathPrefix + "src/main/webapp");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);

    server.setHandler(context);

    server.start();

    client = ClientBuilder.newClient();
    root = client.target("http://" + connector.getHost() + ':' + connector.getPort() + '/');
}
 
Example 5
Source File: ThriftOverHttpClientTServletIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Server startHttp1() throws Exception {
    final Server server = new Server(0);

    final ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH);
    handler.addServletWithMapping(newServletHolder(rootServlet), "/");
    handler.addFilterWithMapping(new FilterHolder(new ConnectionCloseFilter()), "/*",
                                 EnumSet.of(DispatcherType.REQUEST));

    server.setHandler(handler);

    for (Connector c : server.getConnectors()) {
        for (ConnectionFactory f : c.getConnectionFactories()) {
            for (String p : f.getProtocols()) {
                if (p.startsWith("h2c")) {
                    fail("Attempted to create a Jetty server without HTTP/2 support, but failed: " +
                         f.getProtocols());
                }
            }
        }
    }

    server.start();
    return server;
}
 
Example 6
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());

    ServerConnector connector = new ServerConnector(server);

    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example 7
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static Server initServer() {
	Profiles.setProfileAsSystemProperty(Profiles.DEVELOPMENT);
	WebAppContext webAppContext = new WebAppContext();
	Server server = new Server(PORT);
	server.setHandler(webAppContext);
	return server;
}
 
Example 8
Source File: AuthTestMockServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public AuthTestMockServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(AuthTestMockEndpoint.class, "/*");
}
 
Example 9
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static TestServer createAndStartServer(AnnotationConfigWebApplicationContext applicationContext) {
    int port = NEXT_PORT.incrementAndGet();
    Server server = new Server(port);

    try {
        server.setHandler(getServletContextHandler(applicationContext));
        server.start();
    } catch (Exception e) {
        LOGGER.error("Error starting server", e);
    }

    return new TestServer(server, applicationContext, port);
}
 
Example 10
Source File: InfluxDBWarp10Plugin.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  Server server = new Server(new QueuedThreadPool(maxThreads, 8, idleTimeout, queue));
  ServerConnector connector = new ServerConnector(server, acceptors, selectors);
  connector.setIdleTimeout(idleTimeout);
  connector.setPort(port);
  connector.setHost(host);
  connector.setName("Continuum Ingress");
  
  server.setConnectors(new Connector[] { connector });

  HandlerList handlers = new HandlerList();
  
  Handler cors = new CORSHandler();
  handlers.addHandler(cors);

  handlers.addHandler(new InfluxDBHandler(url, token));
  
  server.setHandler(handlers);
  
  JettyUtil.setSendServerVersion(server, false);

  try {
    server.start();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 11
Source File: ReporterFactoryTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
    server = new Server();

    Path keyStorePath = Paths.get(ReporterFactoryTest.class.getResource("/keystore").toURI());
    final SslContextFactory sslContextFactory = new SslContextFactory(keyStorePath.toAbsolutePath().toString());
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.getSslContext();

    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setSecureScheme("https");
    httpConfiguration.setSecurePort(0);

    final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
    final ServerConnector httpsConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(httpsConfiguration));
    httpsConnector.setPort(0);
    server.addConnector(httpsConnector);
    server.setHandler(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
            baseRequest.setHandled(true);
            requestHandled.set(true);
        }
    });
    server.start();
    configuration = SpyConfiguration.createSpyConfig();
    reporterConfiguration = configuration.getConfig(ReporterConfiguration.class);
    when(reporterConfiguration.getServerUrls()).thenReturn(Collections.singletonList(new URL("https://localhost:" + getPort())));
}
 
Example 12
Source File: ProxyIsAHttpProxyTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeClass
protected void setup() throws Exception {
    internalSetup();

    backingServer1 = new Server(0);
    backingServer1.setHandler(newHandler("server1"));
    backingServer1.start();

    backingServer2 = new Server(0);
    backingServer2.setHandler(newHandler("server2"));
    backingServer2.start();
}
 
Example 13
Source File: BaseIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
/**
 * init and start a jetty server, remember to call server.stop when the task is finished
 */
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
  server = new Server(PORT);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(handlers);

  server.setHandler(contexts);
  server.start();

  return server;
}
 
Example 14
Source File: JettyServerFactory.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Creates a server which delegates the request handling to a web
 * application.
 * 
 * @return a server
 */
public static Server createWebAppServer() {
    // Adds an handler to a server and returns it.
    Server server = createBaseServer();
    String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
    Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
    server.setHandler(webAppHandler);

    return server;
}
 
Example 15
Source File: WebSocketServer.java    From marauroa with GNU General Public License v2.0 5 votes vote down vote up
/**
	 * starts the web server
	 *
	 * @throws Exception in case of an unexpected exception
	 */
	public static void startWebSocketServer() throws Exception {
		Configuration conf = Configuration.getConfiguration();
		if (!conf.has("http_port")) {
			return;
		}

		Server server = new Server();

		String host = conf.get("http_host", "localhost");
		int port = -1;
		if (conf.has("http_port")) {
			port = conf.getInt("http_port", 8080);
			ServerConnector connector = new ServerConnector(server);
			connector.setHost(host);
			connector.setPort(port);
// TODO			connector.setForwarded(Boolean.parseBoolean(conf.get("http_forwarded", "false")));
			server.addConnector(connector);
		}

		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		server.setHandler(context);

		ServletHolder holderEvents = new ServletHolder("ws", MarauroaWebSocketServlet.class);
		context.addServlet(holderEvents, "/ws/*");
		
		context.addServlet(new ServletHolder(new WebServletForStaticContent(marauroad.getMarauroa().getRPServerManager())), "/*");

		server.start();
	}
 
Example 16
Source File: WebappBoot.java    From awacs with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");
    handler.setInitParameter("contextConfigLocation", "classpath*:spring-mvc.xml");
    ServletHolder servletHolder = new ServletHolder();
    servletHolder.setInitOrder(1);
    servletHolder.setHeldClass(DispatcherServlet.class);
    servletHolder.setInitParameter("contextConfigLocation", "classpath*:spring-mvc.xml");
    handler.addServlet(servletHolder, "/");
    server.setHandler(handler);
    server.start();
    server.join();
}
 
Example 17
Source File: JettyFactory.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static Server initServer() {
	Profiles.setProfileAsSystemProperty(Profiles.DEVELOPMENT);
	WebAppContext webAppContext = new WebAppContext();
	Server server = new Server(PORT);
	server.setHandler(webAppContext);
	return server;
}
 
Example 18
Source File: Main.java    From homework_tester with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int port = 8080;

    logger.info("Starting at http://127.0.0.1:" + port);

    AccountServer accountServer = new AccountServerImpl();

    createMBean(accountServer);

    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new AdminPageServlet(accountServer)), AdminPageServlet.PAGE_URL);

    ResourceHandler resource_handler = new ResourceHandler();

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

    server.start();
    logger.info("Server started");

    server.join();
}
 
Example 19
Source File: ZMSClientTimeoutTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {

            // Create a simple embedded jetty server on a given port

            server = new Server(port);

            // Define a raw servlet that does nothing but sleep for a configured
            // number of seconds so we get a read timeout from the client

            ServletHandler handler = new ServletHandler();
            server.setHandler(handler);
            handler.addServletWithMapping(SimpleServlet.class, "/*");

            // start our jetty server

            server.start();
        }
 
Example 20
Source File: ITRestClientTest.java    From kylin with Apache License 2.0 3 votes vote down vote up
protected static void startJetty() throws Exception {

        server = new Server(PORT);

        WebAppContext context = new WebAppContext();
        context.setDescriptor("../server/src/main/webapp/WEB-INF/web.xml");
        context.setResourceBase("../server/src/main/webapp");
        context.setContextPath("/kylin");
        context.setParentLoaderPriority(true);

        server.setHandler(context);

        server.start();

    }