Java Code Examples for org.eclipse.core.runtime.IPath#makeRelativeTo()

The following examples show how to use org.eclipse.core.runtime.IPath#makeRelativeTo() . 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: 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 2
Source File: SARLProposalProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static String extractProjectPath(IPath fileWorkspacePath, IJavaProject javaProject) {
	if (javaProject != null && javaProject.exists() && javaProject.isOpen()) {
		try {
			for (final IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
				if (!root.isArchive() && !root.isExternal()) {
					final IResource resource = root.getResource();
					if (resource != null) {
						final IPath sourceFolderPath = resource.getFullPath();
						if (sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
							final IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
							return claspathRelativePath.removeLastSegments(1)
									.toString().replace("/", "."); //$NON-NLS-1$//$NON-NLS-2$
						}
					}
				}
			}
		} catch (JavaModelException e) {
			Logger.getLogger(SARLProposalProvider.class).error(e.getLocalizedMessage(), e);
		}
	}
	return null;
}
 
Example 3
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private IPath computeDestinationContainerPath(Path resourcePath) {
    IPath destinationContainerPath = fDestinationContainerPath;

    // We need to figure out the new destination path relative to the
    // selected "base" source directory.
    // Here for example, the selected source directory is /home/user
    if ((fImportOptionFlags & ImportTraceWizardPage.OPTION_PRESERVE_FOLDER_STRUCTURE) != 0) {
        // /home/user/bar/foo/trace -> /home/user/bar/foo
        IPath sourceContainerPath = resourcePath.removeLastSegments(1);
        if (fBaseSourceContainerPath.equals(resourcePath)) {
            // Use resourcePath directory if fBaseSourceContainerPath
            // points to a directory trace
            sourceContainerPath = resourcePath;
        }
        // /home/user/bar/foo, /home/user -> bar/foo
        IPath relativeContainerPath = sourceContainerPath.makeRelativeTo(fBaseSourceContainerPath);
        // project/Traces + bar/foo -> project/Traces/bar/foo
        destinationContainerPath = fDestinationContainerPath.append(relativeContainerPath);
    }
    return destinationContainerPath;
}
 
Example 4
Source File: FolderStub.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IPath getFullPath() {
    //        return Path.fromOSString(FileUtils.getFileAbsolutePath(this.folder));
    String fileAbsolutePath = FileUtils.getFileAbsolutePath(this.folder);
    String workspaceAbsolutePath = FileUtils.getFileAbsolutePath(this.project.getProjectRoot().getParentFile());

    IPath fromOSString = Path.fromOSString(fileAbsolutePath);
    IPath workspace = Path.fromOSString(workspaceAbsolutePath);
    return fromOSString.makeRelativeTo(workspace);
}
 
Example 5
Source File: FlexExistingArtifactDeployCommandHandlerTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void setUpDeployPreferences(boolean asRelativePath) throws BackingStoreException {
  IPath workspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
  IPath appYaml = projectCreator.getProject().getFile("app.yaml").getLocation();
  IPath jar = projectCreator.getProject().getFile("my-app.jar").getLocation();

  if (asRelativePath) {
    appYaml = appYaml.makeRelativeTo(workspace);
    jar = jar.makeRelativeTo(workspace);
  }

  preferences.setAppYamlPath(appYaml.toString());
  preferences.setDeployArtifactPath(jar.toString());
  preferences.save();
}
 
Example 6
Source File: Animator.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private void addAnimationMarker(EObject eobject) {
	IResource resource = null;
	IWorkspace workspace = ResourcesPlugin.getWorkspace(); 
	if (workspace != null) {
		URI uri = eobject.eResource().getURI();
		if (uri.isPlatform()) {
			resource = workspace.getRoot().getFile(new Path(uri.toPlatformString(true)));
		} else {
			IPath fs = new Path(uri.toFileString());
			for (IProject proj : workspace.getRoot().getProjects()) {
				if (proj.getLocation().isPrefixOf(fs)) {
					IPath relative = fs.makeRelativeTo(proj.getLocation());
					resource = proj.findMember(relative);
				}
			}
		}
	}
	if (resource != null && resource.exists()) {
		IMarker imarker = null;
		try {
			imarker = resource.createMarker(AnimationConfig.TXTUML_ANIMATION_MARKER_ID);
			imarker.setAttribute(EValidator.URI_ATTRIBUTE, URI.createPlatformResourceURI(resource.getFullPath().toString(), true) + "#" + EcoreUtil.getURI(eobject).fragment());
		} catch (CoreException e) {
			e.printStackTrace();
		}
		if (imarker != null) {
			IPapyrusMarker marker = PapyrusMarkerAdapter.wrap(eobject.eResource(), imarker);
			eobjectToMarker.put(eobject, marker);
		}
	}
}
 
Example 7
Source File: EFSUtils.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getRelativePath
 * 
 * @param parentFileStore
 * @param childFileStore
 * @return
 */
public static IPath getRelativePath(IFileStore parentFileStore, IFileStore childFileStore)
{
	if (parentFileStore.isParentOf(childFileStore))
	{
		IPath parentPath = Path.fromPortableString(parentFileStore.toURI().getPath());
		IPath childPath = Path.fromPortableString(childFileStore.toURI().getPath());
		return childPath.makeRelativeTo(parentPath);
	}
	return null;
}
 
Example 8
Source File: WorkspaceModelsManager.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param filePath
 * @return
 */
private IFile findInWorkspace(final IPath originalPath) {
	// GAMA.getGui().debug("WorkspaceModelsManager.findInWorkspace " + originalPath);
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	final IPath workspacePath = new Path(Platform.getInstanceLocation().getURL().getPath());
	final IPath filePath = originalPath.makeRelativeTo(workspacePath);
	IFile file = null;
	try {
		file = workspace.getRoot().getFile(filePath);
	} catch (final Exception e) {
		return null;
	}
	if ( !file.exists() ) { return null; }
	return file;
}
 
Example 9
Source File: GamlEditorDragAndDropHandler.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private String obtainRelativePath(final IFile file) {
	final IPath path = file.getFullPath();
	final IPath editorFile = new Path(editor.getURI().toPlatformString(true)).removeLastSegments(1);
	final IPath newRelativePath = path.makeRelativeTo(editorFile);
	final String name = newRelativePath.toString();
	return name;
}
 
Example 10
Source File: XtendUIValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected String getExpectedPackageName(XtendFile xtendFile) {
	URI fileURI = xtendFile.eResource().getURI();
	for(Pair<IStorage, IProject> storage: storage2UriMapper.getStorages(fileURI)) {
		if(storage.getFirst() instanceof IFile) {
			IPath fileWorkspacePath = storage.getFirst().getFullPath();
			IJavaProject javaProject = JavaCore.create(storage.getSecond());
			if(javaProject != null && javaProject.exists() && javaProject.isOpen()) {
				try {
					for(IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
						if(!root.isArchive() && !root.isExternal()) {
							IResource resource = root.getResource();
							if(resource != null) {
								IPath sourceFolderPath = resource.getFullPath();
								if(sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
									IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
									return claspathRelativePath.removeLastSegments(1).toString().replace("/", ".");
								}
							}
						}
					}
				} catch (JavaModelException e) {
					LOG.error("Error resolving expected path for XtendFile", e);
				}
			}
		}
	}
	return null;
}
 
Example 11
Source File: FindBugsWorker.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param filePath
 *            path (eventually absolute) to a file
 * @param commonPath
 *            absolute path of some common location
 * @return path relative to common root if given path is contained under the
 *         common directory, otherwise unchanged path
 */
private static IPath getRelativePath(IPath filePath, IPath commonPath) {
    if (!filePath.isAbsolute()) {
        return filePath;
    }
    // since Equinox 3.5 we can use IPath.makeRelativeTo(IPath)
    IPath relativeTo = filePath.makeRelativeTo(commonPath);
    return relativeTo;
}
 
Example 12
Source File: InvisibleProjectImporter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static String inferPackageNameFromPath(IPath javaFile, IPath workspaceRoot, String[][] srcPrefixes) {
	IPath parentPath = javaFile.removeTrailingSeparator().removeLastSegments(1);
	IPath relativePath = parentPath.makeRelativeTo(workspaceRoot);
	List<String> segments = Arrays.asList(relativePath.segments());
	for (int i = 0; i < srcPrefixes.length; i++) {
		int index = Collections.indexOfSubList(segments, Arrays.asList(srcPrefixes[i]));
		if (index > -1) {
			return String.join(JDTUtils.PERIOD, segments.subList(index + srcPrefixes[i].length, segments.size()));
		}
	}

	return String.join(JDTUtils.PERIOD, segments);
}
 
Example 13
Source File: BuildPathCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IPath getWorkspacePath(IPath path) {
	PreferenceManager manager = JavaLanguageServerPlugin.getPreferencesManager();
	Collection<IPath> rootPaths = manager.getPreferences().getRootPaths();
	if (rootPaths != null) {
		for (IPath rootPath : rootPaths) {
			if (rootPath.isPrefixOf(path)) {
				return path.makeRelativeTo(rootPath.append(".."));
			}
		}
	}

	return path;
}
 
Example 14
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeGrammar_Name(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	Resource resource = model.eResource();
	URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		IPath path = new Path(uri.toPlatformString(true));
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		IProject project = file.getProject();
		IJavaProject javaProject = JavaCore.create(project);
		if (javaProject != null) {
			try {
				for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
					IPath packageFragmentRootPath = packageFragmentRoot.getPath();
					if (packageFragmentRootPath.isPrefixOf(path)) {
						IPath relativePath = path.makeRelativeTo(packageFragmentRootPath);
						relativePath = relativePath.removeFileExtension();
						String result = relativePath.toString();
						result = result.replace('/', '.');
						acceptor.accept(createCompletionProposal(result, context));
						return;
					}
				}
			} catch (JavaModelException ex) {
				// nothing to do
			}
		}
	}
}
 
Example 15
Source File: FileStub.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public IPath getFullPath() {
    IPath projectPath = Path.fromOSString(FileUtils.getFileAbsolutePath(project.getProjectRoot()));
    IPath filePath = Path.fromOSString(FileUtils.getFileAbsolutePath(file));
    return filePath.makeRelativeTo(projectPath);
}
 
Example 16
Source File: BuildPathCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static Result listSourcePaths() {
	List<SourcePath> sourcePathList = new ArrayList<>();
	IProject[] projects = ProjectUtils.getAllProjects();
	for (IProject project : projects) {
		if (!ProjectsManager.DEFAULT_PROJECT_NAME.equals(project.getName()) && ProjectUtils.isJavaProject(project)) {
			try {
				IPath[] paths = ProjectUtils.listSourcePaths(JavaCore.create(project));
				for (IPath path : paths) {
					IPath entryPath = path;
					String projectName = project.getName();
					String projectType = "General";
					if (ProjectUtils.isMavenProject(project)) {
						projectType = "Maven";
					}

					if (ProjectUtils.isGradleProject(project)) {
						projectType = "Gradle";
					}

					IContainer projectRoot = project;
					if (!ProjectUtils.isVisibleProject(project)) {
						projectType = "Workspace";
						IFolder workspaceLinkFolder = project.getFolder(ProjectUtils.WORKSPACE_LINK);
						if (!workspaceLinkFolder.isLinked()) {
							continue;
						}

						projectRoot = workspaceLinkFolder;
					}

					IPath relativePath = entryPath.makeRelativeTo(projectRoot.getFullPath());
					IPath location = projectRoot.getRawLocation().append(relativePath);
					IPath displayPath = getWorkspacePath(location);
					sourcePathList.add(new SourcePath(location != null ? location.toOSString() : "",
						displayPath != null ? displayPath.toOSString() : entryPath.toOSString(),
						entryPath.toOSString(),
						projectName,
						projectType));
				}
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.logException("Failed to resolve the existing source paths in current workspace.", e);
				return new ListCommandResult(false, e.getMessage());
			}
		}
	}

	return new ListCommandResult(true, null, sourcePathList.toArray(new SourcePath[0]));
}
 
Example 17
Source File: BuildPathCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static Result removeFromSourcePath(String sourceFolderUri) {
	IPath sourceFolderPath = ResourceUtils.filePathFromURI(sourceFolderUri);
	IProject targetProject = findBelongedProject(sourceFolderPath);
	if (targetProject != null && !ProjectUtils.isGeneralJavaProject(targetProject)) {
		String message = ProjectUtils.isGradleProject(targetProject) ? UNSUPPORTED_ON_GRADLE : UNSUPPORTED_ON_MAVEN;
		return new Result(false, message);
	}

	IPath projectLocation = null;
	IContainer projectRootResource = null;
	if (targetProject == null) {
		IPath workspaceRoot = ProjectUtils.findBelongedWorkspaceRoot(sourceFolderPath);
		if (workspaceRoot == null) {
			return new Result(false, Messages.format("The folder ''{0}'' doesn''t belong to any workspace.", getWorkspacePath(sourceFolderPath).toOSString()));
		}

		String invisibleProjectName = ProjectUtils.getWorkspaceInvisibleProjectName(workspaceRoot);
		targetProject = ResourcesPlugin.getWorkspace().getRoot().getProject(invisibleProjectName);
		if (!targetProject.exists()) {
			return new Result(true, Messages.format("No need to remove it from source path, because the folder ''{0}'' isn''t on any project''s source path.", getWorkspacePath(sourceFolderPath).toOSString()));
		}

		projectLocation = workspaceRoot;
		projectRootResource = targetProject.getFolder(ProjectUtils.WORKSPACE_LINK);
	} else {
		projectLocation = targetProject.getLocation();
		projectRootResource = targetProject;
	}

	IPath relativeSourcePath = sourceFolderPath.makeRelativeTo(projectLocation);
	IPath sourcePath = relativeSourcePath.isEmpty() ? projectRootResource.getFullPath() : projectRootResource.getFolder(relativeSourcePath).getFullPath();
	IJavaProject javaProject = JavaCore.create(targetProject);
	try {
		if (ProjectUtils.removeSourcePath(sourcePath, javaProject)) {
			return new Result(true, Messages.format("Successfully removed ''{0}'' from the project {1}''s source path.", new String[] { getWorkspacePath(sourceFolderPath).toOSString(), targetProject.getName() }));
		} else {
			return new Result(true, Messages.format("No need to remove it from source path, because the folder ''{0}'' isn''t on any project''s source path.", getWorkspacePath(sourceFolderPath).toOSString()));
		}
	} catch (CoreException e) {
		return new Result(false, e.getMessage());
	}
}
 
Example 18
Source File: LatexRunner.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Adds a problem marker
 * 
 * @param error The error or warning string
 * @param causingSourceFile name of the sourcefile
 * @param linenr where the error occurs
 * @param severity
 * @param resource
 * @param layout true, if this is a layout warning
 */
private void addProblemMarker(String error, String causingSourceFile,
        int linenr, int severity, IResource resource, boolean layout) {
    
    
	IProject project = resource.getProject();
    IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project);
    
    IResource extResource = null;
    if (causingSourceFile != null) {
    	IPath p = new Path(causingSourceFile);
    	
    	if (p.isAbsolute()) {
    		//Make absolute path relative to source directory
    		//or to the directory of the resource
    		if (sourceDir.getLocation().isPrefixOf(p)) {
    			p = p.makeRelativeTo(sourceDir.getLocation());
    		}
    		else if (resource.getParent().getLocation().isPrefixOf(p)) {
    			p = p.makeRelativeTo(resource.getParent().getLocation());
    		}
    	}

    	extResource = sourceDir.findMember(p);
        if (extResource == null) {
            extResource = resource.getParent().findMember(p);
        }
    }
    if (extResource == null)
        createMarker(resource, null, error + (causingSourceFile != null ? " (Occurance: "
                + causingSourceFile + ")" : ""), severity);
    else {
        if (linenr >= 0) {
            if (layout)
                createLayoutMarker(extResource, new Integer(linenr), error);
            else
                createMarker(extResource, new Integer(linenr), error, severity);
        } else
            createMarker(extResource, null, error, severity);
    }
}
 
Example 19
Source File: RelativeFileFieldSetter.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
@Override
protected IPath postProcessResultPath(IPath resultPath) {
  return resultPath.makeRelativeTo(basePath);
}
 
Example 20
Source File: TmfCommonProjectElement.java    From tracecompass with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Return the element destination path relative to its common element (traces
 * folder, experiments folder or experiment element).
 *
 * @param destinationPath
 *            Full destination path
 *
 * @return The element destination path
 * @since 3.3
 */
public @NonNull String getDestinationPathRelativeToParent(IPath destinationPath) {
    ITmfProjectModelElement parent = getParent();
    while (!(parent instanceof TmfTracesFolder || parent instanceof TmfExperimentElement || parent instanceof TmfExperimentFolder)) {
        parent = parent.getParent();
    }
    IPath path = destinationPath.makeRelativeTo(parent.getPath());
    return checkNotNull(path.toString());
}