public class GlusterServerTableLabelProvider extends TableLabelProviderAdapter {
  private GUIHelper guiHelper = GUIHelper.getInstance();

  @Override
  public Image getColumnImage(Object element, int columnIndex) {
    if (!(element instanceof GlusterServer)) {
      return null;
    }

    GlusterServer server = (GlusterServer) element;
    if (columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.STATUS.ordinal()) {
      SERVER_STATUS status = server.getStatus();
      if (status == SERVER_STATUS.ONLINE) {
        return guiHelper.getImage(IImageKeys.STATUS_ONLINE_16x16);
      } else {
        return guiHelper.getImage(IImageKeys.STATUS_OFFLINE_16x16);
      }
    }

    return null;
  }

  @Override
  public String getColumnText(Object element, int columnIndex) {
    if (!(element instanceof GlusterServer)) {
      return null;
    }

    GlusterServer server = (GlusterServer) element;

    if (server.getStatus() == SERVER_STATUS.OFFLINE
        && columnIndex != GLUSTER_SERVER_TABLE_COLUMN_INDICES.NAME.ordinal()
        && columnIndex != GLUSTER_SERVER_TABLE_COLUMN_INDICES.STATUS.ordinal()) {
      return "NA";
    }

    return (columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.NAME.ordinal()
        ? server.getName()
        : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.STATUS.ordinal()
            ? server.getStatusStr()
            // : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.PREFERRED_NETWORK.ordinal() ?
            // server.getPreferredNetworkInterface().getName()
            : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.NUM_OF_CPUS.ordinal()
                ? "" + server.getNumOfCPUs()
                // : columnIndex == SERVER_DISK_TABLE_COLUMN_INDICES.CPU_USAGE.ordinal() ? "" +
                // server.getCpuUsage()
                : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.TOTAL_MEMORY.ordinal()
                    ? "" + NumberUtil.formatNumber((server.getTotalMemory() / 1024))
                    // : columnIndex == SERVER_DISK_TABLE_COLUMN_INDICES.MEMORY_IN_USE.ordinal() ?
                    // "" + server.getMemoryInUse()
                    : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.TOTAL_FREE_SPACE.ordinal()
                        ? NumberUtil.formatNumber((server.getFreeDiskSpace() / 1024))
                        : columnIndex == GLUSTER_SERVER_TABLE_COLUMN_INDICES.IP_ADDRESSES.ordinal()
                            ? server.getIpAddressesAsString()
                            : columnIndex
                                    == GLUSTER_SERVER_TABLE_COLUMN_INDICES.TOTAL_DISK_SPACE
                                        .ordinal()
                                ? NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024))
                                : "Invalid");
  }
}
예제 #2
0
/** Login dialog, which prompts for the user's account info, and has Login and Cancel buttons. */
public class LoginDialog extends Dialog {
  public static final int RETURN_CODE_ERROR = 2;
  private Text userIdText = null;
  private Text passwordText = null;
  private Button okButton;

  private final ConnectionDetails connectionDetails = new ConnectionDetails("gluster", "");
  private final GUIHelper guiHelper = GUIHelper.getInstance();
  private Composite composite;

  public LoginDialog(Shell parentShell) {
    super(parentShell);
  }

  @Override
  protected void configureShell(Shell newShell) {
    super.configureShell(newShell);

    newShell.setText("Gluster Management Console");
    addEscapeListener(newShell);
  }

  private void addEscapeListener(Shell shell) {
    shell.addTraverseListener(
        new TraverseListener() {

          @Override
          public void keyTraversed(TraverseEvent e) {
            if (e.keyCode == SWT.ESC) {
              cancelPressed();
            }
          }
        });
  }

  private void createUserIdLabel(Composite composite) {
    Label userIdLabel = new Label(composite, SWT.NONE);
    userIdLabel.setText("&User ID:");
    userIdLabel.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false));
  }

  private void createUserIdText(Composite composite) {
    userIdText = new Text(composite, SWT.BORDER);
    userIdText.setText("gluster");
    userIdText.setEnabled(false);

    GridData layoutData = new GridData(convertWidthInCharsToPixels(32), 15);
    userIdText.setLayoutData(layoutData);
  }

  private void createPasswordLabel(Composite composite) {
    Label passwordLabel = new Label(composite, SWT.NONE);
    passwordLabel.setText("&Password:"******"&Cancel", false);
    cancelButton.setLayoutData(layoutData);

    layoutData = new GridData();
    layoutData.widthHint = 70;
    layoutData.horizontalAlignment = SWT.LEFT;
    layoutData.grabExcessHorizontalSpace = true;

    okButton = createButton(parent, IDialogConstants.OK_ID, "&Login", true);
    okButton.setLayoutData(layoutData);

    setupDataBinding();
  }

  private void setupAutoLoginIfRequired() {
    final String password = System.getProperty(ConsoleConstants.PROPERTY_AUTO_LOGIN_PASSWORD, null);
    if (password == null) {
      return;
    }
    getShell()
        .addShellListener(
            new ShellAdapter() {
              @Override
              public void shellActivated(ShellEvent e) {
                super.shellActivated(e);

                if (passwordText.getText().isEmpty()) {
                  // Check whether the password has been passed as system parameter. This can be
                  // used for avoiding
                  // human intervention on login dialog while running SWTBot automated tests.
                  passwordText.setText(password);
                  okPressed();
                }
              }
            });
  }

  /**
   * Sets up data binding between the text fields and the connection details object. Also attaches a
   * "string required" validator to the "password" text field. This validator is configured to do
   * the following on validation failure<br>
   * <li>show an ERROR decorator
   * <li>disable the "Login" button
   */
  private void setupDataBinding() {
    DataBindingContext dataBindingContext =
        new DataBindingContext(SWTObservables.getRealm(Display.getCurrent()));
    UpdateValueStrategy passwordBindingStrategy =
        new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE);

    // The Validator shows error decoration and disables OK button on
    // validation failure
    passwordBindingStrategy.setBeforeSetValidator(
        new StringRequiredValidator(
            "Please enter password!", guiHelper.createErrorDecoration(passwordText), okButton));

    dataBindingContext.bindValue(
        WidgetProperties.text(SWT.Modify).observe(passwordText),
        PojoProperties.value("password").observe(connectionDetails),
        passwordBindingStrategy,
        passwordBindingStrategy);

    UpdateValueStrategy userIdBindingStrategy =
        new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE);
    dataBindingContext.bindValue(
        WidgetProperties.text(SWT.Modify).observe(userIdText),
        PojoProperties.value("userId").observe(connectionDetails),
        userIdBindingStrategy,
        userIdBindingStrategy);
  }

  protected void okPressed() {
    String user = connectionDetails.getUserId();
    String password = connectionDetails.getPassword();

    UsersClient usersClient = new UsersClient();
    try {
      usersClient.authenticate(user, password);
    } catch (Exception e) {
      MessageDialog.openError(getShell(), "Authentication Failed", e.getMessage());
      setReturnCode(RETURN_CODE_ERROR);
      return;
    }

    // authentication successful. close the login dialog and open the next one.
    close();

    IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
    boolean showClusterSelectionDialog =
        preferenceStore.getBoolean(PreferenceConstants.P_SHOW_CLUSTER_SELECTION_DIALOG);

    // If the password is default, Let user to change the password
    if (password.equalsIgnoreCase(CoreConstants.DEFAULT_PASSWORD)) {
      ChangePasswordDialog dialog = new ChangePasswordDialog(getShell());

      if (dialog.open() == Dialog.CANCEL) {
        MessageDialog.openError(
            getShell(),
            "Change password Cancelled",
            "Password must be changed on first login!"
                + CoreConstants.NEWLINE
                + "Application will close.");
        cancelPressed();
        return;
      }

      // after first login, cluster selection dialog must be shown.
      showClusterSelectionDialog = true;
    }

    ClustersClient clustersClient = new ClustersClient();

    CLUSTER_MODE mode;
    String clusterName = null;
    if (!showClusterSelectionDialog) {
      clusterName = preferenceStore.getString(PreferenceConstants.P_DEFAULT_CLUSTER_NAME);
      if (clusterName == null || clusterName.isEmpty()) {
        // Cluster name not available in preferences. Hence we must show the cluster selection
        // dialog.
        showClusterSelectionDialog = true;
      } else {
        mode = CLUSTER_MODE.SELECT;
      }
    }

    String serverName = null;

    if (showClusterSelectionDialog) {
      ClusterSelectionDialog clusterDialog =
          new ClusterSelectionDialog(getParentShell(), clustersClient.getClusterNames());
      int userAction = clusterDialog.open();
      if (userAction == Window.CANCEL) {
        MessageDialog.openError(
            getShell(),
            "Login Cancelled",
            "User cancelled login at cluster selection. Application will close!");
        cancelPressed();
        return;
      }
      mode = clusterDialog.getClusterMode();
      clusterName = clusterDialog.getClusterName();
      serverName = clusterDialog.getServerName();
    } else {
      mode = CLUSTER_MODE.SELECT;
    }

    try {
      createOrRegisterCluster(clustersClient, clusterName, serverName, mode);

      final String clusterName1 = clusterName;
      new ProgressMonitorDialog(getShell())
          .run(
              true,
              false,
              new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  GlusterDataModelManager.getInstance().initializeModel(clusterName1, monitor);
                }
              });
      super.okPressed();
    } catch (Exception e) {
      String errMsg;
      if (e instanceof InvocationTargetException) {
        errMsg = ((InvocationTargetException) e).getTargetException().getMessage();
      } else {
        errMsg = e.getMessage();
      }
      setReturnCode(RETURN_CODE_ERROR);
      MessageDialog.openError(getShell(), "Gluster Management Console", errMsg);
    }
  }

  public void createOrRegisterCluster(
      ClustersClient clustersClient, String clusterName, String serverName, CLUSTER_MODE mode) {
    switch (mode) {
      case SELECT:
        return;
      case CREATE:
        clustersClient.createCluster(clusterName);
        break;
      case REGISTER:
        clustersClient.registerCluster(clusterName, serverName);
        break;
    }
  }
}