public void testMovePackage2() throws JavaModelException {
    IPath projectPath = env.addProject("Project"); // $NON-NLS-1$
    env.addExternalJars(projectPath, Util.getJavaClassLibs());
    env.removePackageFragmentRoot(projectPath, ""); // $NON-NLS-1$
    IPath src = env.addPackageFragmentRoot(projectPath, "src"); // $NON-NLS-1$
    IPath other = env.addFolder(projectPath, "other"); // $NON-NLS-1$
    env.setOutputFolder(projectPath, "bin"); // $NON-NLS-1$

    IPath classA =
        env.addClass(
            src,
            "p",
            "A", //$NON-NLS-1$ //$NON-NLS-2$
            "package p; \n"
                + //$NON-NLS-1$
                "public class A extends Missing {}"); //$NON-NLS-1$
    IPath classB =
        env.addClass(
            src,
            "p.q",
            "B", //$NON-NLS-1$ //$NON-NLS-2$
            "package p.q; \n"
                + //$NON-NLS-1$
                "public class B extends Missing {}"); //$NON-NLS-1$

    fullBuild(projectPath);
    expectingSpecificProblemFor(
        classA,
        new Problem(
            "",
            "Missing cannot be resolved to a type",
            new Path("/Project/src/p/A.java"),
            35,
            42,
            CategorizedProblem.CAT_TYPE,
            IMarker.SEVERITY_ERROR) // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$		
        );
    expectingSpecificProblemFor(
        classB,
        new Problem(
            "",
            "Missing cannot be resolved to a type",
            new Path("/Project/src/p/q/B.java"),
            37,
            44,
            CategorizedProblem.CAT_TYPE,
            IMarker.SEVERITY_ERROR) // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$		
        );

    try {
      IProject p = env.getProject(projectPath);
      IFolder pFolder = p.getWorkspace().getRoot().getFolder(classA.removeLastSegments(1));
      pFolder.move(other.append("p"), true, false, null);
    } catch (CoreException e) {
      env.handle(e);
    }

    incrementalBuild(projectPath);
    expectingNoProblems();
  }
Example #2
0
    @Override
    protected IStatus run(IProgressMonitor monitor) {
      IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
      monitor.beginTask("Refreshing git managed projects", projects.length);

      while (projectsToScan.size() > 0) {
        IProject p;
        synchronized (projectsToScan) {
          if (projectsToScan.size() == 0) break;
          Iterator<IProject> i = projectsToScan.iterator();
          p = i.next();
          i.remove();
        }
        ISchedulingRule rule = p.getWorkspace().getRuleFactory().refreshRule(p);
        try {
          getJobManager().beginRule(rule, monitor);
          p.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));
        } catch (CoreException e) {
          logError("Failed to refresh projects from index changes", e);
          return new Status(IStatus.ERROR, getPluginId(), e.getMessage());
        } finally {
          getJobManager().endRule(rule);
        }
      }
      monitor.done();
      return Status.OK_STATUS;
    }
Example #3
0
  protected void checkIfPathValid() {
    fFolder = null;
    IContainer folder = null;
    if (fUseFolderButton.isSelected()) {
      String pathStr = fContainerDialogField.getText();
      if (pathStr.length() == 0) {
        fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_enterpath);
        return;
      }
      IPath path = fCurrProject.getFullPath().append(pathStr);
      IWorkspace workspace = fCurrProject.getWorkspace();

      IStatus pathValidation = workspace.validatePath(path.toString(), IResource.FOLDER);
      if (!pathValidation.isOK()) {
        fContainerFieldStatus.setError(
            Messages.format(
                NewWizardMessages.NewSourceFolderDialog_error_invalidpath,
                pathValidation.getMessage()));
        return;
      }
      folder = fCurrProject.getFolder(pathStr);
    } else {
      folder = fCurrProject;
    }
    if (isExisting(folder)) {
      fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_pathexists);
      return;
    }
    fContainerFieldStatus.setOK();
    fFolder = folder;
  }
 private void createExternalSourceArchivesProject(IProject project, IProgressMonitor monitor)
     throws CoreException {
   IProjectDescription desc = project.getWorkspace().newProjectDescription(project.getName());
   IPath stateLocation = CeylonPlugin.getInstance().getStateLocation();
   desc.setLocation(stateLocation.append(EXTERNAL_PROJECT_NAME));
   project.create(desc, IResource.HIDDEN, monitor);
 }
  private IProject createProject(final GridProjectProperties props, final IProgressMonitor monitor)
      throws CoreException {

    monitor.subTask(Messages.getString("GridProjectCreationOperation.init_task")); // $NON-NLS-1$

    String projectName = props.getProjectName();
    IPath projectPath = props.getProjectLocation();
    IProject[] referencesProjects = props.getReferencesProjects();

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = workspaceRoot.getProject(projectName);

    IStatus status = ResourcesPlugin.getWorkspace().validateProjectLocation(project, projectPath);
    if (status.getSeverity() != IStatus.OK) {
      throw new CoreException(status);
    }

    IProjectDescription desc = project.getWorkspace().newProjectDescription(projectName);
    desc.setLocation(projectPath);
    if (referencesProjects != null) {
      desc.setReferencedProjects(referencesProjects);
    }
    project.create(desc, new SubProgressMonitor(monitor, 50));
    project.open(new SubProgressMonitor(monitor, 50));

    createProjectStructure(project, props);
    setProjectProperties(project, props);

    if (monitor.isCanceled()) {
      throw new OperationCanceledException();
    }

    return project;
  }
 public static List<IProject> decodeUsedProjects(String usedProjects, IProject project) {
   if (usedProjects == null || usedProjects.length() == 0) {
     return new ArrayList<IProject>();
   }
   String[] paths = usedProjects.split(";");
   List<IProject> l = new ArrayList<IProject>(paths.length);
   for (int i = 0; i < paths.length; i++) {
     l.add(project.getWorkspace().getRoot().getProject(paths[i]));
   }
   return l;
 }
Example #7
0
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) {
      Set<Repository> repos;
      synchronized (repositoriesChanged) {
        if (repositoriesChanged.isEmpty()) {
          return Status.OK_STATUS;
        }
        repos = new LinkedHashSet<>(repositoriesChanged);
        repositoriesChanged.clear();
      }
      IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
      Set<IProject> toRefresh = new LinkedHashSet<>();
      for (IProject p : projects) {
        if (!p.isAccessible()) {
          continue;
        }
        RepositoryMapping mapping = RepositoryMapping.getMapping(p);
        if (mapping != null && repos.contains(mapping.getRepository())) {
          toRefresh.add(p);
        }
      }
      monitor.beginTask(UIText.Activator_refreshingProjects, toRefresh.size());

      for (IProject p : toRefresh) {
        if (monitor.isCanceled()) {
          return Status.CANCEL_STATUS;
        }
        ISchedulingRule rule = p.getWorkspace().getRuleFactory().refreshRule(p);
        try {
          getJobManager().beginRule(rule, monitor);
          // handle missing projects after branch switch
          if (p.isAccessible()) {
            p.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));
          }
        } catch (CoreException e) {
          handleError(UIText.Activator_refreshFailed, e, false);
          return new Status(IStatus.ERROR, getPluginId(), e.getMessage());
        } finally {
          getJobManager().endRule(rule);
        }
      }
      if (!monitor.isCanceled()) {
        // re-schedule if we got some changes in the meantime
        synchronized (repositoriesChanged) {
          if (!repositoriesChanged.isEmpty()) {
            schedule(100);
          }
        }
      }
      monitor.done();
      return Status.OK_STATUS;
    }
  public SetFilterWizardPage(BPListElement entryToEdit, ArrayList existingEntries) {
    super(PAGE_NAME);
    fExistingEntries = existingEntries;

    setTitle(NewWizardMessages.ExclusionInclusionDialog_title);
    setDescription(NewWizardMessages.ExclusionInclusionDialog_description2);

    fCurrElement = entryToEdit;
    fCurrProject = entryToEdit.getScriptProject().getProject();
    IWorkspaceRoot root = fCurrProject.getWorkspace().getRoot();
    IResource res = root.findMember(entryToEdit.getPath());
    if (res instanceof IContainer) {
      fCurrSourceFolder = (IContainer) res;
    }

    String excLabel = NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_label;
    ImageDescriptor excDescriptor = DLTKPluginImages.DESC_OBJS_EXCLUSION_FILTER_ATTRIB;
    String[] excButtonLabels =
        new String[] {
          NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add,
          NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add_multiple,
          NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_edit,
          null,
          NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_remove
        };

    String incLabel = NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_label;
    ImageDescriptor incDescriptor = DLTKPluginImages.DESC_OBJS_INCLUSION_FILTER_ATTRIB;
    String[] incButtonLabels =
        new String[] {
          NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add,
          NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add_multiple,
          NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_edit,
          null,
          NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_remove
        };

    fExclusionPatternList =
        createListContents(
            entryToEdit, BPListElement.EXCLUSION, excLabel, excDescriptor, excButtonLabels);
    fInclusionPatternList =
        createListContents(
            entryToEdit, BPListElement.INCLUSION, incLabel, incDescriptor, incButtonLabels);
  }
  /**
   * Moves all files currently located in the temporary files folder into the build directory
   *
   * @param monitor progress monitor
   * @throws CoreException if an error occurs
   */
  private void restoreTempFiles(IProgressMonitor monitor) throws CoreException {
    final Set<IPath> tempNames = tracking.getTempFiles();
    if (tempDir == null || tempNames.isEmpty()) {
      movedFiles = new HashSet<IPath>();
      return;
    }

    // Move files and store new paths for later reversal
    project
        .getWorkspace()
        .run(
            new IWorkspaceRunnable() {
              public void run(IProgressMonitor monitor) throws CoreException {
                movedFiles =
                    moveFiles(tempDir, sourceDir, tracking.getTempFiles(), false, false, monitor);
              }
            },
            monitor);
  }
Example #10
0
  /**
   * Determine the exposed (exported) dependencies from the project named 'otherProject' and add
   * them to the accumulatedPathEntries String Set. This will include the output location of the
   * project plus other kinds of entry that are re-exported. If dependent on another project and
   * that project is re-exported, the method will recurse.
   *
   * @param baseProject the original project for which the classpath is being computed
   * @param otherProject a project something in the dependency chain for the original project
   * @param accumulatedPathEntries a String set of classpath entries, into which new entries should
   *     be added
   */
  private static void computeDependenciesFromProject(
      IProject baseProject, String otherProject, Set accumulatedPathEntries)
      throws JavaModelException {

    // First the output location for the project:
    IProject iproject = baseProject.getWorkspace().getRoot().getProject(otherProject);
    IJavaProject ijp = JavaCore.create(iproject);
    accumulatedPathEntries.add(pathToString(ijp.getOutputLocation(), iproject));

    // Look for exported entries from otherProject
    IClasspathEntry[] cpes = ijp.getResolvedClasspath(true);
    if (cpes != null) {
      for (int j = 0; j < cpes.length; j++) {
        IClasspathEntry cpe = cpes[j];
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
          continue;
        }
        if (cpe.isExported()) {
          // TODO should quickly dismiss source entries? others?
          IPath cpePath = cpes[j].getPath();
          String segmentZero = cpePath.segment(0);
          if (segmentZero != null && segmentZero.equals(otherProject)) {
            accumulatedPathEntries.add(
                iproject.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString());
          } else {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
              // segmentZero is a project name
              computeDependenciesFromProject(baseProject, segmentZero, accumulatedPathEntries);
            } else {
              String otherPathElement = null;
              if (segmentZero != null && segmentZero.equals(iproject.getName())) {
                otherPathElement =
                    iproject.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString();
              } else {
                otherPathElement = cpePath.toOSString();
              }
              accumulatedPathEntries.add(otherPathElement);
            }
          }
        }
      }
    }
  }
Example #11
0
 @Override
 protected IStatus run(IProgressMonitor monitor) {
   try {
     // A repository can contain many projects, only scan once
     // (a project could in theory be distributed among many
     // repositories. We discard that as being ugly and stupid for
     // the moment.
     IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
     monitor.beginTask("Scanning Git repositories for changes", projects.length);
     Set<Repository> scanned = new HashSet<Repository>();
     for (IProject p : projects) {
       RepositoryMapping mapping = RepositoryMapping.getMapping(p);
       if (mapping != null) {
         Repository r = mapping.getRepository();
         if (!scanned.contains(r)) {
           if (monitor.isCanceled()) break;
           trace("Scanning " + r + " for changes");
           scanned.add(r);
           ISchedulingRule rule = p.getWorkspace().getRuleFactory().modifyRule(p);
           getJobManager().beginRule(rule, monitor);
           try {
             r.scanForRepoChanges();
           } finally {
             getJobManager().endRule(rule);
           }
         }
       }
       monitor.worked(1);
     }
     monitor.done();
     trace("Rescheduling " + getName() + " job");
     schedule(REPO_SCAN_INTERVAL);
   } catch (Exception e) {
     trace("Stopped rescheduling " + getName() + "job");
     return new Status(
         IStatus.ERROR,
         getPluginId(),
         0,
         "An error occurred while scanning for changes. Scanning aborted",
         e);
   }
   return Status.OK_STATUS;
 }
  /**
   * Moves temporary files out of the build directory, if applicable. A file is considered a
   * temporary file, if
   *
   * <ul>
   *   <li>it had been in the temporary files folder before the build process
   *       <p><b>or</b>
   *   <li>it was created or modified during the build process, and has a temporary file extension
   *       as specified in the preferences
   * </ul>
   *
   * @param excludes set of paths to exclude from moving, e.g. because they are the main output
   *     files
   * @param monitor progress monitor
   * @throws CoreException if an error occurs
   */
  private void moveTempFiles(final Set<IPath> excludes, IProgressMonitor monitor)
      throws CoreException {
    final IContainer aSourceContainer = getActualSourceContainer();
    if (tracking.isInitial() || aSourceContainer == null || !aSourceContainer.exists()) {
      return;
    }

    final boolean markAsDerived =
        "true"
            .equals(
                TexlipseProperties.getProjectProperty(
                    project, TexlipseProperties.MARK_TEMP_DERIVED_PROPERTY));
    final String[] tempExts = TexlipsePlugin.getPreferenceArray(TexlipseProperties.TEMP_FILE_EXTS);

    // Check if there is anything to do
    if (markAsDerived || tempDir != null) {
      // First move temporary files, which had been placed into the source folder
      // just prior to the build;
      // then check for new temporary files, which need to be moved
      project
          .getWorkspace()
          .run(
              new IWorkspaceRunnable() {
                public void run(IProgressMonitor monitor) throws CoreException {
                  if (movedFiles != null) {
                    if (excludes != null) {
                      movedFiles.removeAll(excludes);
                    }
                    moveFiles(sourceDir, tempDir, movedFiles, markAsDerived, true, monitor);
                  }
                  final Set<IPath> newTempNames =
                      tracking.getNewTempNames(aSourceContainer, tempExts, format, monitor);
                  if (excludes != null) {
                    newTempNames.removeAll(excludes);
                  }
                  moveFiles(sourceDir, tempDir, newTempNames, markAsDerived, true, monitor);
                }
              },
              monitor);
    }
  }
  /**
   * Create a new java project
   *
   * @param projectName a project name
   * @return newProject a new project resource handle
   */
  public static IProject createJavaProject(final String projectName) throws CoreException {

    // 1. Get the project from the workspace
    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    final IProject newProject = root.getProject(projectName);
    final IProjectDescription description =
        newProject.getWorkspace().newProjectDescription(projectName);

    // 2. Create a project if it does not already exist
    if (!newProject.exists()) {
      description.setLocation(null);
      newProject.create(description, null);
    }

    if (!newProject.isOpen()) {
      newProject.open(null);
    }

    // 4. Make it a Java Project
    addJavaNature(newProject);

    return newProject;
  }
Example #14
0
  /**
   * Creates the Acceleo project.
   *
   * @param monitor The progress monitor.
   */
  private void createProject(IProgressMonitor monitor) {
    try {
      IProject project =
          ResourcesPlugin.getWorkspace().getRoot().getProject(newProjectPage.getProjectName());
      IPath location = newProjectPage.getLocationPath();
      if (!project.exists()) {
        IProjectDescription desc =
            project.getWorkspace().newProjectDescription(newProjectPage.getProjectName());
        if (ResourcesPlugin.getWorkspace().getRoot().getLocation().equals(location)) {
          location = null;
        }
        desc.setLocation(location);
        project.create(desc, monitor);
        project.open(monitor);

        boolean shouldGenerateModules =
            !(getContainer().getCurrentPage() instanceof WizardNewProjectCreationPage);
        convert(
            project,
            newProjectPage.getSelectedJVM(),
            newAcceleoModulesCreationPage.getAllModules(),
            shouldGenerateModules,
            monitor);

        IWorkingSet[] workingSets = newProjectPage.getSelectedWorkingSets();
        getWorkbench().getWorkingSetManager().addToWorkingSets(project, workingSets);

        project.build(
            IncrementalProjectBuilder.FULL_BUILD,
            AcceleoBuilder.BUILDER_ID,
            new HashMap<String, String>(),
            monitor);
      }
    } catch (CoreException e) {
      AcceleoUIActivator.log(e, true);
    }
  }
  /**
   * Renames output files and/or moves them if necessary. A file is considered an output file, if
   *
   * <ul>
   *   <li>it is the current output file (which can also be from a temporary build)
   *       <p><b>or</b>
   *   <li>it has the same file name as the current input file, apart from its file extension, and
   *       one of the derived file extensions as specified in the preferences
   * </ul>
   *
   * @param monitor progress monitor
   * @return set of paths to the (possibly moved) files
   * @throws CoreException if an error occurs
   */
  private Set<IPath> moveOutputFiles(IProgressMonitor monitor) throws CoreException {
    final boolean markAsDerived =
        "true"
            .equals(
                TexlipseProperties.getProjectProperty(
                    project, TexlipseProperties.MARK_OUTPUT_DERIVED_PROPERTY));
    final String[] derivedExts =
        TexlipsePlugin.getPreferenceArray(TexlipseProperties.DERIVED_FILES);

    final IFile aSourceFile = getActualSourceFile();
    final IContainer aSourceContainer = getActualSourceContainer();
    final IFile sOutputFile = getSelectedOutputFile();
    final IContainer sOutputContainer = getSelectedOutputContainer(markAsDerived, monitor);
    if (aSourceFile == null
        || aSourceContainer == null
        || sOutputFile == null
        || sOutputContainer == null) {
      // Something is wrong with the settings
      return null;
    }

    // Get name without extension from main files for renaming
    final String dotFormat = '.' + format;
    final String sourceBaseName = stripFileExt(aSourceFile.getName(), null);
    final String outputBaseName = stripFileExt(sOutputFile.getName(), dotFormat);

    // Check if files are to be moved or renamed
    final boolean moveFiles =
        !sourceBaseName.equals(outputBaseName) || !sOutputContainer.equals(aSourceContainer);
    // Retrieve output and other derived files along with their extensions
    final Map<IPath, String> outputFiles =
        ProjectFileTracking.getOutputNames(
            aSourceContainer, sourceBaseName, derivedExts, format, monitor);

    // Check if there is anything to do
    if ((moveFiles || markAsDerived) && !outputFiles.isEmpty()) {
      final Set<IPath> movedFiles = new HashSet<IPath>(outputFiles.size());

      project
          .getWorkspace()
          .run(
              new IWorkspaceRunnable() {
                public void run(IProgressMonitor monitor) throws CoreException {
                  // Move files to destination folder and rename
                  for (Entry<IPath, String> entry : outputFiles.entrySet()) {
                    IFile currentFile = project.getFile(entry.getKey());
                    if (moveFiles) {
                      // Determine new file name
                      String destName = outputBaseName + entry.getValue();
                      // Move file
                      IFile dest =
                          moveFile(project, currentFile, sOutputContainer, destName, monitor);
                      if (dest != null && markAsDerived) {
                        dest.setDerived(true);
                      }
                      movedFiles.add(dest.getProjectRelativePath());
                    } else {
                      // Possibly mark as derived
                      if (markAsDerived) {
                        currentFile.setDerived(true);
                      }
                      movedFiles.add(entry.getKey());
                    }
                  }
                }
              },
              monitor);

      return movedFiles;
    } else {
      return outputFiles.keySet();
    }
  }
  /*
   * Update projects references so that the build order is consistent with the classpath
   */
  public void updateProjectReferencesIfNecessary() throws JavaModelException {

    String[] oldRequired =
        this.oldResolvedClasspath == null
            ? CharOperation.NO_STRINGS
            : this.project.projectPrerequisites(this.oldResolvedClasspath);
    IClasspathEntry[] newResolvedClasspath = this.project.getResolvedClasspath();
    String[] newRequired = this.project.projectPrerequisites(newResolvedClasspath);
    final IProject projectResource = this.project.getProject();

    try {
      IProject[] projectReferences = projectResource.getDescription().getDynamicReferences();

      HashSet oldReferences = new HashSet(projectReferences.length);
      for (int i = 0; i < projectReferences.length; i++) {
        String projectName = projectReferences[i].getName();
        oldReferences.add(projectName);
      }
      HashSet newReferences = (HashSet) oldReferences.clone();

      for (int i = 0; i < oldRequired.length; i++) {
        String projectName = oldRequired[i];
        newReferences.remove(projectName);
      }
      for (int i = 0; i < newRequired.length; i++) {
        String projectName = newRequired[i];
        newReferences.add(projectName);
      }

      Iterator iter;
      int newSize = newReferences.size();

      checkIdentity:
      {
        if (oldReferences.size() == newSize) {
          iter = newReferences.iterator();
          while (iter.hasNext()) {
            if (!oldReferences.contains(iter.next())) {
              break checkIdentity;
            }
          }
          return;
        }
      }
      String[] requiredProjectNames = new String[newSize];
      int index = 0;
      iter = newReferences.iterator();
      while (iter.hasNext()) {
        requiredProjectNames[index++] = (String) iter.next();
      }
      Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent

      final IProject[] requiredProjectArray = new IProject[newSize];
      IWorkspaceRoot wksRoot = projectResource.getWorkspace().getRoot();
      for (int i = 0; i < newSize; i++) {
        requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]);
      }

      // ensure that a scheduling rule is used so that the project description is not modified by
      // another thread while we update it
      // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=214981
      // also ensure that if no change (checkIdentify block returned above) we don't reach here
      // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241751
      IWorkspace workspace = projectResource.getWorkspace();
      ISchedulingRule rule =
          workspace
              .getRuleFactory()
              .modifyRule(projectResource); // scheduling rule for modifying the project
      IWorkspaceRunnable runnable =
          new IWorkspaceRunnable() {
            public void run(IProgressMonitor monitor) throws CoreException {
              IProjectDescription description = projectResource.getDescription();
              description.setDynamicReferences(requiredProjectArray);
              projectResource.setDescription(description, IResource.AVOID_NATURE_CONFIG, null);
            }
          };
      workspace.run(runnable, rule, IWorkspace.AVOID_UPDATE, null);
    } catch (CoreException e) {
      if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName()))
        throw new JavaModelException(e);
    }
  }
 private IProject createExternalFoldersProject(IProgressMonitor monitor) {
   IProject project = getExternalFoldersProject();
   if (!project.isAccessible()) {
     try {
       if (!project.exists()) {
         IProjectDescription desc =
             project.getWorkspace().newProjectDescription(project.getName());
         IPath stateLocation = DLTKCore.getPlugin().getStateLocation();
         desc.setLocation(stateLocation.append(EXTERNAL_PROJECT_NAME));
         project.create(desc, IResource.HIDDEN, monitor);
       }
       try {
         project.open(monitor);
       } catch (CoreException e1) {
         // .project or folder on disk have been deleted, recreate
         // them
         IPath stateLocation = DLTKCore.getPlugin().getStateLocation();
         IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME);
         projectPath.toFile().mkdirs();
         FileOutputStream output =
             new FileOutputStream(
                 projectPath.append(IScriptProjectFilenames.PROJECT_FILENAME).toOSString());
         try {
           output.write(
               ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                       + //$NON-NLS-1$
                       "<projectDescription>\n" //$NON-NLS-1$
                       + "	<name>" //$NON-NLS-1$
                       + EXTERNAL_PROJECT_NAME
                       + "</name>\n"
                       + //$NON-NLS-1$
                       "	<comment></comment>\n"
                       + //$NON-NLS-1$
                       "	<projects>\n"
                       + //$NON-NLS-1$
                       "	</projects>\n"
                       + //$NON-NLS-1$
                       "	<buildSpec>\n"
                       + //$NON-NLS-1$
                       "	</buildSpec>\n"
                       + //$NON-NLS-1$
                       "	<natures>\n"
                       + //$NON-NLS-1$
                       "	</natures>\n"
                       + //$NON-NLS-1$
                       "</projectDescription>")
                   .getBytes()); //$NON-NLS-1$
         } finally {
           output.close();
         }
         project.open(null);
       }
     } catch (CoreException e) {
       Util.log(e, "Problem creating hidden project for external folders"); // $NON-NLS-1$
       return project;
     } catch (IOException e) {
       Util.log(e, "Problem creating hidden project for external folders"); // $NON-NLS-1$
       return project;
     }
   }
   return project;
 }
 private String getWorkspacePath() {
   return project.getWorkspace().getRoot().getLocation().toOSString();
 }
Example #19
0
  // public for testing
  public static String calculateClasspath(IJavaProject javaProject) {
    try {
      Set accumulatedPathEntries = new LinkedHashSet();
      IProject project = javaProject.getProject();
      String projectName = project.getName();
      IPath defaultOutputPath = javaProject.getOutputLocation();
      String defaultOutputLocation = pathToString(defaultOutputPath, project);

      IClasspathEntry[] cpes = javaProject.getResolvedClasspath(true);
      if (cpes != null) {
        for (int i = 0, max = cpes.length; i < max; i++) {
          IClasspathEntry cpe = cpes[i];
          if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            continue;
          }
          // Two kinds of entry we are interested in - those relative and those absolute
          // relative example: grails/lib/hibernate3-3.3.1.jar  (where grails is the project name)
          // absolute example: f:/grails-111/dist/grails-core-blah.jar
          // javaProject path is f:\grails\grails
          IPath cpePath = cpe.getPath();
          String pathElement = null;
          String segmentZero = cpePath.segment(0);
          if (segmentZero.equals(projectName)) {
            pathElement =
                project.getFile(cpePath.removeFirstSegments(1)).getRawLocation().toOSString();
          } else {

            // for GRECLIPSE-917.  Entry is something like /SomeOtherProject/foo/bar/doodah.jar
            if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
              try {
                IProject iproject = project.getWorkspace().getRoot().getProject(segmentZero);
                if (iproject != null) {
                  IFile ifile = iproject.getFile(cpePath.removeFirstSegments(1));
                  IPath ipath = (ifile == null ? null : ifile.getRawLocation());
                  pathElement = (ipath == null ? null : ipath.toOSString());
                }
              } catch (Throwable t) {
                t.printStackTrace();
              }
            }
            if (cpe.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
              // the classpath entry is a dependency on another project
              computeDependenciesFromProject(project, segmentZero, accumulatedPathEntries);
              // FIXASC this ought to also allow for separate output folders in the project we
              // depend upon *sigh*
              // FIXASC what does all this look like for batch compilation?  Should it be passed in
              // rather than computed here
            } else {
              if (pathElement == null) {
                pathElement = cpe.getPath().toOSString();
              }
            }
          }
          if (pathElement != null) {
            accumulatedPathEntries.add(pathElement);
          }
        }
        accumulatedPathEntries.add(defaultOutputLocation);
        StringBuilder sb = new StringBuilder();
        Iterator iter = accumulatedPathEntries.iterator();
        while (iter.hasNext()) {
          sb.append((String) iter.next());
          sb.append(File.pathSeparator);
        }
        String classpath = sb.toString();
        //				System.out.println("Project classpath for '"+projectName+"' is "+classpath);
        return classpath;
      }
    } catch (JavaModelException jme) {
      System.err.println(
          "Problem trying to determine classpath of project "
              + javaProject.getProject().getName()
              + ":"); //$NON-NLS-1$ //$NON-NLS-2$
      jme.printStackTrace();
    }
    return ""; //$NON-NLS-1$
  }
 private IWorkspaceRoot getWorkspaceRoot(final IJavaProject javaProject) {
   IProject _project = javaProject.getProject();
   IWorkspace _workspace = _project.getWorkspace();
   return _workspace.getRoot();
 }