/**
   * Create or open the project in the given directory (or the directory containing the given file
   * if the file is not a directory).
   *
   * @param file the file or directory indicating which directory should be the root of the project
   * @param monitor the progress monitor used to provide feedback to the user, or <code>null</code>
   *     if no feedback is desired
   * @return the resource associated with the file that was passed in
   * @throws CoreException if the project cannot be opened or created
   */
  public static IResource createOrOpenProject(File file, IProgressMonitor monitor)
      throws CoreException {
    IResource[] existingResources = ResourceUtil.getResources(file);
    if (existingResources.length == 1) {
      return existingResources[0];
    } else if (existingResources.length > 1) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              DartCore.PLUGIN_ID,
              "Too many files representing " + file.getAbsolutePath()));
    }
    final File projectDirectory;
    if (file.isDirectory()) {
      projectDirectory = file;
    } else {
      projectDirectory = file.getParentFile();
    }
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    workspace.run(
        new IWorkspaceRunnable() {
          @Override
          public void run(IProgressMonitor monitor) throws CoreException {
            String projectName = projectDirectory.getName();
            IProject project = getProject(workspace, projectName);
            IProjectDescription description =
                createProjectDescription(project, projectDirectory.toURI());

            monitor.beginTask("Create project " + projectName, 300); // $NON-NLS-1$
            project.create(description, new SubProgressMonitor(monitor, 100));
            if (monitor.isCanceled()) {
              throw new OperationCanceledException();
            }
            project.open(IResource.NONE, new SubProgressMonitor(monitor, 100));
            if (monitor.isCanceled()) {
              throw new OperationCanceledException();
            }
            DartProjectNature nature = new DartProjectNature();
            nature.setProject(project);
            nature.configure();
            monitor.done();
          }
        },
        monitor);
    IResource[] newResources = ResourceUtil.getResources(file);
    if (newResources.length == 1) {
      return newResources[0];
    } else if (newResources.length == 0) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              DartCore.PLUGIN_ID,
              "No files representing " + file.getAbsolutePath()));
    }
    throw new CoreException(
        new Status(
            IStatus.ERROR,
            DartCore.PLUGIN_ID,
            "Too many files representing " + file.getAbsolutePath()));
  }
  /**
   * Process the given resource within the context of the given working set in order to record the
   * data and relationships found within the resource.
   */
  public void indexResource(File libraryFile, File sourceFile, DartUnit dartUnit)
      throws DartModelException {

    // Get the LibrarySource

    LibrarySource librarySource = dartUnit.getLibrary().getSource();

    // Get the DartLibrary

    DartLibraryImpl library;
    IResource resource = ResourceUtil.getResource(libraryFile);
    if (resource == null) {
      library = new DartLibraryImpl(librarySource);
    } else {
      DartElement element = DartCore.create(resource);
      if (element instanceof CompilationUnitImpl) {
        element = ((CompilationUnitImpl) element).getLibrary();
      }
      if (!(element instanceof DartLibrary)) {
        DartCore.logError("Expected library to be associated with " + libraryFile);
        return;
      }
      library = (DartLibraryImpl) element;
    }

    // Get the CompilationUnit

    DartSource unitSource = (DartSource) dartUnit.getSourceInfo().getSource();
    CompilationUnit compilationUnit;
    IResource res = ResourceUtil.getResource(sourceFile);
    if (res != null) {
      DefaultWorkingCopyOwner workingCopy = DefaultWorkingCopyOwner.getInstance();
      compilationUnit = new CompilationUnitImpl(library, (IFile) res, workingCopy);
    } else {
      String relPath = unitSource.getRelativePath();
      compilationUnit = new ExternalCompilationUnitImpl(library, relPath, unitSource);
    }

    URI unitUri = unitSource.getUri();
    Resource indexerResource;
    if (PackageLibraryManager.isDartUri(unitUri)) {
      indexerResource =
          new Resource(
              ResourceFactory.composeResourceId(
                  librarySource.getUri().toString(), unitUri.toString()));
    } else if (PackageLibraryManager.isPackageUri(unitUri)) {
      indexerResource =
          new Resource(
              ResourceFactory.composeResourceId(
                  libraryFile.toURI().toString(), sourceFile.toURI().toString()));
    } else {
      indexerResource = ResourceFactory.getResource(compilationUnit);
    }

    // Queue the resource to be indexed

    indexResource(indexerResource, libraryFile, compilationUnit, dartUnit);
  }
  private void createFolder(IPath path) {
    final AbstractSample sampleContent = page.getCurrentSample();

    IPath containerPath = path.removeLastSegments(1);

    IResource container = ResourceUtil.getResource(containerPath.toFile());

    if (container != null) {
      IPath newFolderPath = container.getFullPath().append(path.lastSegment());

      final IFolder newFolderHandle =
          IDEWorkbenchPlugin.getPluginWorkspace().getRoot().getFolder(newFolderPath);

      IRunnableWithProgress op =
          new IRunnableWithProgress() {
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
              AbstractOperation op;
              op =
                  new CreateFolderOperation(
                      newFolderHandle,
                      null,
                      IDEWorkbenchMessages.WizardNewFolderCreationPage_title);
              try {

                IStatus status =
                    op.execute(monitor, WorkspaceUndoUtil.getUIInfoAdapter(getShell()));

                if (status.isOK()) {
                  createdFile =
                      createProjectContent(
                          newProject, newFolderHandle, newFolderHandle.getName(), sampleContent);
                }

              } catch (ExecutionException e) {
                throw new InvocationTargetException(e);
              } catch (CoreException e) {
                throw new InvocationTargetException(e);
              }
            }
          };

      try {
        getContainer().run(true, true, op);
      } catch (InterruptedException e) {

      } catch (InvocationTargetException e) {
        // ExecutionExceptions are handled above, but unexpected runtime
        // exceptions and errors may still occur.
        IDEWorkbenchPlugin.log(
            getClass(), "createNewFolder()", e.getTargetException()); // $NON-NLS-1$
        MessageDialog.open(
            MessageDialog.ERROR,
            getContainer().getShell(),
            IDEWorkbenchMessages.WizardNewFolderCreationPage_internalErrorTitle,
            NLS.bind(
                IDEWorkbenchMessages.WizardNewFolder_internalError,
                e.getTargetException().getMessage()),
            SWT.SHEET);
      }

      newProject = newFolderHandle.getProject();
    }
  }