# ClassicAppserverView.java

    /*
    ** Module   : ClassicAppserverView.java
    ** Abstract : ClassicAppserverView is a view for displaying and managing classic appserver processes.
    **
    ** Copyright (c) 2024-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description----------------------
    ** 001 GBB 20240930 Created initial version.
    ** 002 GBB 20250403 Extends the new class BaseAppserverWidget.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.admin.client.application.home.console.appservers;

    import com.goldencode.p2j.admin.*;
    import com.goldencode.p2j.admin.client.widget.*;
    import com.goldencode.p2j.admin.client.widget.dialog.*;
    import com.google.gwt.core.client.*;
    import com.google.gwt.event.dom.client.*;
    import com.google.gwt.i18n.shared.*;
    import com.google.gwt.uibinder.client.*;
    import com.google.gwt.user.client.ui.Widget;
    import com.google.gwt.view.client.*;
    import org.gwtbootstrap3.client.ui.Button;
    import org.gwtbootstrap3.client.ui.*;
    import org.gwtbootstrap3.client.ui.gwt.*;
    import org.gwtbootstrap3.client.ui.html.*;

    import java.util.*;
    import java.util.logging.*;

    /** ClassicAppserverView is a view for displaying and managing classic appserver processes. */
    public class ClassicAppserverView
    extends BaseAppserverWidget
    {
       /** GWT UI creator */
       interface Binder
       extends UiBinder<Widget, ClassicAppserverView>
       {}

       /** Main heading widget */
       @UiField
       Heading nameHeading;

       /** Container widget displaying the appserver configs */
       @UiField
       Div configContainer;

       /** Button for the trimming the extra agents */
       @UiField
       Button trimBtn;

       /** Button for the restarting all agents */
       @UiField
       Button restartAllBtn;

       /** Button for starting a new agent */
       @UiField
       Button startAppserverBtn;

       /** Button for force stopping selected agents */
       @UiField
       Button forceStopSelectedBtn;

       /** Button for refreshing the table of agents */
       @UiField
       Button refreshAgentsListBtn;

       /** The table of agents */
       @UiField(provided = true)
       DataGrid<AppserverInfo.AgentInfo> agentsGrid = GridHelper.create();

       /** The data and time formatter */
       private static final DateTimeFormat DATE_FORMAT =
          DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.RFC_2822);

       /** The column names for the agents table. */
       private static final String[] AGENT_COL_NAMES = { "ID", "PID", "Agent Start Time", "State", "Bound",
          "Session Start Time", "Session Procedure", "Client" };

       /** The column widths for the agents table. */
       private static final int[] AGENT_COL_WIDTHS = { 10, 10, 16, 12, 12, 16, 12, 12 };

       /** Class logger */
       private final Logger logger = Logger.getLogger(getClass().getSimpleName());

       /** The acquired locks grid handle */
       private final GridHandle<AppserverInfo.AgentInfo> gridHandle;

       /** The all agents data provider */
       private final ListDataProvider<AppserverInfo.AgentInfo> agentsProvider;

       /** The agents selection model */
       private final MultiSelectionModel<AppserverInfo.AgentInfo> selectionModel;

       /** The appserver info */
       private final AppserverInfo appserverInfo;

       /** The appserver agents */
       private AppserverInfo.AgentInfo[] agentInfos;

       /** Modal dialog manager */
       private final ModalDialogs modalDialogsManager;

       /**
        * Public constructor.
        *
        * @param    appserverInfo
        *           The appserver info.
        * @param    modalDialogsManager
        *           The common modal dialogs manager
        */
       public ClassicAppserverView(AppserverInfo appserverInfo, ModalDialogs modalDialogsManager)
       {
          Binder uiBinder = GWT.create(Binder.class);
          initWidget(uiBinder.createAndBindUi(this));

          this.appserverInfo = appserverInfo;
          this.modalDialogsManager = modalDialogsManager;

          nameHeading.setText((appserverInfo.isMultiSession ? "Multi-session Agent App " : "Classic Appserver ") + appserverInfo.name);

          addConfigRow("Operating mode: ", appserverInfo.operatingMode);
          addConfigRow("Auto start: ", appserverInfo.autoStartTime);
          addConfigRow("PROPATH: ", appserverInfo.propath);
          addConfigRow("Server log filename: ", appserverInfo.logFilename);
          addConfigRow("Server logging level: ", appserverInfo.loggingLevel);
          addConfigRow("Server log file threshold size: ", appserverInfo.logFileThresholdSize);
          addConfigRow("Maximum number of server log files: ", appserverInfo.logFilesMaxNumber);
          addConfigRow("System User: ", appserverInfo.systemUser);
          addConfigRow("FWD process name: ", appserverInfo.fwdProcessName);
          addConfigRow("Enable SSL: ", appserverInfo.enableSsl);
          addConfigRow("Private key alias name: ", appserverInfo.privateKeyAlias);
          addConfigRow("Initial number of servers to start: ", appserverInfo.initialServers);
          addConfigRow("Minimum servers: ", appserverInfo.minServers);
          addConfigRow("Maximum servers: ", appserverInfo.maxServer);
          addConfigRow("Request timeout: ", appserverInfo.requestTimeout);
          addConfigRow("Auto trim timeout: ", appserverInfo.autoTrimTimeout);
          addConfigRow("Activate procedure: ", appserverInfo.activateProc);
          addConfigRow("Deactivate procedure: ", appserverInfo.deactivateProc);
          addConfigRow("Connect procedure: ", appserverInfo.connectProc);
          addConfigRow("Disconnect procedure: ", appserverInfo.disconnectProc);
          addConfigRow("Startup procedure: ", appserverInfo.startupProc);
          addConfigRow("Shutdown procedure: ", appserverInfo.shutdownProc);
          addConfigRow("Startup procedure parameters: ", appserverInfo.startupProcParams);

          gridHandle = initTable(agentsGrid);
          agentsProvider = gridHandle.getDataProvider();
          selectionModel = (MultiSelectionModel<AppserverInfo.AgentInfo>) gridHandle.getSelectionModel();

          setAgentTable(appserverInfo.agentInfos);
       }

       /**
        * Sets up the agents table with new data.
        *
        * @param    agentInfos
        *           The array of agent descriptors.
        */
       @Override
       void setAgentTable(AppserverInfo.AgentInfo[] agentInfos)
       {
          this.agentInfos = agentInfos;
          GridHelper.updateDataProvider(agentsGrid, agentsProvider, agentInfos);
          this.selectionModel.clear();
       }

       /**
        * Returns the array of agents to be printed.
        *
        * @return   See above.
        */
       @Override
       AppserverInfo.AgentInfo[] getPrintableData()
       {
          return agentInfos == null ? new AppserverInfo.AgentInfo[0] : agentInfos;
       }

       /**
        * The button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("trimBtn")
       void onTrim(ClickEvent event)
       {
          logger.info("Trim agents for appserver " + appserverInfo.name);
          modalDialogsManager.showYesNo("Trim",
                                        "The available agents will be trimmed down to the number of the min " +
                                           "agents configured. Continue?",
                                        MessageType.WARNING,
                                        res ->
                                        {
                                           if (res == 0)
                                           {
                                              getUiHandlers().trimAgents(appserverInfo.name);
                                           }
                                        });
       }

       /**
        * The button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("restartAllBtn")
       void onRestartAll(ClickEvent event)
       {
          logger.info("Restart all agents for appserver " + appserverInfo.name);
          modalDialogsManager.showYesNo("Restart",
                                        "All agents will be stopped and started anew. Continue?",
                                        MessageType.WARNING,
                                        res ->
                                        {
                                           if (res == 0)
                                           {
                                              getUiHandlers().restartAgents(appserverInfo.name);
                                           }
                                        });
       }

       /**
        * The button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("startAppserverBtn")
       void onStartAppserver(ClickEvent event)
       {
          logger.info("Start the appserver " + appserverInfo.name);
          modalDialogsManager.showYesNo("Start",
                                        "A new agent will be started for the appserver. Continue?",
                                        MessageType.INFO,
                                        res ->
                                        {
                                           if (res == 0)
                                           {
                                              getUiHandlers().startAppserver(appserverInfo.name);
                                           }
                                        });
       }

       /**
        * The button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("refreshAgentsListBtn")
       void onRefreshAgentsList(ClickEvent event)
       {
          logger.info("Refresh the list of agents for appserver " + appserverInfo.name);
          getUiHandlers().refreshAgents(appserverInfo.name);
       }

       /**
        * The button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("forceStopSelectedBtn")
       void onForceStopSelected(ClickEvent event)
       {
          AppserverInfo.AgentInfo[] agentInfos = this.selectionModel.getSelectedSet()
                                                                    .toArray(new AppserverInfo.AgentInfo[0]);
          if (agentInfos.length == 0)
          {
             modalDialogsManager.showWarning("No agents selected to be stopped.");
             return;
          }
          int[] agentIds = Arrays.stream(agentInfos).mapToInt(agentInfo -> agentInfo.agentId).toArray();
          if (agentIds.length == 0)
          {
             modalDialogsManager.showWarning("No agents selected to be stopped.");
             return;
          }
          logger.info("Force stop agents with ids " + agentIds + " of appserver " + appserverInfo.name);

          modalDialogsManager.showYesNo("Force Stop",
                                        "The selected agents will be force stopped. Continue?",
                                        MessageType.WARNING,
                                        res ->
                                        {
                                           if (res == 0)
                                           {
                                              getUiHandlers().terminateAgents(appserverInfo.name, agentIds);
                                           }
                                        });
       }

       /**
        * Setups the given table view.
        *
        * @param    grid
        *           The given table view
        *
        * @return   The grid handle
        */
       private GridHandle<AppserverInfo.AgentInfo> initTable(DataGrid<AppserverInfo.AgentInfo> grid)
       {
          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col1 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[0],
                                         agentInfo -> agentInfo.agentId == null ? "" :
                                            String.valueOf(agentInfo.agentId),
                                         (a1, a2) -> a1.agentId - a2.agentId);

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col2 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[1],
                                         agentInfo -> agentInfo.pid == null ? "" : String.valueOf(agentInfo.pid));

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col3 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[2],
                                         agentInfo -> agentInfo.agentStartTime == null ? "" :
                                            DATE_FORMAT.format(agentInfo.agentStartTime),
                                         (a1, a2) -> (int) (a1.agentStartTime.getTime() - a2.agentStartTime.getTime()));

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col4 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[3],
                                         agentInfo -> agentInfo.state == null ? "" : agentInfo.state);

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col5 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[4],
                                         agentInfo -> String.valueOf(agentInfo.bound));

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col6 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[5],
                                         agentInfo -> agentInfo.sessionStartTime == null || agentInfo.sessionProcedure == null ? "" :
                                            DATE_FORMAT.format(agentInfo.sessionStartTime),
                                         (a1, a2) -> (int) (a1.sessionStartTime.getTime() - a2.sessionStartTime.getTime()));

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col7 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[6],
                                         agentInfo -> agentInfo.sessionProcedure == null ? "" : agentInfo.sessionProcedure);

          GridHelper.ColumnInfo<AppserverInfo.AgentInfo> col8 =
             new GridHelper.ColumnInfo<>(AGENT_COL_NAMES[7],
                                         agentInfo -> agentInfo.clientType == null ? "" : agentInfo.clientType);

          col1.setWidthInPercents(AGENT_COL_WIDTHS[0]);
          col2.setWidthInPercents(AGENT_COL_WIDTHS[1]);
          col3.setWidthInPercents(AGENT_COL_WIDTHS[2]);
          col4.setWidthInPercents(AGENT_COL_WIDTHS[3]);
          col5.setWidthInPercents(AGENT_COL_WIDTHS[4]);
          col6.setWidthInPercents(AGENT_COL_WIDTHS[5]);
          col7.setWidthInPercents(AGENT_COL_WIDTHS[6]);
          col8.setWidthInPercents(AGENT_COL_WIDTHS[7]);

          return GridHelper.initListGrid(grid, true, true, col1, col2, col3, col4, col5, col6, col7, col8);
       }

       /**
        * Adds new row to the config container, displaying the configuration name and value.
        *
        * @param    label
        *           The name of the config
        * @param    value
        *           The value of the config
        */
       private void addConfigRow(String label, Object value)
       {
          Div div = new Div();
          configContainer.add(div);
          div.add(new Span(label));
          div.add(new Span(value == null ? "" : String.valueOf(value)));
       }
    }