com.github.yoojia.halo.AssetsTransferAdapter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of halo-assets Show documentation
Show all versions of halo-assets Show documentation
A FAST && THIN && HIGH SCALABLE Java web framework
package com.github.yoojia.halo;
import com.github.yoojia.halo.supports.StatusCode;
import java.io.File;
import java.io.FileInputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Path;
import java.util.Date;
/**
* @author YOOJIA.CHEN ([email protected])
*/
class AssetsTransferAdapter {
private final File inputFile;
private final long lastModified;
private AssetsTransferAdapter(Path path) {
inputFile = path.toFile();
lastModified = inputFile.lastModified();
}
static AssetsTransferAdapter use(Path path) {
return new AssetsTransferAdapter(path);
}
public void dispatch(HaloRequest request, HaloResponse response) throws Exception {
final String lastModifiedDate = new Date(lastModified).toString();
final String clientLastModifiedDate = request.httpRequest.getHeader("If-Modified-Since");
// If resource not modified
if(lastModifiedDate.equalsIgnoreCase(clientLastModifiedDate)){
response.setStatusCode(StatusCode.NOT_MODIFIED);
}else{ // Set last-modified
response.httpResponse.setHeader("Last-Modified", lastModifiedDate);
try(FileChannel in = new FileInputStream(inputFile).getChannel();
WritableByteChannel out = Channels.newChannel(response.httpResponse.getOutputStream())){
in.transferTo(0, in.size(), out);
}
}
}
}