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

The following examples show how to use org.eclipse.jetty.server.Handler. These examples are extracted from open source projects. 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
@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 2
Source Project: quark   Source File: Main.java    License: 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 3
Source Project: gocd   Source File: Jetty9Server.java    License: 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 4
Source Project: htmlunit   Source File: WebServerTestCase.java    License: 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 5
Source Project: PeonyFramwork   Source File: PlayerRequestJettyEntrance.java    License: 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 6
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 7
Source Project: armeria   Source File: ArmeriaServerFactory.java    License: 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 8
Source Project: jaxrs   Source File: EmbeddedServer.java    License: 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 9
Source Project: o2oa   Source File: NodeAgent.java    License: 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 10
Source Project: o2oa   Source File: NodeAgent.java    License: 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 11
Source Project: graphql-java-http-example   Source File: HttpMain.java    License: 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 12
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 13
Source Project: cxf   Source File: OAuthServer.java    License: 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 14
Source Project: Openfire   Source File: HttpBindManager.java    License: 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 15
/**
 * 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 16
Source Project: vk-java-sdk   Source File: Application.java    License: 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 Project: sparkler   Source File: WebServer.java    License: 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 18
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 19
Source Project: joinfaces   Source File: JettyAutoConfiguration.java    License: 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 20
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 21
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 22
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 23
Source Project: cxf   Source File: ResolverTest.java    License: 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 24
Source Project: attic-aurora   Source File: JettyServerModule.java    License: 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 25
Source Project: rest-utils   Source File: ApplicationServer.java    License: Apache License 2.0 5 votes vote down vote up
static Handler wrapWithGzipHandler(RestConfig config, Handler handler) {
  if (config.getBoolean(RestConfig.ENABLE_GZIP_COMPRESSION_CONFIG)) {
    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("GET", "POST");
    gzip.setHandler(handler);
    return gzip;
  }
  return handler;
}
 
Example 26
public static Handler removeContextFromList(List<Handler> hl, String contextPath) {
    Iterator<Handler> hi = hl.iterator();
    while (hi.hasNext()) {
        Handler h = hi.next();
        if ((h instanceof WebAppContext) && ((WebAppContext)h).getContextPath().equals(contextPath)) {
            hi.remove();
            return h;
        }
    }
    return null;
}
 
Example 27
Source Project: konduit-serving   Source File: TestServer.java    License: Apache License 2.0 5 votes vote down vote up
public TestServer(String protocol, String host, int port) {
    server = new Server(port);

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

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
    server.setHandler(handlers);
}
 
Example 28
Source Project: PeonyFramwork   Source File: RequestJettyPBEntrance.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    public void start() throws Exception {
//        log.info(sessionService);
        Handler entranceHandler = new AbstractHandler(){
            @Override
            public void handle(String target, Request baseRequest,
                               HttpServletRequest request, HttpServletResponse response) throws IOException {
                fire(request,response,"RequestJettyPBEntrance");
            }
        };
        server = new Server(this.port);
        server.setHandler(entranceHandler);
        server.start();
    }
 
Example 29
Source Project: lemminx   Source File: FileServer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates an http server on a random port, serving the <code>dir</code>
 * directory (relative to the current project).
 * 
 * @param dir
 * @throws IOException
 */
public FileServer(String dir) throws IOException {
	server = new Server(0);
	ResourceHandler resourceHandler = new ResourceHandler();
	Path base = ProjectUtils.getProjectDirectory().resolve(dir);
	resourceHandler.setResourceBase(base.toUri().toString());
	resourceHandler.setDirectoriesListed(true);
       HandlerList handlers = new HandlerList();
       handlers.setHandlers(new Handler[] { resourceHandler, new DefaultHandler() });
       server.setHandler(handlers);
}
 
Example 30
Source Project: localization_nifi   Source File: TestServer.java    License: 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);
        }
    }
}