/** Handle browse source folder. */
  private void handleBrowseSourceFolder() {

    ContainerSelectionDialog dialog =
        new ContainerSelectionDialog(
            getShell(), project, false, Messages.WizardPageChooseSourceFolderAndPackage_27);
    dialog.showClosedProjects(false);

    if (dialog.open() == Window.OK) {

      Object[] result = dialog.getResult();
      if (result.length == 1) {

        txtJavaSourceFolder.setText(((Path) result[0]).toString());
        // String fullPathWorkspace = GeneratorUtil.replaceAll(project.getLocation().toString(),
        // project.getFullPath().toString(), "");
        String fullPathWorkspace =
            project
                .getLocation()
                .toString()
                .replaceAll(project.getFullPath().toString(), ""); // $NON-NLS-1$
        EclipseGeneratorUtil.fullPathProject = project.getLocation().toString();
        EclipseGeneratorUtil.project = project;
        EclipseGeneratorUtil.projectName = EclipseGeneratorUtil.project.getName();
        EclipseGeneratorUtil.workspaceFolderPath = fullPathWorkspace;

        EclipseGeneratorUtil.javaSourceFolderPath =
            EclipseGeneratorUtil.workspaceFolderPath
                + txtJavaSourceFolder.getText()
                + GeneratorUtil.slash;
        btnPackage.setEnabled(true);
        btnNewPackage.setEnabled(true);
      }
    }
  }
  @Override
  public Composite createContents(final Composite parent) {
    if (mainComposite != null) {
      return mainComposite;
    }

    mainComposite = new Composite(parent, SWT.NONE);
    mainComposite.setLayout(new GridLayout());
    mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

    objects =
        new MyFileListControl(
            mainComposite,
            project.getLocation().toOSString(),
            "additional object files ",
            "object");
    libraries = new MyListControl(mainComposite, "Libraries (-l)", "library");
    librarySearchPath =
        new MyFolderListControl(
            mainComposite,
            project.getLocation().toOSString(),
            "Library search path (-L)",
            "search path");

    disablePredefinedExtrnalDirs = new Button(mainComposite, SWT.CHECK);
    disablePredefinedExtrnalDirs.setText("Disable the entries of predefined libraries");
    disablePredefinedExtrnalDirs.setToolTipText(
        "Right now the OPENSSL_DIR and XMLDIR entries.\n"
            + " Please note that these folders are mandatory for the proper operation of TITAN.");

    return mainComposite;
  }
 public static ProcessBuilder createProcessBuilder(IProject project, String... commands) {
   Path workingDir =
       project != null
           ? project.getLocation().toFile().toPath()
           : EclipseUtils.getWorkspaceRoot().getLocation().toFile().toPath();
   return new ProcessBuilder(commands).directory(workingDir.toFile());
 }
  /**
   * Checks if a file from error output can be found.
   *
   * @throws Exception...
   */
  public void testEfsProjectPushPopDirectory() throws Exception {
    String fileName = "testEfsProjectPushPopDirectory.c";

    IProject efsProject =
        ResourceHelper.createCDTProject("EfsProject", new URI("mem:/ProjectPushPopDirectory"));
    ResourceHelper.createFolder(efsProject, "Folder");
    ResourceHelper.createFolder(efsProject, "Folder/SubFolder");
    ResourceHelper.createFile(efsProject, fileName);
    ResourceHelper.createFile(efsProject, "Folder/" + fileName);
    ResourceHelper.createFile(efsProject, "Folder/SubFolder/" + fileName);

    String lines =
        "make[1]: Entering directory `Folder'\n"
            + "make[2]: Entering directory `SubFolder'\n"
            + "make[2]: Leaving directory `SubFolder'\n"
            + fileName
            + ":1:error\n";

    String[] errorParsers = {MAKE_ERRORPARSER_ID, mockErrorParserId};
    parseOutput(efsProject, efsProject.getLocation(), errorParsers, lines);
    assertEquals(1, errorList.size());

    ProblemMarkerInfo problemMarkerInfo = errorList.get(0);
    assertEquals("L/EfsProject/Folder/" + fileName, problemMarkerInfo.file.toString());
    assertEquals(1, problemMarkerInfo.lineNumber);
    assertEquals("error", problemMarkerInfo.description);
  }
Example #5
0
  /* (non-Javadoc)
   * @see org.eclipse.core.internal.jobs.InternalJob#run(org.eclipse.core.runtime.IProgressMonitor)
   */
  protected IStatus run(IProgressMonitor monitor) {
    TreeNode root = new TreeNode("");

    File it = new File(proj.getLocation().addTrailingSeparator() + "goblin.xml");
    if (!it.canRead())
      return new Status(IStatus.ERROR, "ee.ut.goblin", 97, "Can't read analysis file.", null);

    DefaultHandler handler = new XMLHandler(root);
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
      // Parse the input
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse(it, handler);
    } catch (Throwable t) {
      return new Status(IStatus.ERROR, "ee.ut.goblin", 96, t.getMessage(), t);
    }

    TreeAnalysisMap tam = new TreeAnalysisMap((TreeAnalysis) root.getChildren()[0]);

    try {
      proj.setSessionProperty(GoblinPlugin.RESULT_NAME, tam);
    } catch (CoreException e) {
      return new Status(IStatus.ERROR, "ee.ut.goblin", 95, e.getMessage(), e);
    }

    monitor.done();
    return Status.OK_STATUS;
  }
 private static Path getProjectBaseDir(IProject project) {
   IPath projectLocation = project.getLocation();
   // In some infrequent cases the project may be virtual and don't have physical location
   return projectLocation != null
       ? projectLocation.toFile().toPath()
       : ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().toPath();
 }
  public void testManifestLinkCreatedWithAndroidMavenPlugin4DefaultValue() throws Exception {
    IProject project = importAndroidTestProject("android-maven-plugin-4").into(workspace);

    assertEquals(
        project.getLocation().append("src/main/AndroidManifest.xml"),
        project.getFile("AndroidManifest.xml").getLocation());
  }
  public static ESBArtifact getESBArtifactFromFile(
      IFile refactoredFile, String projectNatureFilter) {
    IProject esbProject = refactoredFile.getProject();
    try {
      esbProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      if (esbProject.isOpen() && esbProject.hasNature(projectNatureFilter)) {

        ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact();
        esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml").getLocation().toFile());
        List<ESBArtifact> allESBArtifacts = esbProjectArtifact.getAllESBArtifacts();

        String originalFileRelativePath =
            FileUtils.getRelativePath(
                    esbProject.getLocation().toFile(), refactoredFile.getLocation().toFile())
                .replaceAll(Pattern.quote(File.separator), "/");

        for (ESBArtifact esbArtifact : allESBArtifacts) {
          if (esbArtifact.getFile().equals(originalFileRelativePath)) {
            return esbArtifact;
          }
        }
      }
    } catch (CoreException e) {
      log.error("Error while reading ESB Project", e);
    } catch (FactoryConfigurationError e) {
      log.error("Error while reading ESB Project", e);
    } catch (Exception e) {
      log.error("Error while reading ESB Project", e);
    }

    return null;
  }
  public boolean markResources(
      LimyQalabEnvironment env, Collection<IResource> resources, IProgressMonitor monitor) {

    try {

      IProject project = env.getProject();

      File binDir = new File(project.getLocation().toFile(), ".bin");
      FileUtils.deleteDirectory(binDir);
      for (IResource resource : resources) {
        ResourceWithBasedir classResource = QalabResourceUtils.getClassResource(env, resource);

        // /javatest/bin/AdBean.class
        String fullPath = classResource.getResource().getFullPath().toString();

        // /javatest/bin
        String baseDir = classResource.getBaseDir().toString();

        // /AdBean.class
        String relativePath = fullPath.substring(baseDir.length() + 1);

        File classFile = new File(binDir, relativePath);
        classFile.getParentFile().mkdirs();
        FileUtils.copyFile(classResource.getResource().getLocation().toFile(), classFile);
      }

      return markAll(env, new String[] {binDir.getAbsolutePath()}, monitor);

    } catch (CoreException e) {
      LimyEclipsePluginUtils.log(e);
    } catch (IOException e) {
      LimyEclipsePluginUtils.log(e);
    }
    return false;
  }
Example #10
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.vimide.core.servlet.VimideHttpServlet#doGet(org.vimide.core.servlet.VimideHttpServletRequest,
   *     org.vimide.core.servlet.VimideHttpServletResponse)
   */
  @Override
  protected void doGet(VimideHttpServletRequest req, VimideHttpServletResponse resp)
      throws ServletException, IOException {
    final List<Map<String, Object>> results = Lists.newArrayList();

    for (IProject project : getProjects()) {
      Map<String, Object> info = Maps.newHashMap();
      info.put("name", project.getName());
      info.put("path", project.getLocation().toOSString());

      if (project.isOpen()) {
        try {
          String[] aliases =
              NaturesMapping.getNatureAliases(project.getDescription().getNatureIds());
          if (null == aliases || aliases.length == 0) aliases = new String[] {"none"};
          info.put("natures", aliases);
        } catch (final Exception e) {
          info.put("natures", ArrayUtils.EMPTY_STRING_ARRAY);
        }
      }

      results.add(info);
    }

    resp.writeAsJson(results);
  }
  /**
   * ************************************************************************ Get the database path
   * for this project
   *
   * @return ***********************************************************************
   */
  @SuppressWarnings("unchecked")
  public String getDatabasePath() {
    HashMap<QualifiedName, Object> properties = null;
    try {
      properties = new HashMap<QualifiedName, Object>(m_project.getPersistentProperties());
    } catch (CoreException e1) {
      System.err.println(
          "Cannot retrieve persistent properties for project " + m_project.getName());
      return null;
    }
    if (!properties.containsKey(ProjectDatabaseProperty.GCS_DATABASE.getKey())) {
      restoreProjectProperties(ProjectDatabaseProperty.GCS_DATABASE);
    }

    try {
      String path = m_project.getPersistentProperty(ProjectDatabaseProperty.GCS_DATABASE.getKey());
      // Relative path
      boolean absolute = true;
      if (!path.isEmpty()) {
        absolute = new File(path).isAbsolute();
      }
      if (!path.isEmpty() && !absolute) {
        IPath projAbsolute = m_project.getLocation();
        String projectPath = projAbsolute.toFile().getAbsolutePath();
        path = projectPath + File.separator + path;
      }
      return path;
    } catch (CoreException e) {
      return null;
    }
  }
Example #12
0
  /**
   * Creates new symbolic file system link from file or folder on project root to another file
   * system file. The filename can include relative path as a part of the name but the the path has
   * to be present on disk.
   *
   * @param project - project where to create the file.
   * @param linkName - name of the link being created.
   * @param realPath - file or folder on the file system, the target of the link.
   * @return file handle.
   * @throws UnsupportedOperationException on Windows where links are not supported.
   * @throws IOException...
   * @throws CoreException...
   */
  public static IResource createSymbolicLink(IProject project, String linkName, IPath realPath)
      throws IOException, CoreException, UnsupportedOperationException {

    if (!isSymbolicLinkSupported()) {
      throw new UnsupportedOperationException("Windows links .lnk are not supported.");
    }

    Assert.assertTrue(
        "Path for symbolic link does not exist: [" + realPath.toOSString() + "]",
        new File(realPath.toOSString()).exists());

    IPath linkedPath = project.getLocation().append(linkName);
    createSymbolicLink(linkedPath, realPath);

    IResource resource = project.getFile(linkName);
    resource.refreshLocal(IResource.DEPTH_ZERO, null);

    if (!resource.exists()) {
      resource = project.getFolder(linkName);
      resource.refreshLocal(IResource.DEPTH_ZERO, null);
    }
    Assert.assertTrue("Failed to create resource form symbolic link", resource.exists());

    externalFilesCreated.add(linkedPath.toOSString());
    ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
    return resource;
  }
  /**
   * Populate properties with everything required for the SonarLint analysis in issues mode.
   *
   * @param monitor
   * @param properties
   * @return
   */
  public Properties configureAnalysis(
      final IProgressMonitor monitor, List<SonarLintProperty> extraProps) {
    Properties properties = new Properties();
    IProject project = request.getProject();
    final File baseDir = project.getLocation().toFile();
    IPath projectSpecificWorkDir = project.getWorkingLocation(SonarLintCorePlugin.PLUGIN_ID);

    // Preview mode by default
    properties.setProperty(
        SonarLintProperties.ANALYSIS_MODE, SonarLintProperties.ANALYSIS_MODE_ISSUES);

    // Configuration by configurators (common and language specific)
    configure(project, this.request.getOnlyOnFiles(), properties, monitor);

    // Append workspace and project properties
    for (SonarLintProperty sonarProperty : extraProps) {
      properties.put(sonarProperty.getName(), sonarProperty.getValue());
    }
    if (this.request.getOnlyOnFiles() != null) {
      Collection<String> paths = new ArrayList<>(this.request.getOnlyOnFiles().size());
      for (IFile file : this.request.getOnlyOnFiles()) {
        MarkerUtils.deleteIssuesMarkers(file);
        paths.add(file.getProjectRelativePath().toString());
      }
      ProjectConfigurator.setPropertyList(properties, "sonar.tests", paths);
      ProjectConfigurator.setPropertyList(properties, "sonar.sources", paths);
    } else {
      MarkerUtils.deleteIssuesMarkers(project);
    }

    properties.setProperty(SonarLintProperties.PROJECT_BASEDIR, baseDir.toString());
    properties.setProperty(SonarLintProperties.WORK_DIR, projectSpecificWorkDir.toString());

    return properties;
  }
  private File[] parseEndorsedDirs(IProject project, String endorsedDirs) {
    if (endorsedDirs == null) {
      return null;
    }
    // Remove quotes, use system separators
    endorsedDirs = endorsedDirs.replaceAll("\"", "");

    // Quote from http://docs.oracle.com/javase/6/docs/technotes/guides/standards/
    // "If more than one directory path is specified by java.endorsed.dirs,
    // they must be separated by File.pathSeparatorChar."
    String[] paths = endorsedDirs.split("" + File.pathSeparatorChar);

    // Convert dir paths to Files
    List<File> dirs = new ArrayList<File>(paths.length);
    for (String path : paths) {
      IPath p = new Path(useSystemSeparator(path));
      if (!p.isAbsolute()) {
        p = project.getLocation().append(p);
      }
      File lib = new File(p.toOSString());
      dirs.add(lib);
    }

    return dirs.toArray(new File[0]);
  }
Example #15
0
 private static ArrayList<IResource> getAllXMLFilesInProject(final IProject project) {
   ArrayList<IResource> allFiles = new ArrayList<>();
   IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
   IPath path = project.getLocation();
   recursivelyFindFilesWithExtension(allFiles, path, wsRoot, "xml");
   return allFiles;
 }
  public static String getLiferayWorkspaceProjectModulesDir(final IProject project) {
    String retval = null;

    if (project != null) {
      final IPath projectLocation = project.getLocation();

      if (projectLocation != null) {
        final IPath gradlePropertiesLocation = projectLocation.append("gradle.properties");

        if (gradlePropertiesLocation.toFile().exists()) {
          try {
            String modulesDir =
                CoreUtil.readPropertyFileValue(
                    gradlePropertiesLocation.toFile(), "liferay.workspace.modules.dir");

            if (modulesDir == null) {
              modulesDir = "modules";
            }

            retval = modulesDir;
          } catch (IOException e) {
            ProjectCore.logError("Can't read gradle properties from workspaceProject. ", e);
          }
        }
      }
    }

    return retval;
  }
  /**
   * Returns whether a given library project is needed by the receiver.
   *
   * <p>If the library is needed, this finds the matching {@link LibraryState}, initializes it so
   * that it contains the library's {@link IProject} object (so that {@link
   * LibraryState#getProjectState()} does not return null) and then returns it.
   *
   * @param libraryProject the library project to check.
   * @return a non null object if the project is a library dependency, <code>null</code> otherwise.
   * @see LibraryState#getProjectState()
   */
  public LibraryState needs(ProjectState libraryProject) {
    // compute current location
    File projectFile = mProject.getLocation().toFile();

    // get the location of the library.
    File libraryFile = libraryProject.getProject().getLocation().toFile();

    // loop on all libraries and check if the path match
    synchronized (mLibraries) {
      for (LibraryState state : mLibraries) {
        if (state.getProjectState() == null) {
          File library = new File(projectFile, state.getRelativePath());
          try {
            File absPath = library.getCanonicalFile();
            if (absPath.equals(libraryFile)) {
              state.setProject(libraryProject);
              return state;
            }
          } catch (IOException e) {
            // ignore this library
          }
        }
      }
    }

    return null;
  }
 @Override
 public void fillContextMenu(IMenuManager aMenu) {
   IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
   if (selection.size() != 1) {
     return;
   }
   Object object = selection.getFirstElement();
   IFolder folder = Adapters.adapt(object, IFolder.class);
   if (folder == null) {
     return;
   }
   if (folder.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).exists()) {
     for (IProject project : folder.getWorkspace().getRoot().getProjects()) {
       if (project.getLocation().equals(folder.getLocation())) {
         // project already in workspace
         SelectProjectForFolderAction action =
             new SelectProjectForFolderAction(project, this.viewer);
         aMenu.appendToGroup(ICommonMenuConstants.GROUP_OPEN, action);
         return;
       }
     }
     OpenFolderAsProjectAction action = new OpenFolderAsProjectAction(folder, this.viewer);
     aMenu.prependToGroup(ICommonMenuConstants.GROUP_PORT, action);
   }
 }
  public String getWarSourceDirectory() {
    Xpp3Dom dom = getConfiguration();
    if (dom == null) {
      return WAR_SOURCE_FOLDER;
    }

    Xpp3Dom[] warSourceDirectory = dom.getChildren("warSourceDirectory");
    if (warSourceDirectory != null && warSourceDirectory.length > 0) {
      // first one wins
      String dir = warSourceDirectory[0].getValue();
      // MNGECLIPSE-1600 fixed absolute warSourceDirectory thanks to Snjezana Peco's patch
      if (project != null) {
        IPath projectLocationPath = project.getLocation();
        if (projectLocationPath != null && dir != null) {
          String projectLocation = projectLocationPath.toOSString();
          if (dir.startsWith(projectLocation)) {
            return dir.substring(projectLocation.length());
          }
        }
      }
      return dir;
    }

    return WAR_SOURCE_FOLDER;
  }
Example #20
0
  public static SDK getSDK(IProject project) {
    SDK retval = null;

    // try to determine SDK based on project location
    IPath projectLocation = project.getRawLocation();

    if (projectLocation == null) {
      projectLocation = project.getLocation();
    }

    if (projectLocation != null) {
      IPath sdkLocation = projectLocation.removeLastSegments(2);

      retval = SDKManager.getInstance().getSDK(sdkLocation);

      if (retval == null) {
        retval = SDKUtil.createSDKFromLocation(sdkLocation);

        if (retval != null) {
          SDKManager.getInstance().addSDK(retval);
        }
      }
    }

    return retval;
  }
Example #21
0
 /**
  * Gets the pom properties.
  *
  * @param project the project
  * @return the pom properties
  */
 public static Map<String, String> getPomProperties(IProject project) {
   Map<String, String> properties = new HashMap<String, String>();
   if (project != null) {
     properties.put("basedir", project.getLocation().makeAbsolute().toOSString());
   }
   return properties;
 }
  public List<IResource> exportArtifact(IProject project) throws Exception {
    String projectPath = project.getLocation().toFile().toString();
    List<IResource> exportResources = new ArrayList<IResource>();
    clearTarget(project);
    IFile pomFile = project.getFile("pom.xml");

    if (pomFile.exists()) {
      MavenProject mavenProject = MavenUtils.getMavenProject(pomFile.getLocation().toFile());
      List<Plugin> plugins = mavenProject.getBuild().getPlugins();
      for (Plugin plugin : plugins) {
        if (plugin.getArtifactId().equals("maven-dataservice-plugin")
            && plugin.getGroupId().equals("org.wso2.maven")) {
          Xpp3Dom artifactNode = ((Xpp3Dom) plugin.getConfiguration()).getChild("artifact");
          String dbsFile = artifactNode.getValue();
          String[] pathArray = dbsFile.split("/");
          IFile dbsFileRef =
              project
                  .getFolder("src")
                  .getFolder("main")
                  .getFolder("dataservice")
                  .getFile(pathArray[pathArray.length - 1]);
          if (dbsFileRef.exists()) {
            exportResources.add((IResource) dbsFileRef);
          }
        }
      }
    } else {
      File[] dbsFiles =
          FileUtils.getAllMatchingFiles(
              project.getLocation().toString(), null, DBS_FILE_EXTENSION, new ArrayList<File>());
      for (File dbsFile : dbsFiles) {
        String filePath = dbsFile.toString();
        // excluded any files inside target dir
        if (!filePath
            .substring(projectPath.length())
            .startsWith(File.separator + "target" + File.separator)) {
          IFile dbsFileRef =
              ResourcesPlugin.getWorkspace()
                  .getRoot()
                  .getFileForLocation(Path.fromOSString(dbsFile.getAbsolutePath()));
          exportResources.add((IResource) dbsFileRef);
        }
      }
    }

    return exportResources;
  }
  /**
   * Unzip all the projects contained by the zip.
   *
   * @param bundleName the bundle name
   * @param zipLocation the zip location inside of the bundle
   * @param monitor the progress monitor
   * @throws IOException if there is an issue copying a file from the zip
   * @throws CoreException if there is an issue creating one of the projects
   */
  public static void unzipAllProjects(
      String bundleName, String zipLocation, IProgressMonitor monitor)
      throws IOException, CoreException {
    final URL interpreterZipUrl =
        FileLocator.find(Platform.getBundle(bundleName), new Path(zipLocation), null);
    final ZipInputStream zipFileStream = new ZipInputStream(interpreterZipUrl.openStream());
    ZipEntry zipEntry = zipFileStream.getNextEntry();

    Set<IProject> projects = new HashSet<IProject>();

    while (zipEntry != null) {
      String projectName = zipEntry.getName().split("/")[0];

      IProject project = createProject(projectName, monitor);
      projects.add(project);

      final File file =
          new File(
              project.getLocation().toString(),
              zipEntry
                  .getName()
                  .replaceFirst(projectName + "/", "")); // $NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$

      if (!zipEntry.isDirectory()) {

        /*
         * Copy files (and make sure parent directory exist)
         */
        final File parentFile = file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
          parentFile.mkdirs();
        }

        OutputStream os = null;

        try {
          os = new FileOutputStream(file);

          final int bufferSize = 102400;
          final byte[] buffer = new byte[bufferSize];
          while (true) {
            final int len = zipFileStream.read(buffer);
            if (zipFileStream.available() == 0) {
              break;
            }
            os.write(buffer, 0, len);
          }
        } finally {
          if (null != os) {
            os.close();
          }
        }
      }
      zipFileStream.closeEntry();
      zipEntry = zipFileStream.getNextEntry();
    }

    ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, monitor);
  }
  /**
   * Tries to delete an open project containing an irremovable file. Works only for Linux with
   * natives.
   */
  public void testDeleteOpenProjectLinux() {
    if (!(Platform.getOS().equals(Platform.OS_LINUX) && isReadOnlySupported())) return;

    IProject project = null;
    File projectRoot = null;
    IFolder folder = null;
    try {
      IWorkspace workspace = getWorkspace();
      project = workspace.getRoot().getProject(getUniqueString());
      folder = project.getFolder("a_folder");
      IFile file1 = folder.getFile("file1.txt");
      IFile file2 = project.getFile("file2.txt");

      ensureExistsInWorkspace(new IResource[] {file1, file2}, true);
      projectRoot = project.getLocation().toFile();

      // marks folder as read-only so its files cannot be deleted on Linux
      setReadOnly(folder, true);

      IFile projectFile = project.getFile(".project");
      assertTrue("1.2", projectFile.exists());
      assertTrue("1.3", projectFile.isSynchronized(IResource.DEPTH_INFINITE));

      try {
        project.delete(IResource.FORCE, getMonitor());
        fail("2.0 - should have failed");
      } catch (CoreException ce) {
        // success - a file couldn't be removed
      }
      assertTrue("2.1", project.exists());
      assertTrue("2.2", file1.exists());
      assertTrue("2.3", !file2.exists());
      assertTrue("2.5", folder.exists());
      assertTrue("2.6", projectFile.exists());
      assertTrue("2.7", project.isSynchronized(IResource.DEPTH_INFINITE));

      setReadOnly(folder, false);

      assertTrue("3.5", project.isSynchronized(IResource.DEPTH_INFINITE));
      try {
        project.delete(IResource.FORCE, getMonitor());
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("4.0", ce);
      }

      assertTrue("5.1", !project.exists());
      assertTrue("5.2", !file1.exists());
      assertTrue("5.3", file1.isSynchronized(IResource.DEPTH_INFINITE));
      assertTrue("5.4", project.isSynchronized(IResource.DEPTH_INFINITE));

      assertTrue("6.0", !projectRoot.exists());
    } finally {
      if (folder != null && folder.exists()) setReadOnly(folder, false);
      if (projectRoot != null) ensureDoesNotExistInFileSystem(projectRoot);
    }
  }
Example #25
0
 /**
  * @param absolute if true, returns an absolute path, otherwise it might be relative
  * @return the file of this suppression
  */
 public File getFile(boolean absolute) {
   final File file;
   if (absolute && !this.file.isAbsolute()) {
     file = new File(project.getLocation().toFile(), this.file.toString());
   } else {
     file = this.file;
   }
   return file;
 }
  public void testNonDefaultInternalAssetsLinkCreated() throws Exception {
    IProject[] projects =
        importAndroidProjects(
            MULTIMODULE_ROOT, new String[] {"pom.xml", "android-internaldirassets/pom.xml"});
    IProject project = projects[1];

    assertEquals(
        project.getLocation().append("assets2"), project.getFolder("assets").getLocation());
  }
Example #27
0
 private void fillTreeItemWithGitDirectory(
     RepositoryMapping m, TreeItem treeItem, boolean isAlternative) {
   if (m.getGitDir() == null)
     treeItem.setText(2, UIText.ExistingOrNewPage_SymbolicValueEmptyMapping);
   else {
     IPath relativePath = new Path(m.getGitDir());
     if (isAlternative) {
       IPath withoutLastSegment = relativePath.removeLastSegments(1);
       IPath path;
       if (withoutLastSegment.isEmpty()) path = Path.fromPortableString("."); // $NON-NLS-1$
       else path = withoutLastSegment;
       treeItem.setText(0, path.toString());
     }
     treeItem.setText(2, relativePath.toOSString());
     try {
       IProject project = m.getContainer().getProject();
       Repository repo =
           new RepositoryBuilder().setGitDir(m.getGitDirAbsolutePath().toFile()).build();
       File workTree = repo.getWorkTree();
       IPath workTreePath = Path.fromOSString(workTree.getAbsolutePath());
       if (workTreePath.isPrefixOf(project.getLocation())) {
         IPath makeRelativeTo = project.getLocation().makeRelativeTo(workTreePath);
         String repoRelativePath =
             makeRelativeTo.append("/.project").toPortableString(); // $NON-NLS-1$
         ObjectId headCommitId = repo.resolve(Constants.HEAD);
         if (headCommitId != null) {
           // Not an empty repo
           RevWalk revWalk = new RevWalk(repo);
           RevCommit headCommit = revWalk.parseCommit(headCommitId);
           RevTree headTree = headCommit.getTree();
           TreeWalk projectInRepo = TreeWalk.forPath(repo, repoRelativePath, headTree);
           if (projectInRepo != null) {
             // the .project file is tracked by this repo
             treeItem.setChecked(true);
           }
           revWalk.dispose();
         }
       }
       repo.close();
     } catch (IOException e1) {
       Activator.logError(UIText.ExistingOrNewPage_FailedToDetectRepositoryMessage, e1);
     }
   }
 }
  /** Tries to delete a folder containing an unremovable file. Works only for Windows. */
  public void testDeleteFolderWindows() {
    if (!isWindows()) return;

    IProject project = null;
    InputStream input = null;
    File projectRoot = null;
    try {
      IWorkspace workspace = getWorkspace();
      project = workspace.getRoot().getProject(getUniqueString());
      IFolder folder = project.getFolder("a_folder");
      IFile file1 = folder.getFile("file1.txt");
      IFile file3 = folder.getFile("file3.txt");

      ensureExistsInWorkspace(new IResource[] {file1, file3}, true);
      projectRoot = project.getLocation().toFile();

      // opens a file so it cannot be removed on Windows
      try {
        input = file1.getContents();
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("1.0");
      }

      try {
        folder.delete(IResource.FORCE, getMonitor());
        fail("2.0 - should have failed");
      } catch (CoreException ce) {
        // success - a file couldn't be removed
      }
      assertTrue("2.2", file1.exists());
      assertTrue("2.4", !file3.exists());
      assertTrue("2.5", folder.exists());
      assertTrue("2.7", folder.isSynchronized(IResource.DEPTH_INFINITE));

      assertClose(input);

      assertTrue("3.5", project.isSynchronized(IResource.DEPTH_INFINITE));
      try {
        folder.delete(IResource.FORCE, getMonitor());
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("4.0", ce);
      }
      assertTrue("5.1", !file1.exists());
      assertTrue("5.2", !folder.exists());
      assertTrue("5.3", file1.isSynchronized(IResource.DEPTH_INFINITE));
      assertTrue("5.4", folder.isSynchronized(IResource.DEPTH_INFINITE));
    } finally {
      try {
        assertClose(input);
      } finally {
        if (projectRoot != null) ensureDoesNotExistInFileSystem(projectRoot);
      }
    }
  }
Example #29
0
 public void createFileInProject(Map<String, String> files, IProject newProjectHandle) {
   if (files != null) {
     String projectPath = newProjectHandle.getLocation().toFile().getAbsolutePath();
     for (Entry<String, String> entry : files.entrySet()) {
       IOTools.copyFile(
           PathTools.getPlugPath(PYTHON_PLUGIN_ID) + entry.getKey(),
           projectPath + File.separator + entry.getValue());
     }
   }
 }
 private boolean doesDDFileExist(IProject project, IPath webXMLPath) {
   return getWebContentPath(project) == null
       ? false
       : project
           .getLocation()
           .append(getWebContentPath(project).lastSegment())
           .append(webXMLPath)
           .toFile()
           .exists();
 }