XmlDtdResource.java

/*
 * Copyright © 2024-2025 The CTAN Team and individual authors
 *
 * This file is distributed under the 3-clause BSD license.
 * See file LICENSE for details.
 */
package org.ctan.site.resources.catalogue.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

import jakarta.annotation.security.PermitAll;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response.Status;

/**
 * The class <code>XmlDtdResource</code> contains the controller for the DTD
 * resource.
 *
 * @author <a href="mailto:gene@ctan.org">Gerd Neugebauer</a>
 */
@Path("/")
@Produces({MediaType.APPLICATION_XML})
public class XmlDtdResource {

    /**
     * The constant <code>VALUES</code> contains the acceptable values for the
     * version number.
     */
    private static final List<String> VALUES =
        List.of("1.0", "1.1", "1.2", "1.3", "2.0", "2.1");

    /**
     * The method <code>getVersion</code> provides means to retrieve the version
     * number of the API in use.
     *
     * @param vers the version
     * @return the DTD
     */
    @GET
    @Path("/xml/{vers}/catalogue.dtd")
    @PermitAll
    public String getDtd(@PathParam("vers") String vers) {

        if (!VALUES.contains(vers)) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
        try (var stream = XmlDtdResource.class
            .getResourceAsStream("/xml/catalogue.dtd");
            var reader =
                new BufferedReader(
                    new InputStreamReader(stream, StandardCharsets.UTF_8))) {
            var out = new StringWriter();
            reader.transferTo(out);
            return out.toString();
        } catch (IOException e) {
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }
}