# RecordLocksView.java

    /*
    ** Module   : RecordLocksView.java
    ** Abstract : RecordLocksView represents a view to access the record locks functionality.
    **
    ** Copyright (c) 2017-2022, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description----------------------
    ** 001 SBI 20170601 Created initial version.
    ** 002 CA  20180605 Added program trace in the record locks view.
    ** 003 TJD 20220331 Removed deprecated reference to Inputdialog.showFilterDialog()
    */
    /*
    ** 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.recordlocks;

    import java.util.Date;

    import org.gwtbootstrap3.client.ui.Button;
    import org.gwtbootstrap3.client.ui.gwt.DataGrid;

    import com.goldencode.p2j.admin.*;
    import com.goldencode.p2j.admin.client.application.home.BaseViewWithUiHandlers;
    import com.goldencode.p2j.admin.client.application.home.console.sessions.SessionView;
    import com.goldencode.p2j.admin.client.widget.GridHandle;
    import com.goldencode.p2j.admin.client.widget.GridHelper;
    import com.goldencode.p2j.admin.client.widget.GridHelper.ColumnInfo;
    import com.goldencode.p2j.admin.client.widget.dialog.InputDialog;
    import com.goldencode.p2j.admin.client.widget.dialog.ModalDialogs;
    import com.goldencode.p2j.security.*;
    import com.google.gwt.event.dom.client.ClickEvent;
    import com.google.gwt.i18n.shared.DateTimeFormat;
    import com.google.gwt.regexp.shared.RegExp;
    import com.google.gwt.safehtml.shared.*;
    import com.google.gwt.uibinder.client.*;
    import com.google.gwt.user.client.ui.*;
    import com.google.gwt.view.client.SelectionChangeEvent;
    import com.google.gwt.view.client.SingleSelectionModel;
    import com.google.inject.*;

    /**
     * A view to access the existing record locks.
     */
    public class RecordLocksView
    extends BaseViewWithUiHandlers<RecordLocksUIHandler>
    implements RecordLocksPresenter.MyView
    {
       /**
        * GWT UI creator.
        */
       interface Binder
       extends UiBinder<Widget, RecordLocksView>
       {}

       /** The record locks table view */
       @UiField(provided = true)
       DataGrid<RecordLockInfo> dataGrid = GridHelper.<RecordLockInfo>create();

       /** The Refresh button */
       @UiField
       Button refresh;

       /** The Filter button */
       @UiField
       Button filter;

       /** The View Program Trace button */
       @UiField
       Button viewTrace;

       /** The modal container */
       @UiField
       HasWidgets modalFragment;

       /** The common input dialogs provider */
       private final Provider<InputDialog> inputDialogProvider;

       /** Modal dialogs */
       private final ModalDialogs dialogs;

       /** Column names. */
       private final String[] columnNames =
       {
          "Record ID",
          "Database",
          "Table Name",
          "Session ID(s)",
          "Program Trace",
          "Lock Type",
          "Acquisition Timestamp"
       };

       /** The date and time formatter */
       private final static DateTimeFormat DATE_FORMAT = DateTimeFormat.getFormat("MM/dd/yyyy hh:mm:ss Z");

       /** The record locks grid handle */
       private final GridHandle<RecordLockInfo> gridHandle;

       /** The record locks selection model */
       private final SingleSelectionModel<RecordLockInfo> selectionModel;

       /**
        * Constructs this view, used by MPV gwtplatform of ArcBees Inc.
        *
        * @param    binder
        *           The injected GWT UI creator
        * @param    dialogs
        *           The injected ModalDialogs provider
        * @param    inputDialogProvider
        *           The injected InputDialog provider
        */
       @Inject
       RecordLocksView(RecordLocksView.Binder binder,
                       ModalDialogs dialogs,
                       Provider<InputDialog> inputDialogProvider)
       {
          this.dialogs = dialogs;

          initWidget(binder.createAndBindUi(this));
          setupModalSlot(RecordLocksPresenter.MODAL_CONTENT, modalFragment);

          this.inputDialogProvider = inputDialogProvider;

          ColumnInfo<RecordLockInfo> col0 = new ColumnInfo<RecordLockInfo>(columnNames[0],
                   (ri) -> {return String.valueOf(ri.getRecordID());},
                   (r1, r2) -> { return r1.getRecordID().compareTo(r2.getRecordID());});
          ColumnInfo<RecordLockInfo> col1 = new ColumnInfo<RecordLockInfo>(columnNames[1],
                   (ri) -> { return String.valueOf(ri.getDatabaseName());},
                   (r1, r2) -> { return r1.getDatabaseName().compareTo(r2.getDatabaseName());});
          ColumnInfo<RecordLockInfo> col2 = new ColumnInfo<RecordLockInfo>(columnNames[2],
                   (ri) -> { return String.valueOf(ri.getTableName());},
                   (r1, r2) -> { return r1.getTableName().compareTo(r2.getTableName());});
          ColumnInfo<RecordLockInfo> col3 = new ColumnInfo<RecordLockInfo>(columnNames[3],
                   (ri) -> {return ri.getLockersPresentation();},
                   (r1, r2) -> { return r1.getLockersPresentation().compareTo(r2.getLockersPresentation());});
          ColumnInfo<RecordLockInfo> col4 = new ColumnInfo<RecordLockInfo>(columnNames[4],
                   (ri) -> { return buildStacktrace(ri); }, true);
          ColumnInfo<RecordLockInfo> col5 = new ColumnInfo<RecordLockInfo>(columnNames[5],
                   (ri) -> { return String.valueOf(ri.getType().name());},
                   (r1, r2) -> { return r1.getType().compareTo(r2.getType());});
          ColumnInfo<RecordLockInfo> col6 = new ColumnInfo<RecordLockInfo>(columnNames[6],
                   (ri) -> { return DATE_FORMAT.format(new Date(ri.getTimeAcquired()));},
                   (r1, r2) -> { return Long.valueOf(r1.getTimeAcquired()).compareTo(r2.getTimeAcquired());});

          this.gridHandle = GridHelper.initListGrid(dataGrid, false,
                                                    col0, col1, col2,
                                                    col3, col4, col5,
                                                    col6);

          this.selectionModel = (SingleSelectionModel<RecordLockInfo>) this.gridHandle.getSelectionModel();

          bindSlot(RecordLocksPresenter.MODAL_CONTENT, modalFragment);

          this.viewTrace.setEnabled(false);
          this.selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
          {
             @Override
             public void onSelectionChange(SelectionChangeEvent event)
             {
                boolean enabled = RecordLocksView.this.selectionModel.getSelectedObject() != null;
                RecordLocksView.this.viewTrace.setEnabled(enabled);
             }
          });
       }

       /**
        * Build the HTML representation of these program traces.
        *
        * @param    ri
        *           The data for the current row.
        *
        * @return   The GWT {@link SafeHtml} object holding this cell's content.
        */
       public static SafeHtml buildStacktrace(RecordLockInfo ri)
       {
          SafeHtmlBuilder html = new SafeHtmlBuilder();

          SessionToken[] lockers = ri.getLockers();
          StacktraceInfo[][] traces = ri.getStacktraces();

          for (int i = 0; i < lockers.length; i++)
          {
             SessionToken session = lockers[i];

             String sessId = "00000000" + Integer.toHexString(session.getSessionID());
             sessId = sessId.substring(sessId.length() - 8);
             String key = "Conversation [" + sessId + ":" + session.getSubject() + "]";
             html.appendHtmlConstant("<b>" + key + "</b><br/>");
             html.append(SessionView.buildStackTrace(traces[i]));
          }

          return html.toSafeHtml();
       }

       /**
        * Sets the record locks table model according to the given filter criteria.
        *
        * @param    rows
        *           The array of records
        * @param    filter
        *           The filter criteria
        */
       @Override
       public void setRecordLocks(RecordLockInfo[] rows, RegExp filter)
       {
          gridHandle.setRows(rows, filter);
       }

       /**
        * The Refresh button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("refresh")
       void onRefresh(ClickEvent e)
       {
          getUiHandlers().updateRecordLocksList();
       }

       /**
        * The View Program Trace button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("viewTrace")
       void onViewTrace(ClickEvent e)
       {
          RecordLockInfo row = this.selectionModel.getSelectedObject();
          StringBuilder sb = new StringBuilder();
          sb.append("<textarea style='height:400px;width:100%'>");

          if (row.getJavaStacktraces() == null)
          {
             sb.append("(no stacktraces available");
          }
          else
          {
             String[][] traces = row.getJavaStacktraces();

             for (int i = 0; i < traces.length; i++)
             {
                if (traces[i] != null)
                {
                   for (String trace : traces[i])
                   {
                      sb.append(trace);
                      sb.append("\n");
                   }
                }

                sb.append("\n");
             }
          }

          sb.append("</textarea>");
          dialogs.showInfo("Java Stacktrace", sb.toString(), null);
       }

       /**
        * The Filter button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("filter")
       void onFilterAction(ClickEvent event)
       {
          InputDialog.Field newFilter;
          InputDialog inputDialog = this.inputDialogProvider.get();
          String hlpText = "<h4>Define the filtering specification below. Press the&nbsp;" +
                           "'OK' button without any specification to remove any&nbsp;" +
                           "previous filter.</h4>";
          inputDialog.build("Filter", hlpText , new InputDialog.Field[]
          {
             newFilter = new InputDialog.Field("Filter", getUiHandlers().getCurrentFilter(), true)
          });
          inputDialog.show(modalFragment, true, values ->
          {
             if (values != null)
             {
                String newFilterValue = (String) values.get(newFilter);
                getUiHandlers().setDataSelectionFilter(newFilterValue);
                logger.info("inputDialog -> " + newFilterValue);
             }
          });
       }

       /**
        * Tests if the given record has been selected.
        *
        * @param    recordLockInfo
        *           The tested record
        *
        * @return   True if the tested record has been selected, otherwise false.
        */
       @Override
       public boolean isRecordSelected(RecordLockInfo recordLockInfo)
       {
          return this.selectionModel.isSelected(recordLockInfo);
       }
    }