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

The following examples show how to use org.eclipse.core.runtime.IPath#segments() . 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: ResourceUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Create the components of the provided folder as required. Assumes the containing project
 * already exists.
 *
 * @param folder the path to be created if it does not already exist
 * @param monitor may be {@code null}
 * @throws CoreException on error
 */
public static void createFolders(IContainer folder, IProgressMonitor monitor)
    throws CoreException {

  IPath path = folder.getProjectRelativePath();
  IContainer current = folder.getProject();
  SubMonitor progress = SubMonitor.convert(monitor, path.segmentCount());
  for (String segment : path.segments()) {
    IFolder child = current.getFolder(new Path(segment));
    if (!child.exists()) {
      child.create(true, true, progress.newChild(1));
    } else {
      progress.worked(1);
    }
    current = child;
  }
}
 
Example 3
Source File: SWTBotUtils.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens a trace in an editor and get the TmfEventsEditor
 *
 * @param bot
 *            the workbench bot
 * @param projectName
 *            the name of the project that contains the trace
 * @param elementPath
 *            the trace element path (relative to Traces folder)
 * @return TmfEventsEditor the opened editor
 */
public static TmfEventsEditor openEditor(SWTWorkbenchBot bot, String projectName, IPath elementPath) {
    final SWTBotView projectExplorerView = bot.viewById(IPageLayout.ID_PROJECT_EXPLORER);
    projectExplorerView.setFocus();
    SWTBot projectExplorerBot = projectExplorerView.bot();

    final SWTBotTree tree = projectExplorerBot.tree();
    projectExplorerBot.waitUntil(ConditionHelpers.isTreeNodeAvailable(projectName, tree));
    final SWTBotTreeItem treeItem = tree.getTreeItem(projectName);
    treeItem.expand();

    SWTBotTreeItem tracesNode = getTraceProjectItem(projectExplorerBot, treeItem, "Traces");
    tracesNode.expand();

    SWTBotTreeItem currentItem = tracesNode;
    for (String segment : elementPath.segments()) {
        currentItem = getTraceProjectItem(projectExplorerBot, currentItem, segment);
        currentItem.doubleClick();
    }

    SWTBotEditor editor = bot.editorByTitle(elementPath.toString());
    IEditorPart editorPart = editor.getReference().getEditor(false);
    assertTrue(editorPart instanceof TmfEventsEditor);
    return (TmfEventsEditor) editorPart;
}
 
Example 4
Source File: ResourceContainer.java    From depan with Apache License 2.0 6 votes vote down vote up
/**
 * Provide {@link ResourceContainer} from supplied {@code refPath}.
 * The {@code refPath} must name a child container, not a resource.
 * 
 * @return {@code null} if {@code refPath} is not a valid descendant.
 */
public ResourceContainer getFromPath(IPath refPath) {
  ResourceContainer result = this;
  String[] segments = refPath.segments();
  if (segments.length < 1) {
    return null;
  }
  if (!(result.getLabel().equals(segments[0]))) {
    return null;
  }
  List<String> children =
      Arrays.asList(segments).subList(1, segments.length);
  for (String segment : children) {
    result = result.getChild(segment);
    if (null == result) {
      return null;
    }
  }

  return result;
}
 
Example 5
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Fuzzy search for Java project in the workspace that matches
 * the given path.
 *
 * @param path the path to match
 * @return the matching Java project or <code>null</code>
 * @since 3.2
 */
private IJavaProject findJavaProject(IPath path) {
	if (path == null)
		return null;

	String[] pathSegments= path.segments();
	IJavaModel model= JavaCore.create(JavaPlugin.getWorkspace().getRoot());
	IJavaProject[] projects;
	try {
		projects= model.getJavaProjects();
	} catch (JavaModelException e) {
		return null; // ignore - use default JRE
	}
	for (int i= 0; i < projects.length; i++) {
		IPath projectPath= projects[i].getProject().getFullPath();
		String projectSegment= projectPath.segments()[0];
		for (int j= 0; j < pathSegments.length; j++)
			if (projectSegment.equals(pathSegments[j]))
				return projects[i];
	}
	return null;
}
 
Example 6
Source File: BaseEditor.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the project for the file that's being edited (or null if not available)
 */
public IProject getProject() {
    IEditorInput editorInput = this.getEditorInput();
    if (editorInput instanceof IAdaptable) {
        IAdaptable adaptable = editorInput;
        IFile file = adaptable.getAdapter(IFile.class);
        if (file != null) {
            return file.getProject();
        }
        IResource resource = adaptable.getAdapter(IResource.class);
        if (resource != null) {
            return resource.getProject();
        }
        if (editorInput instanceof IStorageEditorInput) {
            IStorageEditorInput iStorageEditorInput = (IStorageEditorInput) editorInput;
            try {
                IStorage storage = iStorageEditorInput.getStorage();
                IPath fullPath = storage.getFullPath();
                if (fullPath != null) {
                    IWorkspace ws = ResourcesPlugin.getWorkspace();
                    for (String s : fullPath.segments()) {
                        IProject p = ws.getRoot().getProject(s);
                        if (p.exists()) {
                            return p;
                        }
                    }
                }
            } catch (Exception e) {
                Log.log(e);
            }

        }
    }
    return null;
}
 
Example 7
Source File: ExtLibToolingUtil.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public static boolean isPropertiesOpenInEditor(DesignerProject dproject) {
    
    boolean openInEditor = false;
    
    IFile ifile = dproject.getProject().getFile("/WebContent/WEB-INF/xsp.properties"); //$NON-NLS-1$

    // check if its already open
    IEditorReference[] er = ExtLibPanelUtil.getActiveWorkbenchPage().getEditorReferences();
    for (IEditorReference ref : er) {
        try {
            IEditorInput ei = ref.getEditorInput();
            IFile f = (IFile)ei.getAdapter(IFile.class);
            if (null != f) {
                if  (f.equals(ifile)) {
                    openInEditor = true;
                    break;
                }
                else {
                    IPath proppath = ifile.getFullPath(); 
                    IPath edpath = f.getFullPath();
                    if (edpath.segmentCount() >= 3 && proppath.segmentCount() > 1) {
                        String[] segs = edpath.segments();
                        String nsfname = proppath.segment(0);
                        if (StringUtil.equalsIgnoreCase(nsfname, segs[0]) && StringUtil.equalsIgnoreCase("AppProperties", segs[1])) { //$NON-NLS-1$
                            if (StringUtil.equalsIgnoreCase("database.properties", segs[2])) { //$NON-NLS-1$
                                openInEditor = true;
                                break;
                            }
                        }
                    }
                }
            }
                
        }
        catch(PartInitException pe) {
            ExtLibToolingLogger.EXT_LIB_TOOLING_LOGGER.warn(pe, "exception trying to find open property editors");  // $NLW-ExtLibToolingUtil.exceptiontryingtofind-1$                
        }
    }
    return openInEditor;
}
 
Example 8
Source File: ClasspathChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ArrayList determineAffectedPackageFragments(IPath location) throws JavaModelException {
	ArrayList fragments = new ArrayList();

	// see if this will cause any package fragments to be affected
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IResource resource = null;
	if (location != null) {
		resource = workspace.getRoot().findMember(location);
	}
	if (resource != null && resource.getType() == IResource.FOLDER) {
		IFolder folder = (IFolder) resource;
		// only changes if it actually existed
		IClasspathEntry[] classpath = this.project.getExpandedClasspath();
		for (int i = 0; i < classpath.length; i++) {
			IClasspathEntry entry = classpath[i];
			IPath path = classpath[i].getPath();
			if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
				IPackageFragmentRoot[] roots = this.project.computePackageFragmentRoots(classpath[i]);
				PackageFragmentRoot root = (PackageFragmentRoot) roots[0];
				// now the output location becomes a package fragment - along with any subfolders
				ArrayList folders = new ArrayList();
				folders.add(folder);
				collectAllSubfolders(folder, folders);
				Iterator elements = folders.iterator();
				int segments = path.segmentCount();
				while (elements.hasNext()) {
					IFolder f = (IFolder) elements.next();
					IPath relativePath = f.getFullPath().removeFirstSegments(segments);
					String[] pkgName = relativePath.segments();
					IPackageFragment pkg = root.getPackageFragment(pkgName);
					if (!Util.isExcluded(pkg))
						fragments.add(pkg);
				}
			}
		}
	}
	return fragments;
}
 
Example 9
Source File: ProjectStub.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFile getFile(IPath path) {
    String[] segments = path.segments();
    int segmentCount = path.segmentCount();
    IContainer container = this;
    for (int i = 0; i < segmentCount - i; i++) {
        container = container.getFolder(new Path(segments[i]));
    }
    if (container != this) {
        return container.getFile(new Path(segments[segmentCount - 1]));
    }

    throw new RuntimeException("Finish implementing");
}
 
Example 10
Source File: NodeModuleResolver.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private List<IPath> nodeModulesPaths(IPath start)
{
	String[] parts = start.segments();
	int root = 0;
	for (int x = 0; x < parts.length; x++)
	{
		if (NODE_MODULES.equals(parts[x]))
		{
			root = x;
			break;
		}
	}
	int i = parts.length - 1;
	List<IPath> dirs = new ArrayList<IPath>();
	while (i > root)
	{
		if (NODE_MODULES.equals(parts[i]))
		{
			i--;
			continue;
		}
		IPath dir = start.removeLastSegments(start.segmentCount() - i).append(NODE_MODULES);
		dirs.add(dir);
		i--;
	}

	// Search global folders, see http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
	dirs.addAll(globalFolders());
	return dirs;
}
 
Example 11
Source File: GenerateAll.java    From eip-designer with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * 
 * @param bundleID
 *            is the plug-in ID
 * @param relativePath
 *            is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings("unchecked")
private URI getTemplateURI(String bundleID, IPath relativePath) throws IOException {
	Bundle bundle = Platform.getBundle(bundleID);
	if (bundle == null) {
		// no need to go any further
		return URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	URL url = bundle.getEntry(relativePath.toString());
	if (url == null && relativePath.segmentCount() > 1) {
		Enumeration<URL> entries = bundle.findEntries("/", "*.emtl", true);
		if (entries != null) {
			String[] segmentsRelativePath = relativePath.segments();
			while (url == null && entries.hasMoreElements()) {
				URL entry = entries.nextElement();
				IPath path = new Path(entry.getPath());
				if (path.segmentCount() > relativePath.segmentCount()) {
					path = path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
				}
				String[] segmentsPath = path.segments();
				boolean equals = segmentsPath.length == segmentsRelativePath.length;
				for (int i = 0; equals && i < segmentsPath.length; i++) {
					equals = segmentsPath[i].equals(segmentsRelativePath[i]);
				}
				if (equals) {
					url = bundle.getEntry(entry.getPath());
				}
			}
		}
	}
	URI result;
	if (url != null) {
		result = URI.createPlatformPluginURI(new Path(bundleID).append(new Path(url.getPath())).toString(), false);
	} else {
		result = URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	return result;
}
 
Example 12
Source File: GenerateXml.java    From eip-designer with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * 
 * @param bundleID
 *            is the plug-in ID
 * @param relativePath
 *            is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings("unchecked")
private URI getTemplateURI(String bundleID, IPath relativePath) throws IOException {
	Bundle bundle = Platform.getBundle(bundleID);
	if (bundle == null) {
		// no need to go any further
		return URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	URL url = bundle.getEntry(relativePath.toString());
	if (url == null && relativePath.segmentCount() > 1) {
		Enumeration<URL> entries = bundle.findEntries("/", "*.emtl", true);
		if (entries != null) {
			String[] segmentsRelativePath = relativePath.segments();
			while (url == null && entries.hasMoreElements()) {
				URL entry = entries.nextElement();
				IPath path = new Path(entry.getPath());
				if (path.segmentCount() > relativePath.segmentCount()) {
					path = path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
				}
				String[] segmentsPath = path.segments();
				boolean equals = segmentsPath.length == segmentsRelativePath.length;
				for (int i = 0; equals && i < segmentsPath.length; i++) {
					equals = segmentsPath[i].equals(segmentsRelativePath[i]);
				}
				if (equals) {
					url = bundle.getEntry(entry.getPath());
				}
			}
		}
	}
	URI result;
	if (url != null) {
		result = URI.createPlatformPluginURI(new Path(bundleID).append(new Path(url.getPath())).toString(), false);
	} else {
		result = URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	return result;
}
 
Example 13
Source File: GenerateJava.java    From eip-designer with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * 
 * @param bundleID
 *            is the plug-in ID
 * @param relativePath
 *            is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings("unchecked")
private URI getTemplateURI(String bundleID, IPath relativePath) throws IOException {
	Bundle bundle = Platform.getBundle(bundleID);
	if (bundle == null) {
		// no need to go any further
		return URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	URL url = bundle.getEntry(relativePath.toString());
	if (url == null && relativePath.segmentCount() > 1) {
		Enumeration<URL> entries = bundle.findEntries("/", "*.emtl", true);
		if (entries != null) {
			String[] segmentsRelativePath = relativePath.segments();
			while (url == null && entries.hasMoreElements()) {
				URL entry = entries.nextElement();
				IPath path = new Path(entry.getPath());
				if (path.segmentCount() > relativePath.segmentCount()) {
					path = path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
				}
				String[] segmentsPath = path.segments();
				boolean equals = segmentsPath.length == segmentsRelativePath.length;
				for (int i = 0; equals && i < segmentsPath.length; i++) {
					equals = segmentsPath[i].equals(segmentsRelativePath[i]);
				}
				if (equals) {
					url = bundle.getEntry(entry.getPath());
				}
			}
		}
	}
	URI result;
	if (url != null) {
		result = URI.createPlatformPluginURI(new Path(bundleID).append(new Path(url.getPath())).toString(), false);
	} else {
		result = URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	return result;
}
 
Example 14
Source File: ProjectStub.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFile getFile(IPath path) {
    String[] segments = path.segments();
    int segmentCount = path.segmentCount();
    IContainer container = this;
    for (int i = 0; i < segmentCount - i; i++) {
        container = container.getFolder(new Path(segments[i]));
    }
    if (container != this) {
        return container.getFile(new Path(segments[segmentCount - 1]));
    }

    throw new RuntimeException("Finish implementing");
}
 
Example 15
Source File: GWTProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isTestPath(IPath path) {
  String[] segments = path.segments();
  int length = segments.length;
  String last = length < 1 ? null : segments[length - 1];
  String lastButOne = length < 2 ? null : segments[length - 2];
  String lastButTwo = length < 3 ? null : segments[length - 3];
  return "test".equals(last) || "javatests".equals(last) || "src".equals(lastButTwo) && "test".equals(lastButOne);
}
 
Example 16
Source File: ResourceUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the folder specified by projectRelativeFolderPath, and all parent
 * folders, if they do not already exist.
 *
 * @param project
 * @param projectRelativeFolderPath
 * @throws CoreException
 */
public static void createFolderStructure(IProject project,
    IPath projectRelativeFolderPath) throws CoreException {

  IContainer curContainer = project;

  for (String pathSegment : projectRelativeFolderPath.segments()) {
    curContainer = curContainer.getFolder(new Path(pathSegment));
    createFolderIfNonExistent((IFolder) curContainer,
        new NullProgressMonitor());
  }
}
 
Example 17
Source File: WorkspaceWizardValidatorUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns {@code true} if path is a valid folder path.
 *
 * That means that every segment needs to be a valid folder name.
 *
 */
public static boolean isValidFolderPath(IPath path) {
	for (String segment : path.segments()) {
		if (!isValidFolderName(segment)) {
			return false;
		}
	}
	return true;
}
 
Example 18
Source File: ModuleSpecifierSelectionDialog.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates all non-existing segments of the given path.
 *
 * @param path
 *            The path to create
 * @param parent
 *            The container in which the path should be created in
 * @param monitor
 *            A progress monitor. May be {@code null}
 *
 * @return The folder specified by the path
 */
private IContainer createFolderPath(IPath path, IContainer parent, IProgressMonitor monitor) {
	IContainer activeContainer = parent;

	if (null != monitor) {
		monitor.beginTask("Creating folders", path.segmentCount());
	}

	for (String segment : path.segments()) {
		IFolder folderToCreate = activeContainer.getFolder(new Path(segment));
		try {
			if (!folderToCreate.exists()) {
				createFolder(segment, activeContainer, monitor);
			}
			if (null != monitor) {
				monitor.worked(1);
			}
			activeContainer = folderToCreate;
		} catch (CoreException e) {
			LOGGER.error("Failed to create module folders.", e);
			MessageDialog.open(MessageDialog.ERROR, getShell(),
					FAILED_TO_CREATE_FOLDER_TITLE, String.format(FAILED_TO_CREATE_FOLDER_MESSAGE,
							folderToCreate.getFullPath().toString(), e.getMessage()),
					SWT.NONE);
			break;
		}
	}
	return activeContainer;
}
 
Example 19
Source File: GenerateAll.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * 
 * @param bundleID
 *            is the plug-in ID
 * @param relativePath
 *            is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings ( "unused" )
private URI getTemplateURI ( final String bundleID, final IPath relativePath ) throws IOException
{
    final Bundle bundle = Platform.getBundle ( bundleID );
    if ( bundle == null )
    {
        // no need to go any further 
        return URI.createPlatformResourceURI ( new Path ( bundleID ).append ( relativePath ).toString (), false );
    }
    URL url = bundle.getEntry ( relativePath.toString () );
    if ( url == null && relativePath.segmentCount () > 1 )
    {
        final Enumeration<URL> entries = bundle.findEntries ( "/", "*.emtl", true );
        if ( entries != null )
        {
            final String[] segmentsRelativePath = relativePath.segments ();
            while ( url == null && entries.hasMoreElements () )
            {
                final URL entry = entries.nextElement ();
                IPath path = new Path ( entry.getPath () );
                if ( path.segmentCount () > relativePath.segmentCount () )
                {
                    path = path.removeFirstSegments ( path.segmentCount () - relativePath.segmentCount () );
                }
                final String[] segmentsPath = path.segments ();
                boolean equals = segmentsPath.length == segmentsRelativePath.length;
                for ( int i = 0; equals && i < segmentsPath.length; i++ )
                {
                    equals = segmentsPath[i].equals ( segmentsRelativePath[i] );
                }
                if ( equals )
                {
                    url = bundle.getEntry ( entry.getPath () );
                }
            }
        }
    }
    URI result;
    if ( url != null )
    {
        result = URI.createPlatformPluginURI ( new Path ( bundleID ).append ( new Path ( url.getPath () ) ).toString (), false );
    }
    else
    {
        result = URI.createPlatformResourceURI ( new Path ( bundleID ).append ( relativePath ).toString (), false );
    }
    return result;
}
 
Example 20
Source File: Repository.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
@Override
public IRepositoryFileStore asRepositoryFileStore(final Path path, boolean force)
        throws IOException, CoreException {
    if (!project.isAccessible() || project.getLocation() == null) {
        return null;
    }
    final IPath resourcePath = fromOSString(path.toString()).makeRelativeTo(project.getLocation());
    if (resourcePath.isRoot() || resourcePath.isEmpty()
            || Objects.equals(org.eclipse.core.runtime.Path.fromOSString(".."), resourcePath)) {
        return null;
    }
    IResource iResource = null;
    try {
        iResource = isFile(resourcePath) ? project.getFile(resourcePath) : project.getFolder(resourcePath);
    } catch (IllegalArgumentException e) {
        return null;
    }
    if (!iResource.exists()) {
        if (force) {
            iResource.getParent().refreshLocal(IResource.DEPTH_ONE, NULL_PROGRESS_MONITOR);
            if (!iResource.exists()) {
                throw new FileNotFoundException(path.toFile().getAbsolutePath());
            }
        } else {
            return null;
        }
    }

    final IPath projectRelativePath = iResource.getProjectRelativePath();
    if (projectRelativePath.segmentCount() > 0) {
        final IPath iPath = projectRelativePath.removeFirstSegments(0);
        if (iPath.segmentCount() > 1) {
            final String storeName = iPath.segments()[0];
            final IFile file = getProject().getFile(iPath);
            return getRepositoryStoreByName(storeName)
                    .filter(repositoryStore -> belongToRepositoryStore(repositoryStore, file))
                    .map(repositoryStore -> repositoryStore
                            .createRepositoryFileStore(file.getName()))
                    .orElse(null);
        }
    }
    return null;
}