Java Code Examples for org.eclipse.core.resources.IResource#delete()

The following examples show how to use org.eclipse.core.resources.IResource#delete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResourceUtilTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test {@link ResourceUtil#isSymbolicLink(IResource)}
 *
 * Most test cases are handled in {@link #testCreateSymbolicLink()} when
 * creating and verifying links
 *
 * @throws CoreException
 *             if core error occurs
 */
@Test
public void testIsSymbolicLink() throws CoreException {
    // Test missing cases

    // Create file and check for link
    IResource resource = createAndVerifyResource(TEST_FILE_NAME, true);
    assertFalse(ResourceUtil.isSymbolicLink(resource));
    resource.delete(true, null);

    // Create folder and check for link
    resource = createAndVerifyResource(TEST_FOLDER_NAME, false);
    assertFalse(ResourceUtil.isSymbolicLink(resource));
    resource.delete(true, null);

    // Null resource
    assertFalse(ResourceUtil.isSymbolicLink(null));
}
 
Example 2
Source File: ProjectHelper.java    From eclipse-extras with Eclipse Public License 1.0 6 votes vote down vote up
public static void delete( IResource resource ) {
  int numAttempts = 0;
  boolean success = false;
  while( !success ) {
    try {
      resource.delete( FORCE | ALWAYS_DELETE_PROJECT_CONTENT, new NullProgressMonitor() );
      success = true;
      numAttempts++;
    } catch( CoreException ce ) {
      if( numAttempts > 4 ) {
        throw new RuntimeException( "Failed to delete resource: " + resource, ce );
      }
      System.gc();
      try {
        Thread.sleep( 500 );
      } catch( InterruptedException ignore ) {
        Thread.currentThread().interrupt();
      }
      System.gc();
    }
  }
}
 
Example 3
Source File: ResourceUtilTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private void createCopyAndVerifyResource(String name, boolean isFile, boolean isAbsolute) throws CoreException {
    IResource resource = createAndVerifyResource(name, true);
    IPath newPath;
    if (isAbsolute) {
        newPath = resource.getParent().getFullPath().addTrailingSeparator().append(name + COPY_SUFFIX);
    } else {
        newPath = new Path ("..").append(resource.getParent().getName()).append(name + COPY_SUFFIX);
    }
    resource.setPersistentProperty(new QualifiedName(Activator.PLUGIN_ID, PROPERTY_KEY), PROPERTY_VALUE);
    IResource copyResource = ResourceUtil.copyResource(resource, newPath, IResource.FORCE, new NullProgressMonitor());
    assertNotNull(copyResource);
    Map<QualifiedName, String> persistentProperties = copyResource.getPersistentProperties();
    assertEquals(1, persistentProperties.size());
    for (Map.Entry<QualifiedName, String> entry: persistentProperties.entrySet()) {
        assertEquals(PROPERTY_KEY, entry.getKey().getLocalName());
        assertEquals(Activator.PLUGIN_ID, entry.getKey().getQualifier());
        assertEquals(PROPERTY_VALUE, entry.getValue());
    }
    resource.delete(true, null);
    copyResource.delete(true, null);
}
 
Example 4
Source File: ResourceUtilTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test {@link ResourceUtil#getLocation(IResource)}
 *
 * Most test cases are handled in {@link #testCreateSymbolicLink()} when
 * creating and verifying links
 *
 * @throws IOException
 *             if an IO error occurs
 * @throws CoreException
 *             if core error occurs
 */
@Test
public void testGetLocation() throws IOException, CoreException {
    // Create file and check for link
    IResource resource = createAndVerifyResource(TEST_FILE_NAME, true);
    verifyLocation(resource.getLocation(), resource);
    resource.delete(true, null);

    // Create folder and check for link
    resource = createAndVerifyResource(TEST_FOLDER_NAME, false);
    verifyLocation(resource.getLocation(), resource);
    resource.delete(true, null);

    // Null resource
    assertNull(ResourceUtil.getLocation(null));
}
 
Example 5
Source File: ResourceUtil.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private static boolean checkResource(IResource link, Path linkPath) throws CoreException, IOException {
    if (link.exists()) {
        // Eclipse resource already exists
        if (link.isLinked() ||
                Files.isSymbolicLink(linkPath)) {
            // Remove the link
            link.delete(true, null);
        } else {
            // Abort because folder or file exists
            return false;
        }
    }
    if (Files.isSymbolicLink(linkPath)) {
        // Delete the broken file system symbolic link
        Files.delete(linkPath);
    } else if (linkPath.toFile().exists()) {
        // Abort because folder or file exists
        return false;
    }
    return true;
}
 
Example 6
Source File: ResourceUtil.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Delete a broken symbolic link. Has no effect if the resource is not a
 * symbolic link or if the target of the symbolic link exists.
 *
 * @param resource
 *            the resource in the workspace.
 * @throws CoreException
 *             if an error occurs
 */
public static void deleteIfBrokenSymbolicLink(@Nullable IResource resource) throws CoreException {
    if (resource == null) {
        return;
    }
    if (resource.isLinked()) {
        IPath location = resource.getLocation();
        if (location == null || !location.toFile().exists()) {
            resource.delete(true, null);
        }
    } else {
        URI uri = resource.getLocationURI();
        if (uri != null) {
            Path linkPath = Paths.get(uri);
            if (Files.isSymbolicLink(linkPath) && !resource.exists()) {
                try {
                    Files.delete(linkPath);
                } catch (Exception e) {
                    // Do nothing.
                }
            }
        }
    }
}
 
Example 7
Source File: SelectTracesOperationTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Delete the experiment after each tests.
 */
@After
public void cleanUp() {
    TmfExperimentFolder experimentsFolder = fProjectElement.getExperimentsFolder();
    if (experimentsFolder != null) {
        IResource experimentResource = fExperiment.getResource();
        IPath path = experimentResource.getLocation();
        if (path != null) {
            fExperiment.deleteSupplementaryFolder();
        }

        try {
            experimentResource.delete(true, null);
        } catch (CoreException e) {
            Activator.getDefault().logError("Unable to delete experiment: " + fExperiment.getName(), e);
        }
    }
}
 
Example 8
Source File: ReplaceOperation.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected void execute(SVNTeamProvider provider, IResource[] resources, IProgressMonitor monitor) throws SVNException, InterruptedException {
      monitor.beginTask(null, 100);
try {
	boolean removeUnAdded  = SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_REMOVE_UNADDED_RESOURCES_ON_REPLACE);
          // first we revert to base (otherwise it will do a merge instead of
          // replace resources)
    for (int i = 0; i < resources.length; i++) {
              IResource resource = resources[i];

              ISVNLocalResource localResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
              if(!localResource.isManaged() && removeUnAdded)
      			{
      				try
  					{
  						resource.delete(true, monitor);
  					}
  					catch (CoreException ex)
  					{
  						throw SVNException.wrapException(ex);
  					}
      			}
              else if (localResource.isDirty()) {
             	 	localResource.revert();
              }
              if (!this.revision.equals(SVNRevision.BASE)) {
              	IResource[] updateResources = { resource };
              	super.execute(provider, updateResources, monitor);
              }
          }
} catch (SVNException e) {
	if (e.operationInterrupted()) {
		showCancelledMessage();
	} else {
		collectStatus(e.getStatus());
	}
} finally {
	monitor.done();
}
  }
 
Example 9
Source File: RebuildAffectedResourcesTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@After
@Override
public void tearDown() {
  try {
    this.workbenchTestHelper.tearDown();
    for (final IResource res : this.cleanUp) {
      boolean _exists = res.exists();
      if (_exists) {
        res.delete(true, null);
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 10
Source File: AbstractDefFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void delete() {
 for (IResource localeResource : retrieveLocaleResources(getContent())) {
  try {
	  localeResource.delete(true, new NullProgressMonitor());
  } catch (CoreException e) {
	  BonitaStudioLog.error(e);
  }
 }
 super.delete();
}
 
Example 11
Source File: AbstractFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected void doDelete() {
    try {
        final IResource r = getResource();
        if (r != null && r.exists()) {
            r.delete(true, Repository.NULL_PROGRESS_MONITOR);
        }
    } catch (final CoreException e) {
        BonitaStudioLog.error(e);
    }
}
 
Example 12
Source File: ResourceUtilTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test {@link ResourceUtil#deleteIfBrokenSymbolicLink(IResource)}
 *
 * @throws IOException
 *             if an IO error occurs
 * @throws CoreException
 *             if core error occurs
 */
@Test
public void testDeleteIfBrokenSymbolicLink() throws IOException, CoreException {
    // Create file
    IResource resource = createAndVerifyResource(TEST_FILE_NAME, true);
    // No effect: resource is not a symbolic link
    ResourceUtil.deleteIfBrokenSymbolicLink(resource);
    assertTrue(resource.exists());
    resource.delete(true, null);

    IPath path = new Path(fTargetFile.getAbsolutePath());

    // Create file system symbolic link to a file
    boolean isSymLink = !IS_WINDOWS;
    resource = createAndVerifyLink(path, SYMBOLIC_LINK_FILE_NAME, true, isSymLink);
    // No effect: link target exists
    ResourceUtil.deleteIfBrokenSymbolicLink(resource);
    assertTrue(resource.exists());
    // Broken link is deleted
    fTargetFile.delete();
    fTestFolder.refreshLocal(IResource.DEPTH_ONE, null);
    ResourceUtil.deleteIfBrokenSymbolicLink(resource);
    assertFalse(resource.exists());

    // Re-create target file
    fTargetFile = fTemporaryFolder.newFile(LINK_TARGET_FILE).getCanonicalFile();

    // Create Eclipse link to a file
    resource = createAndVerifyLink(path, ECLIPSE_LINK_FILE_NAME, true, false);
    // No effect: link target exists
    ResourceUtil.deleteIfBrokenSymbolicLink(resource);
    assertTrue(resource.exists());
    // Broken link is deleted
    fTargetFile.delete();
    ResourceUtil.deleteIfBrokenSymbolicLink(resource);
    assertFalse(resource.exists());

    // Re-create target file
    fTargetFile = fTemporaryFolder.newFile(LINK_TARGET_FILE).getCanonicalFile();
}
 
Example 13
Source File: FileTransferDragAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void handleDropMove() {
	final List<IResource> elements= getResources();
	if (elements == null || elements.size() == 0)
		return;

	WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
		@Override
		public void execute(IProgressMonitor monitor) throws CoreException {
			try {
				monitor.beginTask(PackagesMessages.DragAdapter_deleting, elements.size());
				MultiStatus status= createMultiStatus();
				Iterator<IResource> iter= elements.iterator();
				while(iter.hasNext()) {
					IResource resource= iter.next();
					try {
						monitor.subTask(BasicElementLabels.getPathLabel(resource.getFullPath(), true));
						resource.delete(true, null);

					} catch (CoreException e) {
						status.add(e.getStatus());
					} finally {
						monitor.worked(1);
					}
				}
				if (!status.isOK()) {
					throw new CoreException(status);
				}
			} finally {
				monitor.done();
			}
		}
	};
	runOperation(op, true, false);
}
 
Example 14
Source File: TmfCommonProjectElement.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Copy this model element to the destinationPath
 *
 * @param copySuppFiles
 *            Whether to copy supplementary files or not
 * @param copyAsLink
 *            Whether to copy as a link or not
 * @param destinationPath
 *            The path where the element will be copied
 * @return the new Resource object
 * @since 3.3
 */
public IResource copy(final boolean copySuppFiles, final boolean copyAsLink, IPath destinationPath) {
    /* Copy supplementary files first, only if needed */
    if (copySuppFiles) {
        String newElementPath = getDestinationPathRelativeToParent(destinationPath);
        copySupplementaryFolder(newElementPath);
    }
    /* Copy the trace */
    try {
        int flags = IResource.FORCE;
        if (copyAsLink) {
            flags |= IResource.SHALLOW;
        }

        IResource trace = ResourceUtil.copyResource(getResource(), destinationPath, flags, null);

        /* Delete any bookmarks file found in copied trace folder */
        if (trace instanceof IFolder) {
            IFolder folderTrace = (IFolder) trace;
            for (IResource member : folderTrace.members()) {
                String traceTypeId = TmfTraceType.getTraceTypeId(member);
                if (ITmfEventsEditorConstants.TRACE_INPUT_TYPE_CONSTANTS.contains(traceTypeId)
                        || ITmfEventsEditorConstants.EXPERIMENT_INPUT_TYPE_CONSTANTS.contains(traceTypeId)) {
                    member.delete(true, null);
                }
            }
        }
        return trace;
    } catch (CoreException e) {
        Activator.getDefault().logError("Error copying " + getName(), e); //$NON-NLS-1$
    }
    return null;
}
 
Example 15
Source File: FileUtils.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deletes the given resource and tries to store the existing resource to the Eclipse history
 * space.
 *
 * @param resource the resource to delete
 * @throws CoreException
 */
public static void delete(final IResource resource) throws CoreException {
  if (!resource.exists()) {
    log.warn("file for deletion does not exist: " + resource, new StackTrace());
    return;
  }

  resource.delete(IResource.KEEP_HISTORY, null);
}
 
Example 16
Source File: BuildPathsBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void removeOldClassfiles(IResource resource) throws CoreException {
	if (resource.isDerived()) {
		resource.delete(false, null);
	} else if (resource instanceof IContainer) {
		IResource[] members= ((IContainer) resource).members();
		for (int i= 0; i < members.length; i++) {
			removeOldClassfiles(members[i]);
		}
	}
}
 
Example 17
Source File: ImportConflictHandler.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private void delete(IPath tracePath, IProgressMonitor monitor) throws CoreException {
    IResource existingResource = getExistingResource(tracePath);
    if (existingResource == null) {
        return;
    }
    TmfTraceElement existingTraceElement = getExistingTrace(tracePath);
    if (existingTraceElement != null) {
        // Delete existing TmfTraceElement
        existingTraceElement.delete(monitor, true);
        return;
    }

    // Delete resource existing in workspace
    existingResource.delete(true, monitor);
}
 
Example 18
Source File: PlatformResourceURI.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void delete(Consumer<? super IOException> errorHandler) {
	try {
		IResource r = getCachedResource();
		if (r == null) {
			return;
		}
		r.delete(false, null);
	} catch (CoreException e) {
		errorHandler.accept(new IOException(e));
	}
}
 
Example 19
Source File: CommonCoreTest.java    From goclipse with Eclipse Public License 1.0 4 votes vote down vote up
public static void deleteResource(IResource resource) throws CoreException {
	resource.delete(false, new NullProgressMonitor());
}
 
Example 20
Source File: CoreTester.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This is a utility operation that returns the project of the given name
 * for the test. It removes any old test files from the project . It
 * attempts to create the project if it does not exist.
 *
 * @param name
 *            the name of the project to retrieve from the Workspace
 * @return the project
 */
public IProject getProject(String name) {

	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
	URI defaultProjectLocation = null;
	IProject project = null;
	String separator = System.getProperty("file.separator");

	// Setup the project space so that the output file can be checked.
	System.out.println("CoreTester Workspace Root = " + workspaceRoot.getLocation());
	System.out.println("Constructing project " + name);
	try {
		// Get the project handle
		project = workspaceRoot.getProject(name);
		// If the project does not exist, create it
		if (!project.exists()) {
			defaultProjectLocation = (new File(System.getProperty("user.dir") + separator + name)).toURI();
			// Create the project description
			IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(name);
			// Set the location of the project
			desc.setLocationURI(defaultProjectLocation);
			System.out.println("CoreTester Message: " + "Project location is " + desc.getLocationURI());
			// Create the project
			project.create(desc, null);
		}
		// Open the project if it is not already open
		if (project.exists() && !project.isOpen()) {
			project.open(null);
		}
	} catch (CoreException e) {
		// Catch for creating the project
		e.printStackTrace();
		fail();
	}

	// Clean out any old test files
	try {
		for (IResource resource : project.members()) {
			resource.delete(true, null);
		}
	} catch (CoreException e1) {
		// Complain
		e1.printStackTrace();
		fail();
	}

	return project;
}