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

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * Controller for IVOA Data Access Layer Interface (VOSI-capabilities and
 * VOSI-availability endpoints).
 */
@RestController
public class DALIController {

    @Autowired
    private HttpServletRequest request;

    @GetMapping(value = "/vo/capabilities", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
    public String getCapabilities() throws IOException {
        String xml = loadXmlFile("capabilities.xml");
        return xml.replace("{{ base_url }}", getBaseUrl());
    }

    @GetMapping(value = "/vo/availability", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
    public String getAvailability() throws IOException {
        String xml = loadXmlFile("availability.xml");
        return xml.replace("{{ base_url }}", getBaseUrl());
    }

    private String loadXmlFile(String fileName) throws IOException {
        try ( InputStream in = DALIController.class.getClassLoader().getResourceAsStream(fileName)) {
            Scanner s = new Scanner(in).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
    }

    /**
     * Generate base URL considering also proxied requests.
     */
    private String getBaseUrl() {

        String forwaredProtocol = request.getHeader("X-Forwarded-Proto");
        String scheme = forwaredProtocol != null ? forwaredProtocol : request.getScheme();

        String forwardedHost = request.getHeader("X-Forwarded-Host");
        if (forwardedHost != null && forwardedHost.contains(",")) {
            // X-Forwarded-Host can be a list of comma separated values
            forwardedHost = forwardedHost.split(",")[0];
        }
        String host = forwardedHost != null ? forwardedHost : request.getServerName();

        UriComponentsBuilder builder = UriComponentsBuilder.newInstance()
                .scheme(scheme).host(host).path(request.getContextPath());

        if (forwardedHost == null) {
            builder.port(request.getServerPort());
        }

        return builder.toUriString();
    }
}