/**
   * Create rename refactoring session.
   *
   * @param settings rename settings
   * @return the rename refactoring session
   * @throws CoreException when RenameSupport can't be created
   * @throws RefactoringException when Java element was not found
   */
  @POST
  @Path("rename/create")
  @Produces("application/json")
  @Consumes("application/json")
  public RenameRefactoringSession createRenameRefactoring(CreateRenameRefactoring settings)
      throws CoreException, RefactoringException {
    IJavaProject javaProject = model.getJavaProject(settings.getProjectPath());
    IJavaElement elementToRename;
    ICompilationUnit cu = null;
    switch (settings.getType()) {
      case COMPILATION_UNIT:
        elementToRename = javaProject.findType(settings.getPath()).getCompilationUnit();
        break;
      case PACKAGE:
        elementToRename =
            javaProject.findPackageFragment(new org.eclipse.core.runtime.Path(settings.getPath()));
        break;
      case JAVA_ELEMENT:
        cu = javaProject.findType(settings.getPath()).getCompilationUnit();
        elementToRename = getSelectionElement(cu, settings.getOffset());
        break;
      default:
        elementToRename = null;
    }
    if (elementToRename == null) {
      throw new RefactoringException("Can't find java element to rename.");
    }

    return manager.createRenameRefactoring(
        elementToRename, cu, settings.getOffset(), settings.isRefactorLightweight());
  }
Beispiel #2
0
 /** @see AbstractJavaSearchScope#packageFragmentRoot(String, int, String) */
 public IPackageFragmentRoot packageFragmentRoot(
     String resourcePathString, int jarSeparatorIndex, String jarPath) {
   int index = -1;
   boolean isJarFile = jarSeparatorIndex != -1;
   if (isJarFile) {
     // internal or external jar (case 3, 4, or 5)
     String relativePath = resourcePathString.substring(jarSeparatorIndex + 1);
     index = indexOf(jarPath, relativePath);
   } else {
     // resource in workspace (case 1 or 2)
     index = indexOf(resourcePathString);
   }
   if (index >= 0) {
     int idx = this.projectIndexes[index];
     String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
     if (projectPath != null) {
       IJavaProject project =
           JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
       if (isJarFile) {
         IResource resource = JavaModel.getWorkspaceTarget(new Path(jarPath));
         if (resource != null) return project.getPackageFragmentRoot(resource);
         return project.getPackageFragmentRoot(jarPath);
       }
       Object target =
           JavaModel.getWorkspaceTarget(
               new Path(this.containerPaths[index] + '/' + this.relativePaths[index]));
       if (target != null) {
         if (target instanceof IProject) {
           return project.getPackageFragmentRoot((IProject) target);
         }
         IJavaElement element = JavaModelManager.create((IResource) target, project);
         return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
       }
     }
   }
   return null;
 }
Beispiel #3
0
 public String toString() {
   StringBuffer result = new StringBuffer("JavaSearchScope on "); // $NON-NLS-1$
   if (this.elements != null) {
     result.append("["); // $NON-NLS-1$
     for (int i = 0, length = this.elements.size(); i < length; i++) {
       JavaElement element = (JavaElement) this.elements.get(i);
       result.append("\n\t"); // $NON-NLS-1$
       result.append(element.toStringWithAncestors());
     }
     result.append("\n]"); // $NON-NLS-1$
   } else {
     if (this.pathsCount == 0) {
       result.append("[empty scope]"); // $NON-NLS-1$
     } else {
       result.append("["); // $NON-NLS-1$
       String[] paths = new String[this.relativePaths.length];
       int index = 0;
       for (int i = 0; i < this.relativePaths.length; i++) {
         String path = this.relativePaths[i];
         if (path == null) continue;
         String containerPath;
         if (ExternalFoldersManager.isInternalPathForExternalFolder(
             new Path(this.containerPaths[i]))) {
           Object target = JavaModel.getWorkspaceTarget(new Path(this.containerPaths[i]));
           containerPath = ((IFolder) target).getLocation().toOSString();
         } else {
           containerPath = this.containerPaths[i];
         }
         if (path.length() > 0) {
           paths[index++] = containerPath + '/' + path;
         } else {
           paths[index++] = containerPath;
         }
       }
       System.arraycopy(paths, 0, paths = new String[index], 0, index);
       Util.sort(paths);
       for (int i = 0; i < index; i++) {
         result.append("\n\t"); // $NON-NLS-1$
         result.append(paths[i]);
       }
       result.append("\n]"); // $NON-NLS-1$
     }
   }
   return result.toString();
 }
  /**
   * Create move refactoring session.
   *
   * @param cmr move settings, contains resource paths to move.
   * @return refactoring session id.
   * @throws JavaModelException when JavaModel has a failure
   * @throws RefactoringException when impossible to create move refactoring session
   */
  @POST
  @Path("move/create")
  @Consumes("application/json")
  @Produces("text/plain")
  public String createMoveRefactoring(CreateMoveRefactoring cmr)
      throws JavaModelException, RefactoringException {
    IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath());
    IJavaElement[] javaElements;
    try {
      Function<ElementToMove, IJavaElement> map =
          javaElement -> {
            try {
              if (javaElement.isPack()) {
                return javaProject.findPackageFragment(
                    new org.eclipse.core.runtime.Path(javaElement.getPath()));
              } else {
                return javaProject.findType(javaElement.getPath()).getCompilationUnit();
              }
            } catch (JavaModelException e) {
              throw new IllegalArgumentException(e);
            }
          };
      javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new);

    } catch (IllegalArgumentException e) {
      if (e.getCause() instanceof JavaModelException) {
        throw (JavaModelException) e.getCause();
      } else {
        throw e;
      }
    }
    if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) {
      return manager.createMoveRefactoringSession(javaElements);
    }

    throw new RefactoringException("Can't create move refactoring.");
  }
Beispiel #5
0
  /**
   * Add a path to current java search scope or all project fragment roots if null. Use project
   * resolved classpath to retrieve and store access restriction on each classpath entry. Recurse if
   * dependent projects are found.
   *
   * @param javaProject Project used to get resolved classpath entries
   * @param pathToAdd Path to add in case of single element or null if user want to add all project
   *     package fragment roots
   * @param includeMask Mask to apply on classpath entries
   * @param projectsToBeAdded Set to avoid infinite recursion
   * @param visitedProjects Set to avoid adding twice the same project
   * @param referringEntry Project raw entry in referring project classpath
   * @throws JavaModelException May happen while getting java model info
   */
  void add(
      JavaProject javaProject,
      IPath pathToAdd,
      int includeMask,
      HashSet projectsToBeAdded,
      HashSet visitedProjects,
      IClasspathEntry referringEntry)
      throws JavaModelException {
    IProject project = javaProject.getProject();
    if (!project.isAccessible() || !visitedProjects.add(project)) return;

    IPath projectPath = project.getFullPath();
    String projectPathString = projectPath.toString();
    addEnclosingProjectOrJar(projectPath);

    IClasspathEntry[] entries = javaProject.getResolvedClasspath();
    IJavaModel model = javaProject.getJavaModel();
    JavaModelManager.PerProjectInfo perProjectInfo = javaProject.getPerProjectInfo();
    for (int i = 0, length = entries.length; i < length; i++) {
      IClasspathEntry entry = entries[i];
      AccessRuleSet access = null;
      ClasspathEntry cpEntry = (ClasspathEntry) entry;
      if (referringEntry != null) {
        // Add only exported entries.
        // Source folder are implicitly exported.
        if (!entry.isExported() && entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
          continue;
        }
        cpEntry = cpEntry.combineWith((ClasspathEntry) referringEntry);
        //				cpEntry = ((ClasspathEntry)referringEntry).combineWith(cpEntry);
      }
      access = cpEntry.getAccessRuleSet();
      switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
          IClasspathEntry rawEntry = null;
          Map rootPathToRawEntries = perProjectInfo.rootPathToRawEntries;
          if (rootPathToRawEntries != null) {
            rawEntry = (IClasspathEntry) rootPathToRawEntries.get(entry.getPath());
          }
          if (rawEntry == null) break;
          rawKind:
          switch (rawEntry.getEntryKind()) {
            case IClasspathEntry.CPE_LIBRARY:
            case IClasspathEntry.CPE_VARIABLE:
              if ((includeMask & APPLICATION_LIBRARIES) != 0) {
                IPath path = entry.getPath();
                if (pathToAdd == null || pathToAdd.equals(path)) {
                  Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                  if (target instanceof IFolder) // case of an external folder
                  path = ((IFolder) target).getFullPath();
                  String pathToString =
                      path.getDevice() == null ? path.toString() : path.toOSString();
                  add(
                      projectPath.toString(),
                      "",
                      pathToString,
                      false /*not a package*/,
                      access); //$NON-NLS-1$
                  addEnclosingProjectOrJar(entry.getPath());
                }
              }
              break;
            case IClasspathEntry.CPE_CONTAINER:
              IClasspathContainer container =
                  JavaCore.getClasspathContainer(rawEntry.getPath(), javaProject);
              if (container == null) break;
              switch (container.getKind()) {
                case IClasspathContainer.K_APPLICATION:
                  if ((includeMask & APPLICATION_LIBRARIES) == 0) break rawKind;
                  break;
                case IClasspathContainer.K_SYSTEM:
                case IClasspathContainer.K_DEFAULT_SYSTEM:
                  if ((includeMask & SYSTEM_LIBRARIES) == 0) break rawKind;
                  break;
                default:
                  break rawKind;
              }
              IPath path = entry.getPath();
              if (pathToAdd == null || pathToAdd.equals(path)) {
                Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                if (target instanceof IFolder) // case of an external folder
                path = ((IFolder) target).getFullPath();
                String pathToString =
                    path.getDevice() == null ? path.toString() : path.toOSString();
                add(
                    projectPath.toString(),
                    "",
                    pathToString,
                    false /*not a package*/,
                    access); //$NON-NLS-1$
                addEnclosingProjectOrJar(entry.getPath());
              }
              break;
          }
          break;
        case IClasspathEntry.CPE_PROJECT:
          if ((includeMask & REFERENCED_PROJECTS) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              JavaProject referencedProject = (JavaProject) model.getJavaProject(path.toOSString());
              if (!projectsToBeAdded.contains(
                  referencedProject)) { // do not recurse if depending project was used to create
                                        // the scope
                add(
                    referencedProject,
                    null,
                    includeMask,
                    projectsToBeAdded,
                    visitedProjects,
                    cpEntry);
              }
            }
          }
          break;
        case IClasspathEntry.CPE_SOURCE:
          if ((includeMask & SOURCES) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              add(
                  projectPath.toString(),
                  Util.relativePath(path, projectPath.segmentCount() /*remove project segment*/),
                  projectPathString,
                  false /*not a package*/,
                  access);
            }
          }
          break;
      }
    }
  }
  /*
   *  Compute the list of paths which are keying index files.
   */
  private void initializeIndexLocations() {
    IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
    IndexManager manager = JavaModelManager.getIndexManager();
    SimpleSet locations = new SimpleSet();
    IJavaElement focus = MatchLocator.projectOrJarFocus(this.pattern);
    if (focus == null) {
      for (int i = 0; i < projectsAndJars.length; i++) {
        IPath path = projectsAndJars[i];
        Object target = JavaModel.getTarget(path, false /*don't check existence*/);
        if (target instanceof IFolder) // case of an external folder
        path = ((IFolder) target).getFullPath();
        locations.add(manager.computeIndexLocation(path));
      }
    } else {
      try {
        // See whether the state builder might be used to reduce the number of index locations

        // find the projects from projectsAndJars that see the focus then walk those projects
        // looking for the jars from projectsAndJars
        int length = projectsAndJars.length;
        JavaProject[] projectsCanSeeFocus = new JavaProject[length];
        SimpleSet visitedProjects = new SimpleSet(length);
        int projectIndex = 0;
        SimpleSet externalLibsToCheck = new SimpleSet(length);
        ObjectVector superTypes = new ObjectVector();
        IJavaElement[] focuses = getFocusedElementsAndTypes(this.pattern, focus, superTypes);
        char[][][] focusQualifiedNames = null;
        boolean isAutoBuilding = ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
        if (isAutoBuilding && focus instanceof IJavaProject) {
          focusQualifiedNames = getQualifiedNames(superTypes);
        }
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        for (int i = 0; i < length; i++) {
          IPath path = projectsAndJars[i];
          JavaProject project = (JavaProject) getJavaProject(path, model);
          if (project != null) {
            visitedProjects.add(project);
            if (canSeeFocus(focuses, project, focusQualifiedNames)) {
              locations.add(manager.computeIndexLocation(path));
              projectsCanSeeFocus[projectIndex++] = project;
            }
          } else {
            externalLibsToCheck.add(path);
          }
        }
        for (int i = 0; i < projectIndex && externalLibsToCheck.elementSize > 0; i++) {
          IClasspathEntry[] entries = projectsCanSeeFocus[i].getResolvedClasspath();
          for (int j = entries.length; --j >= 0; ) {
            IClasspathEntry entry = entries[j];
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
              IPath path = entry.getPath();
              if (externalLibsToCheck.remove(path) != null) {
                Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                if (target instanceof IFolder) // case of an external folder
                path = ((IFolder) target).getFullPath();
                locations.add(manager.computeIndexLocation(path));
              }
            }
          }
        }
        // jar files can be included in the search scope without including one of the projects that
        // references them, so scan all projects that have not been visited
        if (externalLibsToCheck.elementSize > 0) {
          IJavaProject[] allProjects = model.getJavaProjects();
          for (int i = 0, l = allProjects.length;
              i < l && externalLibsToCheck.elementSize > 0;
              i++) {
            JavaProject project = (JavaProject) allProjects[i];
            if (!visitedProjects.includes(project)) {
              IClasspathEntry[] entries = project.getResolvedClasspath();
              for (int j = entries.length; --j >= 0; ) {
                IClasspathEntry entry = entries[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                  IPath path = entry.getPath();
                  if (externalLibsToCheck.remove(path) != null) {
                    Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                    if (target instanceof IFolder) // case of an external folder
                    path = ((IFolder) target).getFullPath();
                    locations.add(manager.computeIndexLocation(path));
                  }
                }
              }
            }
          }
        }
      } catch (JavaModelException e) {
        // ignored
      }
    }

    this.indexLocations = new IPath[locations.elementSize];
    Object[] values = locations.values;
    int count = 0;
    for (int i = values.length; --i >= 0; )
      if (values[i] != null) this.indexLocations[count++] = (IPath) values[i];
  }