use of org.eclipse.jetty.server.handler.ResourceHandler in project jphp by jphp-compiler.
the class PHttpResourceHandler method __construct.
@Signature
public void __construct(String directory) throws Exception {
resourceHandler = new ResourceHandler();
file(directory);
}
use of org.eclipse.jetty.server.handler.ResourceHandler in project jphp by jphp-compiler.
the class PHttpResourceHandler method __invoke.
@Signature
public void __invoke(PHttpServerRequest request, PHttpServerResponse response) throws Exception {
final boolean[] once = { false };
ResourceHandler resourceHandler = new ResourceHandler() {
@Override
public Resource getResource(String path) {
if (!once[0]) {
once[0] = true;
Object attr = request.getRequest().getAttribute("**");
File file;
if (attr != null) {
file = new File(PHttpResourceHandler.this.file, "/" + attr);
} else {
file = new File(PHttpResourceHandler.this.file);
}
if (file.exists()) {
return new PathResource(file.getAbsoluteFile());
} else {
return null;
}
} else {
return null;
}
}
};
resourceHandler.doStart();
resourceHandler.setResourceBase(file());
if (cacheControl() != null) {
resourceHandler.setCacheControl(cacheControl());
}
resourceHandler.setRedirectWelcome(redirectWelcome());
resourceHandler.setPathInfoOnly(pathInfoOnly());
resourceHandler.setDirectoriesListed(directoriesListed());
resourceHandler.setDirAllowed(dirAllowed());
resourceHandler.setAcceptRanges(acceptRanges());
resourceHandler.setEtags(etags());
Request baseRequest = Request.getBaseRequest(request.getRequest());
resourceHandler.handle(request.getRequest().getRequestURI(), baseRequest, request.getRequest(), response.getResponse());
}
use of org.eclipse.jetty.server.handler.ResourceHandler in project JMRI by JMRI.
the class WebServer method registerResource.
/**
* Register a URL pattern to return resources from the file system. The
* filePath may start with any of the following:
* <ol>
* <li>{@link jmri.util.FileUtil#PREFERENCES}
* <li>{@link jmri.util.FileUtil#PROFILE}
* <li>{@link jmri.util.FileUtil#SETTINGS}
* <li>{@link jmri.util.FileUtil#PROGRAM}
* </ol>
* Note that the filePath can be overridden by an otherwise identical
* filePath starting with any of the portable paths above it in the
* preceding list.
*
* @param urlPattern the pattern to get resources for
* @param filePath the portable path for the resources
* @throws IllegalArgumentException if urlPattern is already registered to
* deny access or for a servlet or if
* filePath is not allowed
*/
public void registerResource(String urlPattern, String filePath) throws IllegalArgumentException {
if (this.registeredUrls.get(urlPattern) != null) {
throw new IllegalArgumentException("urlPattern \"" + urlPattern + "\" is already registered.");
}
this.registeredUrls.put(urlPattern, Registration.RESOURCE);
ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
servletContext.setContextPath(urlPattern);
HandlerList handlers = new HandlerList();
if (filePath.startsWith(FileUtil.PROGRAM) && !filePath.equals(FileUtil.PROGRAM)) {
// make it possible to override anything under program: with an identical path under preference:, profile:, or settings:
log.debug("Setting up handler chain for {}", urlPattern);
ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PREFERENCES)));
ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
ResourceHandler settingsHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.SETTINGS)));
ResourceHandler programHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, settingsHandler, programHandler, new DefaultHandler() });
} else if (filePath.startsWith(FileUtil.SETTINGS) && !filePath.equals(FileUtil.SETTINGS)) {
// make it possible to override anything under settings: with an identical path under preference: or profile:
log.debug("Setting up handler chain for {}", urlPattern);
ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.SETTINGS, FileUtil.PREFERENCES)));
ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
ResourceHandler settingsHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, settingsHandler, new DefaultHandler() });
} else if (filePath.startsWith(FileUtil.PROFILE) && !filePath.equals(FileUtil.PROFILE)) {
// make it possible to override anything under profile: with an identical path under preference:
log.debug("Setting up handler chain for {}", urlPattern);
ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.SETTINGS, FileUtil.PREFERENCES)));
ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, new DefaultHandler() });
} else if (FileUtil.isPortableFilename(filePath)) {
log.debug("Setting up handler chain for {}", urlPattern);
ResourceHandler handler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });
} else if (URIforPortablePath(filePath) == null) {
throw new IllegalArgumentException("\"" + filePath + "\" is not allowed.");
}
ContextHandler handlerContext = new ContextHandler();
handlerContext.setContextPath(urlPattern);
handlerContext.setHandler(handlers);
((ContextHandlerCollection) this.server.getHandler()).addHandler(handlerContext);
}
use of org.eclipse.jetty.server.handler.ResourceHandler in project opennms by OpenNMS.
the class JUnitServer method initializeServerWithConfig.
protected void initializeServerWithConfig(final JUnitHttpServer config) {
Server server = null;
if (config.https()) {
server = new Server();
// SSL context configuration
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(config.keystore());
sslContextFactory.setKeyStorePassword(config.keystorePassword());
sslContextFactory.setKeyManagerPassword(config.keyPassword());
sslContextFactory.setTrustStorePath(config.keystore());
sslContextFactory.setTrustStorePassword(config.keystorePassword());
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(config.port());
http_config.setOutputBufferSize(32768);
http_config.setRequestHeaderSize(8192);
http_config.setResponseHeaderSize(8192);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
// SSL HTTP Configuration
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
sslConnector.setPort(config.port());
server.addConnector(sslConnector);
} else {
server = new Server(config.port());
}
m_server = server;
final ContextHandler context1 = new ContextHandler();
context1.setContextPath("/");
context1.setWelcomeFiles(new String[] { "index.html" });
context1.setResourceBase(config.resource());
context1.setClassLoader(Thread.currentThread().getContextClassLoader());
context1.setVirtualHosts(config.vhosts());
final ContextHandler context = context1;
Handler topLevelHandler = null;
final HandlerList handlers = new HandlerList();
if (config.basicAuth()) {
// check for basic auth if we're configured to do so
LOG.debug("configuring basic auth");
final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile());
loginService.setHotReload(true);
m_server.addBean(loginService);
final ConstraintSecurityHandler security = new ConstraintSecurityHandler();
final Set<String> knownRoles = new HashSet<>();
knownRoles.add("user");
knownRoles.add("admin");
knownRoles.add("moderator");
final Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate(true);
constraint.setRoles(knownRoles.toArray(new String[0]));
final ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec("/*");
mapping.setConstraint(constraint);
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setRealmName("MyRealm");
security.setHandler(context);
topLevelHandler = security;
} else {
topLevelHandler = context;
}
final Webapp[] webapps = config.webapps();
if (webapps != null) {
for (final Webapp webapp : webapps) {
final WebAppContext wac = new WebAppContext();
String path = null;
if (!"".equals(webapp.pathSystemProperty()) && System.getProperty(webapp.pathSystemProperty()) != null) {
path = System.getProperty(webapp.pathSystemProperty());
} else {
path = webapp.path();
}
if (path == null || "".equals(path)) {
throw new IllegalArgumentException("path or pathSystemProperty of @Webapp points to a null or blank value");
}
wac.setWar(path);
wac.setContextPath(webapp.context());
handlers.addHandler(wac);
}
}
final ResourceHandler rh = new ResourceHandler();
rh.setWelcomeFiles(new String[] { "index.html" });
rh.setResourceBase(config.resource());
handlers.addHandler(rh);
// fall through to default
handlers.addHandler(new DefaultHandler());
context.setHandler(handlers);
m_server.setHandler(topLevelHandler);
}
use of org.eclipse.jetty.server.handler.ResourceHandler in project graphhopper by graphhopper.
the class GHServer method start.
public void start(Injector injector) throws Exception {
if (this.injector != null)
throw new IllegalArgumentException("Server already started");
this.injector = injector;
ResourceHandler resHandler = new ResourceHandler();
resHandler.setDirectoriesListed(false);
resHandler.setWelcomeFiles(new String[] { "index.html" });
resHandler.setRedirectWelcome(false);
String contextPath = args.get("jetty.contextpath", "/");
ContextHandler contextHandler = new ContextHandler();
contextHandler.setErrorHandler(new GHErrorHandler());
contextHandler.setContextPath(contextPath);
contextHandler.setBaseResource(Resource.newResource(args.get("jetty.resourcebase", "./web/src/main/webapp")));
contextHandler.setHandler(resHandler);
server = new Server();
// getSessionHandler and getSecurityHandler should always return null
ServletContextHandler servHandler = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
servHandler.setContextPath(contextPath);
// Putting this here (and not in the guice servlet module) because it should take precedence
// over more specific routes. And guice, strangely, is order-dependent (even though, except in the servlet
// extension, modules are _not_ supposed to be ordered).
servHandler.addServlet(new ServletHolder(injector.getInstance(InvalidRequestServlet.class)), "/*");
servHandler.addFilter(new FilterHolder(new GuiceFilter()), "/*", EnumSet.allOf(DispatcherType.class));
ServerConnector connector0 = new ServerConnector(server);
int httpPort = args.getInt("jetty.port", 8989);
String host = args.get("jetty.host", "");
connector0.setPort(httpPort);
int requestHeaderSize = args.getInt("jetty.request_header_size", -1);
if (requestHeaderSize > 0)
connector0.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration().setRequestHeaderSize(requestHeaderSize);
if (!host.isEmpty())
connector0.setHost(host);
server.addConnector(connector0);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { contextHandler, servHandler });
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setIncludedMethods("GET", "POST");
// Note: gzip only affects the response body like our previous 'GHGZIPHook' behaviour: http://stackoverflow.com/a/31565805/194609
// If no mimeTypes are defined the content-type is "not 'application/gzip'", See also https://github.com/graphhopper/directions-api/issues/28 for pitfalls
// gzipHandler.setIncludedMimeTypes();
gzipHandler.setHandler(handlers);
GraphHopperService graphHopper = injector.getInstance(GraphHopperService.class);
graphHopper.start();
createCallOnDestroyModule("AutoCloseable for GraphHopper", graphHopper);
server.setHandler(gzipHandler);
server.setStopAtShutdown(true);
server.start();
logger.info("Started server at HTTP " + host + ":" + httpPort);
}
Aggregations