Example #1
0
  /**
   * Returns the total number of java files in the project by recursively visiting directories.
   *
   * @param resource The location to start counting from. This could be a project, folder or file
   * @return The total number of files with java-like extensions found.
   */
  private int countTotalJavaFiles(IResource resource) {
    if (resource == null) {
      return 0;
    }
    int size = 0;
    try {
      if (resource.getType() == IResource.FOLDER) {
        IFolder folder = (IFolder) resource;
        for (IResource file : folder.members()) {
          size += countTotalJavaFiles(file);
        }
      } else if (resource.getType() == IResource.PROJECT) {
        IProject proj = (IProject) resource;
        for (IResource file : proj.members()) {
          size += countTotalJavaFiles(file);
        }
      }
    } catch (CoreException e) {
      eLog.logException(e);
    }
    if (resource.getType() == IResource.FILE && JavaCore.isJavaLikeFileName(resource.getName()))
      size++;

    return size;
  }
  public synchronized void cleanUp(IProgressMonitor monitor) throws CoreException {
    DeltaProcessingState state = ModelManager.getModelManager().deltaState;
    HashMap roots = state.roots;
    // HashMap sourceAttachments = state.sourceAttachments;
    if (roots == null /* && sourceAttachments == null */) return;
    HashMap knownFolders = getFolders();
    Iterator iterator = knownFolders.keySet().iterator();
    while (iterator.hasNext()) {
      IPath path = (IPath) iterator.next();
      if ((roots != null && !roots.containsKey(path))
      /*
       * & (sourceAttachments != null && !sourceAttachments
       * .containsKey(path))
       */ ) {
        IFolder folder = (IFolder) knownFolders.get(path);
        if (folder != null) folder.delete(true, monitor);
      }
    }
    IProject project = getExternalFoldersProject();
    if (project.isAccessible() && project.members().length == 1 /*
																	 * remaining
																	 * member is
																	 * .project
																	 */) project.delete(true, monitor);
  }
  // Assert that the two projects have equal contents ignoreing the project name
  // and the .vcm_meta file
  protected void assertEquals(IProject container1, IProject container2) throws CoreException {
    List members1 = new ArrayList();
    members1.addAll(Arrays.asList(container1.members()));
    members1.remove(container1.findMember(".project"));

    List members2 = new ArrayList();
    members2.addAll(Arrays.asList(container2.members()));
    members2.remove(container2.findMember(".project"));

    assertTrue(
        "Number of children differs for " + container1.getFullPath(),
        members1.size() == members2.size());
    for (int i = 0; i < members1.size(); i++) {
      IResource member1 = (IResource) members1.get(i);
      IResource member2 = container2.findMember(member1.getName());
      assertNotNull(member2);
      assertEquals(member1, member2);
    }
  }
  private void configure(
      final IProject project,
      Collection<IFile> filesToAnalyze,
      final Properties properties,
      final IProgressMonitor monitor) {
    String projectName = project.getName();
    String encoding;
    try {
      encoding = project.getDefaultCharset();
    } catch (CoreException e) {
      throw new SonarEclipseException("Unable to get charset from project", e);
    }

    properties.setProperty(SonarLintProperties.PROJECT_NAME_PROPERTY, projectName);
    properties.setProperty(SonarLintProperties.PROJECT_VERSION_PROPERTY, "0.1-SNAPSHOT");
    properties.setProperty(SonarLintProperties.ENCODING_PROPERTY, encoding);

    ProjectConfigurationRequest configuratorRequest =
        new ProjectConfigurationRequest(project, filesToAnalyze, properties);
    Collection<ProjectConfigurator> configurators = ConfiguratorUtils.getConfigurators();
    for (ProjectConfigurator configurator : configurators) {
      if (configurator.canConfigure(project)) {
        configurator.configure(configuratorRequest, monitor);
        usedConfigurators.add(configurator);
      }
    }

    ProjectConfigurator.appendProperty(
        properties,
        SonarConfiguratorProperties.TEST_INCLUSIONS_PROPERTY,
        PreferencesUtils.getTestFileRegexps());
    if (!properties.containsKey(SonarConfiguratorProperties.SOURCE_DIRS_PROPERTY)
        && !properties.containsKey(SonarConfiguratorProperties.TEST_DIRS_PROPERTY)) {
      // Try to analyze all files
      properties.setProperty(SonarConfiguratorProperties.SOURCE_DIRS_PROPERTY, ".");
      properties.setProperty(SonarConfiguratorProperties.TEST_DIRS_PROPERTY, ".");
      // Try to exclude derived folders
      try {
        for (IResource member : project.members()) {
          if (member.isDerived()) {
            ProjectConfigurator.appendProperty(
                properties,
                SonarConfiguratorProperties.SOURCE_EXCLUSIONS_PROPERTY,
                member.getName() + "/**/*");
            ProjectConfigurator.appendProperty(
                properties,
                SonarConfiguratorProperties.TEST_EXCLUSIONS_PROPERTY,
                member.getName() + "/**/*");
          }
        }
      } catch (CoreException e) {
        throw new IllegalStateException("Unable to list members of " + project, e);
      }
    }
  }
 public void cleanUp(IProgressMonitor monitor) throws CoreException {
   ArrayList<Entry<IPath, IResource>> toDelete = getSourceArchivesToCleanUp(monitor);
   if (toDelete == null) return;
   for (Iterator<Entry<IPath, IResource>> iterator = toDelete.iterator(); iterator.hasNext(); ) {
     Entry<IPath, IResource> entry = iterator.next();
     IFolder folder = (IFolder) entry.getValue();
     folder.delete(true, monitor);
     IPath key = (IPath) entry.getKey();
     archives.remove(key);
   }
   IProject project = getExternalSourceArchivesProject();
   if (project.isAccessible() && project.members().length == 1 /*remaining member is .project*/)
     project.delete(true, monitor);
 }
  private static Object[] getElementsToExport(IProject project) throws CoreException {

    IJavaProject javaProj = JavaCore.create(project);

    try {
      ILaunchConfiguration launchConfiguration = createLaunchConfigurationForProject(javaProj);
      return getSelectedElementsWithoutContainedChildren(launchConfiguration);

    } catch (CoreException e) {
      LambdaPlugin.getDefault()
          .warn("Unable to resolve dependencies of project " + project.getName(), e);

      // Fall back to export all the file resource inside the project
      return project.members(IResource.FILE);
    }
  }
  private TreeObject addProject(IProject currProject) {
    // TreeParent projNode = new TreeParent(currProject.getName());
    ProjectNode projNode = new ProjectNode(currProject);

    if (!currProject.isOpen()) return projNode;

    try {
      IResource children[] = currProject.members();
      for (int i = 0; i < children.length; i++) {
        projNode.addChild(addResource(children[i]));
      }

    } catch (CoreException ex) {
      ex.printStackTrace();
    }
    return projNode;
  }
 /**
  * Projects do not allow a link to be created if there is another resource (linked or not) whose
  * name is the same as the new name with only case differences. Return <code>true</code> if the
  * project has a member whose name is the same when case is ignored.
  *
  * @param project the project containing the members
  * @param fileName the name being checked for
  * @return <code>true</code> if the project has a member whose name is the same when case is
  *     ignored
  * @throws
  */
 private static boolean hasSimilarChild(IProject project, String fileName) {
   try {
     IResource[] members = project.members();
     if (members == null) {
       return false;
     }
     for (IResource member : members) {
       if (member.getName().equalsIgnoreCase(fileName)) {
         return true;
       }
     }
   } catch (CoreException exception) {
     DartCore.logInformation(
         "Could not get members of project " + project.getLocation(), exception);
   }
   return false;
 }
 private void createBuildProperties(IProject project) {
   IFile file = PDEProject.getBuildProperties(project);
   if (!file.exists()) {
     WorkspaceBuildModel model = new WorkspaceBuildModel(file);
     IBuildEntry ientry = model.getFactory().createEntry("bin.includes"); // $NON-NLS-1$
     try {
       IResource[] res = project.members();
       for (int i = 0; i < res.length; i++) {
         String path = res[i].getProjectRelativePath().toString();
         if (!path.equals(".project")) // $NON-NLS-1$
         ientry.addToken(path);
       }
       model.getBuild().add(ientry);
       model.save();
     } catch (CoreException e) {
     }
   }
 }
 private Map<IPath, IResource> getSourceArchives() {
   if (archives == null) {
     Map<IPath, IResource> tempSourceArchives = new HashMap<>();
     IProject project = getExternalSourceArchivesProject();
     try {
       if (!project.isAccessible()) {
         if (project.exists()) {
           // workspace was moved
           openExternalSourceArchivesProject(project, null /*no progress*/);
         } else {
           // if project doesn't exist, do not open and recreate it as it means that there are no
           // external source archives
           return archives = Collections.synchronizedMap(tempSourceArchives);
         }
       }
       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)) {
           String path = member.getLocationURI().getPath();
           if (path != null) {
             if (path.endsWith(CeylonArchiveFileSystem.JAR_SUFFIX)) {
               path = path.substring(0, path.length() - 2);
             }
             IPath externalSourceArchivePath = new Path(path);
             tempSourceArchives.put(externalSourceArchivePath, member);
           }
         }
       }
     } catch (CoreException e) {
       Util.log(e, "Exception while initializing external folders");
     }
     archives = Collections.synchronizedMap(tempSourceArchives);
   }
   return archives;
 }
 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;
 }
Example #12
0
  /**
   * Process the EGit history associated with a given project.
   *
   * @param selectedProject selected project, presumably an object contribution selection
   * @throws CoreException
   * @throws IOException
   */
  public void processHistory(IProject selectedProject, IProgressMonitor monitor)
      throws CoreException, IOException {

    // find the repository mapping for the project
    // if none found, return
    RepositoryMapping repositoryMapping = RepositoryMapping.getMapping((IResource) selectedProject);
    if (repositoryMapping == null) {
      CertWareLog.logWarning(
          String.format("%s %s", "Missing repository for project", selectedProject.getName()));
      return;
    }

    // build the commit history model, load it from the tree walk
    final CommitHistory commitHistory = ScoFactory.eINSTANCE.createCommitHistory();
    Repository repo = repositoryMapping.getRepository();
    RevWalk revWalk = new RevWalk(repo);
    ObjectId headObject = repo.resolve("HEAD");
    revWalk.markStart(revWalk.parseCommit(headObject));

    final Set<String> repositoryPaths =
        Collections.singleton(repositoryMapping.getRepoRelativePath(selectedProject));
    revWalk.setTreeFilter(PathFilterGroup.createFromStrings(repositoryPaths));

    for (RevCommit commit : revWalk) {
      String commitName = commit.getName();
      ArtifactCommit artifactCommit = ScoFactory.eINSTANCE.createArtifactCommit();
      artifactCommit.setCommitIdentifier(commitName);
      commitHistory.getCommitRecord().add(artifactCommit);
    }

    revWalk.dispose();

    // use the Git provider to find the file history, then converge into the model
    GitProvider provider = (GitProvider) RepositoryProvider.getProvider(selectedProject);
    IFileHistoryProvider fileHistoryProvider = provider.getFileHistoryProvider();
    IResource[] projectMembers = selectedProject.members();

    monitor.beginTask("Processing project resources", projectMembers.length);
    for (IResource resource : projectMembers) {
      processResource(resource, fileHistoryProvider, commitHistory, monitor);
      monitor.worked(1);
      if (monitor.isCanceled()) {
        return;
      }
    }

    // model complete with commit history and associated file sizes
    // write the resulting model to an SCO file
    // expecting preference to have no extension, so add it if necessary
    IPreferenceStore store = Activator.getDefault().getPreferenceStore();
    String fileName = store.getString(PreferenceConstants.P_FILENAME_SCO);
    if (fileName.endsWith(ICertWareConstants.SCO_EXTENSION) == false) {
      fileName = fileName + '.' + ICertWareConstants.SCO_EXTENSION;
    }

    // fully specify the path to the new file given the container project
    final String modelFile =
        selectedProject.getFullPath().toPortableString() + IPath.SEPARATOR + fileName;

    // create the resource in a workspace modify operation
    WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          protected void execute(IProgressMonitor progressMonitor) {
            try {
              // create a resource set and resource for a new file
              ResourceSet resourceSet = new ResourceSetImpl();
              URI fileURI = URI.createPlatformResourceURI(modelFile, true);
              Resource resource = resourceSet.createResource(fileURI);
              resource.getContents().add(commitHistory);

              // save the contents of the resource to the file system
              Map<Object, Object> options = new HashMap<Object, Object>();
              options.put(XMLResource.OPTION_ENCODING, FILE_ENCODING);
              resource.save(options);
            } catch (Exception e) {
              CertWareLog.logError(String.format("%s %s", "Saving SCO file", modelFile), e);
            }
          }
        };

    // modify the workspace
    try {
      operation.run(monitor);
    } catch (Exception e) {
      CertWareLog.logError(
          String.format("%s %s", "Modifying workspace for", selectedProject.getName()), e);
    }

    monitor.done();
  }