Java Code Examples for org.eclipse.core.resources.IWorkspaceRoot#getFile()

The following examples show how to use org.eclipse.core.resources.IWorkspaceRoot#getFile() . 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: ProjectStateChangeListener.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void updateNpmIndex(IProgressMonitor monitor) throws CoreException {
	OutdatedPackageJsonQueue.Task task = packageJsonQueue.exhaust();
	if (task.isEmpty()) {
		return;
	}
	try {
		indexSynchronizer.checkAndClearIndex(monitor);
		Set<URI> toBeUpdated = task.getToBeBuilt().getToBeUpdated();
		IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
		for (URI touchMe : toBeUpdated) {
			if (touchMe.isPlatformResource()) {
				IFile file = workspaceRoot.getFile(new Path(touchMe.toPlatformString(true)));
				// could have been deleted in the meantime
				if (file.exists()) {
					file.touch(monitor);
				}
			}
		}
	} catch (Error | RuntimeException | CoreException e) {
		task.reschedule();
		throw e;
	} finally {
		monitor.done();
	}
}
 
Example 2
Source File: FixedFatJarExportPage.java    From sarl with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the absolute location relative to the workspace.
 * 
 * @param location the location
 * @return the absolute path for the location of the file
 * 
 * @since 3.8
 */
private IPath getAbsoluteLocation(IPath location) {
	if (location.isAbsolute())
		return location;

	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
	if (location.segmentCount() >= 2 && !"..".equals(location.segment(0))) { //$NON-NLS-1$
		IFile file= root.getFile(location);
		IPath absolutePath= file.getLocation();
		if (absolutePath != null) {
			return absolutePath;
		}
	}
	// The path does not exist in the workspace (e.g. because there's no such project).
	// Fallback is to just append the path to the workspace root.
	return root.getLocation().append(location);

}
 
Example 3
Source File: FlexExistingDeployArtifactStagingDelegate.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
public FlexExistingDeployArtifactStagingDelegate(IPath deployArtifact, IPath appEngineDirectory) {
  super(appEngineDirectory);
  Preconditions.checkNotNull(deployArtifact);
  Preconditions.checkArgument(!deployArtifact.isEmpty());
  Preconditions.checkArgument(deployArtifact.isAbsolute());
  Preconditions.checkArgument(appEngineDirectory.isAbsolute());
  this.deployArtifact = deployArtifact;

  // Compute SchedulingRule; will be the artifact itself, if inside the workspace.
  IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
  if (workspaceRoot.getLocation().isPrefixOf(deployArtifact)) {
    IPath relativeToWorkspace = deployArtifact.makeRelativeTo(workspaceRoot.getLocation());
    schedulingRule = workspaceRoot.getFile(relativeToWorkspace);
  } else {
    schedulingRule = null;  // Outside the workspace; we can't lock it.
  }
}
 
Example 4
Source File: FatJarPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the absolute location relative to the workspace.
 * 
 * @param location the location
 * @return the absolute path for the location of the file
 * 
 * @since 3.8
 */
private IPath getAbsoluteLocation(IPath location) {
	if (location.isAbsolute())
		return location;

	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
	if (location.segmentCount() >= 2 && !"..".equals(location.segment(0))) { //$NON-NLS-1$
		IFile file= root.getFile(location);
		IPath absolutePath= file.getLocation();
		if (absolutePath != null) {
			return absolutePath;
		}
	}
	// The path does not exist in the workspace (e.g. because there's no such project).
	// Fallback is to just append the path to the workspace root.
	return root.getLocation().append(location);

}
 
Example 5
Source File: JarPackageData.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the absolute location of the JAR file.
 * This path is normally external to the workspace.
 *
 * @return the absolute path representing the location of the JAR file
 *
 * @since 3.0
 */
public IPath getAbsoluteJarLocation() {
	if (!fJarLocation.isAbsolute()) {
		IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		if (fJarLocation.segmentCount() >= 2 && !"..".equals(fJarLocation.segment(0))) { //$NON-NLS-1$
			// reverse of AbstractJarDestinationWizardPage#handleDestinationBrowseButtonPressed()
			IFile file= root.getFile(fJarLocation);
			IPath absolutePath= file.getLocation();
			if (absolutePath != null) {
				return absolutePath;
			}
		}
		// The path does not exist in the workspace (e.g. because there's no such project).
		// Fallback is to just append the path to the workspace root.
		return root.getLocation().append(fJarLocation);
	}
	return fJarLocation;
}
 
Example 6
Source File: WorkbenchResourceUtil.java    From typescript.java with MIT License 5 votes vote down vote up
public static IFile findFileFromWorkspace(IPath filePath) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	IFile file = root.getFile(filePath);
	if (file.exists()) {
		return file;
	}
	IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(filePath);
	if (files.length > 0) {
		file = files[0];
		if (file.exists()) {
			return file;
		}
	}
	return null;
}
 
Example 7
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a file or folder handle for the source resource as if it were to
 * be created in the destination container.
 *
 * @param destination
 *            destination container
 * @param source
 *            source resource
 * @return IResource file or folder handle, depending on the source type.
 */
IResource createLinkedResourceHandle(IContainer destination, IResource source) {
    IWorkspace workspace = destination.getWorkspace();
    IWorkspaceRoot workspaceRoot = workspace.getRoot();
    IPath linkPath = destination.getFullPath().append(source.getName());
    IResource linkHandle;

    if (source.getType() == IResource.FOLDER) {
        linkHandle = workspaceRoot.getFolder(linkPath);
    } else {
        linkHandle = workspaceRoot.getFile(linkPath);
    }
    return linkHandle;
}
 
Example 8
Source File: DocumentUtils.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Opens the editor for the file located at the given path and reveal the selection.
 * 
 * @param path
 * @param selection
 */
public static void openAndReveal(IPath path, ISelection selection) {
    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    final IFile file = root.getFile(path);
    final IEditorPart editor = openEditor(file);

    if (editor instanceof IShowInTarget) {
        IShowInTarget showIn = (IShowInTarget) editor;
        showIn.show(new ShowInContext(null, selection));
    }
}
 
Example 9
Source File: ResourceUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a file at the given workspace-relative path with the contents from
 * the {@link InputStream}. If the file already exists, then a CoreException
 * will be thrown.
 */
public static IFile createFile(IPath path, InputStream contents)
    throws CoreException {
  IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
  IFile file = root.getFile(path);
  file.create(contents, false, null);
  return file;
}
 
Example 10
Source File: ParallelResourceLoader.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Make sure that all files that are about to be loaded are synchronized with the file system
 */
private void synchronizeResources(Collection<URI> toLoad) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	for(URI uri : toLoad) {
		if (uri.isPlatformResource()) {
			Path path = new Path(uri.toPlatformString(true));
			IFile file = root.getFile(path);
			try {
				file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
 
Example 11
Source File: XmlSourceValidator.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static IFile getFile(String filePath) {
  IPath path = new Path(filePath);
  if (path.segmentCount() > 1) {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile file = root.getFile(path);
    if (file != null && file.exists()) {
      return file;
    }
  }
  return null;
}
 
Example 12
Source File: ContentTypeHelper.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the content of the given buffer.
 * 
 * @param buffer
 * @return the content of the given buffer.
 * @throws CoreException
 */
private static InputStream getContents(ITextFileBuffer buffer) throws CoreException {
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
	IFile file = workspaceRoot.getFile(buffer.getLocation());
	if (file.exists() && buffer.isSynchronized()) {
		return file.getContents();
	}
	return buffer.getFileStore().openInputStream(EFS.NONE, null);
}
 
Example 13
Source File: ProjectConfigurationWorkingCopy.java    From eclipse-cs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Writes a local check configuration.
 *
 * @param checkConfig
 *          the local check configuration
 * @param docRoot
 *          the root element of the project configuration
 */
private void writeLocalConfiguration(ICheckConfiguration checkConfig, Element docRoot) {

  // TODO refactor to avoid code duplication with
  // GlobalCheckConfigurationWorkingSet

  // don't store built-in configurations to persistence or local
  // configurations
  if (checkConfig.getType() instanceof BuiltInConfigurationType || checkConfig.isGlobal()) {
    return;
  }

  // RFE 1420212
  String location = checkConfig.getLocation();
  if (checkConfig.getType() instanceof ProjectConfigurationType) {
    IProject project = mProjectConfig.getProject();
    IWorkspaceRoot root = project.getWorkspace().getRoot();
    IFile configFile = root.getFile(new Path(location));
    IProject configFileProject = configFile.getProject();

    // if the configuration is in *same* project don't store project
    // path part
    if (project.equals(configFileProject)) {
      location = configFile.getProjectRelativePath().toString();
    }
  }

  Element configEl = docRoot.addElement(XMLTags.CHECK_CONFIG_TAG);
  configEl.addAttribute(XMLTags.NAME_TAG, checkConfig.getName());
  configEl.addAttribute(XMLTags.LOCATION_TAG, location);
  configEl.addAttribute(XMLTags.TYPE_TAG, checkConfig.getType().getInternalName());
  if (checkConfig.getDescription() != null) {
    configEl.addAttribute(XMLTags.DESCRIPTION_TAG, checkConfig.getDescription());
  }

  // Write resolvable properties
  for (ResolvableProperty prop : checkConfig.getResolvableProperties()) {

    Element propEl = configEl.addElement(XMLTags.PROPERTY_TAG);
    propEl.addAttribute(XMLTags.NAME_TAG, prop.getPropertyName());
    propEl.addAttribute(XMLTags.VALUE_TAG, prop.getValue());
  }

  // Write additional data
  for (Map.Entry<String, String> entry : checkConfig.getAdditionalData().entrySet()) {

    Element addEl = configEl.addElement(XMLTags.ADDITIONAL_DATA_TAG);
    addEl.addAttribute(XMLTags.NAME_TAG, entry.getKey());
    addEl.addAttribute(XMLTags.VALUE_TAG, entry.getValue());
  }
}
 
Example 14
Source File: XdsRenameResourceChange.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
public Change perform(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask(RefactoringCoreMessages.RenameResourceChange_progress_description, 1);

		IResource resource= getResource();
		File absoluteFile = ResourceUtils.getAbsoluteFile(resource);
		IPath destPath = renamedResourcePath(resource.getRawLocation(), fNewName);
		
		boolean isLinked = resource.isLinked();
		
		long currentStamp= resource.getModificationStamp();
		IPath newPath= renamedResourcePath(fResourcePath, fNewName);
		IFile destIFile = ResourceUtils.getWorkspaceRoot().getFile(newPath);
		Change undoDeleteChange = null;
		if (destIFile.exists()) { // handle rename conflict 
			DeleteResourceChange deleteChange = new DeleteResourceChange(destIFile.getFullPath(), true);
			undoDeleteChange = deleteChange.perform(pm);
		}
		
		resource.move(newPath, IResource.SHALLOW, pm);
		
		if (isLinked) {
			File dest = destPath.toFile();
			FileUtils.deleteQuietly(dest);
			absoluteFile.renameTo(dest);
			
			// get the resource again since after move resource can be inadequate
			IWorkspaceRoot workspaceRoot = ResourceUtils.getWorkspaceRoot();
			resource = workspaceRoot.getFile(newPath);
			((IFile)resource).createLink(destPath, IResource.REPLACE, new NullProgressMonitor());
		}
		if (fStampToRestore != IResource.NULL_STAMP) {
			IResource newResource= ResourcesPlugin.getWorkspace().getRoot().findMember(newPath);
			newResource.revertModificationStamp(fStampToRestore);
		}
		String oldName= fResourcePath.lastSegment();
		XdsRenameResourceChange undoRenameChange = new XdsRenameResourceChange(newPath, oldName, currentStamp);
		if (undoDeleteChange == null) {
			return undoRenameChange;
		}
		else {
			return new CompositeChange(getName(), new Change[]{undoRenameChange, undoDeleteChange}); // constructing undo changes
		}
	} finally {
		pm.done();
	}
}
 
Example 15
Source File: SVNWorkspaceRoot.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
* Returns workspace resource for the given local file system <code>location</code>
* and which is a child of the given <code>parent</code> resource. Returns
* <code>parent</code> if parent's file system location equals to the given
* <code>location</code>. Returns <code>null</code> if <code>parent</code> is the
* workspace root.
*
* Resource does not have to exist in the workspace in which case resource
* type will be determined by the type of the local filesystem object.
*/
  public static IResource getResourceFor(IResource parent, IPath location) {
  	if (parent == null || location == null) {
  		return null;
  	}

  	if (parent instanceof IWorkspaceRoot) {
  		return null;
  	}

  	if (!isManagedBySubclipse(parent.getProject())) {
  		return null;
  	}

  	if (!parent.getLocation().isPrefixOf(location)) {
  		return null;
  	}

int segmentsToRemove = parent.getLocation().segmentCount();
  	IPath fullPath = parent.getFullPath().append(location.removeFirstSegments(segmentsToRemove));

  	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

  	IResource resource = root.findMember(fullPath,true);

  	if (resource != null) {
  		return resource;
  	}

  	if (parent instanceof IFile) {
  		return null;
  	}

if (fullPath.isRoot()) {
	return root;
} else if (fullPath.segmentCount() == 1) {
	return root.getProject(fullPath.segment(0));
}

if (!location.toFile().exists()) {
	if (location.toFile().getName().indexOf(".") == -1) {
		return root.getFolder(fullPath);
	}
}

if (location.toFile().isDirectory()) {
	return root.getFolder(fullPath);
}

return root.getFile(fullPath);
  }
 
Example 16
Source File: ResourceURIConverter.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public IFile toFile(URI uri) {
	IWorkspaceRoot root = workspace.getRoot();
	return root.getFile(new Path(uri.toPlatformString(true)));
}
 
Example 17
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @param path IPath
 * @return A handle to the package fragment root identified by the given path.
 * This method is handle-only and the element may or may not exist. Returns
 * <code>null</code> if unable to generate a handle from the path (for example,
 * an absolute path that has less than 1 segment. The path may be relative or
 * absolute.
 */
public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
	if (!path.isAbsolute()) {
		path = getPath().append(path);
	}
	int segmentCount = path.segmentCount();
	if (segmentCount == 0) {
		return null;
	}
	if (path.getDevice() != null || JavaModel.getExternalTarget(path, true/*check existence*/) != null) {
		// external path
		return getPackageFragmentRoot0(path);
	}
	IWorkspaceRoot workspaceRoot = this.project.getWorkspace().getRoot();
	IResource resource = workspaceRoot.findMember(path);
	if (resource == null) {
		// resource doesn't exist in workspace
		if (path.getFileExtension() != null) {
			if (!workspaceRoot.getProject(path.segment(0)).exists()) {
				// assume it is an external ZIP archive
				return getPackageFragmentRoot0(path);
			} else {
				// assume it is an internal ZIP archive
				resource = workspaceRoot.getFile(path);
			}
		} else if (segmentCount == 1) {
			// assume it is a project
			String projectName = path.segment(0);
			if (getElementName().equals(projectName)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75814
				// default root
				resource = this.project;
			} else {
				// lib being another project
				resource = workspaceRoot.getProject(projectName);
			}
		} else {
			// assume it is an internal folder
			resource = workspaceRoot.getFolder(path);
		}
	}
	return getPackageFragmentRoot(resource);
}
 
Example 18
Source File: CrossflowDiagramEditor.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
/**
* @generated
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
	Shell shell = getSite().getShell();
	IEditorInput input = getEditorInput();
	SaveAsDialog dialog = new SaveAsDialog(shell);
	IFile original = input instanceof IFileEditorInput ? ((IFileEditorInput) input).getFile() : null;
	if (original != null) {
		dialog.setOriginalFile(original);
	}
	dialog.create();
	IDocumentProvider provider = getDocumentProvider();
	if (provider == null) {
		// editor has been programmatically closed while the dialog was open
		return;
	}
	if (provider.isDeleted(input) && original != null) {
		String message = NLS.bind(Messages.CrossflowDiagramEditor_SavingDeletedFile, original.getName());
		dialog.setErrorMessage(null);
		dialog.setMessage(message, IMessageProvider.WARNING);
	}
	if (dialog.open() == Window.CANCEL) {
		if (progressMonitor != null) {
			progressMonitor.setCanceled(true);
		}
		return;
	}
	IPath filePath = dialog.getResult();
	if (filePath == null) {
		if (progressMonitor != null) {
			progressMonitor.setCanceled(true);
		}
		return;
	}
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
	IFile file = workspaceRoot.getFile(filePath);
	final IEditorInput newInput = new FileEditorInput(file);
	// Check if the editor is already open
	IEditorMatchingStrategy matchingStrategy = getEditorDescriptor().getEditorMatchingStrategy();
	IEditorReference[] editorRefs = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
			.getEditorReferences();
	for (int i = 0; i < editorRefs.length; i++) {
		if (matchingStrategy.matches(editorRefs[i], newInput)) {
			MessageDialog.openWarning(shell, Messages.CrossflowDiagramEditor_SaveAsErrorTitle,
					Messages.CrossflowDiagramEditor_SaveAsErrorMessage);
			return;
		}
	}
	boolean success = false;
	try {
		provider.aboutToChange(newInput);
		getDocumentProvider(newInput).saveDocument(progressMonitor, newInput,
				getDocumentProvider().getDocument(getEditorInput()), true);
		success = true;
	} catch (CoreException x) {
		IStatus status = x.getStatus();
		if (status == null || status.getSeverity() != IStatus.CANCEL) {
			ErrorDialog.openError(shell, Messages.CrossflowDiagramEditor_SaveErrorTitle,
					Messages.CrossflowDiagramEditor_SaveErrorMessage, x.getStatus());
		}
	} finally {
		provider.changed(newInput);
		if (success) {
			setInput(newInput);
		}
	}
	if (progressMonitor != null) {
		progressMonitor.setCanceled(!success);
	}
}
 
Example 19
Source File: ProcessDiagramEditor.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
/**
* @generated
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
	Shell shell = getSite().getShell();
	IEditorInput input = getEditorInput();
	SaveAsDialog dialog = new SaveAsDialog(shell);
	IFile original = input instanceof IFileEditorInput ? ((IFileEditorInput) input).getFile() : null;
	if (original != null) {
		dialog.setOriginalFile(original);
	}
	dialog.create();
	IDocumentProvider provider = getDocumentProvider();
	if (provider == null) {
		// editor has been programmatically closed while the dialog was open
		return;
	}
	if (provider.isDeleted(input) && original != null) {
		String message = NLS.bind(Messages.ProcessDiagramEditor_SavingDeletedFile, original.getName());
		dialog.setErrorMessage(null);
		dialog.setMessage(message, IMessageProvider.WARNING);
	}
	if (dialog.open() == Window.CANCEL) {
		if (progressMonitor != null) {
			progressMonitor.setCanceled(true);
		}
		return;
	}
	IPath filePath = dialog.getResult();
	if (filePath == null) {
		if (progressMonitor != null) {
			progressMonitor.setCanceled(true);
		}
		return;
	}
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
	IFile file = workspaceRoot.getFile(filePath);
	final IEditorInput newInput = new FileEditorInput(file);
	// Check if the editor is already open
	IEditorMatchingStrategy matchingStrategy = getEditorDescriptor().getEditorMatchingStrategy();
	IEditorReference[] editorRefs = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
			.getEditorReferences();
	for (int i = 0; i < editorRefs.length; i++) {
		if (matchingStrategy.matches(editorRefs[i], newInput)) {
			MessageDialog.openWarning(shell, Messages.ProcessDiagramEditor_SaveAsErrorTitle,
					Messages.ProcessDiagramEditor_SaveAsErrorMessage);
			return;
		}
	}
	boolean success = false;
	try {
		provider.aboutToChange(newInput);
		getDocumentProvider(newInput).saveDocument(progressMonitor, newInput,
				getDocumentProvider().getDocument(getEditorInput()), true);
		success = true;
	} catch (CoreException x) {
		IStatus status = x.getStatus();
		if (status == null || status.getSeverity() != IStatus.CANCEL) {
			ErrorDialog.openError(shell, Messages.ProcessDiagramEditor_SaveErrorTitle,
					Messages.ProcessDiagramEditor_SaveErrorMessage, x.getStatus());
		}
	} finally {
		provider.changed(newInput);
		if (success) {
			setInput(newInput);
		}
	}
	if (progressMonitor != null) {
		progressMonitor.setCanceled(!success);
	}
}