in fileservice/src/main/java/org/apache/asyncweb/fileservice/FileHttpService.java [92:183]
public void handleRequest(HttpServiceContext context) throws Exception {
URI uri = context.getRequest().getRequestUri();
String path = uri.getPath();
LOG.info("Handling file request : {} from {}",uri,context.getRemoteAddress());
if (!path.startsWith(baseUrl)) {
// error the requested URL is not in the base URL
//TODO : find the good exception to throw
throw new InvalidParameterException("Wrong URL");
}
MutableHttpResponse response = new DefaultHttpResponse();
path = path.substring(baseUrl.length());
File f = new File(basePath + File.separator + path);
if (f.isDirectory()) {
// is the request finishing by the '/' character ?
String urlStr = uri.toString();
if (urlStr.charAt(urlStr.length() - 1) != '/') {
LOG.debug("Redirecting {} to {}/", urlStr, urlStr);
// send back the good URI
response.setStatus(HttpResponseStatus.MOVED_PERMANENTLY);
response.setHeader("Location", urlStr + "/");
context.commitResponse(response);
return;
}
// search for index file
String[] indexes = f.list(indexFileFilter);
if (indexes.length == 0) {
LOG.info("Serving directory index for {}", f.getAbsolutePath());
if (indexGenerator != null) {
// create a directory index page
IoBuffer indexResponse = indexGenerator.generateIndex(f);
indexResponse.flip();
response.setContent(indexResponse);
response.setHeader("Content-Type", "text/html");
response.setStatus(HttpResponseStatus.OK);
context.commitResponse(response);
return;
}
} else {
// just serve the index file (ex:index.html)
f = new File(f.getAbsolutePath() + File.separator + indexes[0]);
}
}
if (f.exists() && !f.isDirectory()) {
LOG.info("Serving file {}",f.getAbsolutePath());
// caching processing
if (cachingPolicy == null
|| !cachingPolicy.isCacheable(f, context.getRequest())) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
} else {
cachingPolicy.testAndSetCacheHit(f, context.getRequest(),
response);
}
// setting mime-type based on the mime-map
String contentType = mimeMap.getContentType(MimeMap.getExtension(f
.getName()));
if (contentType != null)
response.setHeader("Content-Type", contentType);
response.setStatus(HttpResponseStatus.OK);
IoBuffer buffer=fileLoader.loadFile(f);
response.setContent(buffer);
} else {
// the file is not found, we send the famous 404 error
response.setStatus(HttpResponseStatus.NOT_FOUND);
response.setStatusReasonPhrase("File \"" + path + "\"");
LOG.warn("The file {} is not found",f.getAbsolutePath());
}
context.commitResponse(response);
}