Skip to content
CopyController.java 2.56 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.persistence.FileDAO;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import it.inaf.ia2.transfer.service.FileCopyService;
import it.inaf.oats.vospace.exception.InvalidArgumentException;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.inaf.ia2.transfer.auth.TokenPrincipal;

@RestController
public class CopyController extends AuthenticatedFileController {
    
    private static final Logger LOG = LoggerFactory.getLogger(CopyController.class);
    private FileCopyService copyService;

    @PostMapping(value = "/copy", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> copyFiles(@RequestBody CopyRequest copyRequest) {

        String jobId = copyRequest.getJobId();

        if (jobId == null) {
            throw new InvalidArgumentException("Job Id cannot be null");
        } else if (!jobDAO.isJobExisting(jobId)) {
            throw new InvalidArgumentException("Job " + jobId + " not found");
        }
        
        LOG.debug("copyFiles called from jobId {}", jobId);

        TokenPrincipal principal = getPrincipal();        

        // need to make a completable future start
        CompletableFuture.runAsync(() -> {
            handleFileJob(() -> {
                    try {
                    copyService.copyFiles(copyRequest.getSourceRootVosPath(),
                    copyRequest.getDestinationRootVosPath(), copyRequest.getJobId(),
                    principal);
                    } finally {
                        // TODO: cleanup code to remove unpopulated nodes in case
                        // of failure?
                        fileDao.releaseBusyNodesByJobId(jobId);
                    }
            }, jobId);
        });

        return ResponseEntity.ok(
                copyRequest.getJobId() + " copy task accepted by File Service"
    }

    @Override
    protected String getCustomAuthErrorMessage() {
        return "File Copy not allowed to anonymous users";
    }

}