Markdown3Resource.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.content;

import java.io.IOException;
import java.io.StringReader;
import java.util.Map;

import org.ctan.markup.markdown.MarkdownRenderer;

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

/**
 * The class <code>Markdown3Resource</code> contains the controller for the
 * Markdown renderer resource.
 *
 * @author <a href="mailto:gene@ctan.org">Gerd Neugebauer</a>
 */
@Path("/3.0/markdown")
@Produces({MediaType.APPLICATION_JSON})
public class Markdown3Resource {

    /**
     * The field <code>VERSION</code> contains the current version.
     */
    private static final String VERSION = "3.0";

    /**
     * The method <code>getVersion</code> provides means to retrieve the version
     * number of the API.
     *
     * @return a Map with a single attribute <code>version</code> containing the
     *     version number as String.
     */
    @GET
    @Path("/version")
    public Map<String, String> getVersion() {

        return Map.of("version", VERSION);
    }

    /**
     * The method <code>render</code> provides means to translate a markdown
     * text to HTML.
     *
     * @param text the text to expand
     * @return the generated HTML
     */
    @POST
    @PermitAll
    @Path("/render")
    public String render(@NonNull String text) {

        try (var reader = new StringReader(text)) {
            return new MarkdownRenderer(reader, "").render();
        } catch (IOException e) {
            // Does not happen
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

}