use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.
the class DataRateLimitedServletTest method init.
@Before
public void init() throws Exception {
server = new Server();
connector = new LocalConnector(server);
connector.getConnectionFactory(HttpConfiguration.ConnectionFactory.class).getHttpConfiguration().setSendServerVersion(false);
context = new ServletContextHandler();
context.setContextPath("/context");
context.setWelcomeFiles(new String[] { "index.html", "index.jsp", "index.htm" });
File baseResourceDir = testdir.getEmptyPathDir().toFile();
// Use resolved real path for Windows and OSX
Path baseResourcePath = baseResourceDir.toPath().toRealPath();
context.setBaseResource(Resource.newResource(baseResourcePath.toFile()));
ServletHolder holder = context.addServlet(DataRateLimitedServlet.class, "/stream/*");
holder.setInitParameter("buffersize", "" + BUFFER);
holder.setInitParameter("pause", "" + PAUSE);
server.setHandler(context);
server.addConnector(connector);
server.start();
}
use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.
the class JsrBrowserDebugTool method setupServer.
private void setupServer(int port) throws DeploymentException, ServletException, URISyntaxException, MalformedURLException, IOException {
server = new Server();
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSendServerVersion(true);
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConf));
connector.setPort(port);
server.addConnector(connector);
String resourcePath = "/jsr-browser-debug-tool/index.html";
URL urlStatics = JsrBrowserDebugTool.class.getResource(resourcePath);
Objects.requireNonNull(urlStatics, "Unable to find " + resourcePath + " in classpath");
String urlBase = urlStatics.toURI().toASCIIString().replaceFirst("/[^/]*$", "/");
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setBaseResource(Resource.newResource(urlBase));
ServletHolder holder = context.addServlet(DefaultServlet.class, "/");
holder.setInitParameter("dirAllowed", "true");
server.setHandler(context);
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
container.addEndpoint(JsrBrowserSocket.class);
LOG.info("{} setup on port {}", this.getClass().getName(), port);
}
use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.
the class AbstractTest method startServer.
protected void startServer(HttpServlet servlet) throws Exception {
context = new ServletContextHandler();
context.setContextPath("/");
ServletHolder holder = new ServletHolder(servlet);
holder.setAsyncSupported(true);
context.addServlet(holder, servletPath);
startServer(context);
}
use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.
the class Runner method configure.
/**
* Configure a jetty instance and deploy the webapps presented as args
*
* @param args the command line arguments
* @throws Exception if unable to configure
*/
public void configure(String[] args) throws Exception {
// handle classpath bits first so we can initialize the log mechanism.
for (int i = 0; i < args.length; i++) {
if ("--lib".equals(args[i])) {
try (Resource lib = Resource.newResource(args[++i])) {
if (!lib.exists() || !lib.isDirectory())
usage("No such lib directory " + lib);
_classpath.addJars(lib);
}
} else if ("--jar".equals(args[i])) {
try (Resource jar = Resource.newResource(args[++i])) {
if (!jar.exists() || jar.isDirectory())
usage("No such jar " + jar);
_classpath.addPath(jar);
}
} else if ("--classes".equals(args[i])) {
try (Resource classes = Resource.newResource(args[++i])) {
if (!classes.exists() || !classes.isDirectory())
usage("No such classes directory " + classes);
_classpath.addPath(classes);
}
} else if (args[i].startsWith("--"))
i++;
}
initClassLoader();
LOG.info("Runner");
LOG.debug("Runner classpath {}", _classpath);
String contextPath = __defaultContextPath;
boolean contextPathSet = false;
int port = __defaultPort;
String host = null;
int stopPort = 0;
String stopKey = null;
boolean runnerServerInitialized = false;
for (int i = 0; i < args.length; i++) {
switch(args[i]) {
case "--port":
port = Integer.parseInt(args[++i]);
break;
case "--host":
host = args[++i];
break;
case "--stop-port":
stopPort = Integer.parseInt(args[++i]);
break;
case "--stop-key":
stopKey = args[++i];
break;
case "--log":
_logFile = args[++i];
break;
case "--out":
String outFile = args[++i];
PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
LOG.info("Redirecting stderr/stdout to " + outFile);
System.setErr(out);
System.setOut(out);
break;
case "--path":
contextPath = args[++i];
contextPathSet = true;
break;
case "--config":
if (_configFiles == null)
_configFiles = new ArrayList<>();
_configFiles.add(args[++i]);
break;
case "--lib":
//skip
++i;
break;
case "--jar":
//skip
++i;
break;
case "--classes":
//skip
++i;
break;
case "--stats":
_enableStats = true;
_statsPropFile = args[++i];
_statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
break;
default:
if (// log handlers not registered, server maybe not created, etc
!runnerServerInitialized) {
if (// server not initialized yet
_server == null) {
// build the server
_server = new Server();
}
//apply jetty config files if there are any
if (_configFiles != null) {
for (String cfg : _configFiles) {
try (Resource resource = Resource.newResource(cfg)) {
XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
xmlConfiguration.configure(_server);
}
}
}
//check that everything got configured, and if not, make the handlers
HandlerCollection handlers = (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
if (handlers == null) {
handlers = new HandlerCollection();
_server.setHandler(handlers);
}
//check if contexts already configured
_contexts = (ContextHandlerCollection) handlers.getChildHandlerByClass(ContextHandlerCollection.class);
if (_contexts == null) {
_contexts = new ContextHandlerCollection();
prependHandler(_contexts, handlers);
}
if (_enableStats) {
//if no stats handler already configured
if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
StatisticsHandler statsHandler = new StatisticsHandler();
Handler oldHandler = _server.getHandler();
statsHandler.setHandler(oldHandler);
_server.setHandler(statsHandler);
ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
statsContext.setSessionHandler(new SessionHandler());
if (_statsPropFile != null) {
HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile);
Constraint constraint = new Constraint();
constraint.setName("Admin Only");
constraint.setRoles(new String[] { "admin" });
constraint.setAuthenticate(true);
ConstraintMapping cm = new ConstraintMapping();
cm.setConstraint(constraint);
cm.setPathSpec("/*");
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
securityHandler.setLoginService(loginService);
securityHandler.setConstraintMappings(Collections.singletonList(cm));
securityHandler.setAuthenticator(new BasicAuthenticator());
statsContext.setSecurityHandler(securityHandler);
}
}
}
//ensure a DefaultHandler is present
if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
handlers.addHandler(new DefaultHandler());
}
//ensure a log handler is present
_logHandler = (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
if (_logHandler == null) {
_logHandler = new RequestLogHandler();
handlers.addHandler(_logHandler);
}
//check a connector is configured to listen on
Connector[] connectors = _server.getConnectors();
if (connectors == null || connectors.length == 0) {
ServerConnector connector = new ServerConnector(_server);
connector.setPort(port);
if (host != null)
connector.setHost(host);
_server.addConnector(connector);
if (_enableStats)
connector.addBean(new ConnectionStatistics());
} else {
if (_enableStats) {
for (Connector connector : connectors) {
((AbstractConnector) connector).addBean(new ConnectionStatistics());
}
}
}
runnerServerInitialized = true;
}
// Create a context
try (Resource ctx = Resource.newResource(args[i])) {
if (!ctx.exists())
usage("Context '" + ctx + "' does not exist");
if (contextPathSet && !(contextPath.startsWith("/")))
contextPath = "/" + contextPath;
// Configure the context
if (!ctx.isDirectory() && ctx.toString().toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
// It is a context config file
XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
xmlConfiguration.getIdMap().put("Server", _server);
ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
if (contextPathSet)
handler.setContextPath(contextPath);
_contexts.addHandler(handler);
String containerIncludeJarPattern = (String) handler.getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
if (containerIncludeJarPattern == null)
containerIncludeJarPattern = __containerIncludeJarPattern;
else {
if (!containerIncludeJarPattern.contains(__containerIncludeJarPattern)) {
containerIncludeJarPattern = containerIncludeJarPattern + (StringUtil.isBlank(containerIncludeJarPattern) ? "" : "|") + __containerIncludeJarPattern;
}
}
handler.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern);
//check the configurations, if not explicitly set up, then configure all of them
if (handler instanceof WebAppContext) {
WebAppContext wac = (WebAppContext) handler;
if (wac.getConfigurationClasses() == null || wac.getConfigurationClasses().length == 0)
wac.setConfigurationClasses(__plusConfigurationClasses);
}
} else {
// assume it is a WAR file
WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
webapp.setConfigurationClasses(__plusConfigurationClasses);
webapp.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, __containerIncludeJarPattern);
}
}
//reset
contextPathSet = false;
contextPath = __defaultContextPath;
break;
}
}
if (_server == null)
usage("No Contexts defined");
_server.setStopAtShutdown(true);
switch((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
case 1:
usage("Must specify --stop-key when --stop-port is specified");
break;
case 2:
usage("Must specify --stop-port when --stop-key is specified");
break;
case 3:
ShutdownMonitor monitor = ShutdownMonitor.getInstance();
monitor.setPort(stopPort);
monitor.setKey(stopKey);
monitor.setExitVm(true);
break;
}
if (_logFile != null) {
NCSARequestLog requestLog = new NCSARequestLog(_logFile);
requestLog.setExtended(false);
_logHandler.setRequestLog(requestLog);
}
}
use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.
the class QuickStartDescriptorGenerator method outholder.
private void outholder(XmlAppendable out, MetaData md, ServletHolder holder) throws IOException {
if (LOG.isDebugEnabled())
out.openTag("servlet", Collections.singletonMap("source", holder.getSource().toString()));
else
out.openTag("servlet");
String n = holder.getName();
out.tag("servlet-name", n);
String ot = n + ".servlet.";
ServletHolder s = (ServletHolder) holder;
if (s.getForcedPath() != null && s.getClassName() == null)
out.tag("jsp-file", s.getForcedPath());
else
out.tag("servlet-class", origin(md, ot + "servlet-class"), s.getClassName());
for (String p : holder.getInitParameters().keySet()) {
if (//don't preconfigure the temp dir for jsp output
"jsp".equalsIgnoreCase(n) && "scratchdir".equalsIgnoreCase(p))
continue;
out.openTag("init-param", origin(md, ot + "init-param." + p)).tag("param-name", p).tag("param-value", holder.getInitParameter(p)).closeTag();
}
if (s.getInitOrder() >= 0)
out.tag("load-on-startup", Integer.toString(s.getInitOrder()));
if (!s.isEnabled())
out.tag("enabled", origin(md, ot + "enabled"), "false");
out.tag("async-supported", origin(md, ot + "async-supported"), holder.isAsyncSupported() ? "true" : "false");
if (s.getRunAsRole() != null)
out.openTag("run-as", origin(md, ot + "run-as")).tag("role-name", s.getRunAsRole()).closeTag();
Map<String, String> roles = s.getRoleRefMap();
if (roles != null) {
for (Map.Entry<String, String> e : roles.entrySet()) {
out.openTag("security-role-ref", origin(md, ot + "role-name." + e.getKey())).tag("role-name", e.getKey()).tag("role-link", e.getValue()).closeTag();
}
}
//multipart-config
MultipartConfigElement multipartConfig = ((ServletHolder.Registration) s.getRegistration()).getMultipartConfig();
if (multipartConfig != null) {
out.openTag("multipart-config", origin(md, s.getName() + ".servlet.multipart-config"));
if (multipartConfig.getLocation() != null)
out.tag("location", multipartConfig.getLocation());
out.tag("max-file-size", Long.toString(multipartConfig.getMaxFileSize()));
out.tag("max-request-size", Long.toString(multipartConfig.getMaxRequestSize()));
out.tag("file-size-threshold", Long.toString(multipartConfig.getFileSizeThreshold()));
out.closeTag();
}
out.closeTag();
}
Aggregations