下面列出了怎么用org.eclipse.jetty.server.handler.ContextHandler的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
@Test
public void testOrderGetConfigWithNoLocalFileButWithRemoteConfig() throws Exception {
setPropertiesOrderEnabled(true);
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
Map<String, String> configurations = new LinkedHashMap<>();
configurations.put(someKey1, someValue1);
configurations.put(someKey2, someValue2);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.copyOf(configurations));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
}
@Test
public void testGetConfigWithLocalFileAndWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
Properties properties = new Properties();
properties.put(someKey, someValue);
createLocalCachePropertyFile(properties);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, anotherValue));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(anotherValue, config.getProperty(someKey, null));
}
private ContextHandler mockConfigServerHandler(final int statusCode, final ApolloConfig result,
final boolean failedAtFirstTime) {
ContextHandler context = new ContextHandler("/configs/*");
context.setHandler(new AbstractHandler() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
if (failedAtFirstTime && counter.incrementAndGet() == 1) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
baseRequest.setHandled(true);
return;
}
response.setContentType("application/json;charset=UTF-8");
response.setStatus(statusCode);
response.getWriter().println(gson.toJson(result));
baseRequest.setHandled(true);
}
});
return context;
}
public static void main(String[] args) throws Exception {
final ApiServer api = new ApiServer(new InetSocketAddress(9998));
PrometheusConfig cfg = createPrometheusConfig(args);
final Optional<File> _cfg = cfg.getConfiguration();
if (_cfg.isPresent())
registry_ = new PipelineBuilder(_cfg.get()).build();
else
registry_ = new PipelineBuilder(Configuration.DEFAULT).build();
api.start();
Runtime.getRuntime().addShutdownHook(new Thread(api::close));
Server server = new Server(cfg.getPort());
ContextHandler context = new ContextHandler();
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setContextPath(cfg.getPath());
context.setHandler(new DisplayMetrics(registry_));
server.setHandler(context);
server.start();
server.join();
}
@Override
public void lifeCycleStarted(LifeCycle bean) {
if (bean instanceof Server) {
Server server = (Server)bean;
Connector[] connectors = server.getConnectors();
if (connectors == null || connectors.length == 0) {
server.dumpStdErr();
throw new IllegalStateException("No Connector");
} else if (!Arrays.stream(connectors).allMatch(Connector::isStarted)) {
server.dumpStdErr();
throw new IllegalStateException("Connector not started");
}
ContextHandler context = server.getChildHandlerByClass(ContextHandler.class);
if (context == null || !context.isAvailable()) {
server.dumpStdErr();
throw new IllegalStateException("No Available Context");
}
}
}
private static void logStartupBanner(Server server) {
Object banner = null;
ContextHandler contextHandler = server.getChildHandlerByClass(ContextHandler.class);
if (contextHandler != null) {
Context context = contextHandler.getServletContext();
if (context != null) {
banner = context.getAttribute("nexus-banner");
}
}
StringBuilder buf = new StringBuilder();
buf.append("\n-------------------------------------------------\n\n");
buf.append("Started ").append(banner instanceof String ? banner : "Nexus Repository Manager");
buf.append("\n\n-------------------------------------------------");
log.info(buf.toString());
}
/**
* Starts the document storage. Afterwards it will be ready to serve
* documents.
*
* @throws Exception
* error starting the web server
*
* @since 0.7.8
*/
public void start() throws Exception {
if (storagePort < 0) {
return;
}
server = new Server(storagePort);
ContextHandler rootContext = new ContextHandler();
rootContext.setHandler(internalGrammarHandler);
ContextHandler internalGrammarContext = new ContextHandler(
InternalGrammarDocumentHandler.CONTEXT_PATH);
internalGrammarContext.setHandler(internalGrammarHandler);
ContextHandler builtinGrammarContext = new ContextHandler(
BuiltinGrammarHandler.CONTEXT_PATH);
ContextHandlerCollection contexts = new ContextHandlerCollection();
builtinGrammarContext.setHandler(builtinGrammarHandler);
ContextHandler[] handlers = new ContextHandler[] { rootContext,
internalGrammarContext, builtinGrammarContext };
contexts.setHandlers(handlers);
server.setHandler(contexts);
server.start();
LOGGER.info("document storage started on port " + storagePort);
}
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();
}
public static Server startServer(ContextHandler context, String summary) {
// FIXME port hardcoded
int port = Networking.nextAvailablePort(8080);
// use a nice name in the thread pool (otherwise this is exactly the same as Server defaults)
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setName("camp-jetty-server-"+port+"-"+threadPool.getName());
Server server = new Server(threadPool);
ServerConnector httpConnector = new ServerConnector(server);
httpConnector.setPort(port);
server.addConnector(httpConnector);
server.setHandler(context);
try {
server.start();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
log.info("CAMP REST server started ("+summary+") on");
log.info(" http://localhost:"+httpConnector.getLocalPort()+"/");
return server;
}
private static Server startServer(ManagementContext mgmt, ContextHandler context, String summary, boolean disableHighAvailability) {
// TODO this repeats code in BrooklynLauncher / WebServer. should merge the two paths.
boolean secure = mgmt != null && !BrooklynWebConfig.hasNoSecurityOptions(mgmt.getConfig());
if (secure) {
log.debug("Detected security configured, launching server on all network interfaces");
} else {
log.debug("Detected no security configured, launching server on loopback (localhost) network interface only");
if (mgmt!=null) {
log.debug("Detected no security configured, running on loopback; disabling authentication");
((BrooklynProperties)mgmt.getConfig()).put(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME, AnyoneSecurityProvider.class.getName());
}
}
if (mgmt != null && disableHighAvailability) {
mgmt.getHighAvailabilityManager().disabled(false);
}
InetSocketAddress bindLocation = new InetSocketAddress(
secure ? Networking.ANY_NIC : Networking.LOOPBACK,
Networking.nextAvailablePort(FAVOURITE_PORT));
return startServer(mgmt, context, summary, bindLocation);
}
private static Server startServer(ManagementContext mgmt, ContextHandler context, String summary, InetSocketAddress bindLocation) {
Server server = new Server(bindLocation);
initAuth(mgmt, server);
server.setHandler(context);
try {
server.start();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
log.info("Brooklyn REST server started ("+summary+") on");
log.info(" http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort()+"/");
return server;
}
@Test
public void testCreateHandlersCoversExpectedContextPaths() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
WebServer webServer = new WebServer(/* port */ 9999, projectFilesystem, FakeClock.doNotCare());
ImmutableList<ContextHandler> handlers = webServer.createHandlers();
Map<String, ContextHandler> contextPathToHandler = new HashMap<>();
for (ContextHandler handler : handlers) {
contextPathToHandler.put(handler.getContextPath(), handler);
}
Function<String, TemplateHandlerDelegate> getDelegate =
contextPath ->
((TemplateHandler) contextPathToHandler.get(contextPath).getHandler()).getDelegate();
assertTrue(getDelegate.apply("/") instanceof IndexHandlerDelegate);
assertTrue(contextPathToHandler.get("/static").getHandler() instanceof StaticResourcesHandler);
assertTrue(getDelegate.apply("/trace") instanceof TraceHandlerDelegate);
assertTrue(getDelegate.apply("/traces") instanceof TracesHandlerDelegate);
assertTrue(contextPathToHandler.get("/tracedata").getHandler() instanceof TraceDataHandler);
}
private ContextHandler systemRestart() {
AbstractHandler system = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
restartContexts();
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>Done</h1>");
}
};
ContextHandler context = new ContextHandler();
context.setContextPath("/vraptor/restart");
context.setResourceBase(".");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setHandler(system);
return context;
}
private static void startGatewayServer() throws Exception {
// use default Max threads
gatewayServer = new Server(defaultPort);
final ServerConnector connector = new ServerConnector(gatewayServer);
gatewayServer.addConnector(connector);
// workaround so we can add our handler later at runtime
HandlerCollection handlers = new HandlerCollection(true);
// add some initial handlers
ContextHandler context = new ContextHandler();
context.setContextPath("/");
handlers.addHandler(context);
gatewayServer.setHandler(handlers);
// Start Server
gatewayServer.start();
}
/**
* Start Mock Websocket server that acts as backend.
* @throws Exception exception on websocket server start
*/
private static void startWebsocketServer() throws Exception {
backendServer = new Server(new QueuedThreadPool(254));
ServerConnector connector = new ServerConnector(backendServer);
backendServer.addConnector(connector);
final WebsocketEchoHandler handler = new WebsocketEchoHandler();
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(handler);
backendServer.setHandler(context);
// Start Server
backendServer.start();
String host = connector.getHost();
if (host == null) {
host = "localhost";
}
int port = connector.getLocalPort();
backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/ws", host, port));
}
private static void startBackend() throws Exception {
backend = new Server();
connector = new ServerConnector(backend);
backend.addConnector(connector);
/* start backend with Echo socket */
final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
new BadSocket());
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(wsHandler);
backend.setHandler(context);
// Start Server
backend.start();
String host = connector.getHost();
if (host == null) {
host = "localhost";
}
int port = connector.getLocalPort();
serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
private static void startProxy() throws Exception {
GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
proxy = new Server();
proxyConnector = new ServerConnector(proxy);
proxy.addConnector(proxyConnector);
/* start Knox with WebsocketAdapter to test */
final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(wsHandler);
proxy.setHandler(context);
// Start Server
proxy.start();
String host = proxyConnector.getHost();
if (host == null) {
host = "localhost";
}
int port = proxyConnector.getLocalPort();
proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
private static void startBackend() throws Exception {
backend = new Server();
connector = new ServerConnector(backend);
backend.addConnector(connector);
/* start backend with Echo socket */
final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
new EchoSocket());
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(wsHandler);
backend.setHandler(context);
// Start Server
backend.start();
String host = connector.getHost();
if (host == null) {
host = "localhost";
}
int port = connector.getLocalPort();
serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
private static void startProxy() throws Exception {
GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
proxy = new Server();
proxyConnector = new ServerConnector(proxy);
proxy.addConnector(proxyConnector);
/* start Knox with WebsocketAdapter to test */
final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(wsHandler);
proxy.setHandler(context);
// Start Server
proxy.start();
String host = proxyConnector.getHost();
if (host == null) {
host = "localhost";
}
int port = proxyConnector.getLocalPort();
proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
private static void startProxy() throws Exception {
GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
proxy = new Server();
proxyConnector = new ServerConnector(proxy);
proxy.addConnector(proxyConnector);
/* start Knox with WebsocketAdapter to test */
final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
new ProxyWebSocketAdapter(new URI(BAD_BACKEND), Executors.newFixedThreadPool(10), gatewayConfig));
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(wsHandler);
proxy.setHandler(context);
// Start Server
proxy.start();
String host = proxyConnector.getHost();
if (host == null) {
host = "localhost";
}
int port = proxyConnector.getLocalPort();
proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
server = new Server();
ServerConnector connector = new ServerConnector(server);
server.addConnector(connector);
Handler handler = new WebsocketEchoHandler();
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(handler);
server.setHandler(context);
server.start();
String host = connector.getHost();
if (host == null) {
host = "localhost";
}
int port = connector.getLocalPort();
serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/",host,port));
}
static void register(String route, AbstractHandler handler) {
ContextHandler context = new ContextHandler();
context.setContextPath(route);
context.setResourceBase(".");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setHandler(handler);
CONTEXTS.add(context);
}
@Test
public void testGetContextHandler() throws Exception {
String urlStr = "http://localhost:" + PORT1 + "/hello/test";
JettyHTTPServerEngine engine =
factory.createJettyHTTPServerEngine(PORT1, "http");
ContextHandler contextHandler = engine.getContextHandler(new URL(urlStr));
// can't find the context handler here
assertNull(contextHandler);
JettyHTTPTestHandler handler1 = new JettyHTTPTestHandler("string1", true);
JettyHTTPTestHandler handler2 = new JettyHTTPTestHandler("string2", true);
engine.addServant(new URL(urlStr), handler1);
// Note: There appears to be an internal issue in Jetty that does not
// unregister the MBean for handler1 during this setHandler operation.
// This scenario may create a warning message in the logs
// (javax.management.InstanceAlreadyExistsException: org.apache.cxf.
// transport.http_jetty:type=jettyhttptesthandler,id=0)
// when running subsequent tests.
contextHandler = engine.getContextHandler(new URL(urlStr));
contextHandler.stop();
contextHandler.setHandler(handler2);
contextHandler.start();
String response = null;
try {
response = getResponse(urlStr);
} catch (Exception ex) {
fail("Can't get the reponse from the server " + ex);
}
assertEquals("the jetty http handler did not take effect", response, "string2");
JettyHTTPServerEngineFactory.destroyForPort(PORT1);
}
@Test
public void shouldAddRootRequestHandler() throws Exception {
jetty9Server.configure();
jetty9Server.startHandlers();
ContextHandler rootRequestHandler = getLoadedHandlers().get(GoServerLoadingIndicationHandler.class);
assertThat(rootRequestHandler.getContextPath(), is("/"));
}
private ContextHandler createDocsWebApp(final String contextPath) {
try {
final ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(false);
// load the docs directory
final File docsDir = Paths.get("docs").toRealPath().toFile();
final Resource docsResource = Resource.newResource(docsDir);
// load the component documentation working directory
final String componentDocsDirPath = props.getProperty(NiFiProperties.COMPONENT_DOCS_DIRECTORY, "work/docs/components");
final File workingDocsDirectory = Paths.get(componentDocsDirPath).toRealPath().getParent().toFile();
final Resource workingDocsResource = Resource.newResource(workingDocsDirectory);
// load the rest documentation
final File webApiDocsDir = new File(webApiContext.getTempDirectory(), "webapp/docs");
if (!webApiDocsDir.exists()) {
final boolean made = webApiDocsDir.mkdirs();
if (!made) {
throw new RuntimeException(webApiDocsDir.getAbsolutePath() + " could not be created");
}
}
final Resource webApiDocsResource = Resource.newResource(webApiDocsDir);
// create resources for both docs locations
final ResourceCollection resources = new ResourceCollection(docsResource, workingDocsResource, webApiDocsResource);
resourceHandler.setBaseResource(resources);
// create the context handler
final ContextHandler handler = new ContextHandler(contextPath);
handler.setHandler(resourceHandler);
logger.info("Loading documents web app with context path set to " + contextPath);
return handler;
} catch (Exception ex) {
throw new IllegalStateException("Resource directory paths are malformed: " + ex.getMessage());
}
}
@Override
public void run() {
try {
Properties jettyShutUpProperties = new Properties();
jettyShutUpProperties.setProperty("org.eclipse.jetty.LEVEL", "WARN");
StdErrLog.setProperties(jettyShutUpProperties);
server = new Server(master.getConfig().getApiServerPort());
// static resources handler
ContextHandler ctxStatic = new ContextHandler("/");
ResourceHandler staticHandler = new ResourceHandler();
staticHandler.setResourceBase(this.getClass().getClassLoader().getResource(WEB_DIR).toExternalForm());
// staticHandler.setResourceBase("src/main/web/web_resources");
staticHandler.setDirectoriesListed(true);
ctxStatic.setHandler(staticHandler);
// api handler
ContextHandler ctxApi = buildServletContextHandler();
ctxApi.setContextPath("/api");
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { ctxStatic, ctxApi });
server.setHandler(contexts);
server.start();
server.join();
} catch (Exception e) {
// TODO alert master api server api crashed
e.printStackTrace();
}
}
private ContextHandler buildApiHandler() {
final ResourceConfig application = new ResourceConfig();
// setup rest endpoint
application.packages("emissary.server.api").register(JacksonFeature.class);
ServletHolder apiHolder = new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer(application));
// apiHolder.setInitOrder(0);
// apiHolder.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "resource");
ServletContextHandler apiHolderContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
apiHolderContext.addServlet(apiHolder, "/*");
return apiHolderContext;
}
private Map<Class<? extends ContextHandler>, ContextHandler> getLoadedHandlers() throws Exception {
Map<Class<? extends ContextHandler>, ContextHandler> handlerTypeToHandler = new HashMap<>();
for (App app : appCaptor.getAllValues()) {
handlerTypeToHandler.put(app.getContextHandler().getClass(), app.getContextHandler());
}
return handlerTypeToHandler;
}
private String serverBaseUri(NetworkConnector connector) {
if (connector == null) {
return null;
}
ContextHandler context = getChildHandlerByClass(ContextHandler.class);
try {
String protocol = connector.getDefaultConnectionFactory().getProtocol();
String scheme = "http";
if (protocol.startsWith("SSL-") || protocol.equals("SSL"))
scheme = "https";
String host = connector.getHost();
if (context != null && context.getVirtualHosts() != null && context.getVirtualHosts().length > 0)
host = context.getVirtualHosts()[0];
if (host == null)
host = InetAddress.getLocalHost().getHostAddress();
String path = context == null ? null : context.getContextPath();
if (path == null) {
path = FORWARD_SLASH;
}
URI uri = new URI(scheme, null, host, connector.getLocalPort(), path, null, null);
return uri.toString();
}
catch(Exception e) {
LOG.error("Uri error", e);
return null;
}
}