All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.yoojia.halo.AssetsTransferAdapter Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
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);
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy