下面列出了怎么用org.eclipse.jetty.server.Handler的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
});
}
};
}
/**
* 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;
}
@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);
}
/**
* 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;
}
@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();
}
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;
}
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())));
}
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();
}
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();
}
}
}
}
}
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();
}
}
}
}
}
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();
}
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();
}
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();
}
}
/**
* 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;
}
/**
* 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();
}
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();
}
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);
}
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);
}
}
@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);
}
});
}
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;
}
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();
}
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();
}
}
@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();
}
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;
}
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;
}
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;
}
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);
}
@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();
}
/**
* 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);
}
public void clearHandlers() {
HandlerCollection hc = (HandlerCollection) jetty.getHandler();
Handler[] ha = hc.getHandlers();
if (ha != null) {
for (Handler h : ha) {
hc.removeHandler(h);
}
}
}