Java Code Examples for org.eclipse.jetty.server.Handler

The following are top voted examples for showing how to use org.eclipse.jetty.server.Handler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: vk-java-sdk   File: Application.java   Source Code and License 8 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 2
Project: JavaEE   File: Main.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Create a basic Jetty server object that will listen on port 8080
        Server server = new Server(8080);

        // Create the ResourceHandler. It is the object that will actually
        // handle the request for a given file. It is a Jetty Handler object
        // so it is suitable for chaining with other handlers as you will see
        // in other examples
        ResourceHandler resource_handler = new ResourceHandler();

        // Configure the ResourceHandler. Setting the resource base indicates
        // where the files should be served out of
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
        resource_handler.setResourceBase("src/main/webapp/");

        // Add the ResourceHandler to the server
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
        server.setHandler(handlers);

        // Start server
        server.start();
        server.join();
    }
 
Example 3
Project: fwm   File: ScratchPad.java   Source Code and License 6 votes vote down vote up
public static void startServer(String[] args) throws Exception {
	Server server = new Server(8080);
	
	WebAppContext ctx = new WebAppContext();
	ctx.setContextPath("/");
	ctx.setWar("src/main/webapp/");
	HandlerCollection hc = new HandlerCollection();
	hc.setHandlers(new Handler[] {ctx});
	
	server.setHandler(hc);
	server.setStopAtShutdown(true);
	server.start();
	
	server.join();
	
	// server.removeBean(o);
	// server.addBean(o);
}
 
Example 4
Project: otter-G   File: JettyEmbedServer.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
    Resource configXml = Resource.newSystemResource(config);
    XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
    server = (Server) configuration.configure();

    //        Integer port = getPort();
    //        if (port != null && port > 0) {
    //            Connector[] connectors = server.getConnectors();
    //            for (Connector connector : connectors) {
    //                connector.setPort(port);
    //            }
    //        }
    Handler handler = server.getHandler();
    if (handler != null && handler instanceof WebAppContext) {
        WebAppContext webAppContext = (WebAppContext) handler;
        webAppContext.setResourceBase(JettyEmbedServer.class.getResource("/webapp").toString());
    }
    server.start();
    if (logger.isInfoEnabled()) {
        logger.info("##Jetty Embed Server is startup!");
    }
}
 
Example 5
Project: otter-G   File: JettyEmbedServer.java   Source Code and License 6 votes vote down vote up
public void afterPropertiesSet() throws Exception {
    Resource configXml = Resource.newSystemResource(config);
    XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
    server = (Server) configuration.configure();
    Integer port = getPort();
    if (port != null && port > 0) {
        Connector[] connectors = server.getConnectors();
        for (Connector connector : connectors) {
            connector.setPort(port);
        }
    }

    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", htdocsDir);
    }

    server.start();
    if (logger.isInfoEnabled()) {
        logger.info("##Jetty Embed Server is startup!");
    }
}
 
Example 6
Project: otter-G   File: JettyEmbedIntegration.java   Source Code and License 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    Resource jetty_xml = Resource.newSystemResource("jetty/jetty.xml");
    XmlConfiguration configuration = new XmlConfiguration(jetty_xml.getInputStream());
    Server server = (Server) configuration.configure();
    int port = 8081;
    Connector[] connectors = server.getConnectors();
    for (Connector connector : connectors) {
        connector.setPort(port);
    }

    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", "/tmp/");
    }

    server.start();
    server.join();
}
 
Example 7
Project: Cognizant-Intelligent-Test-Scripter   File: DashBoardServer.java   Source Code and License 6 votes vote down vote up
public void prepare() {
    try {
        Tools.verifyLocalPort("DBServer ", port());
        server = new Server();
        DefaultHandler webHandler = new DefaultHandler();
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]{getResourceHandler(),
            getUIWSHandler(), webHandler});

        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port());
        server.setConnectors(new Connector[]{connector});
        server.setHandler(handlers);

        LOG.log(Level.INFO, "DB Server on : http://{0}:{1}",
                new Object[]{Tools.IP(), port() + ""});

    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
}
 
Example 8
Project: paul0-application-server   File: HomeServerConfig.java   Source Code and License 6 votes vote down vote up
private HandlerList getAllServices() throws Exception{
    // File server & Context Handler for root, also setting the index.html
    // to be the "welcome file", i.e, autolink on root addresses.
    ContextHandler rootContext = new ContextHandler();
    rootContext.setContextPath("/*");
    rootContext.setHandler(getResourceHandlers());

    // Possible servlet lists, for all servlets or custom services you want to access later.
    // Warning, it might become a little bit nested if you add to many classes.
    ServletHandler questionHandler = new ServletHandler();
    questionHandler.addServletWithMapping(QuestionHandler.class, "/question");

    // Add the ResourceHandler to the server.
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {
            rootContext ,
            questionHandler,
    });

    return handlers;
}
 
Example 9
Project: marathon-auth-plugin   File: ServletContextHandler.java   Source Code and License 6 votes vote down vote up
/**
 * @param sessionHandler The sessionHandler to set.
 */
public void setSessionHandler(SessionHandler sessionHandler)
{
    if (isStarted())
        throw new IllegalStateException("STARTED");

    Handler next=null;
    if (_sessionHandler!=null)
    {
        next=_sessionHandler.getHandler();
        _sessionHandler.setHandler(null);
        replaceHandler(_sessionHandler,sessionHandler);
    }

    _sessionHandler = sessionHandler;
    if (next!=null && _sessionHandler.getHandler()==null)
        _sessionHandler.setHandler(next);
    relinkHandlers();
}
 
Example 10
Project: marathon-auth-plugin   File: ServletContextHandler.java   Source Code and License 6 votes vote down vote up
/**
 * @param securityHandler The {@link SecurityHandler} to set on this context.
 */
public void setSecurityHandler(SecurityHandler securityHandler)
{
    if (isStarted())
        throw new IllegalStateException("STARTED");

    Handler next=null;
    if (_securityHandler!=null)
    {
        next=_securityHandler.getHandler();
        _securityHandler.setHandler(null);
        replaceHandler(_securityHandler,securityHandler);
    }
    
    _securityHandler = securityHandler;
    if (next!=null && _securityHandler.getHandler()==null)
        _securityHandler.setHandler(next);
    relinkHandlers();
}
 
Example 11
Project: marathon-auth-plugin   File: ServletContextHandler.java   Source Code and License 6 votes vote down vote up
/**
 * @param gzipHandler The {@link GzipHandler} to set on this context.
 */
public void setGzipHandler(GzipHandler gzipHandler)
{
    if (isStarted())
        throw new IllegalStateException("STARTED");

    Handler next=null;
    if (_gzipHandler!=null)
    {
        next=_gzipHandler.getHandler();
        _gzipHandler.setHandler(null);
        replaceHandler(_gzipHandler,gzipHandler);
    }
    
    _gzipHandler = gzipHandler;
    if (next!=null && _gzipHandler.getHandler()==null)
        _gzipHandler.setHandler(next);
    relinkHandlers();
}
 
Example 12
Project: marathon-auth-plugin   File: ServletContextHandler.java   Source Code and License 6 votes vote down vote up
/**
 * @param servletHandler The servletHandler to set.
 */
public void setServletHandler(ServletHandler servletHandler)
{
    if (isStarted())
        throw new IllegalStateException("STARTED");

    Handler next=null;
    if (_servletHandler!=null)
    {
        next=_servletHandler.getHandler();
        _servletHandler.setHandler(null);
        replaceHandler(_servletHandler,servletHandler);
    }
    _servletHandler = servletHandler;
    if (next!=null && _servletHandler.getHandler()==null)
        _servletHandler.setHandler(next);
    relinkHandlers();
}
 
Example 13
Project: nifi-registry   File: JettyServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    try {
        // start the server
        server.start();

        // ensure everything started successfully
        for (Handler handler : server.getChildHandlers()) {
            // see if the handler is a web app
            if (handler instanceof WebAppContext) {
                WebAppContext context = (WebAppContext) handler;

                // see if this webapp had any exceptions that would
                // cause it to be unavailable
                if (context.getUnavailableException() != null) {
                    startUpFailure(context.getUnavailableException());
                }
            }
        }

        dumpUrls();
    } catch (final Throwable t) {
        startUpFailure(t);
    }
}
 
Example 14
Project: Learning   File: EmbeddedServer.java   Source Code and License 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 15
Project: Learning   File: EmbeddedServer.java   Source Code and License 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 16
Project: jetty-server-request-logger   File: JettyServerCustomizer.java   Source Code and License 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory jettyConfigBean() {

    DynamicPropertyFactory propertyFactory = DynamicPropertyFactory.getInstance();
    String accessLogFilePath = propertyFactory.getStringProperty("server.accessLog.config.file", ACCESS_LOG_FILE_PATH).getValue();

    JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory
            = new JettyEmbeddedServletContainerFactory();
    jettyEmbeddedServletContainerFactory.addServerCustomizers(new org.springframework.boot.context.embedded.jetty.JettyServerCustomizer() {
        public void customize(Server server) {
            HandlerCollection handlers = new HandlerCollection();
            for (Handler handler : server.getHandlers()) {
                handlers.addHandler(handler);
            }
            RequestLogHandler requestLogHandler = new RequestLogHandler();
            RequestLogImpl requestLogImpl = new RequestLogImpl();
            requestLogImpl.setFileName(accessLogFilePath);
            requestLogHandler.setRequestLog(requestLogImpl);
            handlers.addHandler(requestLogHandler);
            server.setHandler(handlers);
            LOGGER.info("Jetty Server Customized. Access Log Configuration File - {}", accessLogFilePath);
        }
    });
    return jettyEmbeddedServletContainerFactory;
}
 
Example 17
Project: leopard   File: WebappDaoImpl.java   Source Code and License 6 votes vote down vote up
protected Handler getHandlerList(List<String> hostList) {
	// jettyServer.getWebappService().addHandler(new HostResourceHandler("fshop.leopard.io", "/data/src/fshop_html/"));
	// jettyServer.getWebappService().addHandler(new HostResourceHandler("ftrade.leopard.io", "/data/src/ftrade_html/"));
	if (hostList.contains("fshop.leopard.io")) {
		if (false) {
			return new HostResourceHandler("fshop.leopard.io", "/data/src/fshop_html/");
		}
		HandlerList handlerList = new HandlerList();
		handlerList.addHandler(new HostResourceHandler("fshop.leopard.io", "/data/src/fshop_html/"));
		handlerList.addHandler(new HostResourceHandler("ftrade.leopard.io", "/data/src/ftrade_html/"));
		try {
			handlerList.start();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return handlerList;
	}
	return null;
}
 
Example 18
Project: Camel   File: JettyHttpComponent.java   Source Code and License 6 votes vote down vote up
protected void addJettyHandlers(Server server, List<Handler> handlers) {
    if (handlers != null && !handlers.isEmpty()) {
        for (Handler handler : handlers) {
            if (handler instanceof HandlerWrapper) {
                // avoid setting the security handler more than once
                if (!handler.equals(server.getHandler())) {
                    ((HandlerWrapper) handler).setHandler(server.getHandler());
                    server.setHandler(handler);
                }
            } else {
                HandlerCollection handlerCollection = new HandlerCollection();
                handlerCollection.addHandler(server.getHandler());
                handlerCollection.addHandler(handler);
                server.setHandler(handlerCollection);
            }
        }
    }
}
 
Example 19
Project: joinfaces   File: JsfJettyServerCustomizer.java   Source Code and License 6 votes vote down vote up
@Override
public void customize(Server server) {
	Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
	final WebAppContext webAppContext = (WebAppContext) childHandlersByClass[0];

	try {
		ClassPathResource classPathResource = new ClassPathResource(this.jettyProperties.getClassPathResource());
		webAppContext.setBaseResource(new ResourceCollection(classPathResource.getURI().toString()));

		AccessController.doPrivileged(new PrivilegedAction<Void>() {
			@Override
			public Void run() {
				webAppContext.setClassLoader(new URLClassLoader(new URL[0], this.getClass().getClassLoader()));
				return null;
			}
		});

		log.info("Setting Jetty classLoader to {} directory", this.jettyProperties.getClassPathResource());
	}
	catch (IOException exception) {
		log.error("Unable to configure Jetty classLoader to {} directory {}", this.jettyProperties.getClassPathResource(), exception.getMessage());

		throw new RuntimeException(exception);
	}
}
 
Example 20
Project: MMServerEngine   File: PlayerRequestJettyEntrance.java   Source Code and License 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 21
Project: Camel   File: JettyHttpComponent.java   Source Code and License 6 votes vote down vote up
protected CamelServlet createServletForConnector(Server server, Connector connector,
                                                 List<Handler> handlers, JettyHttpEndpoint endpoint) throws Exception {
    ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    if (Server.getVersion().startsWith("8")) {
        context.getClass().getMethod("setConnectorNames", new Class[] {String[].class})
            .invoke(context, new Object[] {new String[] {connector.getName()}});
    }

    addJettyHandlers(server, handlers);

    CamelServlet camelServlet = new CamelContinuationServlet();
    ServletHolder holder = new ServletHolder();
    holder.setServlet(camelServlet);
    holder.setAsyncSupported(true);
    holder.setInitParameter(CamelServlet.ASYNC_PARAM, Boolean.toString(endpoint.isAsync()));
    context.addServlet(holder, "/*");

    // use rest enabled resolver in case we use rest
    camelServlet.setServletResolveConsumerStrategy(new HttpRestServletResolveConsumerStrategy());

    return camelServlet;
}
 
Example 22
Project: app-runner-router   File: RouterHandlerList.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    Handler[] handlers = getHandlers();
    if (handlers!=null && isStarted())
    {

        if (target.startsWith("/api/") && !AppsCallAggregator.canHandle(target, request)) {
            boolean isLocalRestRequest = target.startsWith("/api/v1/runners") || target.startsWith("/api/v1/system");
            Handler h = isLocalRestRequest ? restService : reverseProxy;
            h.handle(target, baseRequest, request, response);
            if (baseRequest.isHandled()) {
                return;
            }
        }

        for (Handler handler : handlers) {
            handler.handle(target, baseRequest, request, response);
            if (baseRequest.isHandled()) {
                return;
            }
        }

    }
}
 
Example 23
Project: incubator-pulsar   File: ServerManager.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    server.start();

    log.info("Server started at end point {}", getServiceUri());
}
 
Example 24
Project: incubator-pulsar   File: ProxyServer.java   Source Code and License 6 votes vote down vote up
public void start() throws PulsarServerException {
    log.info("Starting web socket proxy at port {}", conf.getWebServicePort());
    try {
        RequestLogHandler requestLogHandler = new RequestLogHandler();
        Slf4jRequestLog requestLog = new Slf4jRequestLog();
        requestLog.setExtended(true);
        requestLog.setLogTimeZone(TimeZone.getDefault().getID());
        requestLog.setLogLatency(true);
        requestLogHandler.setRequestLog(requestLog);
        handlers.add(0, new ContextHandlerCollection());
        handlers.add(requestLogHandler);

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

        HandlerCollection handlerCollection = new HandlerCollection();
        handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
        server.setHandler(handlerCollection);

        server.start();
    } catch (Exception e) {
        throw new PulsarServerException(e);
    }
}
 
Example 25
Project: incubator-pulsar   File: WebService.java   Source Code and License 6 votes vote down vote up
public void start() throws PulsarServerException {
    try {
        RequestLogHandler requestLogHandler = new RequestLogHandler();
        Slf4jRequestLog requestLog = new Slf4jRequestLog();
        requestLog.setExtended(true);
        requestLog.setLogTimeZone(TimeZone.getDefault().getID());
        requestLog.setLogLatency(true);
        requestLogHandler.setRequestLog(requestLog);
        handlers.add(0, new ContextHandlerCollection());
        handlers.add(requestLogHandler);

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

        HandlerCollection handlerCollection = new HandlerCollection();
        handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
        server.setHandler(handlerCollection);

        server.start();

        log.info("Web Service started at {}", pulsar.getWebServiceAddress());
    } catch (Exception e) {
        throw new PulsarServerException(e);
    }
}
 
Example 26
Project: incubator-pulsar   File: WebServer.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    server.start();

    log.info("Server started at end point {}", getServiceUri());
}
 
Example 27
Project: stepic-java-web-service   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    AccountService accountService = new AccountService();

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new SingUpServlet(accountService)), "/signup");
    context.addServlet(new ServletHolder(new SignInServlet(accountService)), "/signin");

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

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

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

    server.start();
    System.out.println("Server started");
    server.join();
}
 
Example 28
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JettyEmbeddedServletContainerFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void wrappedHandlers() throws Exception {
	JettyEmbeddedServletContainerFactory factory = getFactory();
	factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() {
		@Override
		public void customize(Server server) {
			Handler handler = server.getHandler();
			HandlerWrapper wrapper = new HandlerWrapper();
			wrapper.setHandler(handler);
			HandlerCollection collection = new HandlerCollection();
			collection.addHandler(wrapper);
			server.setHandler(collection);
		}
	}));
	this.container = factory
			.getEmbeddedServletContainer(exampleServletRegistration());
	this.container.start();
	assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World");
}
 
Example 29
Project: hazelcast-jetty-sessionmanager   File: HazelcastSessionIdManager.java   Source Code and License 6 votes vote down vote up
public void invalidateAll(String sessionId) {
    synchronized (sessionsIds) {
        sessionsIds.remove(sessionId);

        //tell all contexts that may have a session object with this id to
        //get rid of them
        Handler[] contexts = server.getChildHandlersByClass(ContextHandler.class);
        for (int i = 0; contexts != null && i < contexts.length; i++) {
            SessionHandler sessionHandler = ((ContextHandler) contexts[i]).getChildHandlerByClass(SessionHandler.class);
            if (sessionHandler != null) {
                SessionManager manager = sessionHandler.getSessionManager();
                if (manager != null && manager instanceof HazelcastSessionManager) {
                    ((HazelcastSessionManager) manager).invalidateSession(sessionId);
                }
            }
        }
    }
}
 
Example 30
Project: hazelcast-jetty-sessionmanager   File: HazelcastSessionIdManager.java   Source Code and License 6 votes vote down vote up
@Override
public void renewSessionId(String oldClusterId, String oldNodeId, HttpServletRequest request) {
    //generate a new id
    String newClusterId = newSessionId(request.hashCode());

    synchronized (sessionsIds) {
        //remove the old one from the list
        sessionsIds.remove(oldClusterId);
        //add in the new session id to the list
        sessionsIds.add(newClusterId);

        //tell all contexts to update the id
        Handler[] contexts = server.getChildHandlersByClass(ContextHandler.class);
        for (int i = 0; contexts != null && i < contexts.length; i++) {
            SessionHandler sessionHandler = ((ContextHandler) contexts[i]).getChildHandlerByClass(SessionHandler.class);
            if (sessionHandler != null) {
                SessionManager manager = sessionHandler.getSessionManager();

                if (manager != null && manager instanceof HazelcastSessionManager) {
                    ((HazelcastSessionManager) manager).
                            renewSessionId(oldClusterId, oldNodeId, newClusterId, getNodeId(newClusterId, request));
                }
            }
        }
    }
}
 
Example 31
Project: hazelcast-jetty-sessionmanager   File: HazelcastSessionIdManager.java   Source Code and License 6 votes vote down vote up
@Override
public void invalidateAll(String sessionId) {
    synchronized (sessionsIds) {
        sessionsIds.remove(sessionId);

        //tell all contexts that may have a session object with this id to
        //get rid of them
        Handler[] contexts = server.getChildHandlersByClass(ContextHandler.class);
        for (int i = 0; contexts != null && i < contexts.length; i++) {
            SessionHandler sessionHandler = ((ContextHandler) contexts[i]).getChildHandlerByClass(SessionHandler.class);
            if (sessionHandler != null) {
                SessionManager manager = sessionHandler.getSessionManager();
                if (manager != null && manager instanceof HazelcastSessionManager) {
                    ((HazelcastSessionManager) manager).invalidateSession(sessionId);
                }
            }
        }
    }
}
 
Example 32
Project: apt-graph   File: FileServer.java   Source Code and License 6 votes vote down vote up
/**
 * Start the file server (blocking).
 *
 * @throws Exception If server cannot start
 */
public final void start() throws Exception {
    LOGGER.info("Starting web interface at http://localhost:8000");

    Server server = new Server(8000);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[]{"index.html"});
    resource_handler.setResourceBase("../website");

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

    server.start();
}
 
Example 33
Project: little_mitm   File: PerformanceServer.java   Source Code and License 6 votes vote down vote up
public void run(int port) throws Exception {
    Server server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] { "index.html" });

    resource_handler.setResourceBase("./performance/site/");

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

    server.start();
    System.out.println("Started performance file server at port: " + port);
    server.join();
}
 
Example 34
Project: Learning   File: EmbeddedServer.java   Source Code and License 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 35
Project: Camel   File: WebsocketComponent.java   Source Code and License 6 votes vote down vote up
protected ServletContextHandler createContext(Server server, Connector connector, List<Handler> handlers) throws Exception {
    ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    server.addConnector(connector);

    if (handlers != null && !handlers.isEmpty()) {
        for (Handler handler : handlers) {
            if (handler instanceof HandlerWrapper) {
                ((HandlerWrapper) handler).setHandler(server.getHandler());
                server.setHandler(handler);
            } else {
                HandlerCollection handlerCollection = new HandlerCollection();
                handlerCollection.addHandler(server.getHandler());
                handlerCollection.addHandler(handler);
                server.setHandler(handlerCollection);
            }
        }
    }

    return context;
}
 
Example 36
Project: spring-boot-concourse   File: JettyEmbeddedServletContainerFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void wrappedHandlers() throws Exception {
	JettyEmbeddedServletContainerFactory factory = getFactory();
	factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() {
		@Override
		public void customize(Server server) {
			Handler handler = server.getHandler();
			HandlerWrapper wrapper = new HandlerWrapper();
			wrapper.setHandler(handler);
			HandlerCollection collection = new HandlerCollection();
			collection.addHandler(wrapper);
			server.setHandler(collection);
		}
	}));
	this.container = factory
			.getEmbeddedServletContainer(exampleServletRegistration());
	this.container.start();
	assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World");
}
 
Example 37
Project: jbake-rtl-jalaali   File: JettyServer.java   Source Code and License 5 votes vote down vote up
/**
 * Run Jetty web server serving out supplied path on supplied port
 * 
 * @param path
 * @param port
 */
public void run(String path, String port) {
	Server server = new Server();
	SelectChannelConnector connector = new SelectChannelConnector();
       connector.setPort(Integer.parseInt(port));
       server.addConnector(connector);

       ResourceHandler resource_handler = new ResourceHandler();
       resource_handler.setDirectoriesListed(true);
       resource_handler.setWelcomeFiles(new String[]{ "index.html" });

       resource_handler.setResourceBase(path);

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

       LOGGER.info("Serving out contents of: [{}] on http://localhost:{}/", path, port);
       LOGGER.info("(To stop server hit CTRL-C)");
       
       try {
		server.start();
		server.join();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 38
Project: jetty-reactive-httpclient   File: Usage.java   Source Code and License 5 votes vote down vote up
public void prepare(Handler handler) throws Exception {
    QueuedThreadPool serverThreads = new QueuedThreadPool();
    serverThreads.setName("server");
    server = new Server(serverThreads);
    connector = new ServerConnector(server);
    server.addConnector(connector);
    server.setHandler(handler);
    server.start();

    QueuedThreadPool clientThreads = new QueuedThreadPool();
    clientThreads.setName("client");
    httpClient = new HttpClient();
    httpClient.setExecutor(clientThreads);
    httpClient.start();
}
 
Example 39
Project: rejoiner   File: GraphQlServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Server server = new Server(HTTP_PORT);
  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setWelcomeFiles(new String[] {"index.html"});
  resourceHandler.setDirectoriesListed(false);
  // resource base is relative to the WORKSPACE file
  resourceHandler.setResourceBase("./examples/resources");
  HandlerList handlerList = new HandlerList();
  handlerList.setHandlers(new Handler[] {resourceHandler, new GraphQlServer()});
  server.setHandler(handlerList);
  server.start();
  server.join();
}
 
Example 40
Project: rejoiner   File: GraphQlServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Server server = new Server(HTTP_PORT);
  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setWelcomeFiles(new String[] {"index.html"});
  resourceHandler.setDirectoriesListed(false);
  // resource base is relative to the WORKSPACE file
  resourceHandler.setResourceBase("./examples/resources");
  HandlerList handlerList = new HandlerList();
  handlerList.setHandlers(new Handler[] {resourceHandler, new GraphQlServer()});
  server.setHandler(handlerList);
  server.start();
  server.join();
}