/**
 * Page allows user to select Delimited or Fixed Width column formatted flat file
 *
 * @since 8.0
 */
public class TeiidMetadataImportFormatPage extends AbstractWizardPage implements UiConstants {
  // ===========================================================================================================================
  // Constants

  private static final String I18N_PREFIX =
      I18nUtil.getPropertyPrefix(TeiidMetadataImportFormatPage.class);

  private static final String TITLE = getString("title"); // $NON-NLS-1$
  private static final String INITIAL_MESSAGE = getString("initialMessage"); // $NON-NLS-1$

  private final String EMPTY = StringUtilities.EMPTY_STRING;
  private final int GROUP_HEIGHT_190 = 190;

  private static String getString(final String id) {
    return Util.getString(I18N_PREFIX + id);
  }

  private static String getString(final String id, final Object param) {
    return Util.getString(I18N_PREFIX + id, param);
  }

  private TeiidMetadataImportInfo info;

  private TeiidMetadataFileInfo dataFileInfo;

  // ====================================================
  // GENERAL WIDGETS
  Text selectedFileText;
  Text numberPreviewLinesText;
  Text numberLinesInFileText;

  // ====================================================
  // DELIMITED OPTION WIDGETS
  ListViewer fileContentsViewer;
  Button delimitedColumnsRB;

  // ====================================================
  // FIXED COLUMN WIDTH OPTION WIDGETS
  Button fixedWidthColumnsRB;

  boolean creatingControl = false;

  boolean synchronizing = false;

  /**
   * @param info the import data (cannot be <code>null</code>)
   * @since 4.0
   */
  public TeiidMetadataImportFormatPage(TeiidMetadataImportInfo info) {
    super(TeiidMetadataImportFormatPage.class.getSimpleName(), TITLE);

    CoreArgCheck.isNotNull(info, "info"); // $NON-NLS-1$
    this.info = info;

    setImageDescriptor(UiPlugin.getDefault().getImageDescriptor(Images.IMPORT_TEIID_METADATA));
  }

  @Override
  public void createControl(Composite parent) {
    creatingControl = true;
    // Create page
    final Composite mainPanel = new Composite(parent, SWT.NONE);

    mainPanel.setLayout(new GridLayout(1, false));
    mainPanel.setLayoutData(
        new GridData()); // GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
    mainPanel.setSize(mainPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT));

    setControl(mainPanel);

    // Create Bottom Composite
    Composite upperPanel =
        WidgetFactory.createPanel(mainPanel, SWT.NONE, GridData.FILL_HORIZONTAL, 2, 2);
    upperPanel.setLayout(new GridLayout(2, false));

    setMessage(INITIAL_MESSAGE);

    Label selectedFileLabel = new Label(upperPanel, SWT.NONE);
    selectedFileLabel.setText(getString("selectedFile")); // $NON-NLS-1$

    selectedFileText = new Text(upperPanel, SWT.BORDER); // , SWT.BORDER | SWT.SINGLE);
    selectedFileText.setBackground(
        Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
    selectedFileText.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE));
    selectedFileText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    selectedFileText.setEditable(false);

    createFilePreviewOptionsGroup(mainPanel);

    createColumnOptionsRadioGroup(mainPanel);

    createFileContentsGroup(mainPanel);

    creatingControl = false;

    setPageComplete(false);
  }

  @Override
  public void setVisible(boolean visible) {
    super.setVisible(visible);

    if (visible) {
      TeiidMetadataFileInfo fileInfo = null;
      for (TeiidMetadataFileInfo theFileInfo : info.getFileInfos()) {
        if (theFileInfo.doProcess()) {
          fileInfo = theFileInfo;
          break;
        }
      }
      if (fileInfo != null) {
        this.dataFileInfo = fileInfo;

        loadFileContentsViewers();
      }
      synchronizeUI();

      validatePage();
    }
  }

  private boolean validatePage() {
    if (dataFileInfo == null) return false;

    if (!dataFileInfo.getStatus().isOK()
        && !(dataFileInfo.getStatus().getSeverity() == IStatus.WARNING)) {
      setThisPageComplete(dataFileInfo.getStatus().getMessage(), IStatus.ERROR);
      return false;
    }

    setThisPageComplete(EMPTY, NONE);
    return true;
  }

  private void setThisPageComplete(String message, int severity) {
    WizardUtil.setPageComplete(this, message, severity);
  }

  private void synchronizeUI() {
    synchronizing = true;

    if (dataFileInfo == null) return;

    String charset = this.info.getFileInfo(this.dataFileInfo.getDataFile()).getCharset();
    if (!charset.equals(this.dataFileInfo.getCharset())) {
      this.dataFileInfo = this.info.getFileInfo(this.dataFileInfo.getDataFile());
      loadFileContentsViewers();
    }

    selectedFileText.setText(dataFileInfo.getDataFile().getName());

    boolean isDelimitedOption = this.dataFileInfo.doUseDelimitedColumns();

    { // number of preview lines
      final String numLines = Integer.toString(this.dataFileInfo.getNumberOfCachedFileLines());

      if (!numLines.equals(this.numberPreviewLinesText.getText())) {
        this.numberPreviewLinesText.setText(numLines);
      }
    }

    this.delimitedColumnsRB.setSelection(isDelimitedOption);
    this.fixedWidthColumnsRB.setSelection(!isDelimitedOption);

    this.numberLinesInFileText.setText(
        Integer.toString(this.dataFileInfo.getNumberOfLinesInFile()));

    synchronizing = false;
  }

  private void createColumnOptionsRadioGroup(Composite parent) {
    Group theGroup =
        WidgetFactory.createGroup(
            parent, getString("columnsFormatGroup"), SWT.NONE, 1, 2); // $NON-NLS-1$
    theGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    // delimitedColumnsRB, fixedWidthColumnsRB;
    this.delimitedColumnsRB =
        WidgetFactory.createRadioButton(theGroup, getString("characterDelimited")); // $NON-NLS-1$

    this.delimitedColumnsRB.addSelectionListener(
        new SelectionAdapter() {

          @Override
          public void widgetSelected(final SelectionEvent event) {
            if (!synchronizing && !creatingControl) {
              if (event.getSource() == delimitedColumnsRB) {
                if (delimitedColumnsRB.getSelection() != dataFileInfo.doUseDelimitedColumns()) {
                  dataFileInfo.setUseDelimitedColumns(delimitedColumnsRB.getSelection());
                  dataFileInfo.setFixedWidthColumns(!delimitedColumnsRB.getSelection());
                  if (dataFileInfo.getColumnInfoList().size() > 0) {
                    boolean result =
                        MessageDialog.openQuestion(
                            getShell(),
                            getString("formatChangedTitle"), // $NON-NLS-1$
                            getString("formateChangedMessage")); // $NON-NLS-1$
                    if (result) {
                      dataFileInfo.clearColumns();
                    }
                  }
                  handleInfoChanged(false);
                }
              }
            }
          }
        });

    this.fixedWidthColumnsRB =
        WidgetFactory.createRadioButton(theGroup, getString("fixedWidth")); // $NON-NLS-1$

    this.fixedWidthColumnsRB.addSelectionListener(
        new SelectionAdapter() {

          @Override
          public void widgetSelected(final SelectionEvent event) {
            if (!synchronizing && !creatingControl) {
              if (event.getSource() == fixedWidthColumnsRB) {
                if (fixedWidthColumnsRB.getSelection() != dataFileInfo.isFixedWidthColumns()) {
                  dataFileInfo.setFixedWidthColumns(fixedWidthColumnsRB.getSelection());
                  dataFileInfo.setUseDelimitedColumns(!fixedWidthColumnsRB.getSelection());
                  if (dataFileInfo.getColumnInfoList().size() > 0) {
                    boolean result =
                        MessageDialog.openQuestion(
                            getShell(),
                            getString("formatChangedTitle"), // $NON-NLS-1$
                            getString("formateChangedMessage")); // $NON-NLS-1$
                    if (result) {
                      dataFileInfo.clearColumns();
                    }
                  }
                  handleInfoChanged(false);
                }
              }
            }
          }
        });

    this.delimitedColumnsRB.setSelection(true);
  }

  private void createFilePreviewOptionsGroup(Composite parent) {
    Group theGroup =
        WidgetFactory.createGroup(
            parent, getString("filePreviewOptionsGroup"), SWT.NONE, 1, 5); // $NON-NLS-1$
    theGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Label numberLinesInFileLabel = new Label(theGroup, SWT.NONE);
    numberLinesInFileLabel.setText(getString("numberOfLinesLabel")); // $NON-NLS-1$

    numberLinesInFileText = WidgetFactory.createTextField(theGroup, SWT.NONE);
    numberLinesInFileText.setEditable(false);
    numberLinesInFileText.setBackground(
        Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
    GridData gd = new GridData();
    gd.minimumWidth = 50;

    Label spacer = new Label(theGroup, SWT.NONE);
    spacer.setText("                    "); // $NON-NLS-1$

    Label prefixLabel = new Label(theGroup, SWT.NONE);
    prefixLabel.setText(getString("numberOfPreviewLines")); // $NON-NLS-1$
    prefixLabel.setLayoutData(new GridData()); // new GridData(GridData.FILL_HORIZONTAL));

    this.numberPreviewLinesText = WidgetFactory.createTextField(theGroup, SWT.NONE);
    gd = new GridData();
    gd.minimumWidth = 50;

    this.numberPreviewLinesText.setLayoutData(gd);
    this.numberPreviewLinesText.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(final ModifyEvent event) {
            if (!synchronizing) {
              if (!numberPreviewLinesText.getText().isEmpty()) {
                try {
                  int nLines = Integer.parseInt(numberPreviewLinesText.getText());
                  if (nLines == 0) {
                    setErrorMessage(getString("numberOfLinesCannotBeNullOrZero")); // $NON-NLS-1$
                    return;
                  }
                  if (nLines != dataFileInfo.getNumberOfCachedFileLines()) {
                    dataFileInfo.setNumberOfCachedFileLines(nLines);
                    handleInfoChanged(true);
                  }
                  setErrorMessage(null);
                } catch (NumberFormatException ex) {
                  setErrorMessage(
                      getString(
                          "numberOfLinesMustBeInteger",
                          numberPreviewLinesText.getText())); // $NON-NLS-1$
                  return;
                }
              } else {
                setErrorMessage(getString("numberOfLinesCannotBeNullOrZero")); // $NON-NLS-1$
                return;
              }
            }
          }
        });
  }

  private void createFileContentsGroup(Composite parent) {
    Group theGroup =
        WidgetFactory.createGroup(
            parent, getString("fileContentsGroup"), SWT.NONE, 1, 4); // $NON-NLS-1$
    GridData groupGD = new GridData(GridData.FILL_BOTH);
    groupGD.heightHint = GROUP_HEIGHT_190;
    groupGD.widthHint = 400;
    theGroup.setLayoutData(groupGD);

    this.fileContentsViewer = new ListViewer(theGroup, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
    GridData data = new GridData(GridData.FILL_BOTH);
    data.horizontalSpan = 4;
    this.fileContentsViewer.getControl().setFont(JFaceResources.getTextFont());
    this.fileContentsViewer.getControl().setLayoutData(data);

    if (this.dataFileInfo != null) {
      for (String row : this.dataFileInfo.getCachedFirstLines()) {
        if (row != null) {
          this.fileContentsViewer.add(row);
        }
      }
    }

    // Add a Context Menu
    final MenuManager columnMenuManager = new MenuManager();
    this.fileContentsViewer.getControl().setMenu(columnMenuManager.createContextMenu(parent));
  }

  private void handleInfoChanged(boolean reloadFileContents) {
    if (synchronizing) return;

    synchronizeUI();

    if (reloadFileContents) {
      loadFileContentsViewers();
    }

    validatePage();
  }

  private void loadFileContentsViewers() {
    fileContentsViewer.getList().removeAll();
    for (String row : this.dataFileInfo.getCachedFirstLines()) {
      if (row != null) {
        this.fileContentsViewer.add(row);
      }
    }
  }
}
/** @since 8.0 */
public class ViewConnectionProfileAction extends SortableSelectionAction
    implements IConnectionAction {
  private static final String I18N_PREFIX =
      I18nUtil.getPropertyPrefix(ViewConnectionProfileAction.class);
  private static final String TITLE = getString("title"); // $NON-NLS-1$

  private static String getString(final String id) {
    return DatatoolsUiConstants.UTIL.getString(I18N_PREFIX + id);
  }

  private static String getString(final String id, final Object value) {
    return DatatoolsUiConstants.UTIL.getString(I18N_PREFIX + id, value);
  }

  private ConnectionInfoProviderFactory providerFactory;

  /** @since 5.0 */
  public ViewConnectionProfileAction() {
    super(TITLE, SWT.DEFAULT);
    setImageDescriptor(
        DatatoolsUiPlugin.getDefault()
            .getImageDescriptor(DatatoolsUiConstants.Images.VIEW_CONNECTION_ICON));
    providerFactory = new ConnectionInfoProviderFactory();
  }

  /**
   * @see
   *     org.teiid.designer.ui.actions.SortableSelectionAction#isValidSelection(org.eclipse.jface.viewers.ISelection)
   * @since 5.0
   */
  @Override
  public boolean isValidSelection(ISelection selection) {
    // Enable for single/multiple Virtual Tables
    return sourceModelSelected(selection);
  }

  /**
   * @see org.eclipse.jface.action.IAction#run()
   * @since 5.0
   */
  @Override
  public void run() {
    ModelResource modelResource = null;
    if (!getSelection().isEmpty()) {
      IFile modelFile = (IFile) SelectionUtilities.getSelectedObjects(getSelection()).get(0);
      modelResource = ModelUtilities.getModelResource(modelFile);
    }

    if (modelResource != null) {
      Properties props = getModelConnectionProperties(modelResource);

      if (props == null || props.isEmpty()) {
        MessageDialog.openInformation(
            getShell(),
            getString("noInfo.title"), // $NON-NLS-1$
            getString("noInfo.message", modelResource.getItemName())); // $NON-NLS-1$
        return;
      }
      String name = modelResource.getItemName();

      ConnectionProfileSummaryDialog dialog =
          new ConnectionProfileSummaryDialog(getShell(), name, props);

      dialog.open();
    }
  }

  private Properties getModelConnectionProperties(ModelResource mr) {

    try {
      if (ModelIdentifier.isRelationalSourceModel(mr)) {
        IConnectionInfoProvider provider = null;

        try {
          provider = getProvider(mr);
        } catch (Exception e) {
          // If provider throws exception its OK because some models may not have connection info.
        }

        if (provider != null) {
          Properties properties = provider.getProfileProperties(mr); // ConnectionProperties(mr);
          Properties p2 = provider.getConnectionProperties(mr);
          String translatorName = provider.getTranslatorName(mr);
          for (Object key : p2.keySet()) {
            properties.put(key, p2.get(key));
          }
          if (translatorName != null) {
            properties.put(getString("translatorKey"), translatorName); // $NON-NLS-1$
          }
          if (properties != null && !properties.isEmpty()) {
            return properties;
          }
        }
      }
    } catch (CoreException e) {
      DatatoolsUiConstants.UTIL.log(e);
    }

    return null;
  }

  /**
   * @see
   *     org.teiid.designer.ui.actions.ISelectionAction#isApplicable(org.eclipse.jface.viewers.ISelection)
   * @since 5.0
   */
  @Override
  public boolean isApplicable(ISelection selection) {
    return sourceModelSelected(selection);
  }

  private boolean sourceModelSelected(ISelection theSelection) {
    boolean result = false;
    List<?> allObjs = SelectionUtilities.getSelectedObjects(theSelection);
    if (!allObjs.isEmpty() && allObjs.size() == 1) {
      Iterator<?> iter = allObjs.iterator();
      result = true;
      Object nextObj = null;
      while (iter.hasNext() && result) {
        nextObj = iter.next();

        if (nextObj instanceof IFile) {
          result = ModelIdentifier.isRelationalSourceModel((IFile) nextObj);
        } else {
          result = false;
        }
      }
    }

    return result;
  }

  public IConnectionInfoProvider getProvider(ModelResource modelResource) throws Exception {
    IConnectionInfoProvider provider = null;
    provider = providerFactory.getProvider(modelResource);
    if (null == provider) {
      throw new Exception(getString("noConnectionInfoProvider.message")); // $NON-NLS-1$
    }
    return provider;
  }

  private Shell getShell() {
    return Display.getCurrent().getActiveShell();
  }
}
Ejemplo n.º 3
0
/** @since 8.0 */
public class ImportTextWizard extends AbstractWizard
    implements PluginConstants.Images, IImportWizard, CoreStringUtil.Constants, UiConstants {

  private static final String I18N_PREFIX = I18nUtil.getPropertyPrefix(ImportTextWizard.class);
  private static final String WIDTH = "width"; // $NON-NLS-1$
  private static final String HEIGHT = "height"; // $NON-NLS-1$

  private static final String TITLE = getString("title"); // $NON-NLS-1$
  private static final ImageDescriptor IMAGE =
      TextImportPlugin.getDefault().getImageDescriptor(IMPORT_PROJECT_ICON);
  private static final String NOT_LICENSED_MSG = getString("notLicensedMessage"); // $NON-NLS-1$

  // Set Licensed to true. Leave licencing code in, just in case we decide
  // to license in the future...
  private static boolean importLicensed = true;

  /** @since 4.0 */
  private static String getString(final String id) {
    return Util.getString(I18N_PREFIX + id);
  }

  private ImportTextMainPage importTextMainPage;
  private static ITextImportMainPage[] importers;

  /** @since 4.0 */
  public ImportTextWizard() {
    super(TextImportPlugin.getDefault(), TITLE, IMAGE);
    importers = TextImportContributionManager.getTextImporters();
  }

  Composite createEmptyPageControl(final Composite parent) {
    return new Composite(parent, SWT.NONE);
  }

  /** @see org.eclipse.jface.wizard.IWizard#createPageControls(org.eclipse.swt.widgets.Composite) */
  @Override
  public void createPageControls(Composite pageContainer) {
    if (importLicensed) {
      // If no dialog size settings, then use default of 500X500
      IDialogSettings settings = getDialogSettings();
      // Try to get height and width settings
      try {
        settings.getInt(WIDTH);
        settings.getInt(HEIGHT);
        // If height or width not found, set 500x500 default
      } catch (NumberFormatException e) {
        settings.put(WIDTH, 500);
        settings.put(HEIGHT, 500);
      }
      super.createPageControls(pageContainer);
    }
  }

  /**
   * @see org.eclipse.jface.wizard.IWizard#performFinish()
   * @since 4.0
   */
  @Override
  public boolean finish() {
    boolean result = true;
    String importType = this.importTextMainPage.getImportType();

    for (int i = 0; i < importers.length; i++) {
      if (importers[i].getType().equals(importType)) {
        importers[i].finish();
        break;
      }
    }

    return result;
  }

  /**
   * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
   *     org.eclipse.jface.viewers.IStructuredSelection)
   * @since 4.0
   */
  @Override
  public void init(final IWorkbench workbench, final IStructuredSelection selection) {

    IStructuredSelection finalSelection = selection;
    if (!ModelerUiViewUtils.workspaceHasOpenModelProjects()) {
      IProject newProject = ModelerUiViewUtils.queryUserToCreateModelProject();

      if (newProject != null) {
        finalSelection = new StructuredSelection(newProject);
      }
    }

    if (importLicensed) {
      importTextMainPage = new ImportTextMainPage(finalSelection);
      addPage(importTextMainPage);
      //
      for (int i = 0; i < importers.length; i++) {
        addPage((IWizardPage) importers[i]);
      }
    } else {
      // Create empty page
      WizardPage page =
          new WizardPage(ImportTextWizard.class.getSimpleName(), TITLE, null) {

            @Override
            public void createControl(final Composite parent) {
              setControl(createEmptyPageControl(parent));
            }
          };
      page.setMessage(NOT_LICENSED_MSG, IMessageProvider.ERROR);
      page.setPageComplete(false);
      addPage(page);
    }
  }

  /** @see org.eclipse.jface.wizard.IWizard#getNextPage(org.eclipse.jface.wizard.IWizardPage) */
  @Override
  public IWizardPage getNextPage(final IWizardPage thePage) {
    /*----------------------------------------
     Pages:
        A. importTypeSelectionPage
        B. importPage
    ------------------------------------------*/

    IWizardPage result = null;

    // only need to define logic for those pages where the next page is dynamic.
    // the call to super will handle everything else.

    if (thePage == this.importTextMainPage) {
      String importType = this.importTextMainPage.getImportType();
      for (int i = 0; i < importers.length; i++) {
        if (importers[i].getType().equals(importType)) {
          result = (IWizardPage) importers[i];
          break;
        }
      }
      this.importTextMainPage.saveWidgetValues();
    } else {
      boolean isContributed = false;
      // be sure thePage is contributed
      // for( int i=0; i<importers.length; i++ ) {
      for (int i = 0; i < importers.length; i++) {
        if (thePage.equals(importers[i])) {
          isContributed = true;
          break;
        }
      }
      if (!isContributed)
        CoreArgCheck.isTrue(false, "Unexpected TextImport Wizard Page:" + thePage); // $NON-NLS-1$
    }

    return result;
  }

  /** @see org.eclipse.jface.wizard.IWizard#getPreviousPage(org.eclipse.jface.wizard.IWizardPage) */
  @Override
  public IWizardPage getPreviousPage(IWizardPage thePage) {
    IWizardPage pPage = super.getPreviousPage(thePage);
    pPage.setVisible(true);
    return pPage;
  }

  /**
   * @see org.eclipse.jface.wizard.Wizard#canFinish()
   * @since 4.0
   */
  @Override
  public boolean canFinish() {
    boolean canFinish = false;
    IWizardPage[] pages = this.getPages();
    // Can finish if all pages are complete
    IWizardPage page1 = pages[0];
    if (page1.isPageComplete()) {
      IWizardPage page2 = null;
      String importType = this.importTextMainPage.getImportType();
      for (int i = 0; i < importers.length; i++) {
        if (importers[i].getType().equals(importType)) {
          page2 = (IWizardPage) importers[i];
          break;
        }
      }
      if (page2 != null && page2.isPageComplete()) {
        canFinish = true;
      }
    }
    return canFinish;
  }

  /**
   * @see org.eclipse.jface.wizard.IWizard#dispose()
   * @since 4.0
   */
  @Override
  public void dispose() {
    super.dispose();
  }
}
/** @since 8.0 */
public class DefaultTeiidServerPreferenceContributor
    implements IGeneralPreferencePageContributor, UiConstants {

  private static final String PREF_ID = ITeiidServerManager.DEFAULT_TEIID_SERVER_VERSION_ID;

  private static final String PREFIX =
      I18nUtil.getPropertyPrefix(DefaultTeiidServerPreferenceContributor.class);

  private Shell shell;

  private Combo versionCombo;

  /**
   * {@inheritDoc}
   *
   * @see
   *     org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#createPreferenceEditor(org.eclipse.swt.widgets.Composite)
   */
  @Override
  public void createPreferenceEditor(Composite parent) {
    shell = parent.getShell();
    Composite panel = new Composite(parent, SWT.NONE);
    GridLayoutFactory.swtDefaults().numColumns(2).applyTo(panel);

    versionCombo = new Combo(panel, SWT.DROP_DOWN);
    versionCombo.setFont(JFaceResources.getDialogFont());
    versionCombo.setToolTipText(Util.getStringOrKey(PREFIX + "toolTip")); // $NON-NLS-1$
    GridDataFactory.swtDefaults()
        .grab(true, true)
        .align(SWT.LEFT, SWT.CENTER)
        .applyTo(versionCombo);

    Label title = new Label(panel, SWT.NONE);
    title.setText(Util.getStringOrKey(PREFIX + "title")); // $NON-NLS-1$
    GridDataFactory.swtDefaults().grab(true, true).align(SWT.LEFT, SWT.CENTER).applyTo(title);

    // initialize state
    refresh();
  }

  /**
   * {@inheritDoc}
   *
   * @see org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#getName()
   */
  @Override
  public String getName() {
    return Util.getStringOrKey(PREFIX + "name"); // $NON-NLS-1$
  }

  /**
   * Obtains the <code>IPreferenceStore</code> where this preference is being persisted.
   *
   * @return the preference store
   */
  private IPreferenceStore getPreferenceStore() {
    return UiPlugin.getDefault().getPreferenceStore();
  }

  /**
   * Obtains the {@link IPreferenceStore}'s default or current value for this preference
   *
   * @param defaultFlag indicates if the default or current value is being requested
   * @return the requested value
   */
  private String getPreferenceStoreValue(boolean defaultFlag) {
    IPreferenceStore prefStore = getPreferenceStore();
    String value = null;

    if (defaultFlag) {
      value = prefStore.getDefaultString(PREF_ID);
    } else {
      value = prefStore.getString(PREF_ID);
    }

    if (StringUtilities.isEmpty(value)) {
      value = TeiidServerVersion.deriveUltimateDefaultServerVersion().toString();
    }

    return value;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#getToolTip()
   */
  @Override
  public String getToolTip() {
    return Util.getStringOrKey(PREFIX + "toolTip"); // $NON-NLS-1$
  }

  /**
   * {@inheritDoc}
   *
   * @see org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#performCancel()
   */
  @Override
  public boolean performCancel() {
    return true;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#performDefaults()
   */
  @Override
  public boolean performDefaults() {
    update(getPreferenceStoreValue(true));
    return true;
  }

  private boolean hasOpenEditors() {
    for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
      for (IWorkbenchPage page : window.getPages()) {
        if (page.getEditorReferences().length > 0) return true;
      }
    }
    return false;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#performOk()
   */
  @Override
  public boolean performOk() {
    // persist value
    String versionString = versionCombo.getText();
    ITeiidServerVersion version = new TeiidServerVersion(versionString);

    if (versionString.equals(getPreferenceStoreValue(false))) return true; // same value - no change

    if (ModelerCore.getTeiidServerManager().getDefaultServer() == null && hasOpenEditors()) {
      // No default teiid instance and open editors so modelling diagrams may close which could
      // surprise!
      boolean changeVersion =
          MessageDialog.openQuestion(
              shell,
              Util.getStringOrKey(PREFIX + "versionChangeQuestionTitle"), // $NON-NLS-1$
              Util.getStringOrKey(PREFIX + "versionChangeQuestionMessage")); // $NON-NLS-1$

      if (!changeVersion) return false;
    }

    try {
      for (ITeiidServerVersion regVersion :
          TeiidRuntimeRegistry.getInstance().getSupportedVersions()) {
        if (regVersion.compareTo(version)) {
          getPreferenceStore().setValue(PREF_ID, regVersion.toString());
          return true;
        }
      }
    } catch (Exception ex) {
      Util.log(ex);
    }

    boolean changeVersion =
        MessageDialog.openQuestion(
            shell,
            Util.getStringOrKey(PREFIX + "unsupportedVersionQuestionTitle"), // $NON-NLS-1$
            Util.getStringOrKey(PREFIX + "unsupportedVersionQuestionMesssage")); // $NON-NLS-1$
    if (changeVersion) {
      getPreferenceStore().setValue(PREF_ID, version.toString());
      return true;
    }

    // No runtime client to support default version
    return false;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#refresh()
   */
  @Override
  public void refresh() {
    update(getPreferenceStoreValue(false));
  }

  /**
   * {@inheritDoc}
   *
   * @see
   *     org.teiid.designer.ui.preferences.IGeneralPreferencePageContributor#setWorkbench(org.eclipse.ui.IWorkbench)
   */
  @Override
  public void setWorkbench(IWorkbench theWorkbench) {
    // nothing to do
  }

  /**
   * Updates the radio buttons selection states corresponding to the new value.
   *
   * @param value the new value
   */
  private void update(String value) {

    List<String> items = new ArrayList<String>();

    try {
      Collection<ITeiidServerVersion> registeredServerVersions =
          TeiidRuntimeRegistry.getInstance().getSupportedVersions();
      items = TeiidServerVersion.orderVersions(registeredServerVersions, true);
    } catch (Exception ex) {
      Util.log(ex);
      for (VersionID versionId : VersionID.values()) {
        items.add(versionId.toString());
      }
    }

    versionCombo.setItems(items.toArray(new String[0]));
    versionCombo.setText(value);
  }
}
Ejemplo n.º 5
0
/** @since 8.0 */
public class DeployVdbAction extends Action
    implements ISelectionListener, Comparable, ISelectionAction {

  static final String I18N_PREFIX = I18nUtil.getPropertyPrefix(DeployVdbAction.class);

  private final Collection<IFile> selectedVDBs = new ArrayList<IFile>();

  Properties designerProperties;

  static String failedModelName = null;

  /** Create a new instance */
  public DeployVdbAction() {
    super();
    setImageDescriptor(
        DqpUiPlugin.getDefault().getImageDescriptor(DqpUiConstants.Images.DEPLOY_VDB));
  }

  /**
   * Create a new instance with given properties
   *
   * @param properties the properties
   */
  public DeployVdbAction(Properties properties) {
    super();
    setImageDescriptor(
        DqpUiPlugin.getDefault().getImageDescriptor(DqpUiConstants.Images.DEPLOY_VDB));
    designerProperties = properties;
  }

  @Override
  public int compareTo(Object o) {
    if (o instanceof String) {
      return getText().compareTo((String) o);
    }

    if (o instanceof Action) {
      return getText().compareTo(((Action) o).getText());
    }
    return 0;
  }

  /**
   * {@inheritDoc}
   *
   * @see
   *     org.teiid.designer.ui.actions.ISelectionAction#isApplicable(org.eclipse.jface.viewers.ISelection)
   */
  @Override
  public boolean isApplicable(ISelection selection) {
    List objs = SelectionUtilities.getSelectedObjects(selection);

    if (objs.isEmpty()) {
      return false;
    }

    for (Object obj : objs) {
      if (obj instanceof IFile) {
        String extension = ((IFile) obj).getFileExtension();

        if ((extension == null) || !extension.equals(Vdb.FILE_EXTENSION_NO_DOT)) {
          return false;
        }
      } else {
        return false;
      }
    }
    ITeiidServer teiidServer = getServerManager().getDefaultServer();
    if (teiidServer != null) {
      return true;
    }

    return false;
  }

  /**
   * {@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$
          }
        }
      }
    }
  }

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

  /**
   * {@inheritDoc}
   *
   * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart,
   *     org.eclipse.jface.viewers.ISelection)
   */
  @Override
  public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    this.selectedVDBs.clear();
    boolean enable = isApplicable(selection);

    if (isEnabled() != enable) {
      setEnabled(enable);
    }

    if (isEnabled()) {
      List objs = SelectionUtilities.getSelectedObjects(selection);
      this.selectedVDBs.addAll(objs);
    }
  }

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

  private static ITeiidServerManager getServerManager() {
    return DqpPlugin.getInstance().getServerManager();
  }

  /**
   * @param teiidServer the teiidServer where the VDB is being deployed to (can be <code>null</code>
   *     )
   * @param vdbOrVdbFile the VDB being deployed
   */
  public static boolean deployVdb(ITeiidServer teiidServer, final Object vdbOrVdbFile) {
    return deployVdb(teiidServer, vdbOrVdbFile, shouldAutoCreateDataSource());
  }

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

  /**
   * @return <code>true</code> if data source should be auto-created based on the current preference
   *     value
   */
  static boolean shouldAutoCreateDataSource() {
    return DqpPlugin.getInstance()
        .getPreferences()
        .getBoolean(
            PreferenceConstants.AUTO_CREATE_DATA_SOURCE,
            PreferenceConstants.AUTO_CREATE_DATA_SOURCE_DEFAULT);
  }

  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);
  }
}
Ejemplo n.º 6
0
/**
 * The <code>RuntimeAssistant<code> ensures that the preview preference is enabled and that a default Teiid server exists.
 *
 * @since 8.0
 */
public final class RuntimeAssistant {

  /** The I18n properties prefix key used by this class. */
  private static final String PREFIX = I18nUtil.getPropertyPrefix(RuntimeAssistant.class);

  /**
   * If the preview preference is disabled or a Teiid server does not exist, a dialog is shown
   * asking the user if they want to enable preview and create a server.
   *
   * @param shell the shell used to display dialog if necessary
   * @return <code>true</code> if preview is enabled, a Teiid server exists, and a connection to the
   *     server has been made
   */
  public static boolean ensurePreviewEnabled(Shell shell) {
    boolean previewEnabled = isPreviewEnabled();
    boolean previewServerExists = previewServerExists();

    // dialog message (null if preview preference enabled and server exists)
    String msg = null;

    if (!previewEnabled && !previewServerExists) {
      msg = UTIL.getString(PREFIX + "previewDisabledNoTeiidInstanceMsg"); // $NON-NLS-1$
    } else if (!previewEnabled) {
      msg = UTIL.getString(PREFIX + "previewDisabledMsg"); // $NON-NLS-1$
    } else if (!previewServerExists) {
      msg = UTIL.getString(PREFIX + "noTeiidInstanceMsg"); // $NON-NLS-1$
    }

    // if necessary open question dialog
    if ((msg != null)
        && MessageDialog.openQuestion(
            shell, UTIL.getString(PREFIX + "confirmEnablePreviewTitle"), msg)) { // $NON-NLS-1$
      // if necessary change preference
      if (!previewEnabled) {
        IEclipsePreferences prefs = DqpPlugin.getInstance().getPreferences();
        prefs.putBoolean(PreferenceConstants.PREVIEW_ENABLED, true);

        // save
        try {
          prefs.flush();
        } catch (BackingStoreException e) {
          UTIL.log(e);
        }
      }

      // if necessary create new server
      if (!previewServerExists) {
        runNewServerAction(shell);
      }
    }

    // if dialog was shown get values again
    if (msg != null) {
      previewEnabled = isPreviewEnabled();
      previewServerExists = previewServerExists();

      // if preview is not enabled or server does not exist then user canceled the dialog or the new
      // server wizard
      if (!previewEnabled || !previewServerExists) {
        return false;
      }
    }

    // abort preview if server is not connected
    return serverConnectionExists(shell);
  }

  /**
   * If a Teiid server does not exist, a dialog is shown asking the user if they want to create a
   * server.
   *
   * @param shell the shell used to display dialog if necessary
   * @param dialogMessage the localized question to ask the user if they want to create a new Teiid
   *     instance in order to continue on with task
   * @return <code>true</code> if a Teiid server exists and can be connected to
   */
  public static boolean ensureServerConnection(Shell shell, String dialogMessage) {
    if (!previewServerExists()) {
      if (MessageDialog.openQuestion(
          shell,
          UTIL.getString(PREFIX + "confirmCreateTeiidInstanceTitle"),
          dialogMessage)) { //$NON-NLS-1$
        runNewServerAction(shell);
      }

      // if server does not exist then user canceled the dialog or the new server wizard
      if (!previewServerExists()) {
        return false;
      }
    }

    // abort preview if server is not connected
    return serverConnectionExists(shell);
  }

  /** @return the default Teiid server (can be <code>null</code>) */
  private static ITeiidServer getServer() {
    return getServerManager().getDefaultServer();
  }

  /** @return the server manager (never <code>null</code>) */
  private static TeiidServerManager getServerManager() {
    return DqpPlugin.getInstance().getServerManager();
  }

  /** @return <code>true</code> if the preview preference is enabled */
  private static boolean isPreviewEnabled() {
    return getServerManager().getPreviewManager().isPreviewEnabled();
  }

  /** @return <code>true</code> if a default Teiid server exists */
  private static boolean previewServerExists() {
    return (getServerManager().getDefaultServer() != null);
  }

  /** @param shell the shell used to run the new server wizard */
  public static void runNewServerAction(Shell shell) {
    NewServerAction action = new NewServerAction(shell);
    action.run();
  }

  /** @param shell the shell used to run the new server wizard */
  public static void runEditServerAction(Shell shell) {
    EditServerAction action = new EditServerAction(shell, getServerManager());
    action.run();
  }

  /** Run the set default server action */
  public static void runSetDefaultServerAction() {
    SetDefaultServerAction action = new SetDefaultServerAction(getServerManager());
    action.run();
  }

  /**
   * @param shell the shell where the dialog is displayed if necessary
   * @return <code>true</code> if connection exists
   */
  private static boolean serverConnectionExists(Shell shell) {
    assert (getServer() != null);

    if (!getServer().isConnected()) {
      MessageDialog.openError(
          shell,
          UTIL.getString(PREFIX + "teiidNotConnectedTitle"), // $NON-NLS-1$
          UTIL.getString(PREFIX + "teiidNotConnectedMsg", getServer().getHost())); // $NON-NLS-1$
      return false;
    }

    return true;
  }

  /**
   * Convenience function for adapting a given object to the given class-type using eclipse's
   * registered adapters
   *
   * @param adaptableObject
   * @param klazz
   * @return adapted object or null
   */
  public static <T> T adapt(Object adaptableObject, Class<T> klazz) {
    return (T) Platform.getAdapterManager().getAdapter(adaptableObject, klazz);
  }

  /**
   * Get a {@link ITeiidServer} from the given selection if one can be adapted
   *
   * @param selection
   * @return server or null
   */
  public static ITeiidServer getServerFromSelection(ISelection selection) {
    if (selection == null || !(selection instanceof StructuredSelection)) return null;

    if (selection.isEmpty()) {
      return null;
    }

    StructuredSelection ss = (StructuredSelection) selection;
    Object element = ss.getFirstElement();

    return adapt(element, ITeiidServer.class);
  }

  /** Prevent instance construction. */
  private RuntimeAssistant() {
    // nothing to do
  }

  /**
   * Can display a dialog, allowing the user to select a server should there be more than one or
   * return the single server in the event of only one.
   *
   * @param shell
   * @return a selected {@link ITeiidServer}
   */
  public static ITeiidServer selectServer(Shell shell) {
    ITeiidServer selectedServer = null;

    if (getServerManager().getServers().size() == 1) {
      selectedServer = getServerManager().getServers().iterator().next();
    } else if (getServerManager().getServers().size() > 1) {
      ServerSelectionDialog dialog = new ServerSelectionDialog(shell);
      dialog.open();

      if (dialog.getReturnCode() == Window.OK) {
        selectedServer = dialog.getServer();
      }
    }

    return selectedServer;
  }
}
/**
 * AbstractLanguageObjectBuilder
 *
 * @since 8.0
 */
public abstract class AbstractLanguageObjectBuilder extends Dialog implements UiConstants {

  // /////////////////////////////////////////////////////////////////////////////////////////////
  // CONSTANTS
  // /////////////////////////////////////////////////////////////////////////////////////////////

  private static final String PREFIX =
      I18nUtil.getPropertyPrefix(AbstractLanguageObjectBuilder.class);

  // /////////////////////////////////////////////////////////////////////////////////////////////
  // FIELDS
  // /////////////////////////////////////////////////////////////////////////////////////////////

  private IAction deleteAction;

  private ILanguageObjectEditor editor;

  private ILanguageObject savedSelection;

  protected ILanguageObject savedLangObj;

  // /////////////////////////////////////////////////////////////////////////////////////////////
  // CONTROLS
  // /////////////////////////////////////////////////////////////////////////////////////////////

  protected Button btnSet;

  protected Button btnReset;

  private Label lblTitle;

  private Composite pnlEditor;

  private Composite pnlEditorDetail;

  LanguageObjectBuilderTreeViewer treeViewer;

  private SqlDisplayPanel currentSql;

  private SqlDisplayPanel originalSql;

  private CLabel originalLanguageObjLabel;

  // /////////////////////////////////////////////////////////////////////////////////////////////
  // CONSTRUCTORS
  // /////////////////////////////////////////////////////////////////////////////////////////////

  protected AbstractLanguageObjectBuilder(Shell theParent, String theTitle) {
    super(theParent, theTitle);
  }

  // /////////////////////////////////////////////////////////////////////////////////////////////
  // METHODS
  // /////////////////////////////////////////////////////////////////////////////////////////////

  @Override
  public void create() {
    super.create();

    editor = createEditor(pnlEditorDetail);
    editor
        .getModel()
        .addModelListener(
            new ILanguageObjectEditorModelListener() {
              @Override
              public void modelChanged(LanguageObjectEditorModelEvent theEvent) {
                handleModelChanged();
              }
            });

    lblTitle.setText(editor.getTitle());

    Composite pnlEditorButtons = new Composite(pnlEditor, SWT.NONE);
    pnlEditorButtons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER));
    pnlEditorButtons.setLayout(new GridLayout());

    //
    // pnlEditorButtons contents
    //

    btnSet = new Button(pnlEditorButtons, SWT.NONE);
    btnSet.setEnabled(false);
    btnSet.setText(Util.getString(PREFIX + "btnSet")); // $NON-NLS-1$
    btnSet.setToolTipText(Util.getString(PREFIX + "btnSet.tip")); // $NON-NLS-1$
    btnSet.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent theEvent) {
            handleSetSelected();
          }
        });

    btnReset = new Button(pnlEditorButtons, SWT.NONE);
    btnReset.setEnabled(false);
    btnReset.setText(Util.getString(PREFIX + "btnReset")); // $NON-NLS-1$
    btnReset.setToolTipText(Util.getString(PREFIX + "btnReset.tip")); // $NON-NLS-1$
    btnReset.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent theEvent) {
            handleResetSelected();
          }
        });

    setLanguageObject(null); // needed to establish the viewer input

    // select root tree node after all construction is finished
    Display.getDefault()
        .asyncExec(
            new Runnable() {
              @Override
              public void run() {
                treeViewer.selectRoot();
              }
            });
  }

  /* (non-Javadoc)
   * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
   */
  @Override
  protected Control createDialogArea(Composite theParent) {
    originalLanguageObjLabel =
        WidgetFactory.createLabel(theParent, CoreStringUtil.Constants.EMPTY_STRING);
    Composite pnlContents = (Composite) super.createDialogArea(theParent);

    //
    // main panel contents
    //

    CTabFolder tabFolder = WidgetFactory.createTabFolder(pnlContents);

    //
    // tabFolder contents - 2 tabs (Tree, SQL Text), each with a splitter
    //

    CTabItem treeTab =
        WidgetFactory.createTab(tabFolder, Util.getString(PREFIX + "treeTab")); // $NON-NLS-1$
    treeTab.setToolTipText(Util.getString(PREFIX + "treeTab.tip")); // $NON-NLS-1$

    SashForm treeTabSash = new SashForm(tabFolder, SWT.VERTICAL);
    treeTabSash.setLayoutData(new GridData(GridData.FILL_BOTH));
    treeTab.setControl(treeTabSash);

    CTabItem sqlTab =
        WidgetFactory.createTab(tabFolder, Util.getString(PREFIX + "sqlTab")); // $NON-NLS-1$
    sqlTab.setToolTipText(Util.getString(PREFIX + "sqlTab.tip")); // $NON-NLS-1$

    SashForm sqlTabSash = new SashForm(tabFolder, SWT.VERTICAL);
    sqlTabSash.setLayoutData(new GridData(GridData.FILL_BOTH));
    sqlTab.setControl(sqlTabSash);

    //
    // treeTab contents
    //

    ViewForm formTree = new ViewForm(treeTabSash, SWT.BORDER);
    Composite pnlTree = new Composite(formTree, SWT.NO_TRIM);
    formTree.setContent(pnlTree);
    GridLayout layout = new GridLayout();
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    pnlTree.setLayout(layout);
    pnlTree.setLayoutData(new GridData(GridData.FILL_BOTH));

    ViewForm formEditor = new ViewForm(treeTabSash, SWT.BORDER);
    pnlEditor = new Composite(formEditor, SWT.NO_TRIM);
    formEditor.setContent(pnlEditor);
    pnlEditor.setLayoutData(new GridData(GridData.FILL_BOTH));

    lblTitle = new Label(formEditor, SWT.CENTER);
    lblTitle.setBackground(BuilderUtils.COLOR_HIGHLIGHT);
    formEditor.setTopLeft(lblTitle);

    treeTabSash.setWeights(new int[] {30, 70});

    //
    // sqlTab contents
    //

    ViewForm formCurrentSql = new ViewForm(sqlTabSash, SWT.BORDER);
    ViewForm formOriginalSql = new ViewForm(sqlTabSash, SWT.BORDER);

    //
    // formCurrentSql contents
    //

    Composite pnlCurrentSql = new Composite(formCurrentSql, SWT.NONE);
    formCurrentSql.setContent(pnlCurrentSql);
    pnlCurrentSql.setLayout(new GridLayout());
    pnlCurrentSql.setLayoutData(new GridData(GridData.FILL_BOTH));

    currentSql = new SqlDisplayPanel(pnlCurrentSql);
    currentSql.setLayoutData(new GridData(GridData.FILL_BOTH));

    CLabel lblCurrent = new CLabel(formCurrentSql, SWT.NONE);
    lblCurrent.setBackground(BuilderUtils.COLOR_HIGHLIGHT);
    lblCurrent.setText(Util.getString(PREFIX + "lblCurrent")); // $NON-NLS-1$
    lblCurrent.setToolTipText(Util.getString(PREFIX + "lblCurrent.tip")); // $NON-NLS-1$
    formCurrentSql.setTopLeft(lblCurrent);

    //
    // formOriginalSql contents
    //

    Composite pnlOriginalSql = new Composite(formOriginalSql, SWT.NONE);
    formOriginalSql.setContent(pnlOriginalSql);
    pnlOriginalSql.setLayout(new GridLayout());
    pnlOriginalSql.setLayoutData(new GridData(GridData.FILL_BOTH));

    originalSql = new SqlDisplayPanel(pnlOriginalSql);
    originalSql.setLayoutData(new GridData(GridData.FILL_BOTH));

    CLabel lblOriginal = new CLabel(formOriginalSql, SWT.NONE);
    lblOriginal.setBackground(BuilderUtils.COLOR_HIGHLIGHT);
    lblOriginal.setText(Util.getString(PREFIX + "lblOriginal")); // $NON-NLS-1$
    lblOriginal.setToolTipText(Util.getString(PREFIX + "lblOriginal.tip")); // $NON-NLS-1$
    formOriginalSql.setTopLeft(lblOriginal);

    //
    // pnlTree contents - 2 columns (tree viewer, button panel)
    //

    layout = new GridLayout();
    layout.numColumns = 2;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    pnlTree.setLayout(layout);

    treeViewer = new LanguageObjectBuilderTreeViewer(pnlTree);
    treeViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          @Override
          public void selectionChanged(SelectionChangedEvent theEvent) {
            handleTreeSelection();
          }
        });

    MenuManager menuMgr = new MenuManager();
    menuMgr.setRemoveAllWhenShown(true);
    menuMgr.addMenuListener(
        new IMenuListener() {
          @Override
          public void menuAboutToShow(IMenuManager theMenuMgr) {
            fillContextMenu(theMenuMgr);
          }
        });
    treeViewer.getTree().setMenu(menuMgr.createContextMenu(treeViewer.getTree()));

    Composite pnlButtons = new Composite(pnlTree, SWT.NONE);
    pnlButtons.setLayout(new GridLayout());

    createTreeButtons(pnlButtons);

    //
    // pnlEditor contents
    //

    layout = new GridLayout();
    layout.numColumns = 2;
    pnlEditor.setLayout(layout);

    pnlEditorDetail = new Composite(pnlEditor, SWT.NONE);
    pnlEditorDetail.setLayoutData(new GridData(GridData.FILL_BOTH));
    pnlEditorDetail.setLayout(new GridLayout());
    return pnlContents;
  }

  protected abstract ILanguageObjectEditor createEditor(Composite theParent);

  /**
   * Creates buttons that interact with the tree.
   *
   * @param theParent the panel where the buttons are contained
   */
  protected void createTreeButtons(Composite theParent) {
    Runnable deleteRunner =
        new Runnable() {
          @Override
          public void run() {
            handleDeleteSelected();
          }
        };
    deleteAction = new DeleteViewerObjectAction(theParent, deleteRunner);
  }

  protected void fillContextMenu(IMenuManager theMenuMgr) {
    theMenuMgr.add(deleteAction);
  }

  public ILanguageObjectEditor getEditor() {
    return editor;
  }

  /* (non-Javadoc)
   * @see org.teiid.query.ui.builder.ILanguageObjectInputProvider#getLanguageObject()
   */
  public ILanguageObject getLanguageObject() {
    return treeViewer.getLanguageObject();
  }

  /**
   * Gets the saved <code>LanguageObject</code>.
   *
   * @return the saved <code>LanguageObject</code> or <code>null</code>
   */
  protected ILanguageObject getSavedLanguageObject() {
    return savedLangObj;
  }

  /**
   * Gets a title for the builder. Title is appropriate for use as a dialog title.
   *
   * @return the builder title
   */
  @Override
  public abstract String getTitle();

  protected LanguageObjectBuilderTreeViewer getTreeViewer() {
    return treeViewer;
  }

  protected void handleDeleteSelected() {
    editor.clear();
    treeViewer.deleteSelection();

    // update SQL text
    setCurrentSql(treeViewer.getLanguageObject());

    editor.acceptFocus();
  }

  void handleModelChanged() {
    boolean isEnabled = false;
    boolean isComplete = false;
    boolean hasChanged = false;
    isEnabled = editor.isEnabled();
    if (isEnabled) {
      isComplete = editor.isComplete();
    }
    if (isComplete) {
      hasChanged = editor.hasChanged();
    }
    boolean state = (isEnabled && isComplete && hasChanged);
    btnSet.setEnabled(state);
    btnReset.setEnabled(state);

    setCurrentSql(treeViewer.getLanguageObject());

    // set enable/disable status of buttons
    setEnabledStatus();
  }

  protected void handleResetSelected() {
    editor.reset();

    // put focus back on editor from the reset button
    editor.acceptFocus();
  }

  protected void handleSetSelected() {
    editor.save();

    // need the editor's language object in order to update tree.
    // the language object should never be null. if it was this handler should not have been called
    ILanguageObject langObj = editor.getLanguageObject();

    CoreArgCheck.isNotNull(
        langObj,
        Util.getString(
            PREFIX + "nullLangObj", // $NON-NLS-1$
            new Object[] {"handleSetSelected"})); // $NON-NLS-1$

    // update tree
    treeViewer.modifySelectedItem(langObj, false);

    // update SQL text
    setCurrentSql(treeViewer.getLanguageObject());

    // put focus back on editor from the set button
    editor.acceptFocus();
  }

  protected void handleTreeSelection() {
    IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
    Object selectedObj = selection.getFirstElement();

    if (selectedObj == null) {
      savedSelection = null;

      if (editor.isEnabled()) {
        editor.setEnabled(false);
      }
    } else {
      // selection with either be a LanguageObject or an Undefined object (String)
      savedSelection =
          (selectedObj instanceof ILanguageObject) ? (ILanguageObject) selectedObj : null;
    }

    setEditorLanguageObject(savedSelection);

    // set enable/disable status of buttons
    setEnabledStatus();
  }

  protected boolean isTreeSelectionRoot() {
    boolean isRoot = false;
    IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
    if (selection.size() > 0) {
      Tree tree = treeViewer.getTree();
      // We are assuming that the tree is single-selection.
      TreeItem treeItem = tree.getSelection()[0];
      TreeItem parentItem = treeItem.getParentItem();
      isRoot = (parentItem == null);
    }
    return isRoot;
  }

  protected void setCurrentSql(ILanguageObject theLangObj) {
    IQueryService queryService = ModelerCore.getTeiidQueryService();
    ISQLStringVisitor visitor = queryService.getSQLStringVisitor();

    currentSql.setText(visitor.getSQLString(theLangObj));
  }

  protected void setEditorLanguageObject(ILanguageObject theEditorLangObj) {
    getEditor().setLanguageObject(savedSelection);

    if (!editor.isEnabled()) {
      editor.setEnabled(true);
    }
  }

  protected void setEnabledStatus() {
    //
    // set enabled status of delete button
    //

    boolean canDelete = treeViewer.canDeleteSelection();

    if (canDelete) {
      if (!deleteAction.isEnabled()) {
        deleteAction.setEnabled(true);
      }
    } else {
      if (deleteAction.isEnabled()) {
        deleteAction.setEnabled(false);
      }
    }

    //
    // set enabled status of OK button
    //

    Button btnOk = getButton(OK);
    boolean enable = treeViewer.isComplete();

    if (btnOk.isEnabled() != enable) {
      btnOk.setEnabled(enable);
    }
  }

  public void setLanguageObject(ILanguageObject theLangObj) {
    // language object must be cloned here so that the original isn't modified.
    // this prevents the original from being modified even if the user cancels out of the builder.
    ILanguageObject langObj = (theLangObj == null) ? null : (ILanguageObject) theLangObj.clone();

    savedLangObj = langObj;
    setOriginalSql(langObj);
    setCurrentSql(langObj);
    treeViewer.setLanguageObject(langObj);
    treeViewer.selectRoot();
    treeViewer.expandAll();

    // Defect 22003 - needed a context for the original expression
    // Providing a Lable at the top of the dialog.
    String labelText =
        Util.getString(PREFIX + "initialExpression")
            + //$NON-NLS-1$
            CoreStringUtil.Constants.DBL_SPACE
            + CoreStringUtil.Constants.DBL_SPACE
            + Util.getString(PREFIX + "undefined"); // $NON-NLS-1$
    if (savedLangObj != null) {
      String loString = savedLangObj.toString();
      if (loString.length() > 50) {
        loString = loString.substring(0, 50) + "..."; // $NON-NLS-1$
      }
      labelText =
          Util.getString(PREFIX + "initialExpression")
              + //$NON-NLS-1$
              CoreStringUtil.Constants.DBL_SPACE
              + CoreStringUtil.Constants.DBL_SPACE
              + loString;
    }
    if (originalLanguageObjLabel != null) {
      originalLanguageObjLabel.setText(labelText);
      originalLanguageObjLabel.getParent().layout();
    }
    // select root tree node
    Display.getDefault()
        .asyncExec(
            new Runnable() {
              @Override
              public void run() {
                treeViewer.selectRoot();
              }
            });
  }

  protected void setOriginalSql(ILanguageObject theLangObj) {
    IQueryService queryService = ModelerCore.getTeiidQueryService();
    ISQLStringVisitor visitor = queryService.getSQLStringVisitor();

    originalSql.setText(visitor.getSQLString(theLangObj));
  }
}
Ejemplo n.º 8
0
/**
 * The ConnectorsView provides a tree view of workspace connector bindings which are stored in a
 * configuration.xml file and corresponding model-to-connector mappings in a WorkspaceBindings.def
 * file.
 *
 * @since 8.0
 */
public class TeiidView extends CommonNavigator implements DqpUiConstants {

  /** Text constant for the server hyperlink label when there are servers available */
  private static final String NEW_SERVER_LABEL =
      UTIL.getString("TeiidServerOverviewSection.newHyperlinkLabel"); // $NON-NLS-1$

  /** Text constant for the server hyperlink label when there are servers available */
  private static final String EDIT_SERVER_LABEL =
      UTIL.getString("TeiidServerOverviewSection.editHyperlinkLabel"); // $NON-NLS-1$

  /** A <code>ViewerFilter</code> that hides the translators. */
  static final ViewerFilter TRANSLATORS_FILTER =
      new ViewerFilter() {
        /**
         * {@inheritDoc}
         *
         * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
         *     java.lang.Object, java.lang.Object)
         */
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
          TeiidTranslator teiidTranslator = RuntimeAssistant.adapt(element, TeiidTranslator.class);
          if (teiidTranslator != null) return false;

          return true;
        }
      };

  /** A <code>ViewerFilter</code> that hides Preview Data Sources. */
  static final ViewerFilter PREVIEW_DATA_SOURCE_FILTER =
      new ViewerFilter() {
        /**
         * {@inheritDoc}
         *
         * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
         *     java.lang.Object, java.lang.Object)
         */
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
          TeiidDataSource dataSource = RuntimeAssistant.adapt(element, TeiidDataSource.class);
          if (dataSource != null && dataSource.isPreview()) return false;

          return true;
        }
      };

  /** A <code>ViewerFilter</code> that hides Preview VDBs. */
  static final ViewerFilter PREVIEW_VDB_FILTER =
      new ViewerFilter() {
        /**
         * {@inheritDoc}
         *
         * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
         *     java.lang.Object, java.lang.Object)
         */
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
          TeiidVdb vdb = RuntimeAssistant.adapt(element, TeiidVdb.class);
          if (vdb != null && vdb.isPreviewVdb()) return false;

          return true;
        }
      };

  /** Prefix for language NLS properties */
  static final String PREFIX = I18nUtil.getPropertyPrefix(TeiidView.class);

  /** Used for restoring view state */
  private static IMemento viewMemento;

  static String getString(final String stringId) {
    return UTIL.getString(PREFIX + stringId);
  }

  static String getString(final String stringId, final Object param) {
    return UTIL.getString(PREFIX + stringId, param);
  }

  private Combo jbossServerCombo;

  private CommonViewer viewer;

  private IPropertySourceProvider propertySourceProvider;

  private KeyFromValueAdapter adapter =
      new KeyFromValueAdapter<String, IServer>() {

        @Override
        public String getKey(IServer value) {
          return value.getName();
        }
      };

  private KeyInValueHashMap<String, IServer> serverMap =
      new KeyInValueHashMap<String, IServer>(adapter);

  private IServerLifecycleListener serversListener =
      new ServerLifecycleAdapter() {

        private void refresh() {
          jbossServerCombo
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      populateJBossServerCombo();
                    }
                  });
        }

        @Override
        public void serverAdded(IServer server) {
          refresh();
        }

        @Override
        public void serverRemoved(IServer server) {
          refresh();
        }
      };

  private Hyperlink newServerOrOpenServerViewHyperlink;
  /** The constructor. */
  public TeiidView() {
    this.setPartName(getString("title.text")); // $NON-NLS-1$
    this.setTitleImage(DqpUiPlugin.getDefault().getImage(Images.SOURCE_BINDING_ICON));
    this.setTitleToolTip(getString("title.tooltip")); // $NON-NLS-1$
  }

  /** This is a callback that will allow us to create the viewer and initialize it. */
  @Override
  public void createPartControl(Composite parent) {
    FormToolkit toolkit = new FormToolkit(parent.getDisplay());

    Composite frame = toolkit.createComposite(parent, SWT.BORDER);
    GridLayoutFactory.fillDefaults().numColumns(2).applyTo(frame);

    Composite comboDescFrame = toolkit.createComposite(frame, SWT.NONE);
    GridDataFactory.fillDefaults().applyTo(comboDescFrame);
    GridLayoutFactory.fillDefaults()
        .margins(5, 20)
        .spacing(SWT.DEFAULT, 25)
        .applyTo(comboDescFrame);

    Composite comboFrame = toolkit.createComposite(comboDescFrame, SWT.NONE);
    GridDataFactory.fillDefaults().applyTo(comboFrame);
    GridLayoutFactory.fillDefaults().applyTo(comboFrame);

    Composite labelFrame = toolkit.createComposite(comboFrame, SWT.NONE);
    GridDataFactory.fillDefaults().applyTo(labelFrame);
    GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(labelFrame);

    Label jbLabel =
        WidgetFactory.createLabel(
            labelFrame, UTIL.getString("TeiidServerOverviewSection.jbLabel")); // $NON-NLS-1$
    jbLabel.setForeground(labelFrame.getDisplay().getSystemColor(SWT.COLOR_DARK_BLUE));
    GridDataFactory.swtDefaults().grab(false, false).applyTo(jbLabel);

    newServerOrOpenServerViewHyperlink =
        toolkit.createHyperlink(labelFrame, EDIT_SERVER_LABEL, SWT.NONE);
    GridDataFactory.swtDefaults().applyTo(newServerOrOpenServerViewHyperlink);
    newServerOrOpenServerViewHyperlink.addHyperlinkListener(
        new HyperlinkAdapter() {

          @Override
          public void linkActivated(HyperlinkEvent e) {
            if (serverMap.isEmpty()) {
              // There are no servers so open the server wizard
              NewServerAction action =
                  new NewServerAction(getViewSite().getShell(), getServerManager());
              action.run();
            } else {
              // open the servers view
              IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
              try {
                window
                    .getActivePage()
                    .showView("org.eclipse.wst.server.ui.ServersView"); // $NON-NLS-1$
              } catch (PartInitException ex) {
                UTIL.log(ex);
              }
            }
          }
        });

    jbossServerCombo = new Combo(comboFrame, SWT.READ_ONLY | SWT.DROP_DOWN);
    toolkit.adapt(jbossServerCombo);
    GridDataFactory.swtDefaults().minSize(250, 30).grab(true, false).applyTo(jbossServerCombo);
    jbossServerCombo.addSelectionListener(
        new SelectionListener() {

          @Override
          public void widgetSelected(SelectionEvent e) {
            handleServerComboSelection();
          }

          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            handleServerComboSelection();
          }
        });

    Text descriptionText =
        toolkit.createText(
            comboDescFrame,
            UTIL.getString("TeiidServerOverviewSection.description"), // $NON-NLS-1$
            SWT.MULTI | SWT.WRAP);
    descriptionText.setForeground(comboDescFrame.getDisplay().getSystemColor(SWT.COLOR_DARK_BLUE));
    GridDataFactory.fillDefaults()
        .grab(false, true)
        .hint(100, SWT.DEFAULT)
        .applyTo(descriptionText);

    super.createPartControl(frame);

    viewer = getCommonViewer();
    GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getControl());

    viewer.setSorter(new NameSorter());

    DqpPlugin.getInstance().getServersProvider().addServerLifecycleListener(serversListener);

    // Populate the jboss server combo box which
    // should also populate the viewer as well
    populateJBossServerCombo();

    viewer.expandToLevel(3);
  }

  private void populateJBossServerCombo() {
    serverMap.clear();

    IServer[] servers = DqpPlugin.getInstance().getServersProvider().getServers();
    for (IServer server : servers) {
      if (TeiidServerAdapterUtil.isJBossServer(server)) {
        serverMap.add(server);
      }
    }

    String[] items = serverMap.keySet().toArray(new String[0]);
    jbossServerCombo.setItems(items);

    if (items.length == 0) {
      newServerOrOpenServerViewHyperlink.setText(NEW_SERVER_LABEL);
    } else {
      newServerOrOpenServerViewHyperlink.setText(EDIT_SERVER_LABEL);
      jbossServerCombo.setText(items[0]);
    }

    // even if nothing in combo, still want the viewer to refresh
    handleServerComboSelection();
  }

  /** Take the server combo's selection and apply it to the viewer */
  private void handleServerComboSelection() {
    TeiidEmptyNode emptyNode = new TeiidEmptyNode();
    // populate viewer
    String serverName = jbossServerCombo.getText();
    IServer server = serverMap.get(serverName);
    if (server == null) {
      viewer.setInput(emptyNode);
    } else {
      viewer.setInput(server);
    }

    // Ensures that the action provider is properly initialised in this view
    IStructuredSelection selection = new StructuredSelection(emptyNode);
    getNavigatorActionService().setContext(new ActionContext(selection));
    getNavigatorActionService().fillActionBars(getViewSite().getActionBars());
  }

  @Override
  public void dispose() {
    super.dispose();
  }

  @Override
  public Object getAdapter(Class adapter) {
    if (adapter.equals(IPropertySheetPage.class)) {
      propertySourceProvider = new RuntimePropertySourceProvider();
      ((RuntimePropertySourceProvider) propertySourceProvider).setEditable(true, false);
      PropertySheetPage page = new PropertySheetPage();
      page.setPropertySourceProvider(propertySourceProvider);
      return page;
    }
    return super.getAdapter(adapter);
  }

  /** @return the server manager being used by this view */
  TeiidServerManager getServerManager() {
    return DqpPlugin.getInstance().getServerManager();
  }

  /**
   * {@inheritDoc}
   *
   * @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite, org.eclipse.ui.IMemento)
   */
  @Override
  public void init(IViewSite site, IMemento memento) throws PartInitException {
    // first time a view is opened in a session a memento is passed in. if view is closed and
    // reopened the memento passed in
    // is null. so will save initial non-null memento to use when a view is reopened in same
    // session. however, it will start
    // with the same settings that the session started with.
    if ((viewMemento == null) && (memento != null)) {
      viewMemento = memento;
    }

    super.init(site, memento);
  }

  /** Passing the focus request to the viewer's control. */
  @Override
  public void setFocus() {
    viewer.getControl().setFocus();
  }

  class NameSorter extends ViewerSorter {}
}
/** @since 8.0 */
public class ServerSelectionDialog extends TitleAreaDialog
    implements DqpUiConstants, IChangeListener {

  private static final String PREFIX = I18nUtil.getPropertyPrefix(ServerSelectionDialog.class);

  ITeiidServer selectedServer;

  Combo serversCombo;

  /** @since 5.5.3 */
  public ServerSelectionDialog(Shell parentShell) {
    super(parentShell);
    setShellStyle(getShellStyle() | SWT.RESIZE);
  }

  /**
   * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
   * @since 5.5.3
   */
  @Override
  protected void configureShell(Shell shell) {
    super.configureShell(shell);
    shell.setText(UTIL.getString(PREFIX + "title")); // $NON-NLS-1$
  }

  /**
   * @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite)
   * @since 5.5.3
   */
  @Override
  protected Control createButtonBar(Composite parent) {
    Control buttonBar = super.createButtonBar(parent);
    getButton(OK).setEnabled(false);

    // set the first selection so that initial validation state is set
    // (doing it here since the selection handler uses OK
    // button)

    return buttonBar;
  }

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

  public ITeiidServer getServer() {
    return this.selectedServer;
  }

  /**
   * @see
   *     org.teiid.core.designer.event.IChangeListener#stateChanged(org.teiid.core.designer.event.IChangeNotifier)
   * @since 5.5.3
   */
  @Override
  public void stateChanged(IChangeNotifier theSource) {
    updateState();
  }

  private void updateState() {

    if (this.selectedServer == null) {
      getButton(OK).setEnabled(false);
      if (this.serversCombo.getItemCount() == 0) {
        setErrorMessage(UTIL.getString(PREFIX + "noServersExistMessage")); // $NON-NLS-1$
      } else {
        setErrorMessage(UTIL.getString(PREFIX + "noServerSelectedMessage")); // $NON-NLS-1$
      }

    } else {
      getButton(OK).setEnabled(true);
      setErrorMessage(null);
      setMessage(UTIL.getString(PREFIX + "okMsg")); // $NON-NLS-1$
    }
  }
}
/** @since 8.0 */
public class CreateDataSourceAction extends SortableSelectionAction implements DqpUiConstants {
  private static final String I18N_PREFIX =
      I18nUtil.getPropertyPrefix(CreateDataSourceAction.class);
  private static final String label = DqpUiConstants.UTIL.getString("label"); // $NON-NLS-1$

  private static String getString(final String id) {
    return DqpUiConstants.UTIL.getString(I18N_PREFIX + id);
  }

  private static String getString(final String id, final Object value) {
    return DqpUiConstants.UTIL.getString(I18N_PREFIX + id, value);
  }

  private String pwd;
  private ConnectionInfoProviderFactory providerFactory;

  private ITeiidServer cachedServer;

  /** @since 5.0 */
  public CreateDataSourceAction() {
    super(label, SWT.DEFAULT);
    setImageDescriptor(DqpUiPlugin.getDefault().getImageDescriptor(Images.SOURCE_BINDING_ICON));
    providerFactory = new ConnectionInfoProviderFactory();
  }

  public void setTeiidServer(ITeiidServer teiidServer) {
    this.cachedServer = teiidServer;
  }

  /**
   * @see
   *     org.teiid.designer.ui.actions.SortableSelectionAction#isValidSelection(org.eclipse.jface.viewers.ISelection)
   * @since 5.0
   */
  @Override
  public boolean isValidSelection(ISelection selection) {
    // Enable for single/multiple Virtual Tables
    return sourceModelSelected(selection);
  }

  /**
   * @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$
      }
    }
  }

  private Collection<ModelResource> getRelationalModelsWithConnections() {
    Collection<ModelResource> result = new ArrayList<ModelResource>();

    try {
      ModelResource[] mrs =
          ModelWorkspaceManager.getModelWorkspaceManager().getModelWorkspace().getModelResources();
      for (ModelResource mr : mrs) {
        if (ModelIdentifier.isRelationalSourceModel(mr)) {
          IConnectionInfoProvider provider = null;

          try {
            provider = getProvider(mr);
          } catch (Exception e) {
            // If provider throws exception its OK because some models may not have connection info.
          }

          if (provider != null) {
            Properties properties = provider.getConnectionProperties(mr);
            if (properties != null && !properties.isEmpty()) {
              result.add(mr);
            }
          }
        }
      }

    } catch (CoreException e) {
      DqpUiConstants.UTIL.log(e);
    }

    return result;
  }

  /**
   * @see
   *     org.teiid.designer.ui.actions.ISelectionAction#isApplicable(org.eclipse.jface.viewers.ISelection)
   * @since 5.0
   */
  @Override
  public boolean isApplicable(ISelection selection) {
    return sourceModelSelected(selection);
  }

  private boolean sourceModelSelected(ISelection theSelection) {
    boolean result = false;
    List allObjs = SelectionUtilities.getSelectedObjects(theSelection);
    if (!allObjs.isEmpty() && allObjs.size() == 1) {
      Iterator iter = allObjs.iterator();
      result = true;
      Object nextObj = null;
      while (iter.hasNext() && result) {
        nextObj = iter.next();

        if (nextObj instanceof IFile) {
          result = ModelIdentifier.isRelationalSourceModel((IFile) nextObj);
        } else {
          result = false;
        }
      }
    }

    return result;
  }

  public IConnectionInfoProvider getProvider(ModelResource modelResource) throws Exception {
    IConnectionInfoProvider provider = null;
    provider = providerFactory.getProvider(modelResource);
    if (null == provider) {
      throw new Exception(getString("noConnectionInfoProvider.message")); // $NON-NLS-1$
    }
    return provider;
  }

  private Shell getShell() {
    return Display.getCurrent().getActiveShell();
  }
}
/** @since 8.0 */
public class GenerateRestWarAction extends Action
    implements ISelectionListener, Comparable, ISelectionAction {
  static final String I18N_PREFIX = I18nUtil.getPropertyPrefix(GenerateRestWarAction.class);
  private static final String VDB_EXTENSION = "vdb"; // $NON-NLS-1$
  private static final ModelObjectAnnotationHelper ANNOTATION_HELPER =
      new ModelObjectAnnotationHelper();

  private IFile selectedVDB;
  // Map of models containing restful procedures
  private Map<String, List<RestProcedure>> restfulProcedureMap =
      new HashMap<String, List<RestProcedure>>();

  private Properties designerProperties;

  /** */
  public GenerateRestWarAction() {
    this.setText(UTIL.getString(I18N_PREFIX + "text")); // $NON-NLS-1$
    this.setToolTipText(UTIL.getString(I18N_PREFIX + "tooltip")); // $NON-NLS-1$
    this.setImageDescriptor(
        DqpUiPlugin.getDefault().getImageDescriptor(DqpUiConstants.Images.CREATE_WAR));
    setDisabledImageDescriptor(
        DqpUiPlugin.getDefault().getImageDescriptor(DqpUiConstants.Images.CREATE_WAR));
    setEnabled(false);
  }

  /** @param properties Designer properties for WAR generation */
  public void setDesingerProperties(Properties properties) {
    this.designerProperties = properties;
  }

  @Override
  public int compareTo(Object o) {
    if (o instanceof String) {
      return getText().compareTo((String) o);
    }

    if (o instanceof Action) {
      return getText().compareTo(((Action) o).getText());
    }
    return 0;
  }

  /**
   * @param selection
   * @return
   */
  @Override
  public boolean isApplicable(ISelection selection) {
    boolean result = false;
    if (!SelectionUtilities.isMultiSelection(selection)) {
      Object obj = SelectionUtilities.getSelectedObject(selection);
      if (obj instanceof IFile) {
        String extension = ((IFile) obj).getFileExtension();
        if (extension != null && extension.equals("vdb")) { // $NON-NLS-1$
          result = true;
        }
      }
    }
    return result;
  }

  /** @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */
  @Override
  public void run() {

    final IWorkbenchWindow window =
        DqpUiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    boolean cont = true;
    if (compiler == null) {
      cont =
          MessageDialog.openConfirm(
              window.getShell(),
              UTIL.getString(I18N_PREFIX + "javaWarningTitle"), // $NON-NLS-1$
              UTIL.getString(I18N_PREFIX + "invalidJDKMessage")); // $NON-NLS-1$
    }

    if (!cont) {
      notifyResult(false);
      return;
    }

    RestWarDeploymentInfoDialog dialog = null;
    dialog =
        new RestWarDeploymentInfoDialog(
            window.getShell(),
            this.selectedVDB,
            this.restfulProcedureMap,
            null,
            this.designerProperties);

    int rc = dialog.open();

    // Retrieve the file name for the confirmation dialog
    String warFileName = dialog.getWarFileName();

    final String successMessage =
        UTIL.getString(I18N_PREFIX + "warFileCreated", warFileName); // $NON-NLS-1$

    boolean wasSuccessful = (rc == Window.OK);
    if (wasSuccessful) {
      Display.getDefault()
          .asyncExec(
              new Runnable() {
                @Override
                public void run() {
                  MessageDialog.openInformation(
                      window.getShell(),
                      UTIL.getString(I18N_PREFIX + "creationCompleteTitle"), // $NON-NLS-1$
                      successMessage);
                }
              });
    } else {
      if (rc != Window.CANCEL) {

        MessageDialog.openError(
            window.getShell(),
            UTIL.getString(I18N_PREFIX + "creationFailedTitle"), // $NON-NLS-1$
            dialog.getMessage());
      }
    }
    notifyResult(rc == Window.OK);
  }

  /**
   * @param result
   * @param obj
   */
  private static boolean isVdb(Object obj) {
    if (obj == null) return false;

    if (!(obj instanceof IFile)) return false;

    return VDB_EXTENSION.equals(((IFile) obj).getFileExtension());
  }

  /**
   * @param eObjectList
   * @return list of rest procedures
   */
  private static List<RestProcedure> findRestProcedures(ModelResource modelResource)
      throws Exception {
    List<RestProcedure> restfulProcedureArray = new ArrayList<RestProcedure>();
    Collection<EObject> eObjectList = modelResource.getEObjects();
    for (EObject eObject : eObjectList) {
      if (SqlAspectHelper.isProcedure(eObject)) {
        IPath path = ModelerCore.getModelEditor().getModelRelativePathIncludingModel(eObject);
        final StringBuffer sb = new StringBuffer();
        final String[] segments = path.segments();
        for (int i = 0; i < segments.length; i++) {
          if (i != 0) {
            sb.append('.');
          }
          final String segment = segments[i];
          sb.append(segment);
        }
        String fullName = sb.toString();
        String name = ((ProcedureImpl) eObject).getName();
        createRestProcedureCollection((Procedure) eObject, name, fullName, restfulProcedureArray);
      }
    }

    return restfulProcedureArray;
  }

  /**
   * @param selection
   * @return
   */
  public boolean setSelection(ISelection selection) {
    if (SelectionUtilities.isMultiSelection(selection)) return false;

    Object obj = SelectionUtilities.getSelectedObject(selection);
    // If a VDB is selected and it contains a web service model then
    // enable
    if (!(obj instanceof IFile)) return false;

    if (!isVdb(obj)) return false;

    this.selectedVDB = (IFile) obj;

    boolean result = false;
    try {
      Vdb vdb = new Vdb(this.selectedVDB, new NullProgressMonitor());
      Set<VdbModelEntry> modelEntrySet = vdb.getModelEntries();
      for (VdbModelEntry vdbModelEntry : modelEntrySet) {
        final ModelResource modelResource =
            ModelerCore.getModelWorkspace().findModelResource(vdbModelEntry.getName());
        if (!ModelIdentifier.isVirtualModelType(modelResource)) continue;

        List<RestProcedure> restfulProcedureArray = findRestProcedures(modelResource);
        if (restfulProcedureArray.size() > 0) {
          String modelName =
              FileUtils.getFilenameWithoutExtension(vdbModelEntry.getName().lastSegment());
          restfulProcedureMap.put(modelName, restfulProcedureArray);
          result = true;
        }
      }
    } catch (Exception ex) {
      DqpPlugin.Util.log(ex);
      return false;
    }

    return result;
  }

  @Override
  public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    boolean enable = setSelection(selection);

    setEnabled(enable);
  }

  private static String getHeaders(Procedure procedure) {
    Object headers = null;

    try {
      // try new way first
      ModelObjectExtensionAssistant assistant =
          (ModelObjectExtensionAssistant)
              ExtensionPlugin.getInstance()
                  .getRegistry()
                  .getModelExtensionAssistant(NAMESPACE_PROVIDER.getNamespacePrefix());
      headers =
          assistant.getPropertyValue(procedure, RestModelExtensionConstants.PropertyIds.HEADERS);

      if (headers == null || CoreStringUtil.isEmpty((String) headers)) {
        headers =
            ANNOTATION_HELPER.getPropertyValueAnyCase(
                procedure,
                ModelObjectAnnotationHelper.EXTENDED_PROPERTY_NAMESPACE + "headers"); // $NON-NLS-1$
      }
    } catch (Exception e) {
      UTIL.log(e);
    }

    return headers == null ? StringUtilities.EMPTY_STRING : (String) headers;
  }

  private static String getCharset(Procedure procedure) {
    String charset = null;

    try {
      // try new way first
      ModelObjectExtensionAssistant assistant =
          (ModelObjectExtensionAssistant)
              ExtensionPlugin.getInstance()
                  .getRegistry()
                  .getModelExtensionAssistant(NAMESPACE_PROVIDER.getNamespacePrefix());
      charset =
          assistant.getPropertyValue(procedure, RestModelExtensionConstants.PropertyIds.CHARSET);

      if (CoreStringUtil.isEmpty(charset)) {
        charset =
            (String)
                ANNOTATION_HELPER.getPropertyValueAnyCase(
                    procedure,
                    ModelObjectAnnotationHelper.EXTENDED_PROPERTY_NAMESPACE
                        + "CHARSET"); //$NON-NLS-1$
      }
    } catch (Exception e) {
      UTIL.log(e);
    }

    return charset;
  }

  /**
   * @param eObject
   * @throws ModelerCoreException
   */
  private static void createRestProcedureCollection(
      Procedure procedure, String name, String fullName, List restfulProcedureArray) {
    String restMethod = WarArchiveUtil.getRestMethod(procedure);
    LinkedList<String> queryParameterList = new LinkedList<String>();
    LinkedList<String> headerParameterList = new LinkedList<String>();

    if (restMethod != null) {
      String uri = WarArchiveUtil.getUri(procedure);
      String charSet = getCharset(procedure);
      if (charSet == null) {
        charSet = Charset.defaultCharset().name();
      }

      // the procedure is not eligible for REST exposure without a URI defined
      if (uri != null) {
        boolean hasReturn = false;
        int parameterCount = procedure.getParameters().size();
        int uriParameterCount = 0;
        RestProcedure restProcedure = new RestProcedure();

        // Get all child EObjects for this procedure
        EList<EObject> contents = procedure.eContents();
        for (EObject eobject : contents) {
          // If this is a result set, set hasReturn true and we will
          // add the produces annotation to the RestProcedure instance
          if (SqlAspectHelper.isProcedureResultSet(eobject)) {
            hasReturn = true;
            continue;
          }
        }

        // Check for HTTP Header parameters
        String headers = getHeaders(procedure);
        if (headers.length() > 0) {
          String[] headerParameterArray = headers.split(";"); // $NON-NLS-1$
          for (String param : headerParameterArray) {
            headerParameterList.addLast(param);
          }
        }

        // Check for URI parameters
        String uriString = uri;
        for (int i = 0; i < uriString.length(); i++) {
          String character = uriString.substring(i, i + 1);
          if (character.equals("{")) { // $NON-NLS-1$
            uriParameterCount++;
          }
        }

        // Check for query parameters
        if (uriString.indexOf("&") > -1) { // $NON-NLS-1$
          String[] queryParameterArray = uriString.split("&"); // $NON-NLS-1$
          int i = 0;
          for (String param : queryParameterArray) {
            i++;
            if (i == 1) {
              uri = param; // Set the first token as our URI and continue
              continue;
            }
            queryParameterList.addLast(param);
          }
        }

        restProcedure.setCharSet(charSet);
        restProcedure.setRestMethod(restMethod);
        restProcedure.setUri(uri);
        restProcedure.setProcedureName(name);
        restProcedure.setFullyQualifiedProcedureName(fullName);
        restProcedure.setQueryParameterList(queryParameterList);
        restProcedure.setHeaderParameterList(headerParameterList);

        // Create JSON version
        RestProcedure jsonRestProcedure = new RestProcedure();
        jsonRestProcedure.setCharSet(charSet);
        jsonRestProcedure.setFullyQualifiedProcedureName(
            restProcedure.getFullyQualifiedProcedureName());
        jsonRestProcedure.setModelName(restProcedure.getModelName());
        jsonRestProcedure.setProcedureName(restProcedure.getProcedureName());
        jsonRestProcedure.setRestMethod(restProcedure.getRestMethod());
        jsonRestProcedure.setUri(restProcedure.getUri());
        jsonRestProcedure.setQueryParameterList(queryParameterList);
        jsonRestProcedure.setHeaderParameterList(headerParameterList);

        // If the parameterCount is greater than the number of parameters passed
        // on the URI, we can expect more parameters via an input stream
        // so the consumes annotation will need to be set. We will set for XML and JSON methods.
        boolean hasInputStream = false;
        if (uriParameterCount + headerParameterList.size() < parameterCount
            && queryParameterList.size() + headerParameterList.size() < parameterCount) {
          hasInputStream = true;
          restProcedure.setConsumesAnnotation(
              "@Consumes( MediaType.APPLICATION_XML )"); //$NON-NLS-1$
          jsonRestProcedure.setConsumesAnnotation(
              "@Consumes( MediaType.APPLICATION_JSON )"); //$NON-NLS-1$
        }

        if (hasReturn) {
          restProcedure.setProducesAnnotation(
              "@Produces( MediaType.APPLICATION_XML+"
                  + "\"; charset="
                  + charSet
                  + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          jsonRestProcedure.setProducesAnnotation(
              "@Produces( MediaType.APPLICATION_JSON+"
                  + "\"; charset="
                  + charSet
                  + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }

        restfulProcedureArray.add(restProcedure);

        // Only add JSON operation if there is a return or InputStream. Otherwise, one method will
        // do.
        if (hasReturn || hasInputStream) {
          restfulProcedureArray.add(jsonRestProcedure);
        }
      }
    }
  }
}
Ejemplo n.º 12
0
/**
 * ConstantEditor
 *
 * @since 8.0
 */
public final class ConstantEditor extends AbstractLanguageObjectEditor {

  private static final String PREFIX = I18nUtil.getPropertyPrefix(ConstantEditor.class);

  private Control currentControl;

  private ViewController controller;

  ConstantEditorModel model;

  private StackLayout stackLayout;

  String validChars; // valid characters for selected type

  private Combo cbxType;

  private CalendarWidget dateWidget;

  private Label lblNull;

  private Label lblType;

  private Composite pnlBoolean;

  private Composite pnlContent;

  private Composite pnlDate;

  private Composite pnlNull;

  private Composite pnlText;

  private Group pnlValues;

  private Button rdbFalse;

  private Button rdbTrue;

  private Text txfValue;

  /**
   * Constructs a <code>ConstantEditor</code> using the given model.
   *
   * @param theParent the parent container
   * @param theModel the editor's model
   * @throws IllegalArgumentException if any of the parameters are <code>null</code>
   */
  public ConstantEditor(Composite theParent, ConstantEditorModel theModel) {
    super(theParent, Constant.class, theModel);

    controller = new ViewController();
    model = theModel;
    model.addModelListener(controller);

    // start the controller
    controller.initialize();
  }

  /** @see org.teiid.designer.transformation.ui.builder.ILanguageObjectEditor#acceptFocus() */
  @Override
  public void acceptFocus() {
    if (isConversionType()) {
      cbxType.setFocus();
    } else if (currentControl == pnlNull) {
      cbxType.setFocus();
    } else if (currentControl == pnlBoolean) {
      if (rdbTrue.getSelection()) {
        rdbTrue.setFocus();
      } else {
        rdbFalse.setFocus();
      }
    } else if (currentControl == pnlText) {
      txfValue.setFocus();
    } else if (currentControl == pnlDate) {
      dateWidget.setFocus();
    }
  }

  private void constructBooleanWidgets() {
    if (rdbTrue == null) {
      rdbTrue = new Button(pnlBoolean, SWT.RADIO);
      rdbTrue.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.CENTER));
      rdbTrue.setText(Util.getString(PREFIX + "rdbTrue")); // $NON-NLS-1$
      rdbTrue.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent theEvent) {
              handleTrueSelected();
            }
          });
      rdbTrue.setSelection(true);

      rdbFalse = new Button(pnlBoolean, SWT.RADIO);
      rdbFalse.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.CENTER));
      rdbFalse.setText(Util.getString(PREFIX + "rdbFalse")); // $NON-NLS-1$
      rdbFalse.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent theEvent) {
              handleFalseSelected();
            }
          });

      pnlBoolean.pack();
    }
  }

  private void constructDateWidgets() {
    if (dateWidget == null) {
      dateWidget = new CalendarWidget(pnlDate, SWT.NONE, false);
      dateWidget.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              handleDateChanged();
            }
          });
      dateWidget.setLayoutData(new GridData());

      pnlDate.pack();
    }
  }

  private void constructNullWidgets() {
    if (lblNull == null) {
      lblNull = new Label(pnlNull, SWT.BORDER);
      lblNull.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      lblNull.setText(Util.getString(PREFIX + "txfNull")); // $NON-NLS-1$

      pnlNull.pack();
    }
  }

  private void constructTextWidgets() {
    if (txfValue == null) {
      txfValue = new Text(pnlText, SWT.BORDER);
      txfValue.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

      txfValue.addModifyListener(
          new ModifyListener() {
            @Override
            public void modifyText(ModifyEvent theEvent) {
              handleTextChange();
            }
          });

      txfValue.addVerifyListener(
          new VerifyListener() {
            @Override
            public void verifyText(VerifyEvent theEvent) {
              String text = theEvent.text;

              if ((text != null) && (text.length() > 0)) {
                for (int size = text.length(), i = 0; i < size; i++) {
                  if ((validChars != null) && (validChars.indexOf(text.charAt(i)) == -1)) {
                    theEvent.doit = false;
                    break;
                  } else if (!model.isValidValue(text)) {
                    theEvent.doit = false;
                    break;
                  }
                }
              }
            }
          });

      txfValue.addTraverseListener(
          new TraverseListener() {
            @Override
            public void keyTraversed(TraverseEvent theEvent) {
              // stops the enter key from putting in invisible characters
              if (theEvent.detail == SWT.TRAVERSE_RETURN) {
                theEvent.detail = SWT.TRAVERSE_NONE;
                theEvent.doit = true;
              }
            }
          });

      pnlText.pack();
    }
  }

  /**
   * @see
   *     org.teiid.designer.transformation.ui.builder.AbstractLanguageObjectEditor#createUi(org.eclipse.swt.widgets.Composite)
   */
  @Override
  protected void createUi(Composite theParent) {
    pnlContent = new Composite(theParent, SWT.NONE);
    pnlContent.setLayoutData(new GridData(GridData.FILL_BOTH));
    GridLayout layout = new GridLayout();
    layout.numColumns = 2;
    pnlContent.setLayout(layout);

    //
    // pnlContent contents
    //
    lblType = new Label(pnlContent, SWT.NONE);
    lblType.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
    lblType.setText(Util.getString(PREFIX + "lblType")); // $NON-NLS-1$

    cbxType = new Combo(pnlContent, SWT.BORDER | SWT.READ_ONLY);
    cbxType.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    cbxType.setItems(BuilderUtils.ALL_TYPES);
    cbxType.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent theEvent) {
            handleTypeSelected();
          }
        });

    pnlValues = new Group(pnlContent, SWT.NONE);
    pnlValues.setText(Util.getString(PREFIX + "pnlValues")); // $NON-NLS-1$
    stackLayout = new StackLayout();
    pnlValues.setLayout(stackLayout);
    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.horizontalSpan = 2;
    pnlValues.setLayoutData(gd);

    //
    // pnlValues contents
    //

    pnlText = new Composite(pnlValues, SWT.NONE);
    pnlText.setLayout(new GridLayout());
    pnlText.setLayoutData(new GridData(GridData.FILL_BOTH));

    // contents of pnlText created in constructTextWidgets()

    pnlNull = new Composite(pnlValues, SWT.NONE);
    pnlNull.setLayout(new GridLayout());
    pnlNull.setLayoutData(new GridData(GridData.FILL_BOTH));

    // contents of pnlNull created in constructNullWidgets()

    pnlBoolean = new Composite(pnlValues, SWT.NONE);
    pnlBoolean.setLayout(new GridLayout());
    pnlBoolean.setLayoutData(new GridData(GridData.FILL_BOTH));

    // contents of pnlBoolean created in constructBooleanWidgets()

    pnlDate = new Composite(pnlValues, SWT.NONE);
    pnlDate.setLayout(new GridLayout());
    pnlDate.setLayoutData(new GridData(GridData.FILL_BOTH));

    // contents of pnlDate created in constructDateWidgets()
  }

  void displayBooleanTypeUi() {
    normalizeTypes();
    boolean value = model.getBoolean();

    constructBooleanWidgets();

    if (rdbTrue.getSelection() != value) {
      if (model.getBoolean()) {
        WidgetUtil.selectRadioButton(rdbTrue);
      } else {
        WidgetUtil.selectRadioButton(rdbFalse);
      }
    }

    showControl(pnlBoolean);
  }

  void displayConversionTypeUi() {
    normalizeTypes();

    showValueLabel(false);
  }

  void displayDateTypeUi() {
    normalizeTypes();
    constructDateWidgets();

    dateWidget.setValue(model.getDate());
    dateWidget.showCalendar(true);
    dateWidget.showTime(false);
    pnlDate.pack();
    showControl(pnlDate);
  }

  void displayNullTypeUi() {
    normalizeTypes();
    constructNullWidgets();

    showControl(pnlNull);
  }

  void displayTextTypeUi() {
    normalizeTypes();
    String value = model.getText();

    if (value == null) {
      value = ""; // $NON-NLS-1$
    }

    constructTextWidgets();

    if (!txfValue.getText().equals(value)) {
      txfValue.setText(value); // causes caret to be placed at the beginning
      txfValue.setSelection(value.length()); // place caret at end
    }

    showControl(pnlText);
  }

  void displayTimeTypeUi() {
    normalizeTypes();
    constructDateWidgets();

    dateWidget.setValue(model.getTime());
    dateWidget.showCalendar(false);
    dateWidget.showTime(true);
    pnlDate.pack();
    showControl(pnlDate);
  }

  void displayTimestampTypeUi() {
    normalizeTypes();
    constructDateWidgets();

    dateWidget.setValue(model.getTimestamp());
    dateWidget.showCalendar(true);
    dateWidget.showTime(true);
    pnlDate.pack();
    showControl(pnlDate);
  }

  void displayTypeUi() {
    normalizeTypes();
    constructTextWidgets();

    String modelType = model.getType();

    txfValue.setTextLimit(BuilderUtils.getTextLimit(modelType));
    cbxType.setText(modelType);
  }

  /** @see org.teiid.designer.transformation.ui.builder.ILanguageObjectEditor#getTitle() */
  @Override
  public String getTitle() {
    return Util.getString(PREFIX + "title"); // $NON-NLS-1$
  }

  /**
   * @see org.teiid.designer.transformation.ui.builder.AbstractLanguageObjectEditor#getToolTipText()
   */
  @Override
  public String getToolTipText() {
    return Util.getString(PREFIX + "tip"); // $NON-NLS-1$
  }

  void handleDateChanged() {
    if (dateWidget.isDateWidget()) {
      model.setDate(dateWidget.getDate());
    } else if (dateWidget.isTimeWidget()) {
      model.setTime(dateWidget.getTime());
    } else if (dateWidget.isTimestampWidget()) {
      model.setTimestamp(dateWidget.getTimestamp());
    }
  }

  void handleFalseSelected() {
    // only care about selection, not deselection
    if (rdbFalse.getSelection()) {
      model.setBoolean(false);
    }
  }

  void handleTextChange() {
    // the text entered is set into the model.
    // this causes the view controller to be modified of a text change which sets the text field's
    // text
    model.setText(txfValue.getText());
  }

  void handleTrueSelected() {
    // only care about selection, not deselection
    if (rdbTrue.getSelection()) {
      model.setBoolean(true);
    }
  }

  void handleTypeSelected() {
    int index = cbxType.getSelectionIndex();
    model.setType(cbxType.getItem(index));
  }

  public boolean isConversionType() {
    return model.isConversionType();
  }

  /**
   * The set of available types are different when the constant is a conversion type and when it is
   * not. This method makes sure the types are correct.
   */
  private void normalizeTypes() {
    // processTypeChange = false;
    String selection = cbxType.getText(); // save current selection
    String[] invalidTypes = BuilderUtils.INVALID_CONVERSION_ARG_TYPES;
    boolean conversionType = isConversionType();

    for (int i = 0; i < invalidTypes.length; i++) {
      if (conversionType) {
        if (cbxType.indexOf(invalidTypes[i]) != -1) {
          cbxType.remove(invalidTypes[i]);
        } else {
          // assume if one type is not there then all of them are not there
          break;
        }
      } else {
        if (cbxType.indexOf(invalidTypes[i]) == -1) {
          cbxType.add(invalidTypes[i]);
        } else {
          // assume if one type is there then all of them are there
          break;
        }
      }
    }

    cbxType.setText(selection); // set back to saved selection
    // processTypeChange = true;
  }

  /**
   * @see
   *     org.teiid.designer.transformation.ui.builder.ILanguageObjectEditor#setLanguageObject(org.teiid.query.sql.LanguageObject)
   */
  @Override
  public void setLanguageObject(LanguageObject theLanguageObject) {
    if (theLanguageObject == null) {
      clear();
    } else {
      CoreArgCheck.isTrue(
          (theLanguageObject instanceof Constant),
          Util.getString(
              PREFIX + "invalidLanguageObject", // $NON-NLS-1$
              new Object[] {theLanguageObject.getClass().getName()}));

      model.setLanguageObject(theLanguageObject);
    }
  }

  private void showControl(Control theControl) {
    showValueLabel(true);

    if (currentControl != theControl) {
      currentControl = theControl;
      stackLayout.topControl = currentControl;
      pnlValues.layout();
    }

    acceptFocus();
  }

  /** The value widgets are shown when not displaying a conversion type. */
  private void showValueLabel(boolean theShowFlag) {
    pnlValues.setVisible(theShowFlag);
  }

  /**
   * The <code>ViewController</code> class is a view controller for the <code>ConstantEditor</code>.
   */
  class ViewController implements ILanguageObjectEditorModelListener {

    public void initialize() {
      // set first selection
      Display.getDefault()
          .asyncExec(
              new Runnable() {
                @Override
                public void run() {
                  modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.TYPE));
                }
              });
    }

    /**
     * @see
     *     org.teiid.query.ui.builder.model.ILanguageObjectEditorModelListener#modelChanged(org.teiid.query.ui.builder.model.LanguageObjectEditorModelEvent)
     */
    @Override
    public void modelChanged(LanguageObjectEditorModelEvent theEvent) {
      String type = theEvent.getType();

      if (type.equals(LanguageObjectEditorModelEvent.SAVED)) {
        modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.TYPE));
      } else if (type.equals(ConstantEditorModel.TYPE)) {
        displayTypeUi();

        if (model.isConversionType()) {
          displayConversionTypeUi();
        } else if (model.isText()) {
          modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.TEXT));
        } else if (model.isBoolean()) {
          modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.BOOLEAN));
        } else if (model.isNull()) {
          modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.NULL));
        } else if (model.isDate()) {
          modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.DATE));
        } else if (model.isTime()) {
          modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.TIME));
        } else if (model.isTimestamp()) {
          modelChanged(new LanguageObjectEditorModelEvent(model, ConstantEditorModel.TIMESTAMP));
        }
      } else if (type.equals(ConstantEditorModel.TEXT)) {
        displayTextTypeUi();
      } else if (type.equals(ConstantEditorModel.BOOLEAN)) {
        displayBooleanTypeUi();
      } else if (type.equals(ConstantEditorModel.NULL)) {
        displayNullTypeUi();
      } else if (type.equals(ConstantEditorModel.DATE)) {
        displayDateTypeUi();
      } else if (type.equals(ConstantEditorModel.TIME)) {
        displayTimeTypeUi();
      } else if (type.equals(ConstantEditorModel.TIMESTAMP)) {
        displayTimestampTypeUi();
      }
    }
  }

  /**
   * @see
   *     org.teiid.designer.transformation.ui.builder.AbstractLanguageObjectEditor#getLanguageObject()
   */
  @Override
  public LanguageObject getLanguageObject() {
    return super.getLanguageObject();
  }
}
Ejemplo n.º 13
0
/** @since 8.0 */
public final class NewVdbWizard extends AbstractWizard
    implements IPropertiesContext,
        INewWizard,
        InternalUiConstants.Widgets,
        CoreStringUtil.Constants,
        UiConstants {

  private static final String I18N_PREFIX = I18nUtil.getPropertyPrefix(NewVdbWizard.class);

  private static final String TITLE = getString("title"); // $NON-NLS-1$
  private static final String PAGE_TITLE = getString("pageTitle"); // $NON-NLS-1$
  private static final String VDB_NAME_ERROR = getString("vdbNameError"); // $NON-NLS-1$

  private static final int COLUMN_COUNT = 3;

  private static final String NAME_LABEL = getString("nameLabel"); // $NON-NLS-1$
  private static final String FOLDER_LABEL = getString("folderLabel"); // $NON-NLS-1$

  private static final String INITIAL_MESSAGE = getString("initialMessage"); // $NON-NLS-1$
  private static final String CREATE_FILE_ERROR_MESSAGE =
      getString("createFileErrorMessage"); // $NON-NLS-1$

  private static final String NOT_MODEL_PROJECT_MSG =
      getString("notModelProjectMessage"); // $NON-NLS-1$
  private static final String SELECT_FOLDER_MESSAGE =
      getString("selectFolderMessage"); // $NON-NLS-1$

  static final String ADD_FILE_DIALOG_INVALID_SELECTION_MESSAGE =
      VdbUiConstants.Util.getString("addFileDialogInvalidSelectionMessage"); // $NON-NLS-1$
  static final String ADD_FILE_DIALOG_NON_MODEL_SELECTED_MESSAGE =
      VdbUiConstants.Util.getString("addFileDialogNonModelSelectedMessage"); // $NON-NLS-1$
  static final String ADD_FILE_DIALOG_VDB_SOURCE_MODEL_SELECTED_MESSAGE =
      VdbUiConstants.Util.getString("addFileDialogVdbSourceModelSelectedMessage"); // $NON-NLS-1$

  private static final StringNameValidator nameValidator =
      new StringNameValidator(
          StringNameValidator.DEFAULT_MINIMUM_LENGTH, StringNameValidator.DEFAULT_MAXIMUM_LENGTH);

  static String getString(final String id) {
    return VdbUiConstants.Util.getString(I18N_PREFIX + id);
  }

  String name;
  IContainer folder;

  private WizardPage mainPage;
  Text nameText, folderText;
  TableViewer modelsViewer;
  StyledTextEditor descriptionTextEditor;
  Button btnBrowse;
  Button addModelsButton;

  Button removeModelsButton;
  private ISelectionStatusValidator projectValidator = new ModelProjectSelectionStatusValidator();
  final ModelLabelProvider modelLabelProvider = new ModelLabelProvider();

  IStructuredSelection initialSelection;

  List<IResource> modelsForVdb;

  Properties designerProperties;
  private boolean openProjectExists = true;
  private IProject newProject;

  final ISelectionStatusValidator validator =
      new ISelectionStatusValidator() {
        /**
         * {@inheritDoc}
         *
         * @see org.eclipse.ui.dialogs.ISelectionStatusValidator#validate(java.lang.Object[])
         */
        @Override
        public IStatus validate(final Object[] selection) {
          for (int ndx = selection.length; --ndx >= 0; ) {
            Object obj = selection[ndx];
            if (obj instanceof IContainer) {
              return new Status(
                  IStatus.ERROR,
                  VdbUiConstants.PLUGIN_ID,
                  0,
                  ADD_FILE_DIALOG_INVALID_SELECTION_MESSAGE,
                  null);
            } else if (obj instanceof IFile) {
              IFile file = (IFile) obj;

              if (!ModelUtilities.isModelFile(file) && !ModelUtil.isXsdFile(file)) {
                return new Status(
                    IStatus.ERROR,
                    VdbUiConstants.PLUGIN_ID,
                    0,
                    ADD_FILE_DIALOG_NON_MODEL_SELECTED_MESSAGE,
                    null);
              }
              if (ModelUtilities.isVdbSourceModel(file)) {
                return new Status(
                    IStatus.ERROR,
                    VdbUiConstants.PLUGIN_ID,
                    0,
                    ADD_FILE_DIALOG_VDB_SOURCE_MODEL_SELECTED_MESSAGE,
                    null);
              }
            }
          }

          return new Status(IStatus.OK, VdbUiConstants.PLUGIN_ID, 0, EMPTY_STRING, null);
        }
      };

  /** @since 4.0 */
  public NewVdbWizard() {
    super(UiPlugin.getDefault(), TITLE, null);
    this.modelsForVdb = new ArrayList<IResource>();
  }

  /**
   * @see org.eclipse.jface.wizard.IWizard#performFinish()
   * @since 4.0
   */
  @Override
  public boolean finish() {
    // append VDB file extension if needed
    if (!name.endsWith(ModelerCore.VDB_FILE_EXTENSION)) {
      name += ModelerCore.VDB_FILE_EXTENSION;
    }

    if (designerProperties != null) {
      DesignerPropertiesUtil.setVdbName(designerProperties, name);
    }

    // create VDB resource
    final IRunnableWithProgress op =
        new IRunnableWithProgress() {
          @Override
          public void run(final IProgressMonitor monitor) throws InvocationTargetException {
            try {
              final IFile vdbFile =
                  NewVdbWizard.this.folder.getFile(new Path(NewVdbWizard.this.name));
              vdbFile.create(new ByteArrayInputStream(new byte[0]), false, monitor);
              Vdb newVdb = new Vdb(vdbFile, false, monitor);
              String desc = descriptionTextEditor.getText();
              if (desc != null && desc.length() > 0) {
                newVdb.setDescription(desc);
              }
              newVdb.save(monitor);
              NewVdbWizard.this.folder.refreshLocal(IResource.DEPTH_INFINITE, monitor);

              // open editor
              IWorkbenchPage page =
                  UiPlugin.getDefault().getCurrentWorkbenchWindow().getActivePage();
              IDE.openEditor(page, vdbFile);

              // Thread.sleep(200);

              if (modelsForVdb != null && !modelsForVdb.isEmpty()) {
                VdbEditor editor = getVdbEditor(vdbFile);

                if (editor != null) {
                  List<IFile> models = new ArrayList<IFile>();

                  for (IResource nextModel : modelsForVdb) {
                    models.add((IFile) nextModel);
                  }

                  editor.addModels(models);
                  editor.doSave(new NullProgressMonitor());
                }
              }

            } catch (final Exception err) {
              throw new InvocationTargetException(err);
            } finally {
              monitor.done();
            }
          }
        };
    try {
      new ProgressMonitorDialog(getShell()).run(false, true, op);
      return true;
    } catch (Throwable err) {
      if (err instanceof InvocationTargetException) {
        err = ((InvocationTargetException) err).getTargetException();
      }
      VdbUiConstants.Util.log(err);
      WidgetUtil.showError(CREATE_FILE_ERROR_MESSAGE);
      return false;
    }
  }

  /**
   * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
   *     org.eclipse.jface.viewers.IStructuredSelection)
   * @since 4.0
   */
  @Override
  public void init(final IWorkbench workbench, final IStructuredSelection originalSelection) {

    IStructuredSelection selection = originalSelection;
    openProjectExists = ModelerUiViewUtils.workspaceHasOpenModelProjects();
    if (!openProjectExists) {
      newProject = ModelerUiViewUtils.queryUserToCreateModelProject();

      if (newProject != null) {
        selection = new StructuredSelection(newProject);
        openProjectExists = true;
      } else {
        openProjectExists = false;
      }
    }

    if (isAllModelsSelected(selection)) {
      initialSelection = new StructuredSelection(selection.toArray());
    }
    if (selection != null && !selection.isEmpty()) {
      this.folder = ModelUtil.getContainer(selection.getFirstElement());
    }

    if (folder != null && !folderInModelProject()) {
      // Create empty page
      this.mainPage =
          new WizardPage(NewVdbWizard.class.getSimpleName(), PAGE_TITLE, null) {
            @Override
            public void createControl(final Composite parent) {
              setControl(createEmptyPageControl(parent));
            }
          };
      this.mainPage.setMessage(NOT_MODEL_PROJECT_MSG, IMessageProvider.ERROR);
    } else {

      // Create and add page
      this.mainPage =
          new WizardPage(NewVdbWizard.class.getSimpleName(), PAGE_TITLE, null) {
            @Override
            public void createControl(final Composite parent) {
              setControl(createPageControl(parent));
            }
          };
      this.mainPage.setMessage(INITIAL_MESSAGE);

      // If current selection not null, set folder to selection if a folder, or to containing folder
      // if not
      if (this.folder != null) {
        if (!projectValidator.validate(new Object[] {this.folder}).isOK()) {
          this.folder = null;
        }
      } else { // folder == null
        this.mainPage.setMessage(SELECT_FOLDER_MESSAGE, IMessageProvider.ERROR);
      }
    }

    this.mainPage.setPageComplete(false);
    addPage(mainPage);
  }

  private boolean folderInModelProject() {
    boolean result = false;

    if (this.folder != null) {
      IProject project = this.folder.getProject();
      try {
        if (project != null && project.getNature(PluginConstants.MODEL_PROJECT_NATURE_ID) != null) {
          result = true;
        }
      } catch (CoreException ex) {
        VdbUiConstants.Util.log(ex);
      }
    }

    return result;
  }

  /**
   * Indicates if all selected objects are {@link IResource}s.
   *
   * @param theSelection the selection being checked
   * @return <code>true</code> if all selected objects are <code>EObject</code>; <code>false</code>
   *     otherwise.
   */
  boolean isAllModelsSelected(ISelection theSelection) {
    if ((theSelection == null) || theSelection.isEmpty()) {
      return true;
    }
    boolean result =
        (theSelection instanceof IStructuredSelection)
            && SelectionUtilities.isAllIResourceObjects(theSelection);

    if (result) {
      @SuppressWarnings("rawtypes")
      List selectedObjects = SelectionUtilities.getSelectedObjects(theSelection);
      for (@SuppressWarnings("rawtypes") Iterator iter = selectedObjects.iterator();
          iter.hasNext(); ) {
        IResource res = (IResource) iter.next();
        if (!ModelUtilities.isModelFile(res)) {
          result = false;
          break;
        }
      }
    }

    return result;
  }

  /**
   * @see org.eclipse.jface.wizard.IWizard#canFinish()
   * @since 4.0
   */
  @Override
  public boolean canFinish() {
    // defect 16154 -- Finish can be enabled even if errors on page.
    // check the page's isComplete status (in super) -- just follow its advice.
    return super.canFinish();
  }

  Composite createEmptyPageControl(final Composite parent) {
    return new Composite(parent, SWT.NONE);
  }

  /**
   * @param parent
   * @return composite the page
   * @since 4.0
   */
  @SuppressWarnings({"unused", "unchecked"})
  Composite createPageControl(final Composite parent) {
    // Create page
    final Composite mainPanel = new Composite(parent, SWT.NONE);
    mainPanel.setLayout(new GridLayout(COLUMN_COUNT, false));
    // Add widgets to page
    WidgetFactory.createLabel(mainPanel, FOLDER_LABEL);
    final String name =
        (this.folder == null ? null : this.folder.getFullPath().makeRelative().toString());
    this.folderText =
        WidgetFactory.createTextField(mainPanel, GridData.FILL_HORIZONTAL, 1, name, SWT.READ_ONLY);
    this.folderText.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(final ModifyEvent event) {
            folderModified();
          }
        });
    btnBrowse = WidgetFactory.createButton(mainPanel, BROWSE_BUTTON);
    btnBrowse.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(final SelectionEvent event) {
            browseButtonSelected();
          }
        });
    WidgetFactory.createLabel(mainPanel, NAME_LABEL);
    this.nameText =
        WidgetFactory.createTextField(mainPanel, GridData.HORIZONTAL_ALIGN_FILL, COLUMN_COUNT - 1);
    this.nameText.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(final ModifyEvent event) {
            nameModified();
          }
        });

    // set focus to browse button if no folder selected. otherwise set focus to text field
    if (folder == null) {
      btnBrowse.setFocus();
    } else {
      nameText.setFocus();
    }

    DESCRIPTION_GROUP:
    {
      final Group descGroup =
          WidgetFactory.createGroup(
              mainPanel, getString("description"), GridData.FILL_HORIZONTAL, 3); // $NON-NLS-1$
      descriptionTextEditor =
          new StyledTextEditor(
              descGroup, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP | SWT.BORDER);
      final GridData descGridData = new GridData(GridData.FILL_BOTH);
      descGridData.horizontalSpan = 1;
      descGridData.heightHint = 50;
      descGridData.minimumHeight = 30;
      descGridData.grabExcessVerticalSpace = true;
      descriptionTextEditor.setLayoutData(descGridData);
      descriptionTextEditor.setText(""); // $NON-NLS-1$
    }

    MODELS_GROUP:
    {
      Group group =
          WidgetFactory.createGroup(
              mainPanel,
              getString("selectedModelsGroupTitle"),
              GridData.FILL_BOTH,
              COLUMN_COUNT,
              COLUMN_COUNT); //$NON-NLS-1$
      group.setLayout(new GridLayout(2, false));
      GridData gd = new GridData(GridData.FILL_BOTH);
      gd.heightHint = 200;
      gd.horizontalSpan = 3;
      group.setLayoutData(gd);

      Composite leftToolbarPanel = new Composite(group, SWT.NONE);
      leftToolbarPanel.setLayout(new GridLayout());
      GridData ltpGD = new GridData(GridData.FILL_VERTICAL);
      ltpGD.heightHint = 120;
      leftToolbarPanel.setLayoutData(ltpGD);

      addModelsButton = new Button(leftToolbarPanel, SWT.PUSH);
      addModelsButton.setText(getString("add")); // $NON-NLS-1$
      addModelsButton.setToolTipText(getString("addModelsTooltip")); // $NON-NLS-1$
      addModelsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      addModelsButton.addSelectionListener(
          new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
              handleAddModelsSelected();
              if (!modelsViewer.getSelection().isEmpty()) {
                removeModelsButton.setEnabled(true);
              }
            }
          });

      removeModelsButton = new Button(leftToolbarPanel, SWT.PUSH);
      removeModelsButton.setText(getString("remove")); // $NON-NLS-1$
      removeModelsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      removeModelsButton.setEnabled(false);
      removeModelsButton.addSelectionListener(
          new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
              Collection<IResource> models = new ArrayList<IResource>();

              IStructuredSelection selection = (IStructuredSelection) modelsViewer.getSelection();
              for (Object obj : selection.toArray()) {
                if (obj instanceof IResource) {
                  models.add((IResource) obj);
                }
              }
              removeModels(models);
              removeModelsButton.setEnabled(false);
            }
          });

      this.modelsViewer = new TableViewer(group);
      GridData gdv = new GridData(GridData.FILL_BOTH);
      // gdv.horizontalSpan = COLUMN_COUNT;
      modelsViewer.getControl().setLayoutData(gdv);
      modelsViewer.setContentProvider(new ListContentProvider());
      modelsViewer.setLabelProvider(new ModelExplorerLabelProvider());
      // Add Models from properties if available
      if (this.designerProperties != null && !this.designerProperties.isEmpty()) {
        IFile sourceMdl = DesignerPropertiesUtil.getSourceModel(this.designerProperties);
        IFile viewMdl = DesignerPropertiesUtil.getViewModel(this.designerProperties);
        if (sourceMdl != null) this.modelsForVdb.add(sourceMdl);
        if (viewMdl != null) this.modelsForVdb.add(viewMdl);
      } else {
        this.modelsForVdb.addAll(SelectionUtilities.getSelectedIResourceObjects(initialSelection));
      }
      modelsViewer.setInput(this.modelsForVdb);
      modelsViewer.addSelectionChangedListener(
          new ISelectionChangedListener() {

            @Override
            public void selectionChanged(SelectionChangedEvent event) {
              removeModelsButton.setEnabled(!event.getSelection().isEmpty());
            }
          });
    }

    updateForProperties();
    return mainPanel;
  }

  void handleAddModelsSelected() {
    final ViewerFilter filter =
        new ViewerFilter() {
          /**
           * {@inheritDoc}
           *
           * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
           *     java.lang.Object, java.lang.Object)
           */
          @Override
          public boolean select(final Viewer viewer, final Object parent, final Object element) {
            if (element instanceof IContainer) return true;

            final IFile file = (IFile) element;

            if (ModelUtilities.isModelFile(file) || ModelUtil.isXsdFile(file)) {
              return true;
            }

            return false;
          }
        };
    ModelingResourceFilter wsFilter = new ModelingResourceFilter(filter);
    wsFilter.setShowHiddenProjects(true);
    final Object[] models =
        WidgetUtil.showWorkspaceObjectSelectionDialog(
            getString("selectModelsTitle"), // $NON-NLS-1$
            getString("selectModelsMessage"), // $NON-NLS-1$
            true,
            null,
            wsFilter,
            validator,
            modelLabelProvider);

    addModels(models);
  }

  void addModels(Object[] models) {
    for (Object model : models) {
      if (!modelsForVdb.contains(model)) {
        modelsForVdb.add((IResource) model);
      }
    }

    this.modelsViewer.refresh();
  }

  void removeModels(Collection<IResource> models) {
    for (IResource model : models) {
      modelsForVdb.remove(model);
    }
    this.modelsViewer.refresh();
  }

  /** @since 4.0 */
  void browseButtonSelected() {
    ModelingResourceFilter resFilter = new ModelingResourceFilter();
    resFilter.addFilter(new SingleProjectFilter(this.designerProperties));
    this.folder = WidgetUtil.showFolderSelectionDialog(this.folder, resFilter, projectValidator);

    if (folder != null) {
      this.folderText.setText(folder.getFullPath().makeRelative().toString());

      if (CoreStringUtil.isEmpty(nameText.getText())) {
        nameText.setFocus();
      }
    }

    validatePage();
  }

  /** @since 4.0 */
  void folderModified() {
    validatePage();
  }

  /** @since 4.0 */
  void nameModified() {
    validatePage();
  }

  /** @since 4.0 */
  private void validatePage() {
    final IContainer folder;
    try {
      folder =
          WizardUtil.validateFileAndFolder(
              this.nameText, this.folderText, this.mainPage, ModelerCore.VDB_FILE_EXTENSION, false);
      if (this.mainPage.getMessageType() == IMessageProvider.ERROR) {
        // WizardUtil.validateFileAndFolder can set error message and message type so no need to do
        // further
        // validation if an error was already found (JBEDSP-588)
        return;
      }

      IStatus status = projectValidator.validate(new Object[] {folder});
      String proposedName = this.nameText.getText();

      if (!status.isOK()) {
        // only update the message if the vFolder is non-null;
        // if WizardUtil returned null, it already set the status
        // this corrects the case where the wrong message shows for
        // a bad filename.
        if (folder != null) {
          this.mainPage.setErrorMessage(status.getMessage());
          this.mainPage.setPageComplete(false);
        } // endif
      } else if (!nameValidator.isValidName(proposedName)) {
        this.mainPage.setErrorMessage(VDB_NAME_ERROR);
        this.mainPage.setPageComplete(false);
      } else if (ModelUtilities.vdbNameReservedValidation(proposedName) != null) {
        this.mainPage.setErrorMessage(ModelUtilities.vdbNameReservedValidation(proposedName));
        this.mainPage.setPageComplete(false);
      } else {
        this.mainPage.setErrorMessage(null);
        this.mainPage.setPageComplete(true);
      }

      if (this.mainPage.isPageComplete()) {
        this.name = proposedName;
        this.folder = folder;
      }
    } catch (final CoreException err) {
      VdbUiConstants.Util.log(err);
      WizardUtil.setPageComplete(this.mainPage, err.getLocalizedMessage(), IMessageProvider.ERROR);
    }
  }

  /**
   * Finds the visible VDB Editor for the supplied VDB
   *
   * <p>If an editor is NOT open for this vdb, then null is returned.
   *
   * @param vdb
   * @return the VdbEditor
   */
  public VdbEditor getVdbEditor(final IFile vdb) {
    final IWorkbenchWindow window = UiPlugin.getDefault().getCurrentWorkbenchWindow();

    if (window != null) {
      final IWorkbenchPage page = window.getActivePage();

      if (page != null) {
        VdbEditor editor = findEditorPart(page, vdb);
        if (editor != null) {
          return editor;
        }
      }
    }
    return null;
  }

  private VdbEditor findEditorPart(final IWorkbenchPage page, IFile vdbFile) {
    // look through the open editors and see if there is one available for
    // this model file.
    final IEditorReference[] editors = page.getEditorReferences();
    for (int i = 0; i < editors.length; ++i) {

      final IEditorPart editor = editors[i].getEditor(false);
      if (editor instanceof VdbEditor) {
        final VdbEditor vdbEditor = (VdbEditor) editor;
        final IPath editorVdbPath = vdbEditor.getVdb().getName();
        if (vdbFile.getFullPath().equals(editorVdbPath)) return vdbEditor;
      }
    }

    return null;
  }

  /** */
  @Override
  public void setProperties(Properties properties) {
    this.designerProperties = properties;
  }

  private void updateForProperties() {
    if (this.folder == null && this.designerProperties != null) {
      // Get Project from Properties - if it exists.
      IProject project = DesignerPropertiesUtil.getProject(this.designerProperties);
      if (project != null) {
        this.folder = project;
        this.folderText.setText(this.folder.getFullPath().makeRelative().toString());
        if (CoreStringUtil.isEmpty(nameText.getText())) {
          nameText.setFocus();
        }
      }
    }

    if (this.designerProperties != null && !this.openProjectExists) {
      DesignerPropertiesUtil.setProjectStatus(
          this.designerProperties, IPropertiesContext.NO_OPEN_PROJECT);
    }
  }
}
/**
 * The <code>TreeMappingAdapter</code> class
 *
 * @since 8.0
 */
public class TreeMappingAdapter implements PluginConstants {
  // private PerformanceTracker pTracker = new PerformanceTracker(getClass().getName());

  ///////////////////////////////////////////////////////////////////////////////////////////////
  // CONSTANTS
  ///////////////////////////////////////////////////////////////////////////////////////////////

  /** Properties file key prefix. Used for logging and localization. */
  private static final String PREFIX = I18nUtil.getPropertyPrefix(TreeMappingAdapter.class);

  ///////////////////////////////////////////////////////////////////////////////////////////////
  // FIELDS
  ///////////////////////////////////////////////////////////////////////////////////////////////

  /** The tree root. */
  private EObject root;

  /**
   * Structure content object to keep efficiently keep track of mapping classes, staging tables and
   * their referenced locations in XML Document tree
   */
  private TreeMappingClassLocator mappingLocator;

  private boolean generatingMappingClasses = false;

  // private boolean doTrack = true;

  ///////////////////////////////////////////////////////////////////////////////////////////////
  // CONSTRUCTORS
  ///////////////////////////////////////////////////////////////////////////////////////////////

  /**
   * Constructs a <code>TreeMappingAdapter</code> for the specified tree root.
   *
   * @param theTreeRoot the tree root
   */
  public TreeMappingAdapter(EObject theTreeRoot) {
    // startTracking("TreeMappingAdapter()"); //$NON-NLS-1$
    CoreArgCheck.isNotNull(theTreeRoot);

    mappingLocator = new TreeMappingClassLocator(theTreeRoot);

    root = theTreeRoot;

    mappingLocator.loadTreeNodesToMappingClassScopeMap();

    // stopTracking("TreeMappingAdapter()"); //$NON-NLS-1$
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////
  // METHODS
  ///////////////////////////////////////////////////////////////////////////////////////////////

  //    public void resetTracker() {
  //        pTracker.reset();
  //        mappingLocator.resetTracker();
  //    }
  //
  //
  //    public void print() {
  //        pTracker.print();
  //        mappingLocator.print();
  //        //System.out.println(mappingLocator.toString());
  //    }
  //
  //    private void startTracking(String method) {
  //        if( doTrack ) {
  //            pTracker.start(method);
  //        }
  //    }
  //
  //    private void stopTracking(String method) {
  //        if( doTrack ) {
  //            pTracker.stop(method);
  //        }
  //    }

  public boolean isGeneratingMappingClasses() {
    return generatingMappingClasses;
  }

  public void setGeneratingMappingClasses(boolean isGenerating) {
    this.generatingMappingClasses = isGenerating;
    mappingLocator.setGeneratingMappingClasses(isGenerating);
  }

  public void addMappingClassAtLocation(
      EObject treeMappingRoot, MappingClass theMappingClass, EObject location) {
    mappingLocator.addMappingClassAtLocation(treeMappingRoot, theMappingClass, location);
  }

  public List getAllMappingClassLocations() {
    return new ArrayList(mappingLocator.getAllMappingClassLocations());
  }

  public void addStagingTableAtLocation(
      EObject treeMappingRoot, StagingTable theStagingTable, EObject location) {
    mappingLocator.addMappingClassAtLocation(treeMappingRoot, theStagingTable, location);
  }

  public boolean containsMappingClassWithName(String someName) {
    return mappingLocator.containsMappingClassWithName(someName);
  }

  /**
   * Maps the specified <code>MappingClass</code> to the specified tree node (<code>EObject</code>).
   *
   * @param theMappingClass the <code>Mapping</code> input
   * @param theTreeNode the <code>Mapping</code> output
   * @throws IllegalArgumentException if either input parameter is <code>null</code>
   */
  public void addMappingClassLocation(MappingClass theMappingClass, EObject theTreeNode) {
    // startTracking("addMappingClassLocation()"); //$NON-NLS-1$

    CoreArgCheck.isNotNull(theMappingClass);
    CoreArgCheck.isNotNull(theTreeNode);

    if (!mappingLocator.containsLocation(theMappingClass, theTreeNode)) {
      try {
        TreeMappingRoot treeMappingRoot =
            (TreeMappingRoot) mappingLocator.getMappingRoot(theMappingClass);
        mappingLocator.addOutputLocation(theMappingClass, theTreeNode);

        //                if( !isGeneratingMappingClasses() ) {
        addMappingClassAtLocation(treeMappingRoot, theMappingClass, theTreeNode);
        //                }

      } catch (Exception e) {
        PluginConstants.Util.log(IStatus.ERROR, e, e.getMessage());
      }
    }
    // stopTracking("addMappingClassLocation()"); //$NON-NLS-1$
  }

  /**
   * Maps the specified <code>MappingClassColumn</code> to the specified tree node (<code>EObject
   * </code>).
   *
   * @param theMappingColumn the <code>Mapping</code> input
   * @param theTreeNode the <code>Mapping</code> output
   * @throws IllegalArgumentException if either input parameter is <code>null</code>
   */
  public void addMappingClassColumnLocation(
      MappingClassColumn theMappingColumn, EObject theTreeNode) {
    // startTracking("addMappingClassColumnLocation()"); //$NON-NLS-1$

    CoreArgCheck.isNotNull(theMappingColumn);
    CoreArgCheck.isNotNull(theTreeNode);

    mappingLocator.addMappingClassColumnLocation(theMappingColumn, theTreeNode);

    // stopTracking("addMappingClassColumnLocation()"); //$NON-NLS-1$
  }

  /**
   * Creates a {@link MappingRoot} having the specified <code>MappingClass</code> as it's input.
   *
   * @param theMappingClass the <code>MappingClass</code> used to create the mapping root
   * @return the index in the <code>mappingRoots</code> list of the new root
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public EObject createTreeMappingRoot(MappingClass theMappingClass) {
    // startTracking("createTreeMappingRoot(GENERATING)"); //$NON-NLS-1$

    CoreArgCheck.isNotNull(theMappingClass);
    if (mappingLocator.hasTreeRoot(theMappingClass)) {
      return mappingLocator.getMappingRoot(theMappingClass);
    }

    TreeMappingRoot newRoot = null;
    try {
      // Defect 18433 - BML 8/31/05 - Changed call to create tree mapping root using a new
      // utility method that correctly adds it to the model (via addValue()) and also performs
      // additional work (i.e.adding nested Sql Helpers.
      newRoot =
          ModelResourceContainerFactory.createNewTreeMappingRoot(this.root, this.root.eResource());

      // Now add the mapping class to the Inputs list of the tree mapping root
      ModelerCore.getModelEditor().addValue(newRoot, theMappingClass, newRoot.getInputs());

    } catch (Exception theException) {
      Util.log(
          IStatus.ERROR,
          theException,
          Util.getString(
              PREFIX + "createMappingRootProblem", // $NON-NLS-1$
              new Object[] {root, theMappingClass}));
    }

    // stopTracking("createTreeMappingRoot(GENERATING)"); //$NON-NLS-1$
    return newRoot;
  }

  /**
   * Obtains all {@link MappingClass}es for this adapter's tree root.
   *
   * @return the <code>MappingClass</code>es or an empty list
   */
  public List getAllMappingClasses() {
    // startTracking("getAllMappingClasses()"); //$NON-NLS-1$
    List returnList = Collections.unmodifiableList(mappingLocator.getMappingClasses());
    // stopTracking("getAllMappingClasses()"); //$NON-NLS-1$
    return returnList;
  }

  /**
   * Obtains all {@link StagingTable} for this adapter's tree root.
   *
   * @return the <code>StagingTable</code>s or an empty list
   */
  public List getAllStagingTables() {
    return Collections.unmodifiableList(mappingLocator.getStagingTables());
  }

  /**
   * Obtains the <code>FragmentMappingAdapter</code> for this adapter's tree root.
   *
   * @return the <code>FragmentMappingAdapter</code> (never <code>null</code>)
   */
  public FragmentMappingAdapter getFragmentMappingAdapter() {
    return mappingLocator.getFragmentAdapter();
  }

  /**
   * Obtains the tree node where the specified <code>StagingTable</code> is mapped.
   *
   * @param theStagingTable the <code>StagingTable</code> whose mapped tree node is being requested
   * @return the mapped tree node
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public EObject getStagingTableOutputLocation(StagingTable theStagingTable) {
    return mappingLocator.getStagingTableLocation(theStagingTable);
  }

  /**
   * Obtains all tree nodes that are mapped to the specified <code>MappingClass</code>.
   *
   * @param theMappingClass the <code>MappingClass</code> whose mapped tree nodes are being
   *     requested
   * @return an unmodifiable list of mapped tree nodes or an empty list
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public List getMappingClassOutputLocations(MappingClass theMappingClass) {
    // startTracking("getMappingClassOutputLocations()"); //$NON-NLS-1$

    List resultsList =
        Collections.unmodifiableList(mappingLocator.getMappingClassLocations(theMappingClass));

    // stopTracking("getMappingClassOutputLocations()"); //$NON-NLS-1$
    return resultsList;
  }

  /**
   * Obtains the tree nodes that are mapped to the specified <code>MappingClassColumn</code>.
   *
   * @param theMappingColumn the <code>MappingClassColumn</code> whose mapped tree nodes are being
   *     requested
   * @return an unmodifiable list of mapped tree nodes or an empty list
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public List getMappingClassColumnOutputLocations(MappingClassColumn theMappingColumn) {
    return mappingLocator.getMappingClassColumnOutputLocations(theMappingColumn);
  }

  /**
   * Return the StagingTable located at the specified node, if one exists at this node.
   *
   * @param theTreeNode
   * @return
   */
  public StagingTable getStagingTable(EObject theTreeNode) {
    CoreArgCheck.isNotNull(theTreeNode);

    return (StagingTable) mappingLocator.getStagingTable(theTreeNode);
  }

  /**
   * Return the MappingClass located at the specified node, if one exists at this node.
   *
   * @param theTreeNode
   * @return
   */
  public EObject getMappingClassLocation(MappingClass theMappingClass) {
    // startTracking("getMappingClassLocation()"); //$NON-NLS-1$
    CoreArgCheck.isNotNull(theMappingClass);
    List locations = mappingLocator.getMappingClassLocations(theMappingClass);
    EObject location = null;
    if (!locations.isEmpty()) {
      location = (EObject) locations.get(0);
    }
    // stopTracking("getMappingClassLocation()"); //$NON-NLS-1$
    return location;
  }

  /**
   * Return the MappingClass located at the specified node, if one exists at this node.
   *
   * @param theTreeNode
   * @return
   */
  public MappingClass getMappingClass(EObject theTreeNode) {
    CoreArgCheck.isNotNull(theTreeNode);

    return (MappingClass) mappingLocator.getMappingClass(theTreeNode);
  }

  public MappingClassColumn getMappingClassColumn(
      EObject theTreeNode, MappingClass theMappingClass) {
    CoreArgCheck.isNotNull(theTreeNode);

    MappingClassColumn result = mappingLocator.getMappingClassColumn(theTreeNode, theMappingClass);

    return result;
  }

  public MappingClass getMappingClassForTreeNode(EObject theTreeNode) {
    return mappingLocator.getMappingClassForTreeNode(theTreeNode);
  }

  /**
   * Obtain an ordered list of all locations visible in the TreeViewer that are in the extent of the
   * specified MappingClass. This method is based on getCoarseMappingExtentNodes(MappingClass
   * theMappingClass) from MappingAdapterFilter.
   *
   * @param theMappingClass
   * @return
   */
  public List getTreeNodesInAMappingClassScope(MappingClass theMappingClass) {
    // startTracking("getTreeNodesInAMappingClassScope()"); //$NON-NLS-1$

    List extentNodes = mappingLocator.getTreeNodesInAMappingClassScope(theMappingClass);

    // stopTracking("getTreeNodesInAMappingClassScope()"); //$NON-NLS-1$
    return extentNodes;
  }

  /**
   * return a list of all location mapped to the attributes of the specified MappingClass
   *
   * @param theMappingClass
   * @return
   */
  public List getColumnLocations(MappingClass theMappingClass) {
    return mappingLocator.getColumnLocations(theMappingClass);
  }

  /**
   * Obtains the <code>MappingClassColumn</code> where the specified tree node is mapped.
   *
   * @param theTreeNode the tree node whose <code>MappingClassColumn</code> is being requested
   * @return the <code>MappingClassColumn</code> or <code>null</code> if not mapped
   */
  public MappingClassColumn getMappingClassColumn(EObject theTreeNode) {
    /*
     * jh Lyra enh:
     *
     * This is a linear search, and the MCs are not necessarily in any
     *    optimal order.  Let's replace this with a HashMap.
     *
     * jhTODO
     * Major question:  This map is created in the constructor of this class;
     *                  Should it be recreated any other times prior to
     *                  recreating this class (TreeMappingAdapter)?
     *                  Yes: on NewMappingLinkAction and DeleteMappingLinksAction
     *                  [fixed 2/1/2006]
     */
    CoreArgCheck.isNotNull(theTreeNode);

    MappingClassColumn result = mappingLocator.getMappingClassColumn(theTreeNode);
    //
    //        result = (MappingClassColumn)getTreeNodesToMappingClassColumnsMap( false ).get(
    // theTreeNode );
    //
    return result;
  }

  /**
   * Indicates if the specified tree node has been mapped.
   *
   * @param theTreeNode the tree node whose mapped status is being requested
   * @return <code>true</code> if mapped; <code>false</code> otherwise.
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public boolean isMapped(EObject theTreeNode) {
    CoreArgCheck.isNotNull(theTreeNode);
    return getMappingClassColumn(theTreeNode) != null;
  }

  /**
   * Indicates if the specified tree node has been mapped.
   *
   * @param theTreeNode the tree node whose mapped status is being requested
   * @return <code>true</code> if mapped; <code>false</code> otherwise.
   * @throws IllegalArgumentException if input parameter is <code>null</code>
   */
  public StagingTable getStagingTableForRootTreeNode(EObject theTreeNode) {
    return (StagingTable) mappingLocator.getStagingTable(theTreeNode);
  }

  /**
   * Removes the specified {@link org.eclipse.emf.mapping.Mapping}.
   *
   * @param theMappingClass the <code>Mapping</code> input
   * @param theTreeNode the <code>Mapping</code> output
   * @throws IllegalArgumentException if either input parameter is <code>null</code>
   */
  public void removeMappingClassLocation(MappingClass theMappingClass, EObject theTreeNode) {
    CoreArgCheck.isNotNull(theMappingClass);
    CoreArgCheck.isNotNull(theTreeNode);

    try {
      mappingLocator.removeOutputLocation(theMappingClass, theTreeNode);
    } catch (Exception e) {
      Util.log(
          IStatus.ERROR,
          e,
          Util.getString(
              PREFIX + "removeLocationTreeNodeNotFound", // $NON-NLS-1$
              new Object[] {
                theTreeNode,
                "MappingClass", //$NON-NLS-1$
                theMappingClass
              }));
    }
  }

  /**
   * Deletes all mappings associated with the specified MappingClass, but does not delete the
   * MappingClass itself.
   *
   * @param theMappingClass
   * @throws ModelerCoreException
   */
  public void deleteMappingClass(MappingClass theMappingClass) throws ModelerCoreException {
    CoreArgCheck.isNotNull(theMappingClass);

    mappingLocator.deleteMappingClass(theMappingClass);
  }

  /**
   * Removes the specified {@link org.eclipse.emf.mapping.Mapping}.
   *
   * @param theMappingColumn the <code>Mapping</code> input
   * @param theTreeNode the <code>Mapping</code> output
   * @throws IllegalArgumentException if either input parameter is <code>null</code>
   */
  public void removeMappingClassColumnLocation(
      MappingClassColumn theMappingColumn, EObject theTreeNode) {

    CoreArgCheck.isNotNull(theMappingColumn);
    CoreArgCheck.isNotNull(theTreeNode);

    mappingLocator.removeMappingClassColumnLocation(theMappingColumn, theTreeNode);
  }

  public List getParentMappingClasses(
      MappingClass theMappingClass, EObject docRoot, boolean includeStagingTables) {
    return getParentMappingClasses(
        theMappingClass, new DefaultMappableTree(docRoot), includeStagingTables);
  }

  /**
   * Obtain an ordered list of all MappingClasses located above the specified instance. Note: this
   * method may also be called for StagingTables, which extend MappingClass.
   *
   * @param theMappingClass the MappingClass or StagingTable
   * @return
   */
  public List getParentMappingClasses(
      MappingClass theMappingClass, IMappableTree theMappableTree, boolean includeStagingTables) {
    List result = new ArrayList();
    List locations = null;

    if (theMappingClass instanceof StagingTable) {
      locations = new ArrayList();
      locations.add(getStagingTableOutputLocation((StagingTable) theMappingClass));

    } else {
      locations = new ArrayList();
      locations.addAll(getMappingClassOutputLocations(theMappingClass));
    }
    List mappingClasses = getAllMappingClasses();
    for (Iterator iter = mappingClasses.iterator(); iter.hasNext(); ) {
      MappingClass mc = (MappingClass) iter.next();

      MAPPING_CLASS_LOOP:
      if (mc != null && !mc.equals(theMappingClass)) {
        for (Iterator testLocIter = getMappingClassOutputLocations(mc).iterator();
            testLocIter.hasNext() && locations.size() != 0; ) {
          EObject possibleLoc = (EObject) testLocIter.next();
          for (int i = 0; i < locations.size(); ++i) {
            // mc is a parent if one of it's locations is an ancestor of theMappingClass's location
            if (theMappableTree.isAncestorOf(possibleLoc, (EObject) locations.get(i))) {
              result.add(mc);
              break MAPPING_CLASS_LOOP;
            }
          }
        }
      }
    }

    return result;
  }

  /**
   * Obtain the document node eObject for this mapping
   *
   * @return
   */
  public EObject getDocument() {
    List mappingRoots = mappingLocator.getMappingRoots();
    if (mappingRoots != null && !mappingRoots.isEmpty()) {
      EObject firstRoot = (EObject) mappingRoots.get(0);
      if (firstRoot != null && firstRoot instanceof TransformationMappingRoot) {
        return ((TransformationMappingRoot) firstRoot).getTarget();
      }
    }

    return null;
  }
}