Skip to content
ArchiveFileController.java 2.73 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.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.service.ArchiveJob;
import it.inaf.ia2.transfer.service.ArchiveJob.Type;
import it.inaf.ia2.transfer.service.ArchiveService;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ArchiveFileController extends AuthenticatedFileController {

    @Autowired
    private ArchiveService archiveService;
    
    @Autowired
    private HttpServletRequest servletRequest;
    @Autowired
    private HttpServletResponse response;

    @PostMapping(value = "/archive", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> createArchiveFile(@RequestBody ArchiveRequest archiveRequest) {

        Type type = Type.valueOf(archiveRequest.getType());

        ArchiveJob job = new ArchiveJob();
        job.setPrincipal(getPrincipal());
        job.setJobId(archiveRequest.getJobId());
        job.setType(type);
        job.setVosPaths(archiveRequest.getPaths());

        CompletableFuture.runAsync(() -> {
            handleFileJob(() -> archiveService.createArchive(job, servletRequest), job.getJobId());

        HttpHeaders headers = new HttpHeaders();
        headers.set("Location", request.getRequestURL() + "/" + archiveRequest.getJobId() + "." + type.getExtension());
        return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER);
    }

    @GetMapping(value = "/archive/{fileName}")
    public void getArchiveFile(@PathVariable("fileName") String fileName) {
        TokenPrincipal principal = getPrincipal();

        File file = archiveService.getArchiveParentDir(principal).toPath().resolve(fileName).toFile();

        FileResponseUtil.getFileResponse(response, file);
    @Override
    protected String getCustomAuthErrorMessage() {
        return "Tar/Zip archive generation not allowed to anonymous users";