/**
   * @see
   *     org.eclipse.jface.dialogs.TitleAreaDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
   * @since 5.5.3
   */
  @SuppressWarnings("unused")
  @Override
  protected Control createDialogArea(Composite parent) {

    Composite pnlOuter = (Composite) super.createDialogArea(parent);
    Composite panel = new Composite(pnlOuter, SWT.NONE);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 2;
    panel.setLayout(gridLayout);
    panel.setLayoutData(new GridData(GridData.FILL_BOTH));

    // set title
    setTitle(UTIL.getString(PREFIX + "title")); // $NON-NLS-1$
    setMessage(UTIL.getString(PREFIX + "initialMessage")); // $NON-NLS-1$

    //		Group serversGroup = WidgetFactory.createGroup(panel, UTIL.getString(PREFIX +
    // "teiidServers"), GridData.FILL_BOTH, 2, 2); //$NON-NLS-1$
    //		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
    //		gd.horizontalSpan = 2;
    //		serversGroup.setLayoutData(gd);

    ACTION_COMBO:
    {
      serversCombo = new Combo(panel, SWT.NONE | SWT.READ_ONLY);
      GridData gd = new GridData(GridData.FILL_HORIZONTAL);
      gd.horizontalSpan = 2;
      serversCombo.setLayoutData(gd);

      serversCombo.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent ev) {
              selectedServer = null;
              String serverName = serversCombo.getItem(serversCombo.getSelectionIndex());

              Collection<ITeiidServer> teiidServers =
                  DqpPlugin.getInstance().getServerManager().getServers();
              for (ITeiidServer teiidServer : teiidServers) {
                if (teiidServer.getCustomLabel().equalsIgnoreCase(serverName)) {
                  selectedServer = teiidServer;
                  break;
                }
              }

              updateState();
            }
          });
      Collection<ITeiidServer> teiidServers =
          DqpPlugin.getInstance().getServerManager().getServers();
      List<String> nameList = new ArrayList<String>();
      for (ITeiidServer teiidServer : teiidServers) {
        nameList.add(teiidServer.getCustomLabel());
      }
      WidgetUtil.setComboItems(serversCombo, nameList, null, true);
    }

    return panel;
  }
  /**
   * Get an {@link IExecutionAdmin} applicable for the given server
   *
   * @param teiidServer
   * @return instance of {@link IExecutionAdmin}
   * @throws Exception
   */
  public IExecutionAdmin getExecutionAdmin(ITeiidServer teiidServer) throws Exception {
    IExecutionAdminFactory factory = search(teiidServer.getServerVersion());
    if (factory == null)
      throw new Exception(
          "No ExecutionAdmin factory registered for teiid server version "
              + teiidServer.getServerVersion()); // $NON-NLS-1$

    return factory.createExecutionAdmin(teiidServer);
  }
  /**
   * {@inheritDoc}
   *
   * @see org.eclipse.jface.action.Action#run()
   */
  @Override
  public void run() {
    // Make sure default teiid instance is connected
    if (!checkForConnectedServer()) return;

    ITeiidServer teiidServer = getServerManager().getDefaultServer();

    for (IFile nextVDB : this.selectedVDBs) {
      boolean doDeploy = VdbRequiresSaveChecker.insureOpenVdbSaved(nextVDB);
      if (doDeploy) {
        boolean deploySuccess = deployVdb(teiidServer, nextVDB);

        String vdbName = nextVDB.getFullPath().removeFileExtension().lastSegment();
        try {
          // make sure deployment worked before going on to the next one
          if (!teiidServer.hasVdb(vdbName)) {
            deploySuccess = false;
            break;
          }
        } catch (Exception ex) {
          DqpPlugin.Util.log(ex);
          Shell shell = UiUtil.getWorkbenchShellOnlyIfUiThread();
          String title =
              UTIL.getString(
                  I18N_PREFIX + "problemDeployingVdbDataSource.title",
                  vdbName,
                  teiidServer); //$NON-NLS-1$
          String message =
              UTIL.getString(
                  I18N_PREFIX + "problemDeployingVdbDataSource.msg",
                  vdbName,
                  teiidServer); //$NON-NLS-1$
          ErrorDialog.openError(
              shell, title, null, new Status(IStatus.ERROR, PLUGIN_ID, message, ex));
        }

        if (deploySuccess) {
          try {
            CreateVdbDataSourceAction.doCreateDataSource(vdbName, teiidServer);
          } catch (Exception ex) {
            Shell shell = UiUtil.getWorkbenchShellOnlyIfUiThread();
            MessageDialog.openError(
                shell,
                UTIL.getString("CreateVdbDataSourceAction.errorCreatingDataSourceForVDB", vdbName),
                ex.getMessage()); // $NON-NLS-1$
            DqpUiConstants.UTIL.log(
                IStatus.ERROR,
                ex,
                UTIL.getString(
                    "CreateVdbDataSourceAction.errorCreatingDataSourceForVDB",
                    vdbName)); //$NON-NLS-1$
          }
        }
      }
    }
  }
 private void createVdbDataSource(Object vdbOrVdbFile, String displayName, String jndiName)
     throws Exception {
   Vdb vdb =
       ((vdbOrVdbFile instanceof IFile)
           ? new Vdb((IFile) vdbOrVdbFile, null)
           : (Vdb) vdbOrVdbFile);
   ITeiidServer teiidServer = getServerManager().getDefaultServer();
   String vdbName = vdb.getFile().getFullPath().removeFileExtension().lastSegment();
   teiidServer.createVdbDataSource(vdbName, displayName, jndiName);
 }
 /*
  * Check that the default teiid instance is connected.  Show dialog if it is not.
  * @return 'true' if default teiid instance is connected, 'false' if not.
  */
 private boolean checkForConnectedServer() {
   ITeiidServer teiidServer = getServerManager().getDefaultServer();
   if (teiidServer == null || !teiidServer.isConnected()) {
     Shell shell = UiUtil.getWorkbenchShellOnlyIfUiThread();
     String title = UTIL.getString("ActionRequiresServer.title"); // $NON-NLS-1$
     String msg = UTIL.getString("ActionRequiresServer.msg"); // $NON-NLS-1$
     MessageDialog.openInformation(shell, title, msg);
     return false;
   }
   return true;
 }
  /** Ask the user to select the vdb and deploy it */
  public void queryUserAndRun() {
    // Make sure default teiid instance is connected
    if (!checkForConnectedServer()) return;

    ITeiidServer teiidServer = getServerManager().getDefaultServer();

    DeployVdbDialog dialog =
        new DeployVdbDialog(
            DqpUiPlugin.getDefault().getCurrentWorkbenchWindow().getShell(), designerProperties);

    dialog.open();

    if (dialog.getReturnCode() == Window.OK) {
      IFile vdb = dialog.getSelectedVdb();
      boolean doCreateDS = dialog.doCreateVdbDataSource();
      String jndiName = dialog.getVdbDataSourceJndiName();
      if (vdb != null) {
        boolean doDeploy = VdbRequiresSaveChecker.insureOpenVdbSaved(vdb);
        if (doDeploy) {
          deployVdb(teiidServer, vdb, true);
        }

        String vdbName = vdb.getFullPath().removeFileExtension().lastSegment();
        try {
          if (teiidServer.hasVdb(vdbName) && doCreateDS) {
            createVdbDataSource(vdb, jndiName, jndiName);
          }
        } catch (Exception ex) {
          DqpPlugin.Util.log(ex);
          Shell shell = UiUtil.getWorkbenchShellOnlyIfUiThread();
          String title =
              UTIL.getString(
                  I18N_PREFIX + "problemDeployingVdbDataSource.title",
                  vdbName,
                  teiidServer); //$NON-NLS-1$
          String message =
              UTIL.getString(
                  I18N_PREFIX + "problemDeployingVdbDataSource.msg",
                  vdbName,
                  teiidServer); //$NON-NLS-1$
          ErrorDialog.openError(
              shell, title, null, new Status(IStatus.ERROR, PLUGIN_ID, message, ex));
        }
      }
    }
  }
  /**
   * Default Constructor
   *
   * @param teiidServer the server this admin belongs to (never <code>null</code>)
   * @throws Exception if there is a problem connecting the server
   */
  public ExecutionAdmin(ITeiidServer teiidServer) throws Exception {
    ArgCheck.isNotNull(teiidServer, "server"); // $NON-NLS-1$

    ITeiidAdminInfo teiidAdminInfo = teiidServer.getTeiidAdminInfo();
    char[] passwordArray = null;
    if (teiidAdminInfo.getPassword() != null) {
      passwordArray = teiidAdminInfo.getPassword().toCharArray();
    }

    this.admin =
        AdminFactory.getInstance()
            .createAdmin(teiidAdminInfo.getUsername(), passwordArray, teiidAdminInfo.getUrl());

    this.teiidServer = teiidServer;
    this.eventManager = teiidServer.getEventManager();
    this.connectionMatcher = new ModelConnectionMatcher();

    init();
  }
  /**
   * Constructor used for testing purposes only.
   *
   * @param admin the associated Teiid Admin API (never <code>null</code>)
   * @param teiidServer the server this admin belongs to (never <code>null</code>)
   * @throws Exception if there is a problem connecting the server
   */
  ExecutionAdmin(Admin admin, ITeiidServer teiidServer) throws Exception {
    ArgCheck.isNotNull(admin, "admin"); // $NON-NLS-1$
    ArgCheck.isNotNull(teiidServer, "server"); // $NON-NLS-1$

    this.admin = admin;
    this.teiidServer = teiidServer;
    this.eventManager = teiidServer.getEventManager();
    this.connectionMatcher = new ModelConnectionMatcher();

    init();
  }
  private IStatus pingJdbc() {
    String host = teiidServer.getHost();
    ITeiidJdbcInfo teiidJdbcInfo = teiidServer.getTeiidJdbcInfo();

    Connection teiidJdbcConnection = null;
    String url = "jdbc:teiid:ping@mm://" + host + ':' + teiidJdbcInfo.getPort(); // $NON-NLS-1$

    try {
      admin.deployVDB(
          "ping-vdb.xml",
          (InputStream) new ByteArrayInputStream(TEST_VDB.getBytes())); // $NON-NLS-1$
      try {
        String urlAndCredentials =
            url
                + ";user="******";password="******"ping", 1); // $NON-NLS-1$

        if (teiidJdbcConnection != null) {
          teiidJdbcConnection.close();
        }
      }
    } catch (Exception ex) {
      String msg = NLS.bind(Messages.serverDeployUndeployProblemPingingTeiidJdbc, url);
      return new Status(IStatus.ERROR, PLUGIN_ID, msg, ex);
    }

    return Status.OK_STATUS;
  }
  @Override
  public IStatus ping(PingType pingType) {
    String msg =
        NLS.bind(Messages.cannotConnectToServer, teiidServer.getTeiidAdminInfo().getUsername());
    try {
      if (this.admin == null) throw new Exception(msg);

      switch (pingType) {
        case JDBC:
          return pingJdbc();
        case ADMIN:
        default:
          return pingAdmin();
      }
    } catch (Exception ex) {
      return new Status(IStatus.ERROR, PLUGIN_ID, msg, ex);
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see org.eclipse.jface.action.Action#run()
   */
  @Override
  public void run() {
    // Server may have already been selected by the action
    // having its updateSelection called. If it hasn't then find
    // a server to edit accordingly
    if (this.serverBeingEdited == null) {
      // Choose Server to Edit
      serverBeingEdited = RuntimeAssistant.selectServer(getShell(), false);
      if (RuntimeAssistant.selectServerWasCancelled()) return;
    }

    if (serverBeingEdited == null) {
      String title = UTIL.getString("noServerAvailableTitle"); // $NON-NLS-1$
      String message = UTIL.getString("noServerAvailableMessage"); // $NON-NLS-1$
      MessageDialog.openError(getShell(), title, message);
      return;
    }

    ServerUIPlugin.editServer(serverBeingEdited.getParent());
  }
  /**
   * Deploy the given vdb to the given Teiid Instance
   *
   * @param teiidServer the Teiid Instance
   * @param vdbOrVdbFile the VDB
   * @param doCreateDataSource 'true' to create corresponding datasource, 'false' if not.
   */
  public static boolean deployVdb(
      ITeiidServer teiidServer, final Object vdbOrVdbFile, final boolean doCreateDataSource) {
    Shell shell = UiUtil.getWorkbenchShellOnlyIfUiThread();

    try {
      if (!(vdbOrVdbFile instanceof IFile) && !(vdbOrVdbFile instanceof Vdb)) {
        throw new IllegalArgumentException(
            UTIL.getString(I18N_PREFIX + "selectionIsNotAVdb")); // $NON-NLS-1$
      }

      // make sure there is a Teiid connection
      if (!teiidServer.isConnected()) {
        return false;
      }

      Vdb vdb =
          ((vdbOrVdbFile instanceof IFile)
              ? new Vdb((IFile) vdbOrVdbFile, null)
              : (Vdb) vdbOrVdbFile);

      if (!vdb.isSynchronized()) {
        String title = UTIL.getString("VdbNotSyncdDialog.title"); // $NON-NLS-1$
        String msg = UTIL.getString("VdbNotSyncdDialog.msg"); // $NON-NLS-1$
        if (!MessageDialog.openQuestion(shell, title, msg)) return false;
      }

      final VdbDeployer deployer = new VdbDeployer(shell, vdb, teiidServer, doCreateDataSource);
      ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);

      failedModelName = null;

      IRunnableWithProgress runnable =
          new IRunnableWithProgress() {
            /**
             * {@inheritDoc}
             *
             * @see
             *     org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
             */
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
              try {
                failedModelName = deployer.deploy(monitor);
              } catch (Exception e) {
                throw new InvocationTargetException(e);
              }
            }
          };

      // deploy using progress monitor (UI is blocked)
      dialog.run(true, false, runnable);

      // process results
      VdbDeployer.DeployStatus status = deployer.getStatus();

      if (status.isError()) {
        String message = null;

        if (VdbDeployer.DeployStatus.CREATE_DATA_SOURCE_FAILED == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "createDataSourceFailed",
                  deployer.getVdbName(),
                  failedModelName); //$NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.DEPLOY_VDB_FAILED == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "vdbFailedToDeploy", deployer.getVdbName()); // $NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.TRANSLATOR_PROBLEM == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "translatorDoesNotExistOnServer",
                  deployer.getVdbName()); // $NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.SOURCE_CONNECTION_INFO_PROBLEM == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "sourceMissingConnectionInfo",
                  deployer.getVdbName()); // $NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.EXCEPTION == status) {
          throw deployer.getException(); // let catch block below
          // handle
        } else {
          // unexpected
          message =
              UTIL.getString(
                  I18N_PREFIX + "unknownDeployError", deployer.getVdbName(), status); // $NON-NLS-1$
        }

        // show user the error
        MessageDialog.openError(
            shell, UTIL.getString(I18N_PREFIX + "vdbNotDeployedTitle"), message); // $NON-NLS-1$
        return false;
      } else if (status.isDeployed()) {
        if (teiidServer.wasVdbRemoved(deployer.getVdbName())) {
          StringBuilder message =
              new StringBuilder(
                  UTIL.getString(
                      I18N_PREFIX + "vdbNotActiveMessage", // $NON-NLS-1$
                      vdb.getName()));

          for (String error : teiidServer.retrieveVdbValidityErrors(deployer.getVdbName())) {
            message.append(
                UTIL.getString(I18N_PREFIX + "notActiveErrorMessage", error)); // $NON-NLS-1$
          }

          MessageDialog.openWarning(
              shell,
              UTIL.getString(I18N_PREFIX + "vdbNotActiveTitle"),
              message.toString()); // $NON-NLS-1$
          return true;
        }
      } else {
        return false;
      }
    } catch (Throwable e) {
      if (e instanceof InvocationTargetException) {
        e = ((InvocationTargetException) e).getCause();
      }

      String vdbName = null;

      if (vdbOrVdbFile instanceof IFile) {
        vdbName = ((IFile) vdbOrVdbFile).getName();
      } else if (vdbOrVdbFile instanceof Vdb) {
        vdbName = ((Vdb) vdbOrVdbFile).getFile().getName();
      } else {
        vdbName = UTIL.getString(I18N_PREFIX + "selectionIsNotAVdb"); // $NON-NLS-1$
      }

      String message =
          UTIL.getString(
              I18N_PREFIX + "problemDeployingVdbToServer", vdbName, teiidServer); // $NON-NLS-1$
      UTIL.log(e);
      ErrorDialog.openError(shell, message, null, new Status(IStatus.ERROR, PLUGIN_ID, message, e));

      return false;
    }

    return true;
  }
  /**
   * @see org.eclipse.jface.action.IAction#run()
   * @since 5.0
   */
  @Override
  public void run() {
    final IWorkbenchWindow iww = VdbUiPlugin.singleton.getCurrentWorkbenchWindow();
    // A) get the selected model and extract a "ConnectionProfileInfo" from it using the
    // ConnectionProfileInfoHandler

    // B) Use ConnectionProfileHandler.getConnectionProfile(connectionProfileInfo) to query the user
    // to
    // select a ConnectionProfile (or create new one)

    // C) Get the resulting ConnectionProfileInfo from the dialog and re-set the model's connection
    // info
    // via the ConnectionProfileInfoHandler
    ModelResource modelResource = null;
    if (!getSelection().isEmpty()) {
      IFile modelFile = (IFile) SelectionUtilities.getSelectedObjects(getSelection()).get(0);
      modelResource = ModelUtilities.getModelResource(modelFile);
    }
    try {

      ITeiidServer teiidServer = cachedServer;
      if (teiidServer == null) {
        if (DqpPlugin.getInstance().getServerManager().getDefaultServer() == null) {
          MessageDialog.openConfirm(
              iww.getShell(),
              getString("noServer.title"), // $NON-NLS-1$
              getString("noServer.message")); // $NON-NLS-1$
          return;
        } else if (DqpPlugin.getInstance().getServerManager().getDefaultServer().isConnected()) {
          teiidServer = DqpPlugin.getInstance().getServerManager().getDefaultServer();
        } else {
          MessageDialog.openConfirm(
              iww.getShell(),
              getString("noServerConnection.title"), // $NON-NLS-1$
              getString("noServerConnection.message")); // $NON-NLS-1$
          return;
        }

        teiidServer.connect();
      }

      Collection<ModelResource> relationalModels = getRelationalModelsWithConnections();
      final CreateDataSourceWizard wizard =
          new CreateDataSourceWizard(teiidServer, relationalModels, modelResource);

      wizard.init(iww.getWorkbench(), new StructuredSelection());
      final WizardDialog dialog = new WizardDialog(wizard.getShell(), wizard);
      final int rc = dialog.open();
      if (rc == Window.OK) {
        // Need to check if the connection needs a password

        TeiidDataSourceInfo info = wizard.getTeiidDataSourceInfo();
        Properties props = info.getProperties();
        IConnectionInfoProvider provider = info.getConnectionInfoProvider();
        boolean cancelledPassword = false;
        if (null != provider.getDataSourcePasswordPropertyKey()
            && props.get(provider.getDataSourcePasswordPropertyKey()) == null) {

          int result =
              new AbstractPasswordDialog(
                  iww.getShell(), getString("passwordTitle"), null) { // $NON-NLS-1$
                @SuppressWarnings("synthetic-access")
                @Override
                protected boolean isPasswordValid(final String password) {
                  pwd = password;
                  return true;
                }
              }.open();
          if (result == Window.OK) {
            props.put(provider.getDataSourcePasswordPropertyKey(), this.pwd);
          } else {
            cancelledPassword = true;
          }
        }

        if (!cancelledPassword) {
          teiidServer.getOrCreateDataSource(
              info.getDisplayName(), info.getJndiName(), provider.getDataSourceType(), props);
        }
      }
      // createDataSource(modelFile);
    } catch (Exception e) {
      if (modelResource != null) {
        MessageDialog.openError(
            getShell(),
            getString("errorCreatingDataSourceForModel", modelResource.getItemName()),
            e.getMessage()); // $NON-NLS-1$
        DqpUiConstants.UTIL.log(
            IStatus.ERROR,
            e,
            getString(
                "errorCreatingDataSourceForModel", modelResource.getItemName())); // $NON-NLS-1$
      } else {
        MessageDialog.openError(
            getShell(), getString("errorCreatingDataSource"), e.getMessage()); // $NON-NLS-1$
        DqpUiConstants.UTIL.log(
            IStatus.ERROR, e, getString("errorCreatingDataSource")); // $NON-NLS-1$
      }
    }
  }