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

The following examples show how to use org.eclipse.core.runtime.IPath#lastSegment() . 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: GitUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public static String getRelativePath(IPath filePath, IPath pathToGitRoot) {
	StringBuilder sb = new StringBuilder();
	String file = null;
	if (!filePath.hasTrailingSeparator()) {
		file = filePath.lastSegment();
		filePath = filePath.removeLastSegments(1);
	}
	for (int i = 0; i < pathToGitRoot.segments().length; i++) {
		if (pathToGitRoot.segments()[i].equals(".."))
			sb.append(filePath.segment(filePath.segments().length - pathToGitRoot.segments().length + i)).append("/");
		// else TODO
	}
	if (file != null)
		sb.append(file);
	return sb.toString();
}
 
Example 2
Source File: WizardFileSystemResourceExportPage2.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the name of a container with a location that encompasses targetDirectory. Returns null if there is no
 * conflict.
 * @param targetDirectory
 *            the path of the directory to check.
 * @return the conflicting container name or <code>null</code>
 */
protected String getConflictingContainerNameFor(String targetDirectory) {

	IPath rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
	IPath testPath = new Path(targetDirectory);
	// cannot export into workspace root
	if (testPath.equals(rootPath))
		return rootPath.lastSegment();

	// Are they the same?
	if (testPath.matchingFirstSegments(rootPath) == rootPath.segmentCount()) {
		String firstSegment = testPath.removeFirstSegments(rootPath.segmentCount()).segment(0);
		if (!Character.isLetterOrDigit(firstSegment.charAt(0)))
			return firstSegment;
	}

	return null;

}
 
Example 3
Source File: WorkspaceModelsManager.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param lastSegment
 * @param modelFolder
 * @return
 */
private IFile createUniqueFileFrom(final IFile originalFile, final IFolder modelFolder) {
	IFile file = originalFile;
	final Pattern p = Pattern.compile("(.*?)(\\d+)?(\\..*)?");
	while (file.exists()) {
		final IPath path = file.getLocation();
		String fName = path.lastSegment();
		final Matcher m = p.matcher(fName);
		if ( m.matches() ) {// group 1 is the prefix, group 2 is the number, group 3 is the suffix
			fName = m.group(1) + (m.group(2) == null ? 1 : Integer.parseInt(m.group(2)) + 1) +
				(m.group(3) == null ? "" : m.group(3));
		}
		file = modelFolder.getFile(fName);
	}
	return file;

}
 
Example 4
Source File: BundleUtil.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the javadoc location for the given bundle.
 *
 * <p>We can't use P2Utils and we can't use SimpleConfiguratorManipulator because of
 * API breakage between 3.5 and 4.2.
 * So we do a bit EDV (Computer data processing) ;-)
 *
 * @param bundle the bundle for which the javadoc location must be computed.
 * @param bundleLocation the location of the bundle, as replied by {@link #getBundlePath(Bundle)}.
 * @return the path to the javadoc folder of the bundle, or {@code null} if undefined.
 * @see #getBundlePath(Bundle)
 */
public static IPath getJavadocBundlePath(Bundle bundle, IPath bundleLocation) {
	IPath sourcesPath = null;
	// Not an essential functionality, make it robust
	try {
		final IPath srcFolderPath = getSourceRootProjectFolderPath(bundle);
		if (srcFolderPath == null) {
			//common case, jar file.
			final IPath bundlesParentFolder = bundleLocation.removeLastSegments(1);
			final String binaryJarName = bundleLocation.lastSegment();
			final String symbolicName = bundle.getSymbolicName();
			final String sourceJarName = binaryJarName.replace(symbolicName,
					symbolicName.concat(JAVADOC_SUFIX));
			final IPath potentialSourceJar = bundlesParentFolder.append(sourceJarName);
			if (potentialSourceJar.toFile().exists()) {
				sourcesPath = potentialSourceJar;
			}
		} else {
			sourcesPath = srcFolderPath;
		}
	} catch (Throwable t) {
		throw new RuntimeException(t);
	}
	return sourcesPath;
}
 
Example 5
Source File: PreferenceStoreHelper.java    From tlaplus with MIT License 6 votes vote down vote up
/**
    * Stores root file name in project preferences
    * @param project
    * @param rootFilename
    */
public static void storeRootFilename(IProject project, String rootFilename) {
	// If this condition does not hold, the subsequent code but also
	// AddModuleHandler will not work. The claim is that spec files are
	// always in the parent folder of the IProject.
	final IPath path = new Path(rootFilename);
	Assert.isTrue(ResourceHelper.isProjectParent(path.removeLastSegments(1), project),
			project.getLocation().toOSString() + " is *not* a subdirectory of " + rootFilename
					+ ". This is commonly caused by a symlink contained in the latter path.");
	// Store the filename *without* any path information, but prepend the
	// magical PARENT-1-PROJECT-LOC. It indicates that the file can be found
	// *one* level up (hence the "1") from the project location.
	// readProjectRootFile can later easily deduce the relative location of
	// the file.
	rootFilename = ResourceHelper.PARENT_ONE_PROJECT_LOC + path.lastSegment();
       IEclipsePreferences projectPrefs = getProjectPreferences(project);
       projectPrefs.put(IPreferenceConstants.P_PROJECT_ROOT_FILE, rootFilename);
       storePreferences(projectPrefs);        
   }
 
Example 6
Source File: PerformanceTestProjectSetup.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public static void setUp() throws Exception {
	testProject = createJavaProject("performance.test.project",
			new String[] {
					JavaCore.NATURE_ID,
					"org.eclipse.pde.PluginNature"
			}
	);
	new ToggleXtextNatureCommand().toggleNature(testProject.getProject());
	IFolder sourceFolder = JavaProjectSetupUtil.addSourceFolder(testProject, "src");
	JavaProjectSetupUtil.addSourceFolder(testProject, "xtend-gen");

	List<String> filesToCopy = readResource("/files.list");
	
	for(String fileToCopy: filesToCopy) {
		IPath filePath = new Path(fileToCopy);
		IFolder packageFolder = sourceFolder.getFolder(filePath.removeLastSegments(1));
		if (!packageFolder.exists())
			createFolderRecursively(packageFolder);
		List<String> content = readResource(fileToCopy);
		String contentAsString = Strings.concat("\n", content);
		String fileName = filePath.lastSegment();
		createFile(fileName.substring(0, fileName.length() - ".txt".length()), packageFolder, contentAsString);
	}
	waitForBuild();
}
 
Example 7
Source File: StandardSREPage.java    From sarl with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the dialogs fields.
 */
private void initializeFields() {
	final IPath path = this.workingCopy.getJarFile();
	String tooltip = null;
	String basename = null;
	if (path != null) {
		tooltip = path.toOSString();
		final IPath tmpPath = path.removeTrailingSeparator();
		if (tmpPath != null) {
			basename = tmpPath.lastSegment();
		}
	}
	this.sreLibraryTextField.setText(Strings.nullToEmpty(basename));
	this.sreLibraryTextField.setToolTipText(Strings.nullToEmpty(tooltip));
	//
	final String name = this.workingCopy.getNameNoDefault();
	this.sreNameTextField.setText(Strings.nullToEmpty(name));
	//
	final String mainClass = this.workingCopy.getMainClass();
	this.sreMainClassTextField.setText(Strings.nullToEmpty(mainClass));
	//
	this.sreIdTextField.setText(this.workingCopy.getId());
}
 
Example 8
Source File: BazelProjectSupport.java    From eclipse with Apache License 2.0 6 votes vote down vote up
private static void createClasspath(IPath root, List<String> paths, IJavaProject javaProject,
    int javaLanguageLevel) throws CoreException {
  String name = root.lastSegment();
  IFolder base = javaProject.getProject().getFolder(name);
  if (!base.isLinked()) {
    base.createLink(root, IResource.NONE, null);
  }
  List<IClasspathEntry> list = new LinkedList<>();
  for (String path : paths) {
    IPath workspacePath = base.getFullPath().append(path);
    list.add(JavaCore.newSourceEntry(workspacePath));
  }
  list.add(JavaCore.newContainerEntry(new Path(BazelClasspathContainer.CONTAINER_NAME)));

  list.add(
      JavaCore.newContainerEntry(new Path(STANDARD_VM_CONTAINER_PREFIX + javaLanguageLevel)));
  IClasspathEntry[] newClasspath = list.toArray(new IClasspathEntry[0]);
  javaProject.setRawClasspath(newClasspath, null);
}
 
Example 9
Source File: URIUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public static String getFileName(URI uri)
{
	if (uri == null)
	{
		return null;
	}
	String uriPath = uri.getPath();
	IPath path = Path.fromPortableString(uriPath);
	if (path == null)
	{
		return null;
	}
	return path.lastSegment();
}
 
Example 10
Source File: AddModuleHandler.java    From tlaplus with MIT License 5 votes vote down vote up
public IFile createModuleFile(final Spec spec, String moduleFileName, final IPath modulePath) {
	// Convert the OS specific absolute path to an Eclipse
	// specific relative one that is portable iff the resource
	// is in the project's folder hierarchy.
	// Technically this will always evaluate to true. One of the
	// checks above makes sure that one can only add modules
	// residing in the project's parent.
	if (ResourceHelper.isProjectParent(modulePath.removeLastSegments(1), spec.getProject())) {
		moduleFileName = ResourceHelper.PARENT_ONE_PROJECT_LOC + modulePath.lastSegment();
	}
	// adding the file to the spec
	return ResourceHelper.getLinkedFile(spec.getProject(), moduleFileName, true);
}
 
Example 11
Source File: MavenUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a MavenInfo instance based on the path to a Maven artifact in a local repository and
 * the artifact's group id.
 *
 * @param artifactPath the path to the artifact in the user's local repository (e.g.,
 *        <code>/home/user/.m2/repository/com/google/gwt/gwt
 *          -user/2.1-SNAPSHOT/gwt-user-2.1-SNAPSHOT.jar</code>)
 * @param groupId the group id of the artifact (e.g., <code>com.google.gwt</code>)
 * @return an instance of MavenInfo, or null if one could not be found due to a mismatch between
 *         the group id and the artifact path
 */
public static MavenInfo create(IPath artifactPath, String groupId) {
  if (artifactPath == null || artifactPath.isEmpty() || groupId == null
      || StringUtilities.isEmpty(groupId)) {
    return null;
  }

  IPath groupPath = Path.fromPortableString(groupId.replace('.', '/'));
  final int numTrailingSegmentsAfterRepositoryBase =
      NUM_TRAILING_SEGMENTS_AFTER_GROUP_ID + groupPath.segmentCount();

  if (artifactPath.segmentCount() <= numTrailingSegmentsAfterRepositoryBase) {
    return null;
  }

  String artifactName = artifactPath.lastSegment();
  String version =
      artifactPath.segment(artifactPath.segmentCount() - VERSION_INDEX_FROM_END_OF_MAVEN_PATH
          - 1);
  String artifactId =
      artifactPath.segment(artifactPath.segmentCount()
          - ARTIFACTID_INDEX_FROM_END_OF_MAVEN_PATH - 1);

  if (!artifactPath.removeLastSegments(NUM_TRAILING_SEGMENTS_AFTER_GROUP_ID)
      .removeTrailingSeparator().toPortableString().endsWith(groupPath.toPortableString())) {
    return null;
  }

  IPath repositoryPath =
      artifactPath.removeLastSegments(numTrailingSegmentsAfterRepositoryBase);

  return new MavenInfo(repositoryPath, groupId, artifactId, artifactName, version);
}
 
Example 12
Source File: LocalRoot.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private static File getWindowsHomeFile() {
    File desktop = getWindowsDesktopFile();
    if (desktop == null) {
        return null;
    }
    IPath homePath = new Path(HOME_DIR);
    String homeFilename = homePath.lastSegment();
    File[] files = FileSystemView.getFileSystemView().getFiles(desktop, false);
    for (File file : files) {
        if (file.getName().equals(homeFilename)) {
            return file;
        }
    }
    return null;
}
 
Example 13
Source File: Clone.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public JSONObject toJSON(IPath path, URI baseLocation, String cloneUrl, JSONArray parents) throws IOException, URISyntaxException {
	id = Activator.LOCATION_FILE_SERVLET + '/' + path.toString();
	name = path.lastSegment();
	this.path = path;
	this.cloneUrl = cloneUrl;
	this.baseLocation = baseLocation;
	this.parents = parents;
	return toJSON();
}
 
Example 14
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static String getDevJarName(IPath sdkLocation) {
  IPath devJarPath = sdkLocation.append(GwtSdk.GWT_DEV_NO_PLATFORM_JAR);

  if (devJarPath.toFile().exists()) {
    return devJarPath.lastSegment();
  }

  return "gwt-dev-" + getPlatformName() + ".jar";
}
 
Example 15
Source File: AbstractNewFileWizard.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Ensure the new file's name ends with the default file extension.
 * 
 * @return the filename ending with the file extension
 */
private IPath getNormalizedFilePath() {
  IPath newFilePath = getFilePath();
  String newFilename = newFilePath.lastSegment();
  String ext = getFileExtension();
  if (ext != null && ext.length() != 0) {
    if (!(newFilename.endsWith("." + ext))) {
      return newFilePath.addFileExtension(ext);
    }
  }

  return newFilePath;
}
 
Example 16
Source File: ClasspathResourceUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Determines if a resource is available on a project's classpath. This method searches both source paths and JAR/ZIP
 * files.
 */
public static boolean isResourceOnClasspath(IJavaProject javaProject, IPath resourcePath) throws JavaModelException {
  String pckg = JavaUtilities.getPackageNameFromPath(resourcePath.removeLastSegments(1));
  String fileName = resourcePath.lastSegment();

  for (IPackageFragment pckgFragment : JavaModelSearch.getPackageFragments(javaProject, pckg)) {
    if (ClasspathResourceUtilities.isFileOnPackageFragment(fileName, pckgFragment)) {
      return true;
    }
  }

  // If the resource doesn't follow normal java naming convention for resources, such as /resources/folder-name/file-name.js
  for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
    IPackageFragment folderFragment = root.getPackageFragment(pckg);
    IResource folder = folderFragment.getResource();
    if (folder == null || !folder.exists() || !(folder instanceof IContainer)) {
      continue;
    }
    IResource resource = ((IContainer) folder).findMember(fileName);
    if (resource != null && resource.exists()) {
      return true;
    }
  }

  // Not there
  return false;
}
 
Example 17
Source File: AbstractGWTRuntimeTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean assertGWTRuntimeEntry(IPath runtimePath,
    IClasspathEntry[] entries) {
  boolean hasGWTRuntime = false;

  for (IClasspathEntry entry : entries) {
    IPath entryPath = entry.getPath();

    if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
      if (GWTRuntimeContainer.isPathForGWTRuntimeContainer(entryPath)) {
        // Make sure we have only one GWT runtime
        if (hasGWTRuntime) {
          return false;
        }

        // We found at a GWT runtime
        hasGWTRuntime = true;

        // Make sure it's the one we're looking for
        if (!entryPath.equals(runtimePath)) {
          return false;
        }
      }
    }

    // Make sure we don't have any gwt-user.jar dependencies
    if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
      String jarName = entryPath.lastSegment();
      if (jarName.equals(GwtSdk.GWT_USER_JAR)) {
        return false;
      }
    }
  }

  return hasGWTRuntime;
}
 
Example 18
Source File: FilenameDifferentiator.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private Map<IEditorPart, String> getUnambiguousTitles(Collection<IEditorPart> list)
{
	Map<IEditorPart, IPath> map = new HashMap<IEditorPart, IPath>();
	int min = Integer.MAX_VALUE;
	IPath path;
	for (IEditorPart part : list)
	{
		path = getPath(part);
		if (path == null)
		{
			continue;
		}
		min = Math.min(path.segmentCount(), min);
		map.put(part, path);
	}

	// Need to disambiguate the titles!
	Map<IEditorPart, String> returnMap = new HashMap<IEditorPart, String>();
	Set<String> curSegments = new HashSet<String>();
	for (int i = 2; i <= min; i++)
	{
		returnMap.clear();
		curSegments.clear();
		for (Map.Entry<IEditorPart, IPath> entry : map.entrySet())
		{
			path = entry.getValue();
			String segment = path.segment(path.segmentCount() - i);
			if (curSegments.contains(segment))
			{
				break;
			}
			curSegments.add(segment);
			String title = path.lastSegment() + SEPARATOR + segment;
			returnMap.put(entry.getKey(), title);
		}
		// They're all unique, return them all!
		if (curSegments.size() == map.size())
		{
			return returnMap;
		}
	}

	// Something failed! What do we do now?
	return Collections.emptyMap();
}
 
Example 19
Source File: RemoteGenerateManifestOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Scan traceFolder for files that match the patterns specified in the
 * template file. When there is a match, the trace package element is used
 * to determine the trace name and trace type.
 *
 * @param traceGroup
 *                The parent trace group element
 * @param parentElement
 *                The immediate parent trace group or folder element
 * @param traceFolder
 *                The folder to scan
 * @param recursionLevel
 *                The recursion level (needed to find directory traces under the traceFolder
 * @param monitor
 *                The progress monitor
 * @throws CoreException
 *                Thrown by the file system implementation
 * @throws InterruptedException
 *                Thrown if operation was cancelled
 */
private void generateElementsFromArchive(
        final RemoteImportTraceGroupElement traceGroup,
        final TracePackageElement parentElement,
        final IFileStore traceFolder,
        final int recursionLevel,
        IProgressMonitor monitor)
                throws CoreException, InterruptedException {

    int localRecursionLevel = recursionLevel + 1;
    IFileStore[] sources = traceFolder.childStores(EFS.NONE, monitor);

    for (int i = 0; i < sources.length; i++) {
        ModalContext.checkCanceled(monitor);
        SubMonitor subMonitor = SubMonitor.convert(monitor, sources.length);

        IFileStore fileStore = sources[i];
        IPath fullArchivePath = TmfTraceCoreUtils.newSafePath(fileStore.toURI().getPath());

        IFileInfo sourceInfo = fileStore.fetchInfo();
        if (!sourceInfo.isDirectory()) {

            String rootPathString = traceGroup.getRootImportPath();
            IPath rootPath = TmfTraceCoreUtils.newSafePath(rootPathString);
            IPath relativeTracePath = Path.EMPTY;
            if (rootPath.isPrefixOf(fullArchivePath)) {
                relativeTracePath = fullArchivePath.makeRelativeTo(rootPath);
            }
            Entry<Pattern, TracePackageTraceElement> matchingTemplateEntry = getMatchingTemplateElement(relativeTracePath);
            if (matchingTemplateEntry != null) {
                TracePackageTraceElement matchingTemplateElement = matchingTemplateEntry.getValue();
                String traceType = matchingTemplateElement.getTraceType();

                // If a single file is part of a directory trace, use the parent directory instead
                TracePackageElement parent = parentElement;
                if (matchesDirectoryTrace(relativeTracePath, matchingTemplateEntry)) {
                    fullArchivePath = fullArchivePath.removeLastSegments(1);
                    fDirectoryTraces.add(fullArchivePath);
                    fileStore = fileStore.getParent();
                    sourceInfo = fileStore.fetchInfo();
                    parent = parentElement.getParent();
                    // Let the auto-detection choose the best trace type
                    traceType = null;
                } else if ((localRecursionLevel > 1) && (!traceGroup.isRecursive())) {
                    // Don't consider file traces on level 2 if it's not recursive
                    continue;
                }

                if (sourceInfo.getLength() > 0 || sourceInfo.isDirectory()) {
                    // Only add non-empty files
                    String traceName = fullArchivePath.lastSegment();
                    String fileName = fileStore.getName();
                    // create new elements to decouple from input elements
                    TracePackageTraceElement traceElement = new TracePackageTraceElement(parent, traceName, traceType);
                    RemoteImportTraceFilesElement tracePackageFilesElement = new RemoteImportTraceFilesElement(traceElement, fileName, fileStore);
                    tracePackageFilesElement.setVisible(false);
                }
            }
        } else {
            if (traceGroup.isRecursive() || localRecursionLevel < 2) {
                RemoteImportFolderElement folder = new RemoteImportFolderElement(parentElement, fileStore.getName());
                generateElementsFromArchive(traceGroup, folder, fileStore, localRecursionLevel, subMonitor);
            }
        }
    }
}
 
Example 20
Source File: JreServiceProjectSREProviderFactory.java    From sarl with Apache License 2.0 4 votes vote down vote up
private static ProjectSREProvider findOnClasspath(IJavaProject project) {
	try {
		final IClasspathEntry[] classpath = project.getResolvedClasspath(true);
		for (final IClasspathEntry entry : classpath) {
			final IPath path;
			final String id;
			final String name;
			switch (entry.getEntryKind()) {
			case IClasspathEntry.CPE_LIBRARY:
				path = entry.getPath();
				if (path != null) {
					id = path.makeAbsolute().toPortableString();
					name = path.lastSegment();
				} else {
					id  = null;
					name = null;
				}
				break;
			case IClasspathEntry.CPE_PROJECT:
				final IResource res = project.getProject().getParent().findMember(entry.getPath());
				if (res instanceof IProject) {
					final IProject dependency = (IProject) res;
					final IJavaProject javaDependency = JavaCore.create(dependency);
					path = javaDependency.getOutputLocation();
					id = javaDependency.getHandleIdentifier();
					name = javaDependency.getElementName();
					break;
				}
				continue;
			default:
				continue;
			}
			if (path != null && !SARLRuntime.isPackedSRE(path) && !SARLRuntime.isUnpackedSRE(path)) {
				final String bootstrap = SARLRuntime.getDeclaredBootstrap(path);
				if (!Strings.isEmpty(bootstrap)) {
					final List<IRuntimeClasspathEntry> 	classpathEntries = Collections.singletonList(new RuntimeClasspathEntry(entry));
					return new JreServiceProjectSREProvider(
							id, name,
							project.getPath().toPortableString(),
							bootstrap,
							classpathEntries);
				}
			}
		}
	} catch (JavaModelException exception) {
		//
	}
	return null;
}