com.github.yoojia.halo.DownloadManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of halo-download Show documentation
Show all versions of halo-download Show documentation
A FAST && THIN && HIGH SCALABLE Java web framework
package com.github.yoojia.halo;
import com.github.yoojia.halo.supports.*;
import com.github.yoojia.halo.utils.SystemTime;
import com.google.common.base.Strings;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author YOOJIA.CHEN ([email protected])
*/
public class DownloadManager extends HaloModule {
private static final int DEFAULT_PRIORITY = 50;
private static final String DIR = "/files";
private Context mContext;
@Override
public void init(Context context, Config config) {
mLogger.debug("Init...");
mContext = context;
}
@Override
public void onService(HaloRequest request, HaloResponse response, KernelChain chain) throws Exception {
final String userSetPath = Downloads.getResourcePath(request);
if(Strings.isNullOrEmpty(userSetPath)) {
chain.onService(request, response, chain);
return;
}
final long start = System.nanoTime();
try{
final Path local = mContext.resolve(Paths.get(DIR, userSetPath));
response.setStatusCode(StatusCode.OK);
if (Files.exists(local)){
response.httpResponse.setContentLengthLong(Files.size(local));
response.setContentType("application/octet-stream");
final String userSetName = Downloads.getResourceName(request);
final String attachName = userSetName != null ? userSetName : local.getFileName().toString();
response.httpResponse.addHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(attachName, "UTF-8"));
DownloadTransferAdapter.use(local).dispatch(response);
}else{
response.setStatusCode(StatusCode.NOT_FOUND);
}
}finally {
SystemTime.log(start, String.format("DownloadManager.send(:%s)", request.uri));
}
}
@Override
public int getPriority() {
return DEFAULT_PRIORITY;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy