org.apache.http.nio.entity.NFileEntity Java Examples

The following examples show how to use org.apache.http.nio.entity.NFileEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StaticFileServingHandler.java    From Repeat with Apache License 2.0 4 votes vote down vote up
@Override
public Void handleRequest(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
	LOGGER.fine("Path is " + request.getRequestLine().getUri());
	if (!request.getRequestLine().getMethod().equalsIgnoreCase("GET")) {
		return HttpServerUtilities.prepareTextResponse(exchange, 400, "Only accept GET requests.");
	}

	String requestUri = request.getRequestLine().getUri();
	if (!requestUri.startsWith("/static/")) {
		return HttpServerUtilities.prepareTextResponse(exchange, 500, "URI must start with '/static/'.");
	}

	String uriWithoutParamter = "";
	try {
		URI uri = new URI(requestUri);
		uriWithoutParamter = new URI(uri.getScheme(),
                   uri.getAuthority(),
                   uri.getPath(),
                   null, // Ignore the query part of the input url.
                   uri.getFragment()).toString();
	} catch (URISyntaxException e) {
		LOGGER.log(Level.WARNING, "Encountered exception when trying to remove query parameters.", e);
		return HttpServerUtilities.prepareTextResponse(exchange, 500, "Encountered exception when trying to remove query parameters.");
	}

	String path = uriWithoutParamter.substring("/static/".length());

	String rootPath = new File(root).getCanonicalPath();
	File file = new File(root, URLDecoder.decode(path, "UTF-8"));
	if (!file.getCanonicalPath().startsWith(rootPath)) {
		return HttpServerUtilities.prepareTextResponse(exchange, 404, String.format("File does not exist %s.", path));
	}

	HttpResponse response = exchange.getResponse();
	if (!file.exists()) {
		return HttpServerUtilities.prepareTextResponse(exchange, 404, String.format("File does not exist %s.", path));
	} else if (!file.canRead() || file.isDirectory()) {
		return HttpServerUtilities.prepareTextResponse(exchange, 403, String.format("Cannot read file %s.", path));
	} else if (!file.canRead()) {
		return HttpServerUtilities.prepareTextResponse(exchange, 400, String.format("Path is a directory %s.", path));
	} else {
           response.setStatusCode(HttpStatus.SC_OK);
           response.addHeader("Cache-Control", "max-age=3600"); // Max age = 1 hour.
           String contentType = contentType(file.toPath());
           NFileEntity body = new NFileEntity(file, ContentType.create(contentType));
           response.setEntity(body);
           exchange.submitResponse(new BasicAsyncResponseProducer(response));
           return null;
       }
}
 
Example #2
Source File: LocalWebServerHttpRequestHandler.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private void handleRequest(HttpRequest request, HttpResponse response, boolean head) throws HttpException,
		IOException, CoreException, URISyntaxException
{
	String target = URLDecoder.decode(request.getRequestLine().getUri(), IOUtil.UTF_8);
	URI uri = URIUtil.fromString(target);
	IFileStore fileStore = uriMapper.resolve(uri);
	IFileInfo fileInfo = fileStore.fetchInfo();
	if (fileInfo.isDirectory())
	{
		fileInfo = getIndex(fileStore);
		if (fileInfo.exists())
		{
			fileStore = fileStore.getChild(fileInfo.getName());
		}
	}
	if (!fileInfo.exists())
	{
		response.setStatusCode(HttpStatus.SC_NOT_FOUND);
		response.setEntity(createTextEntity(MessageFormat.format(
				Messages.LocalWebServerHttpRequestHandler_FILE_NOT_FOUND, uri.getPath())));
	}
	else if (fileInfo.isDirectory())
	{
		response.setStatusCode(HttpStatus.SC_FORBIDDEN);
		response.setEntity(createTextEntity(Messages.LocalWebServerHttpRequestHandler_FORBIDDEN));
	}
	else
	{
		response.setStatusCode(HttpStatus.SC_OK);
		if (head)
		{
			response.setEntity(null);
		}
		else
		{
			File file = fileStore.toLocalFile(EFS.NONE, new NullProgressMonitor());
			final File temporaryFile = (file == null) ? fileStore.toLocalFile(EFS.CACHE, new NullProgressMonitor())
					: null;
			response.setEntity(new NFileEntity((file != null) ? file : temporaryFile, getMimeType(fileStore
					.getName()))
			{
				@Override
				public void close() throws IOException
				{
					try
					{
						super.close();
					}
					finally
					{
						if (temporaryFile != null && !temporaryFile.delete())
						{
							temporaryFile.deleteOnExit();
						}
					}
				}
			});
		}
	}
}