/**
   * Returns a VDB editor given a vdb resource if editor is open
   *
   * @param vdb the vdb
   * @return the vdb editor
   */
  public static VdbEditor getVdbEditorForFile(IResource vdb) {
    if (vdb != null && vdb.exists()) {
      IWorkbenchWindow window = UiPlugin.getDefault().getCurrentWorkbenchWindow();

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

        if (page != null) {
          // look through the open editors and see if there is one available for this model file.
          IEditorReference[] editors = page.getEditorReferences();
          for (int i = 0; i < editors.length; ++i) {

            IEditorPart editor = editors[i].getEditor(false);
            if (editor != null) {
              IEditorInput input = editor.getEditorInput();
              if (input instanceof IFileEditorInput) {
                if (vdb.equals(((IFileEditorInput) input).getFile())
                    || vdb.getFullPath()
                        .equals(((IFileEditorInput) input).getFile().getFullPath())) {
                  // found it;
                  if (ModelUtil.isVdbArchiveFile(vdb)) {
                    return (VdbEditor) editor;
                  }
                  break;
                }
              }
            }
          }
        }
      }
    }

    return null;
  }
  private boolean isValidModelResource(Object oSelection) {
    boolean bResult = false;
    if (oSelection instanceof IResource) {
      try {

        IResource resource = (IResource) oSelection;

        if (ModelUtilities.isModelFile(resource)) {
          ModelResource mr = ModelUtil.getModelResource((IFile) resource, true);
          if (mr.getModelType() != null) {
            if (mr.getModelType().equals(newModelInfo.getModelType())) {
              if (mr.getPrimaryMetamodelDescriptor() != null) {
                if (mr.getPrimaryMetamodelDescriptor()
                    .getNamespaceURI()
                    .equals(newModelInfo.getModelURI())) {
                  bResult = true;
                }
              }
            }
          }
        }
      } catch (ModelWorkspaceException mwe) {
        ModelerCore.Util.log(IStatus.ERROR, mwe, mwe.getMessage());
      }
    }
    return bResult;
  }
        /**
         * {@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);
        }
  /**
   * We will compute column-level statistics (min-value, max-value, # of null values, # of distinct
   * values) for all columns in tables in the model IFF the model is physical relational with a Jdbc
   * source. We must first prompt the user for the password, as it is not stored with the Jdbc
   * import settings.
   *
   * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
   * @since 4.3
   */
  @Override
  public void run() {
    if (isEnabled()) {
      final Shell shell = UiPlugin.getDefault().getCurrentWorkbenchWindow().getShell();
      try {
        ModelResource modelResource = ModelUtil.getModelResource(this.selectedModel, false);
        if (modelResource != null) {

          boolean cancelled = openEditorIfNeeded(modelResource);

          if (cancelled) {
            return;
          }
          final Resource resource = modelResource.getEmfResource();

          executeInTransaction(resource, shell);
        }
      } catch (Exception e) {
        InternalModelerJdbcUiPluginConstants.Util.log(e);
        final String title =
            InternalModelerJdbcUiPluginConstants.Util.getString(
                "CostAnalysisAction.errorTitle"); //$NON-NLS-1$
        final String message =
            InternalModelerJdbcUiPluginConstants.Util.getString(
                "CostAnalysisAction.errorMessage"); //$NON-NLS-1$
        MessageDialog.openError(shell, title, message);
      }
    }
  }
  private boolean folderReadOnlyCheck() {
    boolean allOK = true;
    if (resSelectedResource != null && resSelectedResource instanceof IFolder) {
      // Is Folder, check read-only of contents
      IResource[] contents = null;
      try {
        contents = ((IFolder) resSelectedResource).members();
      } catch (CoreException e) {
      }
      if (contents != null) {
        // Check all resources
        boolean allWritable = true;
        for (int i = 0; i < contents.length; i++) {
          if (ModelUtil.isIResourceReadOnly(contents[i])) {
            allWritable = false;
          }
          if (!allWritable) break;
        }
        if (!allWritable) {
          allOK = false;
          // tell the user they can't rename:
          String message =
              UiConstants.Util.getString(
                  "RenameRefactorAction.folderContainsReadOnlyFiles", //$NON-NLS-1$
                  resSelectedResource.getName());
          MessageDialog.openError(getShell(), READ_ONLY_FILE_IN_FOLDER_TITLE, message);
        }
      }
    }

    return allOK;
  }
  /**
   * @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);
  }
 @Override
 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
   boolean enable = false;
   try {
     if (!SelectionUtilities.isMultiSelection(selection)) {
       Object obj = SelectionUtilities.getSelectedObject(selection);
       if (obj instanceof IFile && ModelUtilities.isModelFile((IFile) obj)) {
         ModelResource modelResource = ModelUtil.getModelResource((IFile) obj, false);
         if (ModelUtilities.hasJdbcSource(modelResource)) {
           this.selectedModel = (IFile) obj;
           enable = true;
         }
       }
     }
   } catch (ModelWorkspaceException err) {
     UiConstants.Util.log(err);
   } finally {
     setEnabled(enable);
   }
 }
  @Override
  public boolean isApplicable(ISelection selection) {
    boolean result = false;
    try {
      if (!SelectionUtilities.isMultiSelection(selection)) {
        Object obj = SelectionUtilities.getSelectedObject(selection);
        if (obj instanceof IFile && ModelUtilities.isModelFile((IFile) obj)) {
          ModelResource modelResource = ModelUtil.getModelResource((IFile) obj, false);
          if (ModelUtilities.hasJdbcSource(modelResource)) {
            this.selectedModel = (IFile) obj;
            result = true;
          }
        }
      }
    } catch (ModelWorkspaceException err) {
      UiConstants.Util.log(err);
    }

    return result;
  }
  private ModelResource getSelectedResource() {
    ModelResource selectedResource = null;
    if (selection != null && SelectionUtilities.isSingleSelection(selection)) {
      Object obj = SelectionUtilities.getSelectedObject(selection);
      if (obj instanceof IFile) {
        if (ModelUtilities.isModelFile((IFile) obj)) {
          try {
            selectedResource = ModelUtil.getModelResource((IFile) obj, false);
            if (!selectedResource
                .getPrimaryMetamodelDescriptor()
                .equals(this.metamodelDescriptor)) {
              selectedResource = null;
            }
          } catch (ModelWorkspaceException e) {
            // no need to log, just launch the dialog empty
          }
        }
      }
    }

    return selectedResource;
  }
  /** @see IDialogPage#createControl(Composite) */
  @Override
  public void createControl(Composite parent) {

    ModelResource selectedResource = null;
    if (selection != null && SelectionUtilities.isSingleSelection(selection)) {
      Object obj = SelectionUtilities.getSelectedObject(selection);
      if (obj instanceof IFile) {
        if (ModelUtilities.isModelFile((IFile) obj)) {
          try {
            selectedResource = ModelUtil.getModelResource((IFile) obj, false);
            if (!selectedResource
                .getPrimaryMetamodelDescriptor()
                .equals(this.metamodelDescriptor)) {
              selectedResource = null;
            } else {
              setPageComplete(true);
            }
          } catch (ModelWorkspaceException e) {
            // no need to log, just launch the dialog empty
          }
        }
      }
    }

    if (selectedResource != null) {
      sourceIsPhysical = ModelIdentifier.isPhysicalModelType(selectedResource);
    }
    panel =
        new TreeViewerWizardPanel(
            parent,
            this,
            metamodelDescriptor,
            selectedResource,
            sourceIsPhysical,
            targetIsVirtual,
            false);
    setControl(panel);
  }
 @Override
 public void run() {
   ISelection cachedSelection = getSelection();
   if (cachedSelection != null && !cachedSelection.isEmpty()) {
     Object selectedObj = SelectionUtilities.getSelectedObject(cachedSelection);
     if (selectedObj != null && selectedObj instanceof IFile) {
       ModelResource modelResource = null;
       try {
         modelResource = ModelUtil.getModelResource(((IFile) selectedObj), false);
         if (modelResource != null) {
           String fileName = askUserForOutputFilename();
           if (fileName != null) {
             String fileOuputString = getSqlOutputString(modelResource);
             exportSqlToFile(
                 fileName, UiConstants.Util.getString(EXPORT_DEFAULT_FILEEXT), fileOuputString);
           }
         }
       } catch (ModelWorkspaceException e) {
         UiConstants.Util.log(e);
       }
     }
   }
   selectionChanged(null, new StructuredSelection());
 }
 private boolean isXsdResource(final IFile resource) {
   return ModelUtil.isXsdFile(resource);
 }