HmiSchemaBootstrap.java

package com.workbenchclassic.hmi;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Idempotent schema creation on deployment for Oracle and SQL Server.
 * Existing CUST schema is used; no DBA user/schema creation on Oracle.
 * DDL runs under the permissions of dsCustNJTA (must have CREATE TABLE).
 */
public final class HmiSchemaBootstrap implements ServletContextListener {
    private static final Logger LOG = Logger.getLogger(HmiSchemaBootstrap.class.getName());
    private static final Object START_LOCK = new Object();
    private static volatile boolean ready = false;
    private static volatile String state = "Not initialized";
    // The public health endpoint exposes only fixed diagnostic codes, never SQL errors or connection credentials.
    private static volatile String phase = "NOT_STARTED";
    private static volatile String code = "NONE";
    private static volatile boolean poolConnected = false;
    private static volatile String databaseKind = "UNKNOWN";
    static boolean isReady() { return ready; }
    static String state() { return state; }
    static String phase() { return phase; }
    static String failureCode() { return code; }
    static boolean poolConnected() { return poolConnected; }
    static String databaseKind() { return databaseKind; }


    static void retryInitialization() { new HmiSchemaBootstrap().contextInitialized(null); }

    @Override public void contextInitialized(ServletContextEvent event) {
        synchronized (START_LOCK) {
        ready = false;
        poolConnected = false;
        databaseKind = "UNKNOWN";
        code = "NONE";
        phase = "DATASOURCE_LOOKUP";
        try (Connection c = HmiDb.open()) {
            poolConnected = true;
            phase = "DATABASE_DETECTION";
            String product = c.getMetaData().getDatabaseProductName().toLowerCase(Locale.ROOT);
            boolean oracle = product.contains("oracle");
            boolean sqlServer = product.contains("microsoft sql server") || product.contains("sql server");
            if (!oracle && !sqlServer) {
                code = "UNSUPPORTED_DATABASE";
                throw new SQLException("Unsupported dsCustNJTA database: " + product);
            }
            databaseKind = oracle ? "ORACLE" : "SQL_SERVER";
            phase = "SCHEMA_CHECK";
            if (sqlServer) createSqlServerSchema(c);
            else assertOracleSchemaExists(c);

            phase = "SCHEMA_INITIALIZATION";
            String prefix = oracle ? "CUST." : "cust.";
            String text = oracle ? "CLOB" : "NVARCHAR(MAX)";
            String shortText = oracle ? "VARCHAR2" : "NVARCHAR";
            String numeric = oracle ? "NUMBER(10)" : "INT";
            String date = oracle ? "TIMESTAMP" : "DATETIME2";
            String now = oracle ? "SYSTIMESTAMP" : "SYSUTCDATETIME()";
            createIfMissing(c, "HMI_APP_PAGE", "CREATE TABLE " + prefix + "HMI_APP_PAGE ("
                + "ID " + shortText + "(64) NOT NULL PRIMARY KEY, PAGE_KEY " + shortText + "(120) NOT NULL UNIQUE, "
                + "TITLE " + shortText + "(255) NOT NULL, MENU_GROUP " + shortText + "(120), "
                + "PARENT_PAGE_ID " + shortText + "(64), "
                + "SORT_ORDER " + numeric + " DEFAULT 0 NOT NULL, ENABLED " + numeric + " DEFAULT 1 NOT NULL)");
            // V5.2: compatible migration for existing Oracle and SQL Server installations.
            // Never drops or recreates HMI_APP_PAGE, preserving all published templates/layouts.
            addParentPageColumnIfMissing(c, oracle);
            createIfMissing(c, "HMI_APP_TEMPLATE", "CREATE TABLE " + prefix + "HMI_APP_TEMPLATE ("
                + "ID " + shortText + "(64) NOT NULL PRIMARY KEY, PAGE_ID " + shortText + "(64) NOT NULL, "
                + "VERSION_NO " + numeric + " NOT NULL, STATUS " + shortText + "(20) NOT NULL, "
                + "LAYOUT_JSON " + text + " NOT NULL, UPDATED_BY " + shortText + "(255), "
                + "UPDATED_AT " + date + " DEFAULT " + now + " NOT NULL)");
            createIfMissing(c, "HMI_APP_ASSIGNMENT", "CREATE TABLE " + prefix + "HMI_APP_ASSIGNMENT ("
                + "ID " + shortText + "(64) NOT NULL PRIMARY KEY, PAGE_ID " + shortText + "(64) NOT NULL, "
                + "SCOPE_TYPE " + shortText + "(20) NOT NULL, SCOPE_ID " + shortText + "(255) NOT NULL, "
                + "TEMPLATE_ID " + shortText + "(64) NOT NULL, PRIORITY " + numeric + " DEFAULT 0 NOT NULL)");
            createIfMissing(c, "HMI_APP_LAYOUT", "CREATE TABLE " + prefix + "HMI_APP_LAYOUT ("
                + "USER_ID " + shortText + "(255) NOT NULL, PAGE_ID " + shortText + "(64) NOT NULL, "
                + "STATION_ID " + shortText + "(120) DEFAULT '*' NOT NULL, BASE_TEMPLATE_ID " + shortText + "(64), OVERRIDES_JSON " + text + " NOT NULL, "
                + "UPDATED_AT " + date + " DEFAULT " + now + " NOT NULL, "
                + "PRIMARY KEY (USER_ID, PAGE_ID, STATION_ID))");
            createIfMissing(c, "HMI_APP_PREF", "CREATE TABLE " + prefix + "HMI_APP_PREF ("
                + "SCOPE_TYPE " + shortText + "(20) NOT NULL, SCOPE_ID " + shortText + "(255) NOT NULL, "
                + "PREFS_JSON " + text + " NOT NULL, UPDATED_AT " + date + " DEFAULT " + now + " NOT NULL, "
                + "PRIMARY KEY (SCOPE_TYPE, SCOPE_ID))");
            createIfMissing(c, "HMI_APP_GROUP_MEMBER", "CREATE TABLE " + prefix + "HMI_APP_GROUP_MEMBER ("
                + "USER_ID " + shortText + "(255) NOT NULL, GROUP_ID " + shortText + "(120) NOT NULL, "
                + "PRIMARY KEY (USER_ID, GROUP_ID))");
            createIfMissing(c, "HMI_APP_AUDIT", "CREATE TABLE " + prefix + "HMI_APP_AUDIT ("
                + "ID " + shortText + "(64) NOT NULL PRIMARY KEY, ACTOR " + shortText + "(255) NOT NULL, "
                + "ACTION_NAME " + shortText + "(120) NOT NULL, ENTITY_ID " + shortText + "(255), "
                + "DETAILS " + shortText + "(1000), CREATED_AT " + date + " DEFAULT " + now + " NOT NULL)");
            // Versioned ios.css content, separate from the immutable WAR fallback.
            createIfMissing(c, "HMI_APP_CSS_REVISION", "CREATE TABLE " + prefix + "HMI_APP_CSS_REVISION ("
                + "ID " + shortText + "(64) NOT NULL PRIMARY KEY, VERSION_NO " + numeric + " NOT NULL UNIQUE, "
                + "STATUS " + shortText + "(20) NOT NULL, CSS_CONTENT " + text + " NOT NULL, "
                + "UPDATED_BY " + shortText + "(255), UPDATED_AT " + date + " DEFAULT " + now + " NOT NULL)");
            // V5: Person-oriented roles, groups and uploaded HMI image assets.
            String binary = oracle ? "BLOB" : "VARBINARY(MAX)";
            createIfMissing(c, "HMI_APP_ROLE", "CREATE TABLE " + prefix + "HMI_APP_ROLE ("
                + "ROLE_KEY " + shortText + "(120) NOT NULL PRIMARY KEY, DESCRIPTION " + shortText + "(255))");
            createIfMissing(c, "HMI_APP_GROUP_DEF", "CREATE TABLE " + prefix + "HMI_APP_GROUP_DEF ("
                + "GROUP_KEY " + shortText + "(120) NOT NULL PRIMARY KEY, DESCRIPTION " + shortText + "(255))");
            createIfMissing(c, "HMI_APP_GROUP_ROLE", "CREATE TABLE " + prefix + "HMI_APP_GROUP_ROLE ("
                + "GROUP_KEY " + shortText + "(120) NOT NULL, ROLE_KEY " + shortText + "(120) NOT NULL, PRIMARY KEY (GROUP_KEY,ROLE_KEY))");
            createIfMissing(c, "HMI_APP_PERSON_ROLE", "CREATE TABLE " + prefix + "HMI_APP_PERSON_ROLE ("
                + "PERS_ID " + shortText + "(120) NOT NULL, ROLE_KEY " + shortText + "(120) NOT NULL, PRIMARY KEY (PERS_ID,ROLE_KEY))");
            createIfMissing(c, "HMI_APP_PERSON_GROUP", "CREATE TABLE " + prefix + "HMI_APP_PERSON_GROUP ("
                + "PERS_ID " + shortText + "(120) NOT NULL, GROUP_KEY " + shortText + "(120) NOT NULL, PRIMARY KEY (PERS_ID,GROUP_KEY))");
            createIfMissing(c, "HMI_APP_LOGIN_PERSON", "CREATE TABLE " + prefix + "HMI_APP_LOGIN_PERSON ("
                + "LOGIN_ID " + shortText + "(255) NOT NULL PRIMARY KEY, PERS_ID " + shortText + "(120) NOT NULL)");
            // First-run administration: one permanent, database-locked claim marker.
            createIfMissing(c, "HMI_APP_BOOTSTRAP", "CREATE TABLE " + prefix + "HMI_APP_BOOTSTRAP ("
                + "ID " + shortText + "(24) NOT NULL PRIMARY KEY, CLAIMED_BY " + shortText + "(255), CLAIMED_AT " + date + ")");
            try(PreparedStatement ps=c.prepareStatement("SELECT ID FROM " + prefix + "HMI_APP_BOOTSTRAP WHERE ID='GLOBAL'");
                ResultSet rs=ps.executeQuery()) {
                if(!rs.next())try(PreparedStatement insert=c.prepareStatement(
                    "INSERT INTO " + prefix + "HMI_APP_BOOTSTRAP(ID) VALUES ('GLOBAL')")) {
                    try{insert.executeUpdate();}catch(SQLException concurrent){
                        try(PreparedStatement chk=c.prepareStatement("SELECT ID FROM " + prefix + "HMI_APP_BOOTSTRAP WHERE ID='GLOBAL'");
                            ResultSet check=chk.executeQuery()){if(!check.next())throw concurrent;}
                    }
                }
            }
            createIfMissing(c, "HMI_APP_ASSET", "CREATE TABLE " + prefix + "HMI_APP_ASSET ("
                + "ID " + shortText + "(64) NOT NULL PRIMARY KEY, ORIGINAL_NAME " + shortText + "(255) NOT NULL, "
                + "MIME_TYPE " + shortText + "(80) NOT NULL, CONTENT " + binary + " NOT NULL, "
                + "CONTENT_SIZE " + numeric + " NOT NULL, UPDATED_BY " + shortText + "(255) NOT NULL)");
            createIfMissing(c, "HMI_APP_SCHEMA_VERSION", "CREATE TABLE " + prefix + "HMI_APP_SCHEMA_VERSION ("
                + "VERSION_NO " + numeric + " NOT NULL PRIMARY KEY, INSTALLED_AT " + date + " DEFAULT " + now + " NOT NULL)");
            // Fail closed when a v1 schema exists: do not alter existing PKs on a production database.
            // See hmi-docs/migrate-v1-to-v2-*.sql for non-destructive, operator-reviewed migration.
            phase = "SCHEMA_VERIFICATION";
            verifyLayoutStationKey(c, oracle);
            try (PreparedStatement check = c.prepareStatement("SELECT VERSION_NO FROM " + prefix + "HMI_APP_SCHEMA_VERSION WHERE VERSION_NO = 7");
                 ResultSet rs = check.executeQuery()) {
                if (!rs.next()) {
                    try (PreparedStatement insert = c.prepareStatement("INSERT INTO " + prefix + "HMI_APP_SCHEMA_VERSION(VERSION_NO) VALUES (7)")) {
                        insert.executeUpdate();
                    } catch (SQLException concurrent) { // A second cluster member may have inserted simultaneously.
                        try (PreparedStatement confirm = c.prepareStatement("SELECT VERSION_NO FROM " + prefix + "HMI_APP_SCHEMA_VERSION WHERE VERSION_NO = 7");
                             ResultSet rs2 = confirm.executeQuery()) {
                            if (!rs2.next()) throw concurrent;
                        }
                    }
                }
            }
            HmiDb.useDatabase(oracle);
            ready = true;
            HmiInitialAdmin.initialize(c);
            HmiSchemaRecovery.clear();
            phase = "READY";
            code = "NONE";
            state = "Initialized: " + product + ", schema " + (oracle ? "CUST" : "cust") + ", version 7";
            LOG.info("HMI " + state);
        } catch (Exception ex) {
            ready = false;
            if ("NONE".equals(code)) {
                if (!poolConnected) code = "POOL_CONNECTION_FAILED";
                else if ("SCHEMA_VERIFICATION".equals(phase)) code = "SCHEMA_MIGRATION_REQUIRED";
                else if ("SCHEMA_INITIALIZATION".equals(phase) || "SCHEMA_CHECK".equals(phase)) code = "SCHEMA_SETUP_FAILED";
                else code = "DATABASE_ERROR";
            }
            state = "Database initialization failed; inspect GlassFish logs";
            HmiSchemaRecovery.enableAfterFailure();
            LOG.log(Level.SEVERE, "HMI schema initialization FAILED [" + code + ", phase=" + phase + "]; HMI endpoints remain unavailable", ex);
        }
        } // START_LOCK
    }

    private boolean pageParentColumnExists(Connection c, boolean oracle) throws SQLException {
        DatabaseMetaData md = c.getMetaData();
        String schemaName = oracle ? "CUST" : "cust";
        try (ResultSet rs = md.getColumns(null, schemaName, "HMI_APP_PAGE", "PARENT_PAGE_ID")) {
            if (rs.next()) return true;
        }
        // Some SQL Server drivers return the schema with different capitalization.
        try (ResultSet rs = md.getColumns(null, schemaName.toUpperCase(Locale.ROOT), "HMI_APP_PAGE", "PARENT_PAGE_ID")) {
            return rs.next();
        }
    }
    private void addParentPageColumnIfMissing(Connection c, boolean oracle) throws SQLException {
        if (pageParentColumnExists(c, oracle)) return;
        String ddl = oracle
            ? "ALTER TABLE CUST.HMI_APP_PAGE ADD (PARENT_PAGE_ID VARCHAR2(64))"
            : "ALTER TABLE cust.HMI_APP_PAGE ADD PARENT_PAGE_ID NVARCHAR(64) NULL";
        try (Statement st = c.createStatement()) {
            st.execute(ddl);
            LOG.info("HMI schema V5.2: added HMI_APP_PAGE.PARENT_PAGE_ID");
        } catch (SQLException error) {
            // A second GlassFish instance might have applied the same migration.
            if (!pageParentColumnExists(c, oracle)) throw error;
        }
    }

    private void verifyLayoutStationKey(Connection c, boolean oracle) throws SQLException {
        DatabaseMetaData md = c.getMetaData();
        String schema = oracle ? "CUST" : "cust";
        boolean station = false, user = false, page = false;
        try (ResultSet columns = md.getColumns(null, schema, "HMI_APP_LAYOUT", "STATION_ID")) {
            if (!columns.next()) throw new SQLException("HMI schema v1 layout detected (STATION_ID missing); apply documented v1 to v2 migration");
        }
        try (ResultSet pk = md.getPrimaryKeys(null, schema, "HMI_APP_LAYOUT")) {
            while (pk.next()) {
                String name = pk.getString("COLUMN_NAME");
                station |= "STATION_ID".equalsIgnoreCase(name);
                user |= "USER_ID".equalsIgnoreCase(name);
                page |= "PAGE_ID".equalsIgnoreCase(name);
            }
        }
        if (!station || !user || !page) {
            throw new SQLException("HMI_APP_LAYOUT requires composite primary key USER_ID, PAGE_ID, STATION_ID; apply documented v1 to v2 migration");
        }
    }
    private void createSqlServerSchema(Connection c) throws SQLException {
        try (Statement st = c.createStatement()) {
            st.execute("IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'cust') EXEC('CREATE SCHEMA cust')");
        }
    }
    private void assertOracleSchemaExists(Connection c) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement("SELECT 1 FROM ALL_USERS WHERE USERNAME = 'CUST'");
             ResultSet rs = ps.executeQuery()) {
            if (!rs.next()) throw new SQLException("Oracle schema CUST does not exist. Provision it first using DBA privileges.");
        }
    }
    private void createIfMissing(Connection c, String table, String ddl) throws SQLException {
        if (exists(c, table)) return;
        try (Statement st = c.createStatement()) {
            st.execute(ddl);
            LOG.info("Created HMI table CUST." + table);
        } catch (SQLException e) {
            if (!exists(c, table)) throw e; // Only suppress a concurrent, successful table creation.
        }
    }
    private boolean exists(Connection c, String table) throws SQLException {
        DatabaseMetaData m = c.getMetaData();
        try (ResultSet rs = m.getTables(null, "CUST", table, new String[]{"TABLE"})) {
            if (rs.next()) return true;
        }
        try (ResultSet rs = m.getTables(null, "cust", table, new String[]{"TABLE"})) {
            return rs.next();
        }
    }
    @Override public void contextDestroyed(ServletContextEvent event) { ready = false; phase = "STOPPED"; }
}