use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.
the class WebSocketServerContainerInitializer method onStartup.
@Override
public void onStartup(Set<Class<?>> c, ServletContext context) throws ServletException {
if (!isEnabledViaContext(context, ENABLE_KEY, true)) {
LOG.info("JSR-356 is disabled by configuration");
return;
}
ContextHandler handler = ContextHandler.getContextHandler(context);
if (handler == null) {
throw new ServletException("Not running on Jetty, JSR-356 support unavailable");
}
if (!(handler instanceof ServletContextHandler)) {
throw new ServletException("Not running in Jetty ServletContextHandler, JSR-356 support unavailable");
}
ServletContextHandler jettyContext = (ServletContextHandler) handler;
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(context.getClassLoader());
// Create the Jetty ServerContainer implementation
ServerContainer jettyContainer = configureContext(jettyContext);
// make sure context is cleaned up when the context stops
context.addListener(new ContextDestroyListener());
if (c.isEmpty()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No JSR-356 annotations or interfaces discovered");
}
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Found {} classes", c.size());
}
// Now process the incoming classes
Set<Class<? extends Endpoint>> discoveredExtendedEndpoints = new HashSet<>();
Set<Class<?>> discoveredAnnotatedEndpoints = new HashSet<>();
Set<Class<? extends ServerApplicationConfig>> serverAppConfigs = new HashSet<>();
filterClasses(c, discoveredExtendedEndpoints, discoveredAnnotatedEndpoints, serverAppConfigs);
if (LOG.isDebugEnabled()) {
LOG.debug("Discovered {} extends Endpoint classes", discoveredExtendedEndpoints.size());
LOG.debug("Discovered {} @ServerEndpoint classes", discoveredAnnotatedEndpoints.size());
LOG.debug("Discovered {} ServerApplicationConfig classes", serverAppConfigs.size());
}
// Process the server app configs to determine endpoint filtering
boolean wasFiltered = false;
Set<ServerEndpointConfig> deployableExtendedEndpointConfigs = new HashSet<>();
Set<Class<?>> deployableAnnotatedEndpoints = new HashSet<>();
for (Class<? extends ServerApplicationConfig> clazz : serverAppConfigs) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found ServerApplicationConfig: {}", clazz);
}
try {
ServerApplicationConfig config = clazz.newInstance();
Set<ServerEndpointConfig> seconfigs = config.getEndpointConfigs(discoveredExtendedEndpoints);
if (seconfigs != null) {
wasFiltered = true;
deployableExtendedEndpointConfigs.addAll(seconfigs);
}
Set<Class<?>> annotatedClasses = config.getAnnotatedEndpointClasses(discoveredAnnotatedEndpoints);
if (annotatedClasses != null) {
wasFiltered = true;
deployableAnnotatedEndpoints.addAll(annotatedClasses);
}
} catch (InstantiationException | IllegalAccessException e) {
throw new ServletException("Unable to instantiate: " + clazz.getName(), e);
}
}
// Default behavior if nothing filtered
if (!wasFiltered) {
deployableAnnotatedEndpoints.addAll(discoveredAnnotatedEndpoints);
// Note: it is impossible to determine path of "extends Endpoint" discovered classes
deployableExtendedEndpointConfigs = new HashSet<>();
}
if (LOG.isDebugEnabled()) {
LOG.debug("Deploying {} ServerEndpointConfig(s)", deployableExtendedEndpointConfigs.size());
}
// Deploy what should be deployed.
for (ServerEndpointConfig config : deployableExtendedEndpointConfigs) {
try {
jettyContainer.addEndpoint(config);
} catch (DeploymentException e) {
throw new ServletException(e);
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Deploying {} @ServerEndpoint(s)", deployableAnnotatedEndpoints.size());
}
for (Class<?> annotatedClass : deployableAnnotatedEndpoints) {
try {
jettyContainer.addEndpoint(annotatedClass);
} catch (DeploymentException e) {
throw new ServletException(e);
}
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.
the class MessageReceivingTest method startServer.
@BeforeClass
public static void startServer() throws Exception {
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.addConnector(connector);
handler = new EchoHandler();
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setHandler(handler);
server.setHandler(context);
// Start Server
server.start();
String host = connector.getHost();
if (host == null) {
host = "localhost";
}
int port = connector.getLocalPort();
serverUri = new URI(String.format("ws://%s:%d/", host, port));
}
use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.
the class TestServer method main.
public static void main(String[] args) throws Exception {
((StdErrLog) Log.getLog()).setSource(false);
String jetty_root = "../../..";
// Setup Threadpool
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(100);
// Setup server
Server server = new Server(threadPool);
server.manage(threadPool);
// Setup JMX
MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
server.addBean(Log.getLog());
// Common HTTP configuration
HttpConfiguration config = new HttpConfiguration();
config.setSecurePort(8443);
config.addCustomizer(new ForwardedRequestCustomizer());
config.addCustomizer(new SecureRequestCustomizer());
config.setSendDateHeader(true);
config.setSendServerVersion(true);
// Http Connector
HttpConnectionFactory http = new HttpConnectionFactory(config);
ServerConnector httpConnector = new ServerConnector(server, http);
httpConnector.setPort(8080);
httpConnector.setIdleTimeout(30000);
server.addConnector(httpConnector);
// Handlers
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
// Add restart handler to test the ability to save sessions and restart
RestartHandler restart = new RestartHandler();
restart.setHandler(handlers);
server.setHandler(restart);
// Setup context
HashLoginService login = new HashLoginService();
login.setName("Test Realm");
login.setConfig(jetty_root + "/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/etc/realm.properties");
server.addBean(login);
File log = File.createTempFile("jetty-yyyy_mm_dd", "log");
NCSARequestLog requestLog = new NCSARequestLog(log.toString());
requestLog.setExtended(false);
requestLogHandler.setRequestLog(requestLog);
server.setStopAtShutdown(true);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/test");
webapp.setParentLoaderPriority(true);
webapp.setResourceBase("./src/main/webapp");
webapp.setAttribute("testAttribute", "testValue");
File sessiondir = File.createTempFile("sessions", null);
if (sessiondir.exists())
sessiondir.delete();
sessiondir.mkdir();
sessiondir.deleteOnExit();
DefaultSessionCache ss = new DefaultSessionCache(webapp.getSessionHandler());
FileSessionDataStore sds = new FileSessionDataStore();
ss.setSessionDataStore(sds);
sds.setStoreDir(sessiondir);
webapp.getSessionHandler().setSessionCache(ss);
contexts.addHandler(webapp);
ContextHandler srcroot = new ContextHandler();
srcroot.setResourceBase(".");
srcroot.setHandler(new ResourceHandler());
srcroot.setContextPath("/src");
contexts.addHandler(srcroot);
server.start();
server.join();
}
use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.
the class AliasedConstraintTest method startServer.
@BeforeClass
public static void startServer() throws Exception {
server = new Server();
connector = new LocalConnector(server);
server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler();
SessionHandler session = new SessionHandler();
TestLoginService loginService = new TestLoginService(TEST_REALM);
loginService.putUser("user0", new Password("password"), new String[] {});
loginService.putUser("user", new Password("password"), new String[] { "user" });
loginService.putUser("user2", new Password("password"), new String[] { "user" });
loginService.putUser("admin", new Password("password"), new String[] { "user", "administrator" });
loginService.putUser("user3", new Password("password"), new String[] { "foo" });
context.setContextPath("/ctx");
context.setResourceBase(MavenTestingUtils.getTestResourceDir("docroot").getAbsolutePath());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
server.setHandler(handlers);
context.setHandler(session);
// context.addAliasCheck(new AllowSymLinkAliasChecker());
server.addBean(loginService);
security = new ConstraintSecurityHandler();
session.setHandler(security);
ResourceHandler handler = new ResourceHandler();
security.setHandler(handler);
List<ConstraintMapping> constraints = new ArrayList<>();
Constraint constraint0 = new Constraint();
constraint0.setAuthenticate(true);
constraint0.setName("forbid");
ConstraintMapping mapping0 = new ConstraintMapping();
mapping0.setPathSpec("/forbid/*");
mapping0.setConstraint(constraint0);
constraints.add(mapping0);
Set<String> knownRoles = new HashSet<>();
knownRoles.add("user");
knownRoles.add("administrator");
security.setConstraintMappings(constraints, knownRoles);
server.start();
}
use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.
the class Server method getURI.
/* ------------------------------------------------------------ */
/**
* @return The URI of the first {@link NetworkConnector} and first {@link ContextHandler}, or null
*/
public URI getURI() {
NetworkConnector connector = null;
for (Connector c : _connectors) {
if (c instanceof NetworkConnector) {
connector = (NetworkConnector) c;
break;
}
}
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 = "/";
return new URI(scheme, null, host, connector.getLocalPort(), path, null, null);
} catch (Exception e) {
LOG.warn(e);
return null;
}
}
Aggregations