MultiSessionAppserverView.java

/*
** Module   : MultiSessionAppserverView.java
** Abstract : MultiSessionAppserverView is a view for displaying and managing multi-session appserver 
**            processes.
**
** Copyright (c) 2024-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- ----------------Description----------------------
** 001 GBB 20240930 Created initial version.
** 002 GBB 20250403 View implemented.
*/
/*
** 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.*;
import org.gwtbootstrap3.client.ui.gwt.*;
import org.gwtbootstrap3.client.ui.html.*;

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

/** View for displaying and managing multi-session agent appserver processes. */
public class MultiSessionAppserverView
extends BaseAppserverWidget
{
   /** GWT UI creator */
   interface Binder
   extends UiBinder<Widget, MultiSessionAppserverView>
   {}

   /** Main heading widget */
   @UiField
   Heading nameHeading;
   
   /** Container widget displaying the appserver configs */
   @UiField
   Div configContainer;
   
   /** Button for the trimming the extra sessions */
   @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 sessions */
   @UiField
   Button forceStopSelectedBtn;

   /** Button for refreshing the table of sessions */
   @UiField
   Button refreshSessionsListBtn;
   
   /** The table of appserver sessions */
   @UiField(provided = true)
   DataGrid<MultiSessionAgentSessionDef> sessionsGrid = 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[] SESSION_COL_NAMES = { "Agent Id", "Session Id", "Session Start Time", 
      "State", "Bound", "Connection Model", "Procedure", "Procedure Start Time", "Client" };

   /** The column widths for the agents table. */
   private static final int[] SESSION_COL_WIDTHS = { 4, 4, 16, 10, 10, 16, 20, 16, 4 };
   
   /** Class logger */
   private final Logger logger = Logger.getLogger(getClass().getSimpleName());
   
   /** The appserver info */
   private final AppserverInfo appserverInfo;

   /** The appserver session infos */
   private MultiSessionAgentSessionDef[] sessionInfos;

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

   /** The acquired locks grid handle */
   private final GridHandle<MultiSessionAgentSessionDef> gridHandle;

   /** The all sessions data provider */
   private final ListDataProvider<MultiSessionAgentSessionDef> sessionsProvider;

   /** The agents selection model */
   private final MultiSelectionModel<MultiSessionAgentSessionDef> selectionModel;
   
   /**
    * Constructs this dialog used by by MPV gwtplatform of ArcBees Inc.
    *
    * @param    appserverInfo
    *           The appserver info.
    * @param    modalDialogsManager
    *           The common modal dialogs manager
    */
   public MultiSessionAppserverView(AppserverInfo appserverInfo, ModalDialogs modalDialogsManager)
   {
      Binder uiBinder = GWT.create(Binder.class);
      initWidget(uiBinder.createAndBindUi(this));

      this.appserverInfo = appserverInfo;
      this.modalDialogsManager = modalDialogsManager;
      
      nameHeading.setText("MSA App " + appserverInfo.name);
      
      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 agents to start: ", appserverInfo.initialServers);
      addConfigRow("Minimum agents: ", appserverInfo.minServers);
      addConfigRow("Maximum agents: ", appserverInfo.maxServer);
      addConfigRow("Agent auto trim timeout: ", appserverInfo.autoTrimTimeout);
      addConfigRow("Request wait timeout: ", appserverInfo.requestTimeout);
      addConfigRow("Session activate procedure: ", appserverInfo.activateProc);
      addConfigRow("Session deactivate procedure: ", appserverInfo.deactivateProc);
      addConfigRow("Session connect procedure: ", appserverInfo.connectProc);
      addConfigRow("Session disconnect procedure: ", appserverInfo.disconnectProc);
      addConfigRow("Agent startup procedure: ", appserverInfo.startupProc);
      addConfigRow("Agent shutdown procedure: ", appserverInfo.shutdownProc);
      addConfigRow("Agent startup procedure parameters: ", appserverInfo.startupProcParams);
      
      gridHandle = initTable(sessionsGrid);
      sessionsProvider = gridHandle.getDataProvider();
      selectionModel = (MultiSelectionModel<MultiSessionAgentSessionDef>) gridHandle.getSelectionModel();
      
      setAgentTable(appserverInfo.agentInfos);
   }

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

   /**
    * Sets up the agents table with new data.
    *
    * @param    agentInfos
    *           The array of agent descriptors.
    */
   @Override
   void setAgentTable(AppserverInfo.AgentInfo[] agentInfos)
   {
      this.sessionInfos = agentInfos == null || agentInfos.length == 0 || agentInfos[0].sessionInfos == null ?
         new MultiSessionAgentSessionDef[0] :
         agentInfos[0].sessionInfos;
      
      logger.info("Number of MSA sessions " + sessionInfos.length);
      GridHelper.updateDataProvider(sessionsGrid, sessionsProvider, sessionInfos);
      this.selectionModel.clear();
   }

   
   /**
    * The button click handler.
    *
    * @param    event
    *           Click event
    */
   @UiHandler("trimBtn")
   void onTrim(ClickEvent event)
   {
      logger.info("Trim sessions for MSA app " + appserverInfo.name);
      modalDialogsManager.showYesNo("Trim",
                                    "The idle unbound sessions will shut down. 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 MSA app " + appserverInfo.name);
      modalDialogsManager.showYesNo("Restart",
                                    "The MSA app will be force 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",
                                    "The MSA app will be started. Continue?",
                                    MessageType.INFO,
                                    res ->
                                    {
                                       if (res == 0)
                                       {
                                          getUiHandlers().startAppserver(appserverInfo.name);
                                       }
                                    });
   }

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

   /**
    * The button click handler.
    *
    * @param    event
    *           Click event
    */
   @UiHandler("forceStopSelectedBtn")
   void onForceStopSelected(ClickEvent event)
   {
      MultiSessionAgentSessionDef[] sessionInfos = this.selectionModel.getSelectedSet().toArray(new MultiSessionAgentSessionDef[0]);
      if (sessionInfos.length == 0)
      {
         modalDialogsManager.showWarning("No sessions selected to be stopped.");
         return;
      }
      
      if (logger.isLoggable(Level.INFO))
      {
         int[] sessionIds = Arrays.stream(sessionInfos).mapToInt(MultiSessionAgentSessionDef::getSessionId).toArray();
         logger.info("Force stop sessions with ids " + Arrays.toString(sessionIds) +
                        " of MSA app " + appserverInfo.name);
      }

      modalDialogsManager.showYesNo("Force Stop",
                                    "The selected appserver sessions will be force stopped. Continue?",
                                    MessageType.WARNING,
                                    res ->
                                    {
                                       if (res == 0)
                                       {
                                          getUiHandlers().terminateSessions(appserverInfo.name, sessionInfos);
                                       }
                                    });
   }
   
   /**
    * Setups the given table view.
    *
    * @param    grid
    *           The given table view
    *
    * @return   The grid handle
    */
   private GridHandle<MultiSessionAgentSessionDef> initTable(DataGrid<MultiSessionAgentSessionDef> grid)
   {
      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col1 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[0],
                                     sessionInfo -> String.valueOf(sessionInfo.getAgentId()),
                                     (s1, s2) -> {
                                        int diff = s1.getAgentId() - s2.getAgentId();
                                        return diff != 0 ? diff : s1.getSessionId() - s2.getSessionId();
                                     });

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col2 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[1],
                                     sessionInfo -> String.valueOf(sessionInfo.getSessionId()),
                                     (s1, s2) -> s1.getSessionId() - s2.getSessionId());

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col3 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[2],
                                     sessionInfo -> sessionInfo.getSessionStartTime() == null ? "" :
                                        DATE_FORMAT.format(sessionInfo.getSessionStartTime()),
                                     (s1, s2) -> (int) (s1.getSessionStartTime().getTime() - s2.getSessionStartTime().getTime()));

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col4 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[3],
                                     sessionInfo -> sessionInfo.getState().name());

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col5 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[4],
                                     sessionInfo -> String.valueOf(sessionInfo.isBound()));

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col6 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[5],
                                     sessionInfo -> sessionInfo.getConnectionModel() == null ? "" :
                                        sessionInfo.getConnectionModel());

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col7 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[6],
                                     sessionInfo -> sessionInfo.getRunningProc() == null ? "" :
                                        sessionInfo.getRunningProc());

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col8 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[7],
                                     sessionInfo -> sessionInfo.getRunningProcStartTime() == null ? "" :
                                        DATE_FORMAT.format(sessionInfo.getRunningProcStartTime()),
                                     (s1, s2) -> s1.getRunningProcStartTime() == null ? -1 :
                                        s2.getRunningProcStartTime() == null ? 1 :
                                           (int) (s1.getRunningProcStartTime().getTime() - 
                                              s2.getRunningProcStartTime().getTime()));

      GridHelper.ColumnInfo<MultiSessionAgentSessionDef> col9 =
         new GridHelper.ColumnInfo<>(SESSION_COL_NAMES[8],
                                     sessionInfo -> sessionInfo.getClient() == null ? "" : sessionInfo.getClient());

      col1.setWidthInPercents(SESSION_COL_WIDTHS[0]);
      col2.setWidthInPercents(SESSION_COL_WIDTHS[1]);
      col3.setWidthInPercents(SESSION_COL_WIDTHS[2]);
      col4.setWidthInPercents(SESSION_COL_WIDTHS[3]);
      col5.setWidthInPercents(SESSION_COL_WIDTHS[4]);
      col6.setWidthInPercents(SESSION_COL_WIDTHS[5]);
      col7.setWidthInPercents(SESSION_COL_WIDTHS[6]);
      col8.setWidthInPercents(SESSION_COL_WIDTHS[7]);
      col9.setWidthInPercents(SESSION_COL_WIDTHS[8]);
      
      return GridHelper.initListGrid(grid, true, true, col1, col2, col3, col4, col5, col6, col7, col8, col9);
   }

   /**
    * 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)));
   }
}