| 1 |
package org.astrogrid.samp.httpd; |
| 2 |
|
| 3 |
import java.net.MalformedURLException; |
| 4 |
import java.net.URL; |
| 5 |
|
| 6 |
/** |
| 7 |
* Handler implementation which allows the server to serve a directory |
| 8 |
* full of resources. |
| 9 |
* The {@link URLMapperHandler} class can sort of do the same thing, |
| 10 |
* but it's difficult to get the path right. |
| 11 |
* |
| 12 |
* <p>For if an instance is initialised as |
| 13 |
* <code>new DirectoryMapperHandler("/files", "/data")</code> |
| 14 |
* and installed on a server running at <code>http://localhost:8000/</code>, |
| 15 |
* then a server request for <code>http://localhost:8000/data/xxx</code> |
| 16 |
* would be fulfilled by returning the content of the resource |
| 17 |
* <code>/files/xxx</code> available to the JVM's classloader |
| 18 |
* (for instance within a jar file on the classpath). |
| 19 |
* |
| 20 |
* @author Mark Taylor |
| 21 |
* @since 11 Mar 2016 |
| 22 |
*/ |
| 23 |
public class DirectoryMapperHandler implements HttpServer.Handler { |
| 24 |
|
| 25 |
private final String localDocBase_; |
| 26 |
private final String serverDocPath_; |
| 27 |
|
| 28 |
/** |
| 29 |
* Constructor. |
| 30 |
* |
| 31 |
* @param localDocBase prefix for resources available within the JVM |
| 32 |
* @param serverDocPath prefix for resources made available by this server |
| 33 |
*/ |
| 34 |
public DirectoryMapperHandler( String localDocBase, String serverDocPath ) { |
| 35 |
localDocBase_ = localDocBase; |
| 36 |
serverDocPath_ = serverDocPath; |
| 37 |
} |
| 38 |
|
| 39 |
public HttpServer.Response serveRequest( HttpServer.Request request ) { |
| 40 |
String path = request.getUrl(); |
| 41 |
if ( ! path.startsWith( serverDocPath_ ) ) { |
| 42 |
return null; |
| 43 |
} |
| 44 |
String relPath = path.substring( serverDocPath_.length() ); |
| 45 |
final URL srcUrl = getClass().getResource( localDocBase_ + relPath ); |
| 46 |
return srcUrl == null |
| 47 |
? null |
| 48 |
: URLMapperHandler.mapUrlResponse( request.getMethod(), srcUrl ); |
| 49 |
} |
| 50 |
} |