XmlPkgResource.java

/*
 * Copyright © 2024-2026 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.util.List;

import org.ctan.site.domain.catalogue.Pkg;
import org.ctan.site.domain.catalogue.PkgAlias;
import org.ctan.site.stores.PkgStore;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.dropwizard.hibernate.UnitOfWork;
import jakarta.annotation.security.PermitAll;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response.Status;
import lombok.NonNull;

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

    /**
     * The class <code>Version</code> contains the enumeration for the known
     * versions.
     */
    public enum Version {

        V10, V11, V12, V13, V20, V21, V30;

        /**
         * The method <code>of</code> provides means to get a {@link Version}
         * from a string value.
         *
         * @param value the string representation
         * @return the Version
         */
        public static Version of(String value) {

            return switch (value) {
                case "1.0" -> V10;
                case "1.1" -> V11;
                case "1.2" -> V12;
                case "1.3" -> V13;
                case "2.0" -> V20;
                case "2.1" -> V21;
                case "3.0" -> V30;
                default -> throw new WebApplicationException(Status.NOT_FOUND);
            };
        }

        // /**
        // *
        // * @see java.lang.Enum#toString()
        // */
        // @Override
        // public String toString() {
        //
        // return switch (this) {
        // case V10 -> "1.0";
        // case V11 -> "1.1";
        // case V12 -> "1.2";
        // case V13 -> "1.3";
        // case V20 -> "2.0";
        // case V21 -> "2.1";
        // case V30 -> "3.0";
        // default -> throw new WebApplicationException(Status.NOT_FOUND);
        // };
        // }
    }

    /**
     * The field <code>store</code> contains the underlying repository.
     */
    private PkgStore store;

    /**
     * This is the constructor for the class <code>XmlPkgResource</code>.
     *
     * @param store the underlying store
     */
    @SuppressFBWarnings(value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"})
    public XmlPkgResource(@NonNull PkgStore store) {

        this.store = store;
    }

    /**
     * The method <code>getPkgByKey</code> provides means to retrieve an pkg.
     *
     * @param vers the version
     * @param id the key of the pkg
     * @param ref the indicator whether or not to return the references to the
     *     packages pkged by the pkg
     * @return an pkg or {@code null}
     */
    @GET
    @Path("/xml/{vers}/pkg/{id}")
    @PermitAll
    @UnitOfWork(value = "siteDb")
    public String getPkgByKey(
        @NonNull @PathParam("vers") String vers,
        @NonNull @PathParam("id") String id,
        @QueryParam("ref") @DefaultValue("false") Boolean ref,
        @QueryParam("no-dtd") @DefaultValue("false") Boolean noDtd,
        @QueryParam("no-xml") @DefaultValue("false") Boolean noXml) {

        Version version = Version.of(vers);
        var pkg = store.getByKey(id);
        if (pkg == null) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
        var xml = new XmlWriter();
        if (!noXml) {
            xml.outNl("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        }
        if (!noDtd) {
            xml.outNl("<!DOCTYPE entry SYSTEM 'http://www.ctan.org/xml/" + vers
                + "/catalogue.dtd'>");
        }
        xml.outNl("<entry id=\"", id, "\">");
        xml.outFullTag("name", pkg.getName());
        xml.outFullTag("caption", pkg.getCaption("en"));
        var authors = pkg.getAuthors();
        if (authors != null) {
            for (var a : authors) {
                var author = a.getAuthor();
                xml.out("  <authorref id=\"", author.getKey(), "\"");
                // TODO
                // xml.outIf("familyname=", author.getFamilyname());
                // xml.outIf("givenname=", author.getGivenname());
                xml.outNl(" />");
            }
        }
        var copy = pkg.getCopy();
        if (copy != null) {
            for (var cpy : pkg.getCopy()) {
                xml.outNl("  <copyright owner=\"", cpy.getOwner(), "\" year=\"",
                    cpy.getYear(), "\" />");
            }
        }
        var licenses = pkg.getLicenses();
        if (licenses != null) {
            for (var lic : licenses) {
                xml.outNl("  <license type=\"", lic.getKey(), "\" >");
            }
        }
        if (pkg.getVersionNumber() != null || pkg.getVersionDate() != null) {
            xml.out("  <version");
            xml.outIf("number", pkg.getVersionNumber());
            xml.outIf("date", pkg.getVersionDate());
            xml.outNl(" >");
        }
        String description = pkg.getDescription("en");
        xml.outFullTag("description", description);
        var docs = pkg.getDocs();
        if (docs != null) {
            for (var doc : docs) {
                xml.out("  <documentation");
                xml.outIf("details", doc.getDetails());
                xml.outIf("href", doc.getHref());
                xml.outIf("lang", doc.getLang());
                xml.outNl(" >");
            }
        }
        String home = pkg.getHome();
        switch (version) {
            case V10:
            case V11:
            case V12:
            case V13:
            case V20:
            case V21:
                xml.outFullTag("home",
                    home == null ? null : home.replaceAll(",.*", ""));
                break;
            case V30:
                if (home != null) {
                    for (var val : split(home)) {
                        xml.outFullTag("home", val);
                    }
                }
                break;
            default:
                // nothing to do
        }
        switch (version) {
            case V12:
            case V13:
            case V20:
            case V21:
                xml.out("  <contact type=\"support\" href=\"", pkg.getSupport(),
                    "\" />\n");
                xml.out("  <contact type=\"bugs\" href=\"", pkg.getBugs(),
                    "\" />\n");
                xml.out("  <contact type=\"announce\" href=\"",
                    pkg.getAnnounce(),
                    "\" />\n");
                xml.out("  <contact type=\"repository\" href=\"",
                    pkg.getRepository(),
                    "\" />\n");
                xml.out("  <contact type=\"development\" href=\"",
                    pkg.getDevelopment(),
                    "\" />\n");
                break;
            case V30:
                write(xml, pkg.getSupport(), "support");
                write(xml, pkg.getBugs(), "bugs");
                write(xml, pkg.getAnnounce(), "announce");
                write(xml, pkg.getRepository(), "repository");
                write(xml, pkg.getDevelopment(), "development");
                break;
            default:
                // nothing to do
        }
        var ctanPath = pkg.getCtanPath();
        if (ctanPath != null) {
            xml.out("  <ctan path=\"", ctanPath, "\"");
            xml.outNl(">");
        }
        var installPath = pkg.getInstallPath();
        if (installPath != null) {
            xml.outNl("  <install path=\"", installPath, "\">");
        }
        xml.outTagWithAttribute("miktex", "location", pkg.getMiktexLocation());
        xml.outTagWithAttribute("texlive", "location",
            pkg.getTexliveLocation());
        var topics = pkg.getTopics();
        if (topics != null) {
            switch (version) {
                case V10:
                case V11:
                case V12:
                case V13:
                case V20:
                case V21:
                    for (var top : topics) {
                        xml.outNl("  <keyval key=\"topic\" value=\"",
                            top.getKey(),
                            "\" />");
                    }
                    break;
                case V30:
                    for (var top : topics) {
                        xml.outNl("  <topic id=\"", top.getKey(),
                            "\" />");
                    }
                    break;
                default:
                    // nothing to do
            }
        }
        List<PkgAlias> aliases = pkg.getAliases();
        if (aliases != null) {
            switch (version) {
                case V20:
                case V21:
                case V30:
                    for (var it : aliases) {
                        xml.outNl("  <alias id=\"", it.getKey(), "\" />");
                    }
                    break;
                default:
                    // nothing to do
            }
        }
        List<Pkg> also = pkg.getAlso();
        if (also != null && version == Version.V30) {
            for (var it : also) {
                xml.outNl("  <also id=\"", it.getKey(), "\" />");
            }
        }
        String extraIndex = pkg.getExtraIndex();
        switch (version) {
            case V30:
                if (extraIndex != null) {
                    xml.outNl("  <index>", extraIndex, "</index>");
                }
                String extraIndexEn = pkg.getExtraIndexEn();
                if (extraIndexEn != null) {
                    xml.outNl("  <index language=\"en\">", extraIndexEn,
                        "</index>");
                }
                String extraIndexDe = pkg.getExtraIndexDe();
                if (extraIndexDe != null) {
                    xml.outNl("  <index language=\"de\">", extraIndexDe,
                        "</index>");
                }
                break;
            default:
                if (extraIndex != null) {
                    xml.outNl("  <keyval key=\"index\" value=\"", extraIndex,
                        "\" />");
                }
        }
        xml.outNl("</entry>");
        return xml.toString();
    }

    /**
     * The method <code>getPkgs</code> provides means to retrieve a list of pkgs
     * starting with a given pattern.
     *
     * @param vers the version number
     * @param key the key
     * @return a list of matching pkg summaries
     */
    @GET
    @Path("/xml/{vers}/pkgs")
    @PermitAll
    @UnitOfWork(value = "siteDb")
    public String getPkgs(
        @NonNull @PathParam("vers") String vers,
        @QueryParam("key") String key,
        @QueryParam("no-dtd") @DefaultValue("false") Boolean noDtd,
        @QueryParam("no-xml") @DefaultValue("false") Boolean noXml) {

        switch (vers) {
            case "1.0", "1.1", "1.2", "1.3", "2.0", "2.1", "3.0":
                break;
            default:
                throw new WebApplicationException(Status.NOT_FOUND);
        }
        var xml = new XmlWriter();
        if (!noXml) {
            xml.outNl("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        }
        if (!noDtd) {
            xml.outNl(
                "<!DOCTYPE packages SYSTEM 'http://www.ctan.org/xml/" + vers
                    + "/catalogue.dtd'>");
        }
        var list = store.findAllByKeyStartingWith(key != null ? key : "");
        xml.outNl("<packages>");
        for (var p : list) {
            xml.out("  <package key=\"", p.getKey(), "\"");
            xml.outIf("name", p.getName());
            xml.outIf("caption", p.getCaption("en"));
            xml.outNl(" />");
        }
        xml.outNl("</packages>");
        return xml.toString();
    }

    /**
     * The method <code>split</code> provides means to split a string into an
     * array. The elements must be separate by comma. If the value is
     * <code>null</code> then <code>null</code> is returned.
     *
     * @param value the value
     * @return the splitted value
     */
    private String[] split(String value) {

        return value == null ? null : value.split(",");
    }

    /**
     * The method <code>write</code> provides means to write a contact tag to
     * the given writer.
     *
     * @param xml the output stream
     * @param value the value
     * @param type the type
     */
    void write(XmlWriter xml, String value, String type) {

        if (value == null) {
            return;
        }

        for (var val : value.split(",")) {
            xml.out("  <contact type=\"" + type + "\" href=\"", val,
                "\" />\n");
        }
    }

}