/**
  * Possible failures:
  *
  * <ul>
  *   <li>NO_ELEMENTS_TO_PROCESS - the root supplied to the operation is <code>null</code>.
  *   <li>INVALID_NAME - the name provided to the operation is <code>null</code> or is not a valid
  *       script folder name.
  *   <li>READ_ONLY - the root provided to this operation is read only.
  *   <li>NAME_COLLISION - there is a pre-existing resource (file) with the same name as a folder
  *       in the script folder's hierarchy.
  *   <li>ELEMENT_NOT_PRESENT - the underlying resource for the root is missing
  * </ul>
  *
  * @see IScriptModelStatus
  * @see ScriptConventions
  */
 @Override
 public IModelStatus verify() {
   if (getParentElement() == null) {
     return new ModelStatus(IModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
   }
   IPath packageName = this.pkgName == null ? null : this.pkgName.append("."); // $NON-NLS-1$
   String packageNameValue = null;
   if (packageName != null) {
     packageNameValue = packageName.toOSString();
   }
   if (this.pkgName == null
       || (this.pkgName.segmentCount() > 0
           && !Util.isValidFolderNameForPackage(
               (IContainer) getParentElement().getResource(), packageName.toString()))) {
     return new ModelStatus(IModelStatusConstants.INVALID_NAME, packageNameValue);
   }
   IProjectFragment root = (IProjectFragment) getParentElement();
   if (root.isReadOnly()) {
     return new ModelStatus(IModelStatusConstants.READ_ONLY, root);
   }
   IContainer parentFolder = (IContainer) root.getResource();
   int i;
   for (i = 0; i < this.pkgName.segmentCount(); i++) {
     IResource subFolder = parentFolder.findMember(this.pkgName.segment(i));
     if (subFolder != null) {
       if (subFolder.getType() != IResource.FOLDER) {
         return new ModelStatus(
             IModelStatusConstants.NAME_COLLISION,
             Messages.bind(Messages.status_nameCollision, subFolder.getFullPath().toString()));
       }
       parentFolder = (IContainer) subFolder;
     }
   }
   return ModelStatus.VERIFIED_OK;
 }
  /*
   * Refreshes the external folders referenced on the buildpath of the given
   * source project
   */
  public void refreshReferences(IProject source, IProgressMonitor monitor) {
    IProject externalProject = getExternalFoldersProject();
    if (source.equals(externalProject)) return;
    if (!ScriptProject.hasScriptNature(source)) return;
    try {
      HashSet externalFolders =
          getExternalFolders(((ScriptProject) DLTKCore.create(source)).getResolvedBuildpath());
      if (externalFolders == null) return;
      final Iterator iterator = externalFolders.iterator();
      Job refreshJob =
          new Job(Messages.refreshing_external_folders) {
            public boolean belongsTo(Object family) {
              return family == ResourcesPlugin.FAMILY_MANUAL_REFRESH;
            }

            protected IStatus run(IProgressMonitor pm) {
              try {
                while (iterator.hasNext()) {
                  IPath externalPath = (IPath) iterator.next();
                  IFolder folder = getFolder(externalPath);
                  if (folder != null) folder.refreshLocal(IResource.DEPTH_INFINITE, pm);
                }
              } catch (CoreException e) {
                return e.getStatus();
              }
              return Status.OK_STATUS;
            }
          };
      refreshJob.schedule();
    } catch (CoreException e) {
      Util.log(e, "Exception while refreshing external project"); // $NON-NLS-1$
    }
    return;
  }
예제 #3
0
  public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;

    /* ensure no concurrent write access to index */
    Index index =
        this.manager.getIndex(
            this.containerPath, true /*reuse index file*/, false /*don't create if none*/);
    if (index == null) return true;
    ReadWriteMonitor monitor = index.monitor;
    if (monitor == null) return true; // index got deleted since acquired

    try {
      monitor.enterWrite(); // ask permission to write
      this.manager.saveIndex(index);
    } catch (IOException e) {
      if (JobManager.VERBOSE) {
        Util.verbose(
            "-> failed to save index "
                + this.containerPath
                + " because of the following exception:",
            System.err); // $NON-NLS-1$ //$NON-NLS-2$
        e.printStackTrace();
      }
      return false;
    } finally {
      monitor.exitWrite(); // free write lock
    }
    return true;
  }
 public char[] getContents() {
   // otherwise retrieve it
   try {
     if (this.currentFile != null) return Util.getResourceContentsAsCharArray(this.currentFile);
   } catch (CoreException e) {
     return CharOperation.NO_CHAR;
   }
   return CharOperation.NO_CHAR;
 }
 /**
  * Execute the operation - creates the new script folder and any side effect folders.
  *
  * @exception ModelException if the operation is unable to complete
  */
 @Override
 protected void executeOperation() throws ModelException {
   ModelElementDelta delta = null;
   IProjectFragment root = (IProjectFragment) getParentElement();
   beginTask(Messages.operation_createScriptFolderProgress, this.pkgName.segmentCount());
   IContainer parentFolder = (IContainer) root.getResource();
   IPath sideEffectPackageName = Path.EMPTY;
   ArrayList<IScriptFolder> results = new ArrayList<IScriptFolder>(this.pkgName.segmentCount());
   int i;
   for (i = 0; i < this.pkgName.segmentCount(); i++) {
     String subFolderName = this.pkgName.segment(i);
     sideEffectPackageName = sideEffectPackageName.append(subFolderName);
     IResource subFolder = parentFolder.findMember(subFolderName);
     if (subFolder == null) {
       createFolder(parentFolder, subFolderName, force);
       parentFolder = parentFolder.getFolder(new Path(subFolderName));
       IScriptFolder addedFrag = root.getScriptFolder(sideEffectPackageName);
       if (!Util.isExcluded(parentFolder, root)) {
         if (delta == null) {
           delta = newModelElementDelta();
         }
         delta.added(addedFrag);
       }
       results.add(addedFrag);
     } else {
       parentFolder = (IContainer) subFolder;
     }
     worked(1);
   }
   if (results.size() > 0) {
     this.resultElements = new IModelElement[results.size()];
     results.toArray(this.resultElements);
     if (delta != null) {
       addDelta(delta);
     }
   }
   done();
 }
 private HashMap getFolders() {
   if (this.folders == null) {
     this.folders = new HashMap();
     IProject project = getExternalFoldersProject();
     if (project.isAccessible()) {
       try {
         IResource[] members = project.members();
         for (int i = 0, length = members.length; i < length; i++) {
           IResource member = members[i];
           if (member.getType() == IResource.FOLDER
               && member.isLinked()
               && member.getName().startsWith(LINKED_FOLDER_NAME)) {
             IPath externalFolderPath = member.getLocation();
             this.folders.put(externalFolderPath, member);
           }
         }
       } catch (CoreException e) {
         Util.log(e, "Exception while initializing external folders"); // $NON-NLS-1$
       }
     }
   }
   return this.folders;
 }
예제 #7
0
 public int hashCode() {
   if (this.parent == null) return super.hashCode();
   return Util.combineHashCodes(super.getElementName().hashCode(), this.parent.hashCode());
 }
예제 #8
0
 @Override
 public int hashCode() {
   return Util.combineHashCodes(this.parent.hashCode(), this.nameStart);
 }
예제 #9
0
  public static Object[] computeFolderForeignResources(
      ScriptProject project,
      IContainer folder,
      char[][] inclusionPatterns,
      char[][] exclusionPatterns)
      throws ModelException {
    Object[] nonScriptResources = new IResource[5];
    int nonScriptResourcesCounter = 0;
    try {
      IBuildpathEntry[] classpath = project.getResolvedBuildpath();
      IResource[] members = folder.members();
      nextResource:
      for (int i = 0, max = members.length; i < max; i++) {
        IResource member = members[i];
        switch (member.getType()) {
          case IResource.FILE:
            String fileName = member.getName();

            // ignore .java files that are not excluded
            if (Util.isValidSourceModule(project, member)
                && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
              continue nextResource;
            // ignore .zip file on buildpath
            if (org.eclipse.dltk.compiler.util.Util.isArchiveFileName(
                    DLTKLanguageManager.getLanguageToolkit(project), fileName)
                && isBuildpathEntry(member.getFullPath(), classpath)) continue nextResource;
            // All other resources should be in folders.
            // continue nextResource;
            break;

          case IResource.FOLDER:
            // ignore valid packages or excluded folders that correspond
            // to a nested pkg fragment root
            if (Util.isValidFolderNameForPackage(folder, member.getName())
                && (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
                    || isBuildpathEntry(member.getFullPath(), classpath))) continue nextResource;
            break;
        }
        if (nonScriptResources.length == nonScriptResourcesCounter) {
          // resize
          System.arraycopy(
              nonScriptResources,
              0,
              (nonScriptResources = new IResource[nonScriptResourcesCounter * 2]),
              0,
              nonScriptResourcesCounter);
        }
        nonScriptResources[nonScriptResourcesCounter++] = member;
      }
      if (nonScriptResources.length != nonScriptResourcesCounter) {
        System.arraycopy(
            nonScriptResources,
            0,
            (nonScriptResources = new IResource[nonScriptResourcesCounter]),
            0,
            nonScriptResourcesCounter);
      }
      return nonScriptResources;
    } catch (CoreException e) {
      throw new ModelException(e);
    }
  }
예제 #10
0
 /**
  * Returns the package fragment root corresponding to a given resource path.
  *
  * @param resourcePathString path of expected package fragment root.
  * @return the {@link IProjectFragment package fragment root} which path match the given one or
  *     <code>null</code> if none was found.
  */
 public IProjectFragment projectFragment(String resourcePathString) {
   int index = -1;
   int separatorIndex = resourcePathString.indexOf(FILE_ENTRY_SEPARATOR);
   boolean isZIPFile = separatorIndex != -1;
   boolean isSpecial = resourcePathString.startsWith(IBuildpathEntry.BUILDPATH_SPECIAL);
   if (isZIPFile) {
     // internal or external jar (case 3, 4, or 5)
     String zipPath = resourcePathString.substring(0, separatorIndex);
     String relativePath = resourcePathString.substring(separatorIndex + 1);
     index = indexOf(zipPath, relativePath);
   } else {
     // resource in workspace (case 1 or 2)
     index = indexOf(resourcePathString);
   }
   if (index >= 0) {
     int idx = projectIndexes[index];
     String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
     if (projectPath != null) {
       IScriptProject project =
           DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
       if (isZIPFile) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       if (isSpecial) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       Object target =
           Model.getTarget(
               ResourcesPlugin.getWorkspace().getRoot(),
               Path.fromPortableString(
                   this.containerPaths[index] + '/' + this.relativePaths[index]),
               false);
       if (target instanceof IProject) {
         return project.getProjectFragment((IProject) target);
       }
       if (target instanceof IResource) {
         IModelElement element = DLTKCore.create((IResource) target);
         return (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
       }
       if (target instanceof IFileHandle) {
         try {
           IProjectFragment[] fragments = project.getProjectFragments();
           IFileHandle t = (IFileHandle) target;
           IPath absPath = t.getFullPath();
           for (int i = 0; i < fragments.length; ++i) {
             IProjectFragment f = fragments[i];
             if (f.isExternal()) {
               IPath pPath = f.getPath();
               if (pPath.isPrefixOf(absPath) && !Util.isExcluded(absPath, f, t.isDirectory())) {
                 return f;
               }
             }
           }
         } catch (ModelException e) {
           e.printStackTrace();
           return null;
         }
       }
     }
   }
   return null;
 }
예제 #11
0
  /**
   * Add an element to the script search scope.
   *
   * @param element The element we want to add to current script search scope
   * @throws ModelException May happen if some Script Model info are not available
   */
  public void add(IModelElement element) throws ModelException {
    if (!natureFilter(element)) {
      return;
    }
    IPath containerPath = null;
    String containerPathToString = null;
    int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES;
    switch (element.getElementType()) {
      case IModelElement.SCRIPT_MODEL:
        // a workspace scope should be used
        break;
      case IModelElement.SCRIPT_PROJECT:
        add((ScriptProject) element, null, includeMask, new HashSet<IProject>(2), null);
        break;
      case IModelElement.PROJECT_FRAGMENT:
        IProjectFragment root = (IProjectFragment) element;
        String projectPath = null;
        if (!root.isExternal()) {
          IPath rootPath = root.getPath();
          containerPath =
              root.getKind() == IProjectFragment.K_SOURCE ? root.getParent().getPath() : rootPath;
          containerPathToString = containerPath.toString();
          IResource rootResource = root.getResource();
          projectPath = root.getScriptProject().getPath().toString();
          if (rootResource != null && rootResource.isAccessible()) {
            String relativePath =
                Util.relativePath(rootResource.getFullPath(), containerPath.segmentCount());
            add(projectPath, relativePath, containerPathToString, false /* not a package */, null);
          } else {
            add(
                projectPath,
                org.eclipse.dltk.compiler.util.Util.EMPTY_STRING,
                containerPathToString,
                false /* not a package */,
                null);
          }
        } else {
          projectPath = root.getScriptProject().getPath().toString();
          containerPath = root.getPath();
          containerPathToString = containerPath.toString();
          add(
              projectPath,
              org.eclipse.dltk.compiler.util.Util.EMPTY_STRING,
              containerPathToString,
              false /* not a package */,
              null);
        }
        break;
      case IModelElement.SCRIPT_FOLDER:
        root = (IProjectFragment) element.getParent();
        projectPath = root.getScriptProject().getPath().toString();
        if (root.isArchive()) {
          if (DLTKCore.DEBUG) {
            System.err.println("TODO: Check. Bug possible..."); // $NON-NLS-1$
          }
          String relativePath = ((ModelElement) element).getPath().toString() + '/';
          containerPath = root.getPath();
          containerPathToString = containerPath.toString();
          add(projectPath, relativePath, containerPathToString, true /* package */, null);
        } else {
          IResource resource = element.getResource();
          if (resource != null) {
            if (resource.isAccessible()) {
              containerPath =
                  root.getKind() == IProjectFragment.K_SOURCE
                      ? root.getParent().getPath()
                      : root.getPath();
            } else {
              // for working copies, get resource container full path
              containerPath = resource.getParent().getFullPath();
            }
            containerPathToString = containerPath.toString();
            String relativePath =
                Util.relativePath(resource.getFullPath(), containerPath.segmentCount());
            add(projectPath, relativePath, containerPathToString, true /* package */, null);
          }
        }
        break;
      default:
        // remember sub-cu (or sub-class file) script elements
        if (element instanceof IMember) {
          if (this.elements == null) {
            this.elements = new ArrayList<IModelElement>();
          }
          this.elements.add(element);
        }
        root = (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
        projectPath = root.getScriptProject().getPath().toString();
        String relativePath;
        if (root.getKind() == IProjectFragment.K_SOURCE && !root.isExternal()) {
          containerPath = root.getParent().getPath();
          relativePath = Util.relativePath(getPath(element, false /* full path */), 1 /*
																				 * remove
																				 * project
																				 * segmet
																				 */);
        } else {
          containerPath = root.getPath();
          relativePath = getPath(element, true /* relative path */).toString();
        }
        containerPathToString = containerPath.toString();
        add(projectPath, relativePath, containerPathToString, false /*
																		 * not a
																		 * package
																		 */, null);
    }

    if (containerPath != null) addEnclosingProjectOrArchive(containerPath);
  }
예제 #12
0
  /**
   * Add a path to current script 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 scriptProject 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 buildpath entries
   * @param visitedProjects Set to avoid infinite recursion
   * @param referringEntry Project raw entry in referring project buildpath
   * @throws ModelException May happen while getting script model info
   */
  void add(
      ScriptProject scriptProject,
      IPath pathToAdd,
      int includeMask,
      HashSet<IProject> visitedProjects,
      IBuildpathEntry referringEntry)
      throws ModelException {
    if (!natureFilter(scriptProject)) {
      return;
    }
    IProject project = scriptProject.getProject();
    if (!project.isAccessible() || !visitedProjects.add(project)) return;

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

    // Iterate via project fragments without buildpath entries
    IProjectFragment[] fragments = scriptProject.getProjectFragments();
    for (int i = 0; i < fragments.length; i++) {
      if (fragments[i].getRawBuildpathEntry() == null) {
        add(fragments[i]);
      }
    }

    IBuildpathEntry[] entries = scriptProject.getResolvedBuildpath();
    IScriptModel model = scriptProject.getModel();
    ModelManager.PerProjectInfo perProjectInfo = scriptProject.getPerProjectInfo();
    for (int i = 0, length = entries.length; i < length; i++) {
      IBuildpathEntry entry = entries[i];
      AccessRuleSet access = null;
      BuildpathEntry cpEntry = (BuildpathEntry) entry;
      if (referringEntry != null) {
        // Add only exported entries.
        // Source folder are implicitly exported.
        if (!entry.isExported() && entry.getEntryKind() != IBuildpathEntry.BPE_SOURCE) continue;
        cpEntry = cpEntry.combineWith((BuildpathEntry) referringEntry);
        // cpEntry =
        // ((BuildpathEntry)referringEntry).combineWith(cpEntry);
      }
      access = cpEntry.getAccessRuleSet();
      switch (entry.getEntryKind()) {
        case IBuildpathEntry.BPE_LIBRARY:
          IBuildpathEntry rawEntry = null;
          Map<IPath, IBuildpathEntry> rootPathToRawEntries = perProjectInfo.rootPathToRawEntries;
          if (rootPathToRawEntries != null) {
            rawEntry = rootPathToRawEntries.get(entry.getPath());
          }
          if (rawEntry == null) {
            break;
          }
          switch (rawEntry.getEntryKind()) {
            case IBuildpathEntry.BPE_LIBRARY:
            case IBuildpathEntry.BPE_VARIABLE:
              if ((includeMask & APPLICATION_LIBRARIES) != 0) {
                IPath path = entry.getPath();
                if (pathToAdd == null || pathToAdd.equals(path)) {
                  String pathToString = path.toString();
                  add(
                      projectPath.toString(),
                      "",
                      pathToString,
                      false /* not a package */,
                      access); //$NON-NLS-1$
                  addEnclosingProjectOrArchive(path);
                }
              }
              break;
            case IBuildpathEntry.BPE_CONTAINER:
              IBuildpathContainer container =
                  DLTKCore.getBuildpathContainer(rawEntry.getPath(), scriptProject);
              if (container == null) break;
              if ((container.getKind() == IBuildpathContainer.K_APPLICATION
                      && (includeMask & APPLICATION_LIBRARIES) != 0)
                  || (includeMask & SYSTEM_LIBRARIES) != 0) {
                IPath path = entry.getPath();
                if (pathToAdd == null || pathToAdd.equals(path)) {
                  String pathToString = path.toString();
                  add(
                      projectPath.toString(),
                      "",
                      pathToString,
                      false /* not a package */,
                      access); //$NON-NLS-1$
                  addEnclosingProjectOrArchive(path);
                }
              }
              break;
          }
          break;
        case IBuildpathEntry.BPE_PROJECT:
          if ((includeMask & REFERENCED_PROJECTS) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              add(
                  (ScriptProject) model.getScriptProject(entry.getPath().lastSegment()),
                  null,
                  includeMask,
                  visitedProjects,
                  cpEntry);
            }
          }
          break;
        case IBuildpathEntry.BPE_SOURCE:
          if ((includeMask & SOURCES) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              add(
                  projectPath.toString(),
                  Util.relativePath(path, 1 /*
														 * remove project
														 * segment
														 */),
                  projectPathString,
                  false /*
                         * not a package
                         */,
                  access);
            }
          }
          break;
      }
    }
  }
 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;
 }