Skip to content
FileController.java 2.02 KiB
Newer Older
Sonia Zorba's avatar
Sonia Zorba committed
/*
 * 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.JobDAO;
import it.inaf.oats.vospace.exception.InternalFaultException;
import it.inaf.oats.vospace.exception.VoSpaceErrorSummarizableException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import net.ivoa.xml.uws.v1.ExecutionPhase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class FileController {

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

    @Autowired
    protected HttpServletRequest request;

    public String getPath() {

        String uri = request.getRequestURI().substring(request.getContextPath().length());

        String[] parts = uri.split("/");
        return String.join("/", Arrays.stream(parts)
                .map(p -> URLDecoder.decode(p, StandardCharsets.UTF_8))
                .collect(Collectors.toList()));
    }

    public void handleFileJob(Runnable action, String jobId) {
        try {
            action.run();
            if (jobId != null) {
                jobDAO.updateJobPhase(ExecutionPhase.COMPLETED, jobId);
            }
        } catch (Throwable t) {
            VoSpaceErrorSummarizableException jobException;
            if (t instanceof VoSpaceErrorSummarizableException) {
                jobException = (VoSpaceErrorSummarizableException) t;
            } else {
                LOG.error("Unexpected error happened", t);
                jobException = new InternalFaultException("Unexpected error happened");
            }
            if (jobId != null) {
                jobDAO.setJobError(jobId, jobException);
            }
            throw t;
        }
    }