package org.glassfish.grizzly.http.server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.WriteHandler;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.http.Method;
import org.glassfish.grizzly.http.io.NIOOutputStream;
import org.glassfish.grizzly.http.server.filecache.FileCache;
import org.glassfish.grizzly.http.util.Header;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.grizzly.memory.BufferArray;
import org.glassfish.grizzly.memory.MemoryManager;
import org.glassfish.grizzly.utils.ArraySet;
public class CLStaticHttpHandler extends StaticHttpHandlerBase {
private static final Logger LOGGER = Grizzly.logger(CLStaticHttpHandler.class);
protected static final String CHECK_NON_SLASH_TERMINATED_FOLDERS_PROP = CLStaticHttpHandler.class.getName() + ".check-non-slash-terminated-folders";
private static final boolean CHECK_NON_SLASH_TERMINATED_FOLDERS = System.getProperty(CHECK_NON_SLASH_TERMINATED_FOLDERS_PROP) == null
|| Boolean.getBoolean(CHECK_NON_SLASH_TERMINATED_FOLDERS_PROP);
private static final String SLASH_STR = "/";
private static final String EMPTY_STR = "";
private final ClassLoader classLoader;
private final ArraySet<String> docRoots = new ArraySet<>(String.class);
public CLStaticHttpHandler(final ClassLoader classLoader, final String... docRoots) {
if (classLoader == null) {
throw new IllegalArgumentException("ClassLoader can not be null");
}
this.classLoader = classLoader;
if (docRoots.length > 0) {
for (String docRoot : docRoots) {
if (!docRoot.endsWith("/")) {
throw new IllegalArgumentException("Doc root should end with slash ('/')");
}
}
this.docRoots.addAll(docRoots);
} else {
this.docRoots.add("/");
}
}
public boolean addDocRoot(final String docRoot) {
if (!docRoot.endsWith("/")) {
throw new IllegalArgumentException("Doc root should end with slash ('/')");
}
return docRoots.add(docRoot);
}
public boolean removeDocRoot(final String docRoot) {
return docRoots.remove(docRoot);
}
public ClassLoader getClassLoader() {
return classLoader;
}
@Override
protected boolean handle(String resourcePath, final Request request, final Response response) throws Exception {
URLConnection urlConnection = null;
InputStream urlInputStream = null;
if (resourcePath.startsWith(SLASH_STR)) {
resourcePath = resourcePath.substring(1);
}
boolean mayBeFolder = true;
if (resourcePath.length() == 0 || resourcePath.endsWith("/")) {
resourcePath += "index.html";
mayBeFolder = false;
}
URL url = lookupResource(resourcePath);
if (url == null && mayBeFolder && CHECK_NON_SLASH_TERMINATED_FOLDERS) {
url = lookupResource(resourcePath + "/index.html");
mayBeFolder = false;
}
File fileResource = null;
String filePath = null;
boolean found = false;
if (url != null) {
if ("file".equals(url.getProtocol())) {
final File file = new File(url.toURI());
if (file.exists()) {
if (file.isDirectory()) {
final File welcomeFile = new File(file, "/index.html");
if (welcomeFile.exists() && welcomeFile.isFile()) {
fileResource = welcomeFile;
filePath = welcomeFile.getPath();
found = true;
}
} else {
fileResource = file;
filePath = file.getPath();
found = true;
}
}
} else {
urlConnection = url.openConnection();
if ("jar".equals(url.getProtocol())) {
final JarURLConnection jarUrlConnection = (JarURLConnection) urlConnection;
JarEntry jarEntry = jarUrlConnection.getJarEntry();
final JarFile jarFile = jarUrlConnection.getJarFile();
InputStream is = null;
if (jarEntry.isDirectory() || (is = jarFile.getInputStream(jarEntry)) == null) {
final String welcomeResource = jarEntry.getName().endsWith("/") ? jarEntry.getName() + "index.html"
: jarEntry.getName() + "/index.html";
jarEntry = jarFile.getJarEntry(welcomeResource);
if (jarEntry != null) {
is = jarFile.getInputStream(jarEntry);
}
}
if (is != null) {
urlInputStream = new JarURLInputStream(jarUrlConnection, jarFile, is);
assert jarEntry != null;
filePath = jarEntry.getName();
found = true;
} else {
closeJarFileIfNeeded(jarUrlConnection, jarFile);
}
} else if ("bundle".equals(url.getProtocol())) {
if (mayBeFolder && urlConnection.getContentLength() <= 0) {
final URL welcomeUrl = classLoader.getResource(url.getPath() + "/index.html");
if (welcomeUrl != null) {
url = welcomeUrl;
urlConnection = welcomeUrl.openConnection();
}
}
found = true;
} else {
found = true;
}
}
}
if (!found) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Resource not found {0}", resourcePath);
}
return false;
}
assert url != null;
if (!Method.GET.equals(request.getMethod())) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Resource found {0}, but HTTP method {1} is not allowed", new Object[] { resourcePath, request.getMethod() });
}
response.setStatus(HttpStatus.METHOD_NOT_ALLOWED_405);
response.setHeader(Header.Allow, "GET");
return true;
}
pickupContentType(response, filePath != null ? filePath : url.getPath());
if (fileResource != null) {
addToFileCache(request, response, fileResource);
sendFile(response, fileResource);
} else {
assert urlConnection != null;
if ("jar".equals(url.getProtocol())) {
final File jarFile = getJarFile(
new URI(url.getPath()).getPath());
addTimeStampEntryToFileCache(request, response, jarFile);
}
sendResource(response, urlInputStream != null ? urlInputStream : urlConnection.getInputStream());
}
return true;
}
private URL lookupResource(String resourcePath) {
final String[] docRootsLocal = docRoots.getArray();
if (docRootsLocal == null || docRootsLocal.length == 0) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "No doc roots registered -> resource {0} is not found ", resourcePath);
}
return null;
}
for (String docRoot : docRootsLocal) {
if (SLASH_STR.equals(docRoot)) {
docRoot = EMPTY_STR;
} else if (docRoot.startsWith(SLASH_STR)) {
docRoot = docRoot.substring(1);
}
final String fullPath = docRoot + resourcePath;
final URL url = classLoader.getResource(fullPath);
if (url != null) {
return url;
}
}
return null;
}
private static void sendResource(final Response response, final InputStream input) throws IOException {
response.setStatus(HttpStatus.OK_200);
response.addDateHeader(Header.Date, System.currentTimeMillis());
final int chunkSize = 8192;
response.suspend();
final NIOOutputStream outputStream = response.getNIOOutputStream();
outputStream.notifyCanWrite(new NonBlockingDownloadHandler(response, outputStream, input, chunkSize));
}
private boolean addTimeStampEntryToFileCache(final Request req, final Response res, final File archive) {
if (isFileCacheEnabled()) {
final FilterChainContext fcContext = req.getContext();
final FileCacheFilter fileCacheFilter = lookupFileCache(fcContext);
if (fileCacheFilter != null) {
final FileCache fileCache = fileCacheFilter.getFileCache();
if (fileCache.isEnabled()) {
if (res != null) {
addCachingHeaders(res, archive);
}
fileCache.add(req.getRequest(), archive.lastModified());
return true;
}
}
}
return false;
}
private File getJarFile(final String path) throws MalformedURLException, FileNotFoundException {
final int jarDelimIdx = path.indexOf("!/");
if (jarDelimIdx == -1) {
throw new MalformedURLException("The jar file delimeter were not found");
}
final File file = new File(path.substring(0, jarDelimIdx));
if (!file.exists() || !file.isFile()) {
throw new FileNotFoundException("The jar file was not found");
}
return file;
}
private static class NonBlockingDownloadHandler implements WriteHandler {
private final Response response;
private final NIOOutputStream outputStream;
private final InputStream inputStream;
private final MemoryManager mm;
private final int chunkSize;
NonBlockingDownloadHandler(final Response response, final NIOOutputStream outputStream, final InputStream inputStream, final int chunkSize) {
this.response = response;
this.outputStream = outputStream;
this.inputStream = inputStream;
mm = response.getRequest().getContext().getMemoryManager();
this.chunkSize = chunkSize;
}
@Override
public void onWritePossible() throws Exception {
LOGGER.log(Level.FINE, "[onWritePossible]");
final boolean isWriteMore = sendChunk();
if (isWriteMore) {
outputStream.notifyCanWrite(this);
}
}
@Override
public void onError(Throwable t) {
LOGGER.log(Level.FINE, "[onError] ", t);
response.setStatus(500, t.getMessage());
complete(true);
}
private boolean sendChunk() throws IOException {
Buffer buffer = null;
if (!mm.willAllocateDirect(chunkSize)) {
buffer = mm.allocate(chunkSize);
final int len;
if (!buffer.isComposite()) {
len = inputStream.read(buffer.array(), buffer.position() + buffer.arrayOffset(), chunkSize);
} else {
final BufferArray bufferArray = buffer.toBufferArray();
final int size = bufferArray.size();
final Buffer[] buffers = bufferArray.getArray();
int lenCounter = 0;
for (int i = 0; i < size; i++) {
final Buffer subBuffer = buffers[i];
final int subBufferLen = subBuffer.remaining();
final int justReadLen = inputStream.read(subBuffer.array(), subBuffer.position() + subBuffer.arrayOffset(), subBufferLen);
if (justReadLen > 0) {
lenCounter += justReadLen;
}
if (justReadLen < subBufferLen) {
break;
}
}
bufferArray.restore();
bufferArray.recycle();
len = lenCounter > 0 ? lenCounter : -1;
}
if (len > 0) {
buffer.position(buffer.position() + len);
} else {
buffer.dispose();
buffer = null;
}
} else {
final byte[] buf = new byte[chunkSize];
final int len = inputStream.read(buf);
if (len > 0) {
buffer = mm.allocate(len);
buffer.put(buf);
}
}
if (buffer == null) {
complete(false);
return false;
}
buffer.allowBufferDispose(true);
buffer.trim();
outputStream.write(buffer);
return true;
}
private void complete(final boolean isError) {
try {
inputStream.close();
} catch (IOException e) {
if (!isError) {
response.setStatus(500, e.getMessage());
}
}
try {
outputStream.close();
} catch (IOException e) {
if (!isError) {
response.setStatus(500, e.getMessage());
}
}
if (response.isSuspended()) {
response.resume();
} else {
response.finish();
}
}
}
static class JarURLInputStream extends java.io.FilterInputStream {
private final JarURLConnection jarConnection;
private final JarFile jarFile;
JarURLInputStream(final JarURLConnection jarConnection, final JarFile jarFile, final InputStream src) {
super(src);
this.jarConnection = jarConnection;
this.jarFile = jarFile;
}
@Override
public void close() throws IOException {
try {
super.close();
} finally {
closeJarFileIfNeeded(jarConnection, jarFile);
}
}
}
private static void closeJarFileIfNeeded(final JarURLConnection jarConnection, final JarFile jarFile) throws IOException {
if (!jarConnection.getUseCaches()) {
jarFile.close();
}
}
}