Maven.java

package build;

import client.teavm.common.parameter.event.ExportEventParameters;
import client.teavm.common.parameter.event.ImportEventParameters;
import client.teavm.common.parameter.usage.EventSchemaUsageFormatter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.internal.DefaultConsole;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.healthmarketscience.jackcess.*;
import jakarta.annotation.Nonnull;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebServlet;
import libsidutils.IOUtils;
import libsidutils.siddatabase.SidDatabase;
import libsidutils.stil.STIL;
import net.java.truevfs.access.TArchiveDetector;
import net.java.truevfs.access.TFile;
import net.java.truevfs.access.TVFS;
import server.restful.JSIDPlay2Server;
import server.restful.common.parameter.ServletParameterHelper;
import server.restful.common.parameter.ServletsParameters;
import server.restful.common.parameter.UsageParameter;
import server.restful.common.parameter.usage.ServletsUsageFormatter;
import sidplay.Player;
import sidplay.ini.IniDefaults;
import sidplay.player.DebugUtil;
import ui.common.download.DownloadThread;
import ui.common.util.Extract7ZipUtil;
import ui.entities.DatabaseType;
import ui.entities.PersistenceProperties;
import ui.musiccollection.MusicCollectionType;
import ui.musiccollection.search.SearchIndexCreator;
import ui.musiccollection.search.SearchIndexerThread;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.logging.Logger;
import java.util.stream.Stream;

import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static libsidutils.IOUtils.*;
import static ui.entities.PersistenceProperties.CGSC_DS;
import static ui.entities.PersistenceProperties.HVSC_DS;
import static ui.musiccollection.MusicCollectionType.CGSC;

/**
 * Helper class to support maven build and create all the optional downloadable content of our web-server during
 * deployment.
 *
 * @author ken
 *
 */
public class Maven {

    static {
        DebugUtil.init();
        System.setProperty("com.mysql.cj.disableAbandonedConnectionCleanup", "true");
    }

    @Parameters(resourceBundle = BUNDLE_MAVEN)
    private static final class MavenParameters extends UsageParameter {

        @Parameters(commandNames = CMD_PREPARE_PACKAGE, commandDescriptionKey = "CMD_PREPARE_PACKAGE", resourceBundle = BUNDLE_MAVEN)
        private static final class PreparePackageParameters {

            @Parameter(names = {"--baseDir"}, required = true, descriptionKey = "BASE_DIR", order = 0)
            private String baseDir;

            @Parameter(names = {"--classesDir"}, required = true, descriptionKey = "CLASSES_DIR", order = 1)
            private String classesDir;

        }

        @Parameters(commandNames = CMD_PACKAGE, commandDescriptionKey = "CMD_PACKAGE", resourceBundle = BUNDLE_MAVEN)
        private static final class PackageParameters {

            @Parameter(names = {"--standaloneDir"}, required = true, descriptionKey = "STANDALONE_DIR", order = 0)
            private String standaloneDir;

        }

        @Parameters(commandNames = CMD_INSTALL, commandDescriptionKey = "CMD_INSTALL", resourceBundle = BUNDLE_MAVEN)
        private static final class InstallParameters {

            @Parameter(names = {"--baseDir"}, required = true, descriptionKey = "BASE_DIR", order = 0)
            private String baseDir;

            @Parameter(names = {"--deployDir"}, required = true, descriptionKey = "DEPLOY_DIR", order = 1)
            private String deployDir;

            @Parameter(names = {"--projectVersion"}, required = true, descriptionKey = "PROJECT_VERSION", order = 2)
            private String projectVersion;

            @Parameter(names = {"--upxExe"}, descriptionKey = "UPX_EXE", order = 3)
            private String upxExe = "";

            @Parameter(names = {"--gb64"}, descriptionKey = "GB64", order = 4)
            private String gb64 = "";

            @Parameter(names = {"--hvmec"}, descriptionKey = "HVMEC", order = 5)
            private String hvmec = "";

            @Parameter(names = {"--cgsc"}, descriptionKey = "CGSC", order = 6)
            private String cgsc = "";

            @Parameter(names = {"--hvsc"}, descriptionKey = "HVSC", order = 7)
            private String hvsc = "";

        }

    }

    private static final Logger LOG = Logger.getLogger(Maven.class.getName());

    private static final String BUNDLE_MAVEN = "build.MavenParameters";

    private static final String CMD_PREPARE_PACKAGE = "prepare-package";
    private static final String CMD_PACKAGE = "package";
    private static final String CMD_INSTALL = "install";

    private static final String SERVLET_CLASSES_LIST = "src/main/resources/tomcat-servlets.list";

    private static final String FILTER_CLASSES_LIST = "src/main/resources/tomcat-filters.list";

    private static final String EVENT_PARAMETERS_TXT = "src/main/resources/server/restful/webapp/teavm/README-API.txt";
    private static final String EVENT_JS_PATH = "src/main/resources/server/restful/webapp/teavm/event-api.js";

    private static final String SERVLETS_PARAMETERS_PATH = "src/main/asciidoc/restful-api.adoc";

    private static final String CONVERT_OPTIONS_TS = "src/main/resources/server/restful/webapp/teavm/convertOptions.ts";

    private static final String AUTO_GENERATED_BY_CLASS_BUILD_MAVEN = "// Code generated by " + Maven.class
            + "; DO NOT EDIT.%n";

    private static final String CONVERT_STUB_COMMENT = "// Solely purpose of this stub is to help using IDE's context assistant!\n";

    private static final int MAX_ZIP_FILESIZE = 37748736;

    private static final int CHUNK_SIZE = 1 << 20;

    private void execute(String[] args) throws Exception {
        MavenParameters mavenParameters = new MavenParameters();
        MavenParameters.PreparePackageParameters preparePackageParameters = new MavenParameters.PreparePackageParameters();
        MavenParameters.PackageParameters packageParameters = new MavenParameters.PackageParameters();
        MavenParameters.InstallParameters installParameters = new MavenParameters.InstallParameters();

        JCommander commander = JCommander.newBuilder().addObject(mavenParameters).addCommand(preparePackageParameters)
                .addCommand(packageParameters).addCommand(installParameters).programName(getClass().getName()).build();

        commander.parse(Arrays.stream(args).map(arg -> arg == null ? "" : arg).toArray(String[]::new));
        if (commander.getParsedCommand() == null || mavenParameters.getHelp()) {
            commander.usage();
            System.out.println("Press <enter> to exit!");
            ioWrap(() -> System.in.read());
            System.exit(0);
        }

        if (CMD_PREPARE_PACKAGE.equals(commander.getParsedCommand())) {

            List<String> servletParameterClassNames = createServerClzListAndCheck(preparePackageParameters.baseDir,
                    preparePackageParameters.classesDir);
            createWebWorkerApiDocs(preparePackageParameters.baseDir);
            createServletApiDocs(preparePackageParameters.baseDir, servletParameterClassNames);

        } else if (CMD_PACKAGE.equals(commander.getParsedCommand())) {

            replaceResourceInJar(packageParameters.standaloneDir + "/hardsid-usb-driver-library-java-1.1.jar",
                    "org/usb4java/win32-x86/", "src/main/resources/win32-x86/libusb4java.dll");
            replaceResourceInJar(packageParameters.standaloneDir + "/hardsid-usb-driver-library-java-1.1.jar",
                    "org/usb4java/win32-x86-64/", "src/main/resources/win32-x86-64/libusb4java.dll");

        } else if (CMD_INSTALL.equals(commander.getParsedCommand())) {

            if (!installParameters.upxExe.isEmpty()) {
                upx(installParameters.deployDir, installParameters.upxExe, installParameters.projectVersion);
            }
            createDemos(installParameters.baseDir, installParameters.deployDir);

            if (!installParameters.gb64.isEmpty()) {
                gb64(installParameters.deployDir, installParameters.gb64);
            }
            if (!installParameters.hvmec.isEmpty()) {
                hvmec(installParameters.deployDir, installParameters.hvmec);
            }
            if (!installParameters.cgsc.isEmpty()) {
                cgsc(installParameters.deployDir, installParameters.cgsc);
            }
            if (!installParameters.hvsc.isEmpty()) {
                hvsc(installParameters.deployDir, installParameters.hvsc);
            }
            latestVersion(installParameters.baseDir, installParameters.projectVersion);
        }
    }

    private void upx(String deployDir, String upxExe, String projectVersion) throws IOException, InterruptedException {
        if (!new File(upxExe).exists() || !new File(upxExe).canExecute()) {
            System.err.println("Warning: UPX Program not found or not executable: " + upxExe);
            return;
        }
        Process proc = Runtime.getRuntime().exec(new String[]{upxExe, "--lzma", "--best",
                /* "--ultra-brute", */deployDir + "/jsiddevice-" + projectVersion + ".exe"});

        IOUtils.copy(proc.getErrorStream(), System.err);
        IOUtils.copy(proc.getInputStream(), System.out);

        proc.waitFor();
    }

    private void createDemos(String baseDir, String deployDir) throws IOException {
        ioWrap(new File(deployDir, "online/demos")::mkdirs);

        File demosZipFile = new File(deployDir, "online/demos/Demos.zip");
        File source = new File(baseDir, "src/test/resources/demos/Demos.zip");
        Files.copy(Paths.get(source.toURI()), Paths.get(demosZipFile.toURI()), REPLACE_EXISTING);

        createCRC(demosZipFile, new File(deployDir, "online/demos/Demos.crc"));
    }

    private void gb64(String deployDir, String gb64) throws IOException, SQLException {
        File mdbFile = new File(gb64);
        if (mdbFile.exists()) {
            ioWrap(new File(deployDir, "online/gamebase")::mkdirs);

            File mdbZipFile = new File(deployDir, "/online/gamebase/GameBase64.zip");
            TFile.cp_rp(mdbFile, new TFile(mdbZipFile, mdbFile.getName()), TArchiveDetector.ALL);

            File hsqlFile = new File(deployDir, "/online/gamebase/GameBase64");
            migrate(mdbFile, hsqlFile);
            TFile.cp(new File(hsqlFile.getAbsolutePath() + ".properties"), new TFile(mdbZipFile, hsqlFile.getName() + ".properties"));
            TFile.cp(new File(hsqlFile.getAbsolutePath() + ".script"), new TFile(mdbZipFile, hsqlFile.getName() + ".script"));
            File dataFile = new File(hsqlFile.getAbsolutePath() + ".data");
            if (dataFile.exists()) {
                TFile.cp(dataFile, new TFile(mdbZipFile, hsqlFile.getName() + ".data"));
            }

            TVFS.umount();

            ioWrap(new File(hsqlFile.getAbsolutePath() + ".properties")::delete);
            ioWrap(new File(hsqlFile.getAbsolutePath() + ".script")::delete);
            if (dataFile.exists()) {
                ioWrap(new File(hsqlFile.getAbsolutePath() + ".data")::delete);
            }

            createCRC(mdbZipFile, new File(deployDir, "online/gamebase/GameBase64.crc"));
        }
    }

    private void hvmec(String deployDir, String hvmec) throws IOException {
        File hvmecFile = new File(hvmec);
        if (hvmecFile.exists()) {
            ioWrap(new File(deployDir, "online/hvmec")::mkdirs);

            File hvmecZipFile = new File(deployDir, "/online/hvmec/HVMEC.zip");
            TFile.cp_rp(hvmecFile, hvmecZipFile, TArchiveDetector.ALL);
            TVFS.umount();

            createCRC(hvmecZipFile, new File(deployDir, "online/hvmec/HVMEC.crc"));
        }
    }

    private void cgsc(String deployDir, String cgsc) throws Exception {
        File cgsc7zFile = new File(cgsc);
        if (cgsc7zFile.exists()) {
            ioWrap(new File(deployDir, "online/cgsc")::mkdirs);

            System.out.println("Extracting archive, please wait a moment...");
            File cgscZipFile = new File(deployDir, "/online/cgsc/CGSC.zip");
            Extract7ZipUtil extract7Zip = new Extract7ZipUtil(new File(cgsc), new File(deployDir, "online/cgsc"));
            extract7Zip.extract();

            TFile.cp_rp(new File(deployDir, "online/cgsc/CGSC"), new TFile(cgscZipFile), TArchiveDetector.ALL);
            TVFS.umount();

            deleteDirectory(new File(deployDir, "online/cgsc/CGSC"));

            createCRC(cgscZipFile, new File(deployDir, "online/cgsc/CGSC.crc"));

            doCreateIndex(MusicCollectionType.CGSC, cgscZipFile.getAbsolutePath());
        }
    }

    private void hvsc(String deployDir, String hvsc) throws Exception {
        File hvsc7zFile = new File(hvsc);
        if (hvsc7zFile.exists()) {
            ioWrap(new File(deployDir, "online/hvsc")::mkdirs);

            System.out.println("Extracting archive, please wait a moment...");
            File hvscZipFile = new File(deployDir, "/online/hvsc/C64Music.zip");
            Extract7ZipUtil extract7Zip = new Extract7ZipUtil(new File(hvsc), new File(deployDir, "online/hvsc"));
            extract7Zip.extract();

            TFile.cp_rp(new File(deployDir, "online/hvsc/C64Music"), new TFile(hvscZipFile), TArchiveDetector.ALL);
            TVFS.umount();

            deleteDirectory(new File(deployDir, "online/hvsc/C64Music"));

            createCRC(hvscZipFile, new File(deployDir, "online/hvsc/C64Music.crc"));

            doCreateIndex(MusicCollectionType.HVSC, hvscZipFile.getAbsolutePath());

            doSplit(hvscZipFile.getAbsolutePath());

            ioWrap(hvscZipFile::delete);
        }
    }

    private void latestVersion(String baseDir, String projectVersion)
            throws IOException {
        File versionFile = new File(baseDir, "latest.properties");
        ioWrap(versionFile::delete);
        ioWrap2(versionFile::createNewFile);
        try (Writer writer = new PrintWriter(versionFile, ISO_8859_1)) {
            writer.append("version=").append(projectVersion);
        }
    }

    private void doCreateIndex(MusicCollectionType collectionType, String zipFile) throws Exception {
        File rootFile = new TFile(zipFile);

        String persistenceUnitName = collectionType == CGSC ? CGSC_DS : HVSC_DS;
        File dbFilename = new File(rootFile.getParentFile(), collectionType.toString());
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory(persistenceUnitName,
                new PersistenceProperties(DatabaseType.HSQL_FILE, "", "", dbFilename.getAbsolutePath()));
        EntityManager em = emFactory.createEntityManager();

        Player player = new Player(IniDefaults.DEFAULTS);
        if (collectionType == MusicCollectionType.HVSC) {
            setSIDDatabase(player, rootFile);
            setSTIL(player, rootFile);
        }

        CountDownLatch latch = new CountDownLatch(1);
        SearchIndexCreator searchIndexCreator = new SearchIndexCreator(rootFile, player, em);
        Consumer<Void> searchStart = v -> searchIndexCreator.getSearchStart().accept(v);
        Consumer<File> searchHit = searchIndexCreator.getSearchHit();
        Consumer<Boolean> searchStop = cancelled -> {
            try {
                searchIndexCreator.getSearchStop().accept(cancelled);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                latch.countDown();
            }
        };
        new SearchIndexerThread(rootFile, searchStart, searchHit, searchStop).start();

        System.out.println("Creating index, please wait a moment...");
        try {
            if (!latch.await(20, TimeUnit.MINUTES)) {
                System.err.println("Index creation timed out after 20 minutes");
            }
        } catch (InterruptedException e) {
            System.err.println("Interrupted while sleeping!");
        }
        emFactory.close();
    }

    private void setSTIL(Player player, File zipFile) throws NoSuchFieldException, IllegalAccessException {
        try {
            player.setSTIL(new STIL(zipFile));
        } catch (IOException e) {
            System.err.println("WARNING: STIL can not be read: " + e.getMessage());
        }
    }

    private void setSIDDatabase(Player player, File zipFile) {
        try {
            player.setSidDatabase(new SidDatabase(zipFile));
        } catch (IOException e) {
            System.err.println("WARNING: song length database can not be read: " + e.getMessage());
        }
    }

    private void doSplit(String filename) throws IOException {
        int partNum = 1;
        String output = createOutputFilename(filename, partNum);

        byte[] buffer = new byte[CHUNK_SIZE];
        BufferedOutputStream os = null;
        try (BufferedInputStream is = new BufferedInputStream(Files.newInputStream(new File(filename).toPath()), CHUNK_SIZE)) {
            int bytesRead, totalBytesRead = 0;
            os = createOutputStream(output);
            int len = buffer.length;
            while ((bytesRead = is.read(buffer, 0, len)) >= 0) {
                os.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
                len = Math.min(buffer.length, Maven.MAX_ZIP_FILESIZE - totalBytesRead);
                if (totalBytesRead == Maven.MAX_ZIP_FILESIZE) {
                    os.close();
                    ++partNum;
                    output = createOutputFilename(filename, partNum);
                    os = createOutputStream(output);
                    totalBytesRead = 0;
                }
            }
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOG.severe(e.getMessage());
                    LOG.severe("Error closing output stream.");
                }
            }
        }
    }

    public void migrate(File mdb, File hsqlFile) throws IOException, SQLException {
        System.out.println("Migration of GameBase64, please wait a moment...");

        try (Database db = DatabaseBuilder.open(mdb);
             Connection conn = DriverManager.getConnection(
                     "jdbc:hsqldb:file:" + hsqlFile.getAbsolutePath() + ";shutdown=true",
                     "",
                     ""
             )) {
            conn.setAutoCommit(false);

            for (Table table : db) {
                String tableName = table.getName();

                if (tableName.startsWith("~")) {
                    continue; // Access system tables
                }
                System.out.println("Migrating " + tableName);
                migrateTable(table, conn);
            }
            conn.commit();
        }
    }

    private void migrateTable(Table table, Connection conn) throws SQLException {
        String name = table.getName();

        StringBuilder create = new StringBuilder();

        create.append("CREATE TABLE ")
                .append(name)
                .append("(");

        for (Column c : table.getColumns()) {
            create.append(c.getName())
                    .append(" ");
            create.append(mapType(c));
            create.append(",");
        }
        create.setLength(create.length() - 1);
        create.append(")");

        try (Statement st = conn.createStatement()) {
            st.execute(create.toString());
        }
        StringBuilder insert =
                new StringBuilder("INSERT INTO ")
                        .append(name)
                        .append(" VALUES(");

        insert.append("?,".repeat(table.getColumns().size()));
        insert.setLength(insert.length() - 1);
        insert.append(")");

        try (PreparedStatement ps =
                     conn.prepareStatement(insert.toString())) {

            for (Row row : table) {

                int index = 1;
                for (Column c : table.getColumns()) {

                    ps.setObject(
                            index++,
                            row.get(c.getName())
                    );
                }
                ps.addBatch();
            }
            ps.executeBatch();
        }
    }

    private String mapType(Column c) {

        switch (c.getType()) {
            case LONG -> {
                return "INTEGER";
            }
            case INT -> {
                return "SMALLINT";
            }
            case BOOLEAN -> {
                return "BOOLEAN";
            }
            case TEXT -> {
                int length = c.getLength();
                return "VARCHAR(" + length + ")";
            }
            default -> {
                return "LONGVARCHAR";
            }
        }
    }

    private String createOutputFilename(String filename, int partNum) {
        return IOUtils.getFilenameWithoutSuffix(filename) + format(".%03d", partNum);
    }

    private BufferedOutputStream createOutputStream(String filename) throws IOException {
        return new BufferedOutputStream(Files.newOutputStream(new File(filename).toPath()), CHUNK_SIZE);
    }

    private void createCRC(File demosZipFile, File crcFile)
            throws IOException {
        try (Writer writer = new PrintWriter(crcFile, ISO_8859_1)) {
            Properties properties = new Properties();
            properties.setProperty("filename", demosZipFile.getName());
            properties.setProperty("size", String.valueOf(demosZipFile.length()));
            properties.setProperty("crc32", DownloadThread.calculateCRC32(demosZipFile));
            properties.store(writer, null);
        }
    }

    private void replaceResourceInJar(String jarPath, String jarEntryPath, String resourcePath) throws IOException {
        Path originalJar = Paths.get(jarPath);
        String entryToReplace = jarEntryPath + new File(resourcePath).getName();
        Path replacementFile = Paths.get(resourcePath);
        Path newJar = Paths.get(jarPath + ".patched");

        System.out.println("Patch JAR " + jarPath + " replace " + entryToReplace);
        try (JarFile jarFile = new JarFile(originalJar.toFile());
             JarOutputStream jos = new JarOutputStream(Files.newOutputStream(newJar.toFile().toPath()))) {
            byte[] buffer = new byte[CHUNK_SIZE];

            for (JarEntry entry : java.util.Collections.list(jarFile.entries())) {
                if (entry.getName().equals(entryToReplace)) {
                    // Skip original DLL entry
                    continue;
                }
                jos.putNextEntry(new JarEntry(entry.getName()));
                try (InputStream is = jarFile.getInputStream(entry)) {
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        jos.write(buffer, 0, len);
                    }
                }
                jos.closeEntry();
            }
            // Add replacement DLL
            jos.putNextEntry(new JarEntry(entryToReplace));
            try (InputStream is = Files.newInputStream(replacementFile)) {
                int len;
                while ((len = is.read(buffer)) != -1) {
                    jos.write(buffer, 0, len);
                }
            }
            jos.closeEntry();
        }
        Files.move(newJar, originalJar, REPLACE_EXISTING);
    }

    private List<String> createServerClzListAndCheck(String baseDir, String classesDir)
            throws IOException, SecurityException {
        Path base = new File(baseDir).toPath();
        Path root = new File(classesDir).toPath();

        List<String> classNames = new ArrayList<>();
        Files.walkFileTree(root, new SimpleFileVisitor<>() {
            @Override
            public @Nonnull FileVisitResult visitFile(@Nonnull Path path, @Nonnull BasicFileAttributes attrs) {
                String relPath = root.relativize(path).toFile().getPath();
                if (relPath.endsWith(".class")) {
                    classNames.add(IOUtils.getFilenameWithoutSuffix(relPath.replace(File.separatorChar, '.')));
                }
                return FileVisitResult.CONTINUE;
            }
        });
        classNames.sort(String::compareTo);

        List<String> servletClassNames = new ArrayList<>();
        List<String> servletParameterClassNames = new ArrayList<>();
        List<String> filterClassNames = new ArrayList<>();

        for (String clzName : classNames) {
            try {
                Class<?> clz = getClass().getClassLoader().loadClass(clzName);
                if (clz.isAnnotationPresent(WebServlet.class)) {
                    servletClassNames.add(clzName);
                }
                if (clz.isAnnotationPresent(WebFilter.class)) {
                    filterClassNames.add(clzName);
                }
                if (clz.isAnnotationPresent(Parameters.class)) {
                    // Parameter classes are being checked for development errors at build time
                    if (clzName.startsWith(JSIDPlay2Server.class.getPackage().getName() + ".servlets")) {
                        servletParameterClassNames.add(clzName);
                        // ... check server parameters
                        ServletParameterHelper.check(clz, true);
                    } else {
                        for (Class<?> cls : Stream.of(clz, clz.getEnclosingClass()).filter(Objects::nonNull)
                                .toList()) {
                            try {
                                // ... check main parameters
                                cls.getMethod("main", String[].class);
                                ServletParameterHelper.check(clz, false);
                            } catch (NoSuchMethodException ignored) {
                            }
                        }
                    }
                }
            } catch (ClassNotFoundException e) {
                System.out.println("WARNING: ClassNotFoundException " + e.getMessage());
            }
        }
        try (Writer servletsWriter = new OutputStreamWriter(
                Files.newOutputStream(base.resolve(SERVLET_CLASSES_LIST).toFile().toPath()), UTF_8)) {
            servletsWriter.write(format(AUTO_GENERATED_BY_CLASS_BUILD_MAVEN));
            servletsWriter.write(new ObjectMapper().writeValueAsString(servletClassNames));
        }
        try (Writer filtersWriter = new OutputStreamWriter(
                Files.newOutputStream(base.resolve(FILTER_CLASSES_LIST).toFile().toPath()), UTF_8)) {
            filtersWriter.write(format(AUTO_GENERATED_BY_CLASS_BUILD_MAVEN));
            filtersWriter.write(new ObjectMapper().writeValueAsString(filterClassNames));
        }
        return servletParameterClassNames;
    }

    private void createWebWorkerApiDocs(String baseDir) throws IOException, SecurityException {
        Locale originalLocale = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);

        Path base = new File(baseDir).toPath();
        try (PrintStream ps = new PrintStream(base.resolve(EVENT_PARAMETERS_TXT).toFile(), UTF_8)) {
            ps.printf(AUTO_GENERATED_BY_CLASS_BUILD_MAVEN);
            ExportEventParameters.usage(new DefaultConsole(ps));
            ImportEventParameters.usage(new DefaultConsole(ps));
        }
        try (PrintStream ps = new PrintStream(base.resolve(EVENT_JS_PATH).toFile(), UTF_8)) {
            ps.printf(AUTO_GENERATED_BY_CLASS_BUILD_MAVEN);
            ExportEventParameters.usage(new DefaultConsole(ps),
                    jCommander -> new EventSchemaUsageFormatter(jCommander, true));
        }
        try (PrintStream ps = new PrintStream(base.resolve(CONVERT_OPTIONS_TS).toFile(), UTF_8)) {
            ps.printf(AUTO_GENERATED_BY_CLASS_BUILD_MAVEN);
            ps.printf(CONVERT_STUB_COMMENT);
            ps.printf(ServletParameterHelper.CONVERT_OPTIONS_TS);
            ps.printf(ServletParameterHelper.CONVERT_MESSAGES_TS);
        }
        Locale.setDefault(originalLocale);
    }

    private void createServletApiDocs(String baseDir, List<String> servletParameterClassNames)
            throws IOException, SecurityException, ClassNotFoundException, NoSuchMethodException,
            InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Locale originalLocale = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);

        Path base = new File(baseDir).toPath();
        try (PrintStream ps = new PrintStream(base.resolve(SERVLETS_PARAMETERS_PATH).toFile(), UTF_8)) {
            ps.printf(AUTO_GENERATED_BY_CLASS_BUILD_MAVEN);
            ServletsParameters.usage(new DefaultConsole(ps), ServletsUsageFormatter::new,
                    servletParameterClassNames);
        }
        Locale.setDefault(originalLocale);
    }

    public static void main(String[] args) throws Exception {
        new Maven().execute(args);
    }
}