Exemplo n.º 1
0
 public static IMarker[] getProblemsFor(IResource resource) {
   try {
     if (resource != null && resource.exists()) {
       IMarker[] markers =
           resource.findMarkers(
               IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
       Set markerTypes =
           JavaModelManager.getJavaModelManager().compilationParticipants.managedMarkerTypes();
       if (markerTypes.isEmpty()) return markers;
       ArrayList markerList = new ArrayList(5);
       for (int i = 0, length = markers.length; i < length; i++) {
         markerList.add(markers[i]);
       }
       Iterator iterator = markerTypes.iterator();
       while (iterator.hasNext()) {
         markers = resource.findMarkers((String) iterator.next(), false, IResource.DEPTH_INFINITE);
         for (int i = 0, length = markers.length; i < length; i++) {
           markerList.add(markers[i]);
         }
       }
       IMarker[] result;
       markerList.toArray(result = new IMarker[markerList.size()]);
       return result;
     }
   } catch (CoreException e) {
     // assume there are no problems
   }
   return new IMarker[0];
 }
  ISourceContainer[] getSourceContainers(String location, String id) throws CoreException {

    ISourceContainer[] containers = (ISourceContainer[]) fSourceContainerMap.get(location);
    if (containers != null) {
      return containers;
    }

    ArrayList result = new ArrayList();
    ModelEntry entry = MonitorRegistry.findEntry(id);

    boolean match = false;

    IMonitorModelBase[] models = entry.getWorkspaceModels();
    for (int i = 0; i < models.length; i++) {
      if (isPerfectMatch(models[i], new Path(location))) {
        IResource resource = models[i].getUnderlyingResource();
        // if the plug-in matches a workspace model,
        // add the project and any libraries not coming via a container
        // to the list of source containers, in that order
        if (resource != null) {
          addProjectSourceContainers(resource.getProject(), result);
        }
        match = true;
        break;
      }
    }

    if (!match) {
      File file = new File(location);
      if (file.isFile()) {
        // in case of linked plug-in projects that map to an external JARd plug-in,
        // use source container that maps to the library in the linked project.
        ISourceContainer container = getArchiveSourceContainer(location);
        if (container != null) {
          containers = new ISourceContainer[] {container};
          fSourceContainerMap.put(location, containers);
          return containers;
        }
      }

      models = entry.getExternalModels();
      for (int i = 0; i < models.length; i++) {
        if (isPerfectMatch(models[i], new Path(location))) {
          // try all source zips found in the source code locations
          IClasspathEntry[] entries = MDEClasspathContainer.getExternalEntries(models[i]);
          for (int j = 0; j < entries.length; j++) {
            IRuntimeClasspathEntry rte = convertClasspathEntry(entries[j]);
            if (rte != null) result.add(rte);
          }
          break;
        }
      }
    }

    IRuntimeClasspathEntry[] entries =
        (IRuntimeClasspathEntry[]) result.toArray(new IRuntimeClasspathEntry[result.size()]);
    containers = JavaRuntime.getSourceContainers(entries);
    fSourceContainerMap.put(location, containers);
    return containers;
  }
  protected boolean checkForClassFileChanges(
      IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount)
      throws CoreException {
    IResource resource = binaryDelta.getResource();
    // remember that if inclusion & exclusion patterns change then a full build is done
    boolean isExcluded =
        (md.exclusionPatterns != null || md.inclusionPatterns != null)
            && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
    switch (resource.getType()) {
      case IResource.FOLDER:
        if (isExcluded && md.inclusionPatterns == null)
          return true; // no need to go further with this delta since its children cannot be
        // included

        IResourceDelta[] children = binaryDelta.getAffectedChildren();
        for (int i = 0, l = children.length; i < l; i++)
          if (!checkForClassFileChanges(children[i], md, segmentCount)) return false;
        return true;
      case IResource.FILE:
        if (!isExcluded
            && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
          // perform full build if a managed class file has been changed
          IPath typePath =
              resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
          if (this.newState.isKnownType(typePath.toString())) {
            if (JavaBuilder.DEBUG)
              System.out.println(
                  "MUST DO FULL BUILD. Found change to class file " + typePath); // $NON-NLS-1$
            return false;
          }
          return true;
        }
    }
    return true;
  }
Exemplo n.º 4
0
  /**
   * Final check before the actual refactoring
   *
   * @return status
   * @throws OperationCanceledException
   */
  public RefactoringStatus checkFinalConditions() throws OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();
    IContainer destination = fProcessor.getDestination();
    IProject sourceProject = fProcessor.getSourceSelection()[0].getProject();
    IProject destinationProject = destination.getProject();
    if (sourceProject != destinationProject)
      status.merge(MoveUtils.checkMove(phpFiles, sourceProject, destination));

    // Checks if one of the resources already exists with the same name in
    // the destination
    IPath dest = fProcessor.getDestination().getFullPath();
    IResource[] sourceResources = fProcessor.getSourceSelection();

    for (IResource element : sourceResources) {
      String newFilePath = dest.toOSString() + File.separatorChar + element.getName();
      IResource resource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(newFilePath));
      if (resource != null && resource.exists()) {
        status.merge(
            RefactoringStatus.createFatalErrorStatus(
                NLS.bind(
                    PhpRefactoringCoreMessages.getString("MoveDelegate.6"),
                    element.getName(),
                    dest.toOSString()))); // $NON-NLS-1$
      }
    }
    return status;
  }
Exemplo n.º 5
0
 public static void removeTasksFor(IResource resource) {
   try {
     if (resource != null && resource.exists())
       resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
   } catch (CoreException e) {
     // assume there were no problems
   }
 }
Exemplo n.º 6
0
  private void removeBuildPath(IResource resource, IProject project) {

    IScriptProject projrct = DLTKCore.create(project);
    IPath filePath = resource.getFullPath();

    oldBuildEntries = Arrays.asList(projrct.readRawBuildpath());

    newBuildEntries = new ArrayList<IBuildpathEntry>();

    newBuildEntries.addAll(oldBuildEntries);

    for (int i = 0; i < oldBuildEntries.size(); i++) {
      IBuildpathEntry fEntryToChange = oldBuildEntries.get(i);
      IPath entryPath = fEntryToChange.getPath();

      int mattchedPath = entryPath.matchingFirstSegments(filePath);

      if (mattchedPath == filePath.segmentCount()) {
        newBuildEntries.remove(fEntryToChange);
      } else {
        IBuildpathEntry newEntry =
            RefactoringUtility.createNewBuildpathEntry(
                fEntryToChange, fEntryToChange.getPath(), filePath, ""); // $NON-NLS-1$
        newBuildEntries.remove(fEntryToChange);
        newBuildEntries.add(newEntry);
      }
    }

    oldIncludePath = new ArrayList<IBuildpathEntry>();

    newIncludePathEntries = new ArrayList<IBuildpathEntry>();
    List<IncludePath> includePathEntries =
        Arrays.asList(IncludePathManager.getInstance().getIncludePaths(project));

    for (IncludePath entry : includePathEntries) {
      Object includePathEntry = entry.getEntry();
      IResource includeResource = null;
      if (!(includePathEntry instanceof IBuildpathEntry)) {
        includeResource = (IResource) includePathEntry;
        IPath entryPath = includeResource.getFullPath();

        IBuildpathEntry oldEntry =
            RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
        oldIncludePath.add((IBuildpathEntry) oldEntry);

        if (filePath.isPrefixOf(entryPath) || entryPath.equals(filePath)) {
        } else {
          IBuildpathEntry newEntry =
              RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
          newIncludePathEntries.add(newEntry);
        }
      } else {
        newIncludePathEntries.add((IBuildpathEntry) includePathEntry);
        oldIncludePath.add((IBuildpathEntry) includePathEntry);
      }
    }
  }
Exemplo n.º 7
0
 public static IMarker[] getTasksFor(IResource resource) {
   try {
     if (resource != null && resource.exists())
       return resource.findMarkers(IJavaModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
   } catch (CoreException e) {
     // assume there are no tasks
   }
   return new IMarker[0];
 }
 private void ensureResourceCovered(IResource resource, List list) {
   IPath path = resource.getFullPath();
   for (Iterator iter = list.iterator(); iter.hasNext(); ) {
     IResource root = (IResource) iter.next();
     if (root.getFullPath().isPrefixOf(path)) {
       return;
     }
   }
   list.add(resource);
 }
Exemplo n.º 9
0
 protected IResource findOriginalResource(IPath partialPath) {
   for (int i = 0, l = this.sourceLocations.length; i < l; i++) {
     ClasspathMultiDirectory sourceLocation = this.sourceLocations[i];
     if (sourceLocation.hasIndependentOutputFolder) {
       IResource originalResource = sourceLocation.sourceFolder.getFile(partialPath);
       if (originalResource.exists()) return originalResource;
     }
   }
   return null;
 }
Exemplo n.º 10
0
  protected long computeModificationStamp(IResource resource) {
    long modificationStamp = resource.getModificationStamp();

    IPath path = resource.getLocation();
    if (path == null) {
      return modificationStamp;
    }

    modificationStamp = path.toFile().lastModified();
    return modificationStamp;
  }
  // none -> error
  // error -> none
  // none -> warning
  // warning -> none
  // warning -> error
  // error -> warning
  private boolean hadProblemProperty(ISynchronizeModelElement element, String property) {
    boolean hadError =
        element.getProperty(ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY);
    boolean hadWarning =
        element.getProperty(ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY);

    // Force recalculation of parents of phantom resources
    IResource resource = element.getResource();
    if (resource != null && resource.isPhantom()) {
      return true;
    }

    if (hadError) {
      if (!(property == ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY)) {
        element.setPropertyToRoot(ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY, false);
        if (property != null) {
          // error -> warning
          element.setPropertyToRoot(property, true);
        }
        // error -> none
        // recalculate parents
        return true;
      }
      return false;
    } else if (hadWarning) {
      if (!(property == ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY)) {
        element.setPropertyToRoot(
            ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY, false);
        if (property != null) {
          // warning -> error
          element.setPropertyToRoot(property, true);
          return false;
        }
        // warning ->  none
        return true;
      }
      return false;
    } else {
      if (property == ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY) {
        // none -> error
        element.setPropertyToRoot(property, true);
        return false;
      } else if (property == ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY) {
        // none -> warning
        element.setPropertyToRoot(property, true);
        return true;
      }
      return false;
    }
  }
 /*
  * Determine if the resource is a descendant of an orphaned subtree.
  * If it is, purge the CVS folders of the subtree.
  */
 private void handleOrphanedSubtree(IResource resource) {
   try {
     if (!CVSWorkspaceRoot.isSharedWithCVS(resource)) return;
     ICVSFolder folder;
     if (resource.getType() == IResource.FILE) {
       folder = CVSWorkspaceRoot.getCVSFolderFor(resource.getParent());
     } else {
       folder = CVSWorkspaceRoot.getCVSFolderFor((IContainer) resource);
     }
     handleOrphanedSubtree(folder);
   } catch (CVSException e) {
     CVSProviderPlugin.log(e);
   }
 }
 private IResource createSourceResource(IResourceDelta delta) {
   IPath sourcePath = delta.getMovedFromPath();
   IResource resource = delta.getResource();
   IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
   switch (resource.getType()) {
     case IResource.PROJECT:
       return wsRoot.getProject(sourcePath.segment(0));
     case IResource.FOLDER:
       return wsRoot.getFolder(sourcePath);
     case IResource.FILE:
       return wsRoot.getFile(sourcePath);
   }
   return null;
 }
Exemplo n.º 14
0
  private void createRunConfigurationChange(
      IResource[] sourceResources, CompositeChange rootChange) {

    IResource[] uniqueSourceResources = removeDuplicateResources(sourceResources);
    for (IResource element : uniqueSourceResources) {
      RenameConfigurationChange configPointchanges =
          new RenameConfigurationChange(
              element.getFullPath().removeLastSegments(1),
              fMainDestinationPath,
              element.getName(),
              element.getName());

      rootChange.add(configPointchanges);
    }
  }
Exemplo n.º 15
0
  private void createRenameLibraryFolderChange(
      IResource[] sourceResources, CompositeChange rootChange) {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    LibraryFolderManager lfm = LibraryFolderManager.getInstance();

    for (IResource resource : sourceResources) {
      if (resource.getType() == IResource.FOLDER && lfm.isInLibraryFolder(resource)) {
        IPath newPath = fMainDestinationPath.append(resource.getName());
        IFolder newFolder = root.getFolder(newPath);

        RenameLibraryFolderChange change =
            new RenameLibraryFolderChange((IFolder) resource, newFolder);
        rootChange.add(change);
      }
    }
  }
  /**
   * The worker method. It will find the container, create the file if missing or just replace its
   * contents, and open the editor on the newly created file.
   */
  private void doFinish(String containerName, String fileName, IProgressMonitor monitor)
      throws CoreException {
    // create a sample file
    monitor.beginTask("Creating " + fileName, 2);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = root.findMember(new Path(containerName));

    // if (!(resource.exists()) || !(resource instanceof IContainer)) {
    if (resource == null || !(resource.exists()) || !(resource instanceof IContainer)) {
      // throwCoreException("Container \"" + containerName +
      // "\" does not exist.");
      IProject datamapperProject = root.getProject(containerName);
      datamapperProject.create(null);
      datamapperProject.open(null);
      // datamapperProject.
    }
    IContainer container = (IContainer) resource;
    //
    //
    // final IFile file = container.getFile(new Path(fileName));
    // try {
    // InputStream stream = openContentStream();
    // if (file.exists()) {
    // // file.setContents(null, true, true, monitor);
    // } else {
    // file.create(null, true, monitor);
    //
    // }
    // stream.close();`
    // } catch (IOException e) {
    // }
    // monitor.worked(1);
    // monitor.setTaskName("Opening file for editing...");
    // getShell().getDisplay().asyncExec(new Runnable() {
    // public void run() {
    // IWorkbenchPage page =
    // PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    // try {
    // IDE.openEditor(page, file);
    // } catch (PartInitException e) {
    // }
    // }
    // });
    // monitor.worked(1);
  }
Exemplo n.º 17
0
  public static void removeProblemsFor(IResource resource) {
    try {
      if (resource != null && resource.exists()) {
        resource.deleteMarkers(
            IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);

        // delete managed markers
        Set markerTypes =
            JavaModelManager.getJavaModelManager().compilationParticipants.managedMarkerTypes();
        if (markerTypes.size() == 0) return;
        Iterator iterator = markerTypes.iterator();
        while (iterator.hasNext())
          resource.deleteMarkers((String) iterator.next(), false, IResource.DEPTH_INFINITE);
      }
    } catch (CoreException e) {
      // assume there were no problems
    }
  }
    public boolean include(Object object) {
      if (object instanceof IResource) {
        IResource resource = (IResource) object;
        IPath path =
            IResource.FILE == resource.getType()
                ? resource.getFullPath()
                : resource.getFullPath().addTrailingSeparator();
        object = path.toPortableString();
      }

      for (Iterator iter = filters.iterator(); iter.hasNext(); ) {
        Filter filter = (Filter) iter.next();
        if (filter.matches(object)) {
          return filter.inclusive();
        }
      }
      return default_;
    }
Exemplo n.º 19
0
 boolean filterExtraResource(IResource resource) {
   if (this.extraResourceFileFilters != null) {
     char[] name = resource.getName().toCharArray();
     for (int i = 0, l = this.extraResourceFileFilters.length; i < l; i++)
       if (CharOperation.match(this.extraResourceFileFilters[i], name, true)) return true;
   }
   if (this.extraResourceFolderFilters != null) {
     IPath path = resource.getProjectRelativePath();
     String pathName = path.toString();
     int count = path.segmentCount();
     if (resource.getType() == IResource.FILE) count--;
     for (int i = 0, l = this.extraResourceFolderFilters.length; i < l; i++)
       if (pathName.indexOf(this.extraResourceFolderFilters[i]) != -1)
         for (int j = 0; j < count; j++)
           if (this.extraResourceFolderFilters[i].equals(path.segment(j))) return true;
   }
   return false;
 }
Exemplo n.º 20
0
  /* Return the list of projects for which it requires a resource delta. This builder's project
   * is implicitly included and need not be specified. Builders must re-specify the list
   * of interesting projects every time they are run as this is not carried forward
   * beyond the next build. Missing projects should be specified but will be ignored until
   * they are added to the workspace.
   */
  private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
    if (this.javaProject == null || this.workspaceRoot == null) return new IProject[0];

    ArrayList projects = new ArrayList();
    ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager();
    try {
      IClasspathEntry[] entries = this.javaProject.getExpandedClasspath();
      for (int i = 0, l = entries.length; i < l; i++) {
        IClasspathEntry entry = entries[i];
        IPath path = entry.getPath();
        IProject p = null;
        switch (entry.getEntryKind()) {
          case IClasspathEntry.CPE_PROJECT:
            p =
                this.workspaceRoot.getProject(
                    path.lastSegment()); // missing projects are considered too
            if (((ClasspathEntry) entry).isOptional()
                && !JavaProject.hasJavaNature(p)) // except if entry is optional
            p = null;
            break;
          case IClasspathEntry.CPE_LIBRARY:
            if (includeBinaryPrerequisites && path.segmentCount() > 0) {
              // some binary resources on the class path can come from projects that are not
              // included in the project references
              IResource resource = this.workspaceRoot.findMember(path.segment(0));
              if (resource instanceof IProject) {
                p = (IProject) resource;
              } else {
                resource = externalFoldersManager.getFolder(path);
                if (resource != null) p = resource.getProject();
              }
            }
        }
        if (p != null && !projects.contains(p)) projects.add(p);
      }
    } catch (JavaModelException e) {
      return new IProject[0];
    }
    IProject[] result = new IProject[projects.size()];
    projects.toArray(result);
    return result;
  }
Exemplo n.º 21
0
  private void createBreakPointChange(IResource[] sourceResources, CompositeChange rootChange)
      throws CoreException {
    IResource[] uniqueSourceResources = removeDuplicateResources(sourceResources);
    for (IResource element : uniqueSourceResources) {
      collectBrakePoint(element);

      RenameBreackpointChange breakePointchanges =
          new RenameBreackpointChange(
              element.getFullPath().removeLastSegments(1),
              fMainDestinationPath,
              element.getName(),
              element.getName(),
              fBreakpoints,
              fBreakpointAttributes);

      if (fBreakpoints.getKeys().size() > 0) {
        rootChange.add(breakePointchanges);
      }
    }
  }
Exemplo n.º 22
0
    private boolean moveSettingsIfDerivedChanged(
        IResourceDelta parent,
        IProject currentProject,
        Preferences projectPrefs,
        String[] affectedResources) {
      boolean resourceChanges = false;

      if ((parent.getFlags() & IResourceDelta.DERIVED_CHANGED) != 0) {
        // if derived changed, move encoding to correct preferences
        IPath parentPath = parent.getResource().getProjectRelativePath();
        for (int i = 0; i < affectedResources.length; i++) {
          IPath affectedPath = new Path(affectedResources[i]);
          // if parentPath is an ancestor of affectedPath
          if (parentPath.isPrefixOf(affectedPath)) {
            IResource member = currentProject.findMember(affectedPath);
            if (member != null) {
              Preferences targetPrefs =
                  getPreferences(currentProject, true, member.isDerived(IResource.CHECK_ANCESTORS));
              // if new preferences are different than current
              if (!projectPrefs.absolutePath().equals(targetPrefs.absolutePath())) {
                // remove encoding from old preferences and save in correct preferences
                String currentValue = projectPrefs.get(affectedResources[i], null);
                projectPrefs.remove(affectedResources[i]);
                targetPrefs.put(affectedResources[i], currentValue);
                resourceChanges = true;
              }
            }
          }
        }
      }

      IResourceDelta[] children = parent.getAffectedChildren();
      for (int i = 0; i < children.length; i++) {
        resourceChanges =
            moveSettingsIfDerivedChanged(
                    children[i], currentProject, projectPrefs, affectedResources)
                || resourceChanges;
      }
      return resourceChanges;
    }
Exemplo n.º 23
0
 /**
  * The worker method. It will find the container, create the file if missing or just replace its
  * contents, and open the editor on the newly created file.
  */
 private void doFinish(String containerName, String fileName, IProgressMonitor monitor)
     throws CoreException {
   // create a sample file
   monitor.beginTask("Creating " + fileName, 2);
   IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
   IResource resource = root.findMember(new Path(containerName));
   if (!resource.exists() || !(resource instanceof IContainer)) {
     throwCoreException("Container \"" + containerName + "\" does not exist.");
   }
   IContainer container = (IContainer) resource;
   final IFile file = container.getFile(new Path(fileName));
   try {
     InputStream stream = openContentStream();
     if (file.exists()) {
       file.setContents(stream, true, true, monitor);
     } else {
       file.create(stream, true, monitor);
     }
     stream.close();
   } catch (IOException e) {
   }
   monitor.worked(1);
   monitor.setTaskName("Opening file for editing...");
   getShell()
       .getDisplay()
       .asyncExec(
           new Runnable() {
             public void run() {
               IWorkbenchPage page =
                   PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
               try {
                 IDE.openEditor(page, file, true);
               } catch (PartInitException e) {
               }
             }
           });
   monitor.worked(1);
 }
Exemplo n.º 24
0
 private void registerInWorkspaceIfNeeded() {
   IPath jarPath = fJarPackage.getAbsolutePharLocation();
   IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
   for (int i = 0; i < projects.length; i++) {
     IProject project = projects[i];
     // The Jar is always put into the local file system. So it can only be
     // part of a project if the project is local as well. So using getLocation
     // is currently save here.
     IPath projectLocation = project.getLocation();
     if (projectLocation != null && projectLocation.isPrefixOf(jarPath)) {
       try {
         jarPath = jarPath.removeFirstSegments(projectLocation.segmentCount());
         jarPath = jarPath.removeLastSegments(1);
         IResource containingFolder = project.findMember(jarPath);
         if (containingFolder != null && containingFolder.isAccessible())
           containingFolder.refreshLocal(IResource.DEPTH_ONE, null);
       } catch (CoreException ex) {
         // don't refresh the folder but log the problem
         PHPUiPlugin.log(ex);
       }
     }
   }
 }
Exemplo n.º 25
0
 public void setCharsetFor(IPath resourcePath, String newCharset) throws CoreException {
   // for the workspace root we just set a preference in the instance scope
   if (resourcePath.segmentCount() == 0) {
     IEclipsePreferences resourcesPreferences =
         InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES);
     if (newCharset != null) resourcesPreferences.put(ResourcesPlugin.PREF_ENCODING, newCharset);
     else resourcesPreferences.remove(ResourcesPlugin.PREF_ENCODING);
     try {
       resourcesPreferences.flush();
     } catch (BackingStoreException e) {
       IProject project = workspace.getRoot().getProject(resourcePath.segment(0));
       String message = Messages.resources_savingEncoding;
       throw new ResourceException(
           IResourceStatus.FAILED_SETTING_CHARSET, project.getFullPath(), message, e);
     }
     return;
   }
   // for all other cases, we set a property in the corresponding project
   IResource resource = workspace.getRoot().findMember(resourcePath);
   if (resource != null) {
     try {
       // disable the listener so we don't react to changes made by ourselves
       Preferences encodingSettings =
           getPreferences(
               resource.getProject(), true, resource.isDerived(IResource.CHECK_ANCESTORS));
       if (newCharset == null || newCharset.trim().length() == 0)
         encodingSettings.remove(getKeyFor(resourcePath));
       else encodingSettings.put(getKeyFor(resourcePath), newCharset);
       flushPreferences(encodingSettings, true);
     } catch (BackingStoreException e) {
       IProject project = workspace.getRoot().getProject(resourcePath.segment(0));
       String message = Messages.resources_savingEncoding;
       throw new ResourceException(
           IResourceStatus.FAILED_SETTING_CHARSET, project.getFullPath(), message, e);
     }
   }
 }
 /**
  * Ensure that the sync info for all the provided resources has been loaded. If an out-of-sync
  * resource is found, prompt to refresh all the projects involved.
  */
 protected boolean ensureSyncInfoLoaded(IResource[] resources) throws CVSException {
   boolean keepTrying = true;
   while (keepTrying) {
     try {
       EclipseSynchronizer.getInstance().ensureSyncInfoLoaded(resources, getActionDepth());
       keepTrying = false;
     } catch (CVSException e) {
       if (e.getStatus().getCode() == IResourceStatus.OUT_OF_SYNC_LOCAL) {
         // determine the projects of the resources involved
         Set projects = new HashSet();
         for (int i = 0; i < resources.length; i++) {
           IResource resource = resources[i];
           projects.add(resource.getProject());
         }
         // prompt to refresh
         if (promptToRefresh(
             getShell(),
             (IResource[]) projects.toArray(new IResource[projects.size()]),
             e.getStatus())) {
           for (Iterator iter = projects.iterator(); iter.hasNext(); ) {
             IProject project = (IProject) iter.next();
             try {
               project.refreshLocal(IResource.DEPTH_INFINITE, null);
             } catch (CoreException coreException) {
               throw CVSException.wrapException(coreException);
             }
           }
         } else {
           return false;
         }
       } else {
         throw e;
       }
     }
   }
   return true;
 }
Exemplo n.º 27
0
 protected void splitEncodingPreferences(IProject project) {
   Preferences projectRegularPrefs = getPreferences(project, false, false, false);
   Preferences projectDerivedPrefs = null;
   if (projectRegularPrefs == null) return;
   try {
     boolean prefsChanged = false;
     String[] affectedResources;
     affectedResources = projectRegularPrefs.keys();
     for (int i = 0; i < affectedResources.length; i++) {
       String path = affectedResources[i];
       IResource resource = project.findMember(path);
       if (resource != null) {
         if (resource.isDerived(IResource.CHECK_ANCESTORS)) {
           String value = projectRegularPrefs.get(path, null);
           projectRegularPrefs.remove(path);
           // lazy creation of derived preferences
           if (projectDerivedPrefs == null)
             projectDerivedPrefs = getPreferences(project, true, true, true);
           projectDerivedPrefs.put(path, value);
           prefsChanged = true;
         }
       }
     }
     if (prefsChanged) {
       Map<IProject, Boolean> projectsToSave = new HashMap<>();
       // this is internal change so do not notify charset delta job
       projectsToSave.put(project, Boolean.TRUE);
       job.addChanges(projectsToSave);
     }
   } catch (BackingStoreException e) {
     // problems with the project scope... we will miss the changes (but will log)
     String message = Messages.resources_readingEncoding;
     Policy.log(
         new ResourceStatus(
             IResourceStatus.FAILED_GETTING_CHARSET, project.getFullPath(), message, e));
   }
 }
Exemplo n.º 28
0
 protected void collectBrakePoint(IResource resource) throws CoreException {
   fBreakpoints = new BucketMap<IResource, IBreakpoint>(6);
   fBreakpointAttributes = new HashMap<IBreakpoint, Map<String, Object>>(6);
   final IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
   IMarker[] markers =
       resource.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
   for (IMarker marker : markers) {
     IResource markerResource = marker.getResource();
     IBreakpoint breakpoint = breakpointManager.getBreakpoint(marker);
     if (breakpoint != null) {
       fBreakpoints.add(markerResource, breakpoint);
       fBreakpointAttributes.put(breakpoint, breakpoint.getMarker().getAttributes());
     }
   }
 }
Exemplo n.º 29
0
  private IResource[] removeDuplicateResources(IResource[] sourceResources) {
    // ignore empty array
    if (sourceResources == null || sourceResources.length == 0) {
      return sourceResources;
    }

    ArrayList<IResource> result = new ArrayList<IResource>();

    for (IResource source : sourceResources) {
      if (result.size() == 0) {
        result.add(source);
      } else {
        // check if the resource is parent of any item in the result
        for (IResource existing : result) {
          // if the resource is parent of an existing item in the
          // result.
          // remove the existing item, add the new one.
          if (source.getFullPath().isPrefixOf(existing.getFullPath())) {
            result.remove(existing);
            result.add(source);
          }
        }

        boolean noNeedAdded = false;
        for (IResource existing : result) {
          // if the resource is parent of an existing item in the
          // result.
          // remove the existing item, add the new one.
          if (existing.getFullPath().isPrefixOf(source.getFullPath())) {
            noNeedAdded = true;
          }
        }
        // the source is not in the result after loop
        if (!result.contains(source) && !noNeedAdded) {
          result.add(source);
        }
      }
    }

    IResource[] ret = new IResource[result.size()];

    return result.toArray(ret);
  }
Exemplo n.º 30
0
  /**
   * Checks whether the given move included is vaild
   *
   * @param destination
   * @return a staus indicating whether the included is valid or not
   */
  public RefactoringStatus verifyDestination(IResource destination) {
    RefactoringStatus status = new RefactoringStatus();

    Assert.isNotNull(destination);
    if (!destination.exists() || destination.isPhantom())
      return RefactoringStatus.createFatalErrorStatus(
          PhpRefactoringCoreMessages.getString("MoveDelegate.2")); // $NON-NLS-1$
    if (!destination.isAccessible())
      return RefactoringStatus.createFatalErrorStatus(
          PhpRefactoringCoreMessages.getString("MoveDelegate.3")); // $NON-NLS-1$
    Assert.isTrue(destination.getType() != IResource.ROOT);

    IResource[] sourceResources = fProcessor.getSourceSelection();
    for (IResource element : sourceResources) {
      if (destination.equals(element.getParent()))
        return RefactoringStatus.createFatalErrorStatus(
            PhpRefactoringCoreMessages.getString("MoveDelegate.4")); // $NON-NLS-1$
      if (destination.equals(element)) {
        return RefactoringStatus.createFatalErrorStatus(
            PhpRefactoringCoreMessages.getString("MoveDelegate.5")); // $NON-NLS-1$
      }
    }
    return status;
  }