Skip to content
FileResponseUtil.java 2.15 KiB
Newer Older
/*
 * This file is part of vospace-file-service
 * Copyright (C) 2021 Istituto Nazionale di Astrofisica
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package it.inaf.ia2.transfer.controller;

import it.inaf.oats.vospace.exception.InternalFaultException;
import it.inaf.oats.vospace.exception.NodeNotFoundException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileResponseUtil {

    private static final Logger LOG = LoggerFactory.getLogger(FileResponseUtil.class);

    public static void getFileResponse(HttpServletResponse response, File file) {
        getFileResponse(response, file, null);
    public static void getFileResponse(HttpServletResponse response, File file, String vosPath) {

        String fileName = vosPath == null ? file.getName() : vosPath.substring(vosPath.lastIndexOf("/") + 1);

        if (!file.exists()) {
            LOG.error("File not found: " + file.getAbsolutePath());
            throw new NodeNotFoundException(vosPath == null ? file.getAbsolutePath() : vosPath);
        }

        if (!file.canRead()) {
            LOG.error("File not readable: " + file.getAbsolutePath());
            throw new InternalFaultException("File " + file.getName() + " is not readable");
        }

        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setCharacterEncoding("UTF-8");

        byte[] bytes = new byte[1024];
        try ( OutputStream out = response.getOutputStream();  InputStream is = new FileInputStream(file)) {
            int read;
            while ((read = is.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }
}