package org.eclipse.jetty.server;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jetty.http.CompressedContentFormat;
import org.eclipse.jetty.http.HttpContent;
import org.eclipse.jetty.http.HttpContent.ContentFactory;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.ResourceHttpContent;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceFactory;
public class ResourceContentFactory implements ContentFactory
{
private final ResourceFactory _factory;
private final MimeTypes _mimeTypes;
private final CompressedContentFormat[] _precompressedFormats;
public ResourceContentFactory(ResourceFactory factory, MimeTypes mimeTypes, CompressedContentFormat[] precompressedFormats)
{
_factory = factory;
_mimeTypes = mimeTypes;
_precompressedFormats = precompressedFormats;
}
@Override
public HttpContent getContent(String pathInContext, int maxBufferSize) throws IOException
{
try
{
Resource resource = _factory.getResource(pathInContext);
return load(pathInContext, resource, maxBufferSize);
}
catch (Throwable t)
{
InvalidPathException saferException = new InvalidPathException(pathInContext, "Invalid PathInContext");
saferException.initCause(t);
throw saferException;
}
}
private HttpContent load(String pathInContext, Resource resource, int maxBufferSize)
throws IOException
{
if (resource == null || !resource.exists())
return null;
if (resource.isDirectory())
return new ResourceHttpContent(resource, _mimeTypes.getMimeByExtension(resource.toString()), maxBufferSize);
String mt = _mimeTypes.getMimeByExtension(pathInContext);
if (_precompressedFormats.length > 0)
{
Map<CompressedContentFormat, HttpContent> compressedContents = new HashMap<>(_precompressedFormats.length);
for (CompressedContentFormat format : _precompressedFormats)
{
String compressedPathInContext = pathInContext + format._extension;
Resource compressedResource = _factory.getResource(compressedPathInContext);
if (compressedResource != null && compressedResource.exists() && compressedResource.lastModified() >= resource.lastModified() &&
compressedResource.length() < resource.length())
compressedContents.put(format,
new ResourceHttpContent(compressedResource, _mimeTypes.getMimeByExtension(compressedPathInContext), maxBufferSize));
}
if (!compressedContents.isEmpty())
return new ResourceHttpContent(resource, mt, maxBufferSize, compressedContents);
}
return new ResourceHttpContent(resource, mt, maxBufferSize);
}
@Override
public String toString()
{
return "ResourceContentFactory[" + _factory + "]@" + hashCode();
}
}