view src/app/components/jvm-list/jvm-list.controller.js @ 260:c37b4d997182

Restore reopen system entry functionality to jvm-list Reviewed-by: jkang Review-thread: http://icedtea.classpath.org/pipermail/thermostat/2017-September/025185.html Review-thread: http://icedtea.classpath.org/pipermail/thermostat/2017-October/025438.html
author Andrew Azores <aazores@redhat.com>
date Mon, 25 Sep 2017 16:01:13 -0400
parents ba401daa2732
children
line wrap: on
line source

/**
 * Copyright 2012-2017 Red Hat, Inc.
 *
 * Thermostat is distributed under the GNU General Public License,
 * version 2 or any later version (with a special exception described
 * below, commonly known as the "Classpath Exception").
 *
 * A copy of GNU General Public License (GPL) is included in this
 * distribution, in the file COPYING.
 *
 * Linking Thermostat code with other modules is making a combined work
 * based on Thermostat.  Thus, the terms and conditions of the GPL
 * cover the whole combination.
 *
 * As a special exception, the copyright holders of Thermostat give you
 * permission to link this code with independent modules to produce an
 * executable, regardless of the license terms of these independent
 * modules, and to copy and distribute the resulting executable under
 * terms of your choice, provided that you also meet, for each linked
 * independent module, the terms and conditions of the license of that
 * module.  An independent module is a module which is not derived from
 * or based on Thermostat code.  If you modify Thermostat, you may
 * extend this exception to your version of the software, but you are
 * not obligated to do so.  If you do not wish to do so, delete this
 * exception statement from your version.
 */

import filters from 'shared/filters/filters.module.js';
import services from 'shared/services/services.module.js';
import components from 'shared/components/components.module.js';
import jvmListService from './jvm-list.service.js';
import systemInfoService from 'components/system-info/system-info.service.js';

const LOCAL_STORAGE_KEY = 'jvmListSystemsOpen';

class JvmListController {
  constructor (jvmListService, systemInfoService, localStorage, $state, $timeout, $translate) {
    'ngInject';
    this.jvmListService = jvmListService;
    this.systemInfoService = systemInfoService;
    this.timeout = $timeout;
    this.translate = $translate;

    this.localStorage = localStorage;
    this.systemsOpen = {};
    if (localStorage.hasItem(LOCAL_STORAGE_KEY)) {
      try {
        this.systemsOpen = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
      } catch (e) {
        // This is noncritical, so just leave systemsOpen as an empty object if
        // stored state is unparseable. When this controller is destroyed, any
        // built up systemsOpen state at that time will be persisted again.
      }
    }

    this.aliveOnly = true;

    this.pageConfig = { showPaginationControls: false };
    this.listConfig = {
      showSelectBox: false,
      useExpandingRows: true,
      onClick: item => this.toggleOpenState(item)
    };
    this.jvmConfig = {
      showSelectBox: false,
      useExpandingRows: false,
      onClick: item => $state.go('jvmInfo', { systemId: item.systemId, jvmId: item.jvmId })
    };

    this.emptyStateConfig = {
      icon: 'pficon-warning-triangle-o',
    };

    this.constructToolbarSettings();
  }

  $onInit () {
    this.translate('jvmList.ERR_TITLE').then(s => this.emptyStateConfig.title = s);
    this.translate('jvmList.ERR_MESSAGE').then(s => this.emptyStateConfig.info = s);

    let aliveOnlySwitch = angular.element('#aliveOnlyState');
    aliveOnlySwitch.bootstrapSwitch();
    aliveOnlySwitch.on('switchChange.bootstrapSwitch', (event, state) => {
      this.aliveOnly = state;
      this.loadData();
    });

    this.loadData();
  }

  $onDestroy () {
    this.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.systemsOpen));
  }

  toggleOpenState (item) {
    this.systemsOpen[item.systemId] = !this.systemsOpen[item.systemId];
  }

  loadData () {
    this.allItems = [];
    this.items = this.allItems;
    this.jvmListService.getSystems(this.aliveOnly).then(
      resp => {
        this.showErr = false;
        this.systems = resp.data.response;
        let systemIds = [];
        if (this.systems.length === 1) {
          this.systemsOpen[this.systems[0].systemId] = true;
        }
        for (let i = 0; i < this.systems.length; i++) {
          let system = this.systems[i];
          systemIds.push(system.systemId);
          this.systemInfoService.getSystemInfo(system.systemId).then(
            resp => {
              system.jvms.forEach(jvm => jvm.systemId = system.systemId);
              let item = {
                systemId: system.systemId,
                hostname: resp.data.response[0].hostname,
                jvms: system.jvms,
                timeCreated: resp.data.response[0].timeCreated,
                pageConfig: {
                  pageNumber: 1,
                  pageSize: 5
                }
              };
              if (this.systemsOpen[system.systemId]) {
                item.isExpanded = true;
              }

              this.allItems.push(item);

              this.pageConfig.numTotalItems = this.allItems.length;
              this.pageConfig.pageSize = this.allItems.length;
              this.pageConfig.pageNumber = 1;
              this.listConfig.itemsAvailable = true;
              this.toolbarConfig.filterConfig.resultsCount = this.systems.length;
              this.toolbarConfig.filterConfig.totalCount = this.allItems.length;
            }
          );
        }
        Object.keys(this.systemsOpen).forEach(key => {
          if (!systemIds.includes(key)) {
            delete this.systemsOpen[key];
          }
        });
      },
      () => {
        this.listConfig.itemsAvailable = false;
        this.pageConfig.pageSize = 0;
        this.pageConfig.pageNumber = 0;
        this.showErr = true;
      }
    );
  }

  constructToolbarSettings () {
    this.translate([
      'jvmList.HOSTNAME_TITLE',
      'jvmList.filterConfig.HOSTNAME_PLACEHOLDER',
      'jvmList.filterConfig.JVM_NAME_TITLE',
      'jvmList.filterConfig.JVM_NAME_PLACEHOLDER',
      'jvmList.sortConfig.TIME_CREATED_TITLE',
      'jvmList.sortConfig.NUM_JVMS_TITLE'
    ]).then(translations => {
      this.filterConfig = {
        fields: [
          {
            id: 'hostname',
            filterType: 'text',
            title: translations['jvmList.HOSTNAME_TITLE'],
            placeholder: translations['jvmList.filterConfig.HOSTNAME_PLACEHOLDER']
          },
          {
            id: 'jvmName',
            filterType: 'text',
            title: translations['jvmList.filterConfig.JVM_NAME_TITLE'],
            placeholder: translations['jvmList.filterConfig.JVM_NAME_PLACEHOLDER']
          }
        ],
        resultsCount: 0,
        totalCount: 0,
        appliedFilters: [],
        onFilterChange: filters => {
          this.applyFilters(filters);
          this.toolbarConfig.filterConfig.resultsCount = this.items.length;
        }
      };

      this.sortConfig = {
        fields: [
          {
            id: 'name',
            sortType: 'alpha',
            title: translations['jvmList.HOSTNAME_TITLE']
          },
          {
            id: 'timeCreated',
            sortType: 'numeric',
            title: translations['jvmList.sortConfig.TIME_CREATED_TITLE']
          },
          {
            id: 'numJvms',
            sortType: 'numeric',
            title: translations['jvmList.sortConfig.NUM_JVMS_TITLE']
          }
        ],
        onSortChange: () => {
          this.sortItems();
        }
      };

      this.toolbarConfig = {
        filterConfig: this.filterConfig,
        sortConfig: this.sortConfig
      };
    });
  }

  /**
   * Starter code for matchesFilter, matchesFilters, applyFilters, and compareFn borrowed
   * from the Angular-PatternFly API at:
   * http://www.patternfly.org/angular-patternfly/#/api/patternfly.toolbars.componenet:pfToolbar
   */
  matchesFilter (item, filter) {
    let match = false;
    let re = new RegExp(filter.value, 'i');
    if (filter.id === 'hostname') {
      match = item.hostname.match(re) !== null;
    } else if (filter.id === 'jvmName') {
      for (let i = 0; i < item.jvms.length; i++) {
        match = (item.jvms[i].mainClass).match(re) !== null;
        if (match) {
          break;
        }
      }
    }
    return match;
  }

  matchesFilters (item, filters) {
    let matches = true;
    filters.forEach(filter => {
      if (!this.matchesFilter(item, filter)) {
        matches = false;
        return false;
      } else {
        return true;
      }
    });
    return matches;
  }

  applyFilters (filters) {
    this.items = [];
    if (filters && filters.length > 0) {
      this.allItems.forEach(item => {
        if (this.matchesFilters(item, filters)) {
          this.items.push(item);
        }
      });
    } else {
      this.items = this.allItems;
    }
  }

  compareFn (item1, item2) {
    let compValue = 0;
    if (this.sortConfig.currentField.id === 'name') {
      compValue = item1.hostname.localeCompare(item2.systemId);
    } else if (this.sortConfig.currentField.id === 'timeCreated') {
      compValue = item1.timeCreated.$numberLong > item2.timeCreated.$numberLong ? 1 : -1;
    } else if (this.sortConfig.currentField.id === 'numJvms') {
      compValue = item1.jvms.length > item2.jvms.length ? 1 : -1;
    }
    if (!this.sortConfig.isAscending) {
      compValue = compValue * -1;
    }
    return compValue;
  }

  sortItems () {
    this.items.sort((item1, item2) => this.compareFn(item1, item2));
  }

}

export default angular
  .module('jvmList.controller', [
    'patternfly',
    'patternfly.toolbars',
    filters,
    services,
    components,
    jvmListService,
    systemInfoService
  ])
  .controller('JvmListController', JvmListController)
  .name;