Java Code Examples for org.eclipse.core.resources.IWorkspace#getRoot()

The following examples show how to use org.eclipse.core.resources.IWorkspace#getRoot() . 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: N4JSGenerateImmediatelyBuilderState.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** logic of {@link IN4JSCore#findAllProjects()} with filtering by name */
private IProject findProject(BuildData buildData) {
	String eclipseProjectName = buildData.getProjectName();
	if (Strings.isNullOrEmpty(eclipseProjectName)) {
		return null;
	}
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IWorkspaceRoot root = workspace.getRoot();
	IProject project = root.getProject(eclipseProjectName); // creates a project instance if not existing

	if (null == project || !project.isAccessible()) {
		N4JSProjectName n4jsProjectName = new EclipseProjectName(eclipseProjectName).toN4JSProjectName();

		final IProject externalProject = externalLibraryWorkspace.getProject(n4jsProjectName);
		if (null != externalProject && externalProject.exists()) {
			project = externalProject;
		}
	}

	return project;
}
 
Example 2
Source File: File2Resource.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * get the IResource corresponding to the given file. Given file does not
 * need to exist.
 * 
 * @param file
 * @param isDirectory
 *            if true, an IContainer will be returned, otherwise an IFile
 *            will be returned
 * @return
 */
public static IResource getResource(File file, boolean isDirectory) {
	if (file == null) return null;
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot workspaceRoot = workspace.getRoot();

    IPath pathEclipse = new Path(file.getAbsolutePath());

    IResource resource = null;

    if (isDirectory) {
        resource = workspaceRoot.getContainerForLocation(pathEclipse);
    } else {
        resource = workspaceRoot.getFileForLocation(pathEclipse);
    }
    return resource;
}
 
Example 3
Source File: PythonBaseModelProvider.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void propertyChange(PropertyChangeEvent event) {
    //When a property that'd change an icon changes, the tree must be updated.
    String property = event.getProperty();
    if (PyTitlePreferencesPage.isTitlePreferencesIconRelatedProperty(property)) {
        IWorkspace[] localInput = this.input;
        if (localInput != null) {
            for (IWorkspace iWorkspace : localInput) {
                IWorkspaceRoot root = iWorkspace.getRoot();
                if (root != null) {
                    //Update all children too (getUpdateRunnable wouldn't update children)
                    Runnable runnable = getRefreshRunnable(root);

                    final Collection<Runnable> runnables = new ArrayList<Runnable>();
                    runnables.add(runnable);
                    processRunnables(runnables);
                }
            }
        }

    }
}
 
Example 4
Source File: ResourceUtilTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create test parameter for the parameterized runner.
 *
 * @return The list of test parameters
 * @throws CoreException
 *             if core error occurs
 */
@Parameters(name = "{index}: ({0})")
public static Iterable<Object[]> getTracePaths() throws CoreException {
    IProgressMonitor progressMonitor = new NullProgressMonitor();
    IWorkspace workspace = ResourcesPlugin.getWorkspace();

    // Create a project inside workspace location
    fWorkspaceRoot = workspace.getRoot();
    fSomeProject = fWorkspaceRoot.getProject(SOME_PROJECT_NAME);
    fSomeProject.create(progressMonitor);
    fSomeProject.open(progressMonitor);

    // Create an other project outside the workspace location
    URI projectLocation = fProjectFolder.getRoot().toURI();
    fSomeOtherProject = fWorkspaceRoot.getProject(SOME_OTHER_PROJECT_NAME);
    IProjectDescription description = workspace.newProjectDescription(fSomeOtherProject.getName());
    if (projectLocation != null) {
        description.setLocationURI(projectLocation);
    }
    fSomeOtherProject.create(description, progressMonitor);
    fSomeOtherProject.open(progressMonitor);
    return Arrays.asList(new Object[][] { {fSomeProject}, {fSomeOtherProject} });
}
 
Example 5
Source File: WizardSaveAsPage.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a <code>boolean</code> indicating whether a container name
 * represents a valid container resource in the workbench. An error message
 * is stored for future reference if the name does not represent a valid
 * container.
 * 
 * @return <code>boolean</code> indicating validity of the container name
 */
protected boolean validateContainer( )
{
	IPath path = containerGroup.getContainerFullPath( );
	if ( path == null )
	{
		problemType = PROBLEM_CONTAINER_EMPTY;
		problemMessage = Messages.getString( "WizardSaveAsPage.FolderEmpty" ); //$NON-NLS-1$
		return false;
	}
	IWorkspace workspace = ResourcesPlugin.getWorkspace( );
	String projectName = path.segment( 0 );
	if ( projectName == null
			|| !workspace.getRoot( ).getProject( projectName ).exists( ) )
	{
		problemType = PROBLEM_PROJECT_DOES_NOT_EXIST;
		problemMessage = Messages.getString( "WizardSaveAsPage.NoProject" ); //$NON-NLS-1$
		return false;
	}
	// path is invalid if any prefix is occupied by a file
	IWorkspaceRoot root = workspace.getRoot( );
	while ( path.segmentCount( ) > 1 )
	{
		if ( root.getFile( path ).exists( ) )
		{
			problemType = PROBLEM_PATH_OCCUPIED;
			problemMessage = Messages.getFormattedString( "WizardSaveAsPage.PathOccupied", new Object[]{path.makeRelative( )} ); //$NON-NLS-1$
			return false;
		}
		path = path.removeLastSegments( 1 );
	}
	return true;
}
 
Example 6
Source File: FileUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new project.
 * 
 * @param name
 *            the project name
 */
public static IProject createProject( String name ) throws CoreException
{
	IWorkspace ws = ResourcesPlugin.getWorkspace( );
	IWorkspaceRoot root = ws.getRoot( );
	IProject proj = root.getProject( name );
	if ( !proj.exists( ) )
		proj.create( null );
	if ( !proj.isOpen( ) )
		proj.open( null );
	return proj;
}
 
Example 7
Source File: NewMavenSarlProjectWizard.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public boolean performFinish() {
	if (!super.performFinish()) {
		return false;
	}
	final Job job = new WorkspaceJob("Force the SARL nature") { //$NON-NLS-1$
		@SuppressWarnings({ "deprecation", "synthetic-access" })
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			final Model model = NewMavenSarlProjectWizard.this.lastModel;
			if (model != null) {
				final Plugin plugin = Iterables.find(model.getBuild().getPlugins(), it -> PLUGIN_ARTIFACT_ID.equals(it.getArtifactId()));
				plugin.setExtensions(true);
				final IWorkspace workspace = ResourcesPlugin.getWorkspace();
				final IWorkspaceRoot root = workspace.getRoot();
				final IProject project = NewMavenSarlProjectWizard.this.importConfiguration.getProject(root, model);
				// Fixing the "extensions" within the pom file
				final IFile pomFile = project.getFile(IMavenConstants.POM_FILE_NAME);
				pomFile.delete(true, new NullProgressMonitor());
				MavenPlugin.getMavenModelManager().createMavenModel(pomFile, model);
				// Update the project
				final SubMonitor submon = SubMonitor.convert(monitor);
				MavenPlugin.getProjectConfigurationManager().updateProjectConfiguration(project, submon.newChild(1));
				project.refreshLocal(IResource.DEPTH_ONE, submon.newChild(1));
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
	job.schedule();
	return true;
}
 
Example 8
Source File: EclipseFileSystemTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetURIForImportedProject() {
  try {
    final IWorkspace ws = ResourcesPlugin.getWorkspace();
    final IWorkspaceRoot root = ws.getRoot();
    final IProjectDescription description = ws.newProjectDescription("bar");
    description.setLocation(root.getLocation().append("foo/bar"));
    final IProject project = root.getProject("bar");
    project.create(description, null);
    project.open(null);
    final Path file = new Path("/bar/Foo.text");
    Assert.assertFalse(this.fs.exists(file));
    Assert.assertNull(this.fs.toURI(file));
    try {
      this.fs.setContents(file, "Hello Foo");
      Assert.fail();
    } catch (final Throwable _t) {
      if (_t instanceof IllegalArgumentException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
    Assert.assertFalse(this.fs.exists(file));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 9
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 10
Source File: EclipseUtils.java    From mappwidget with Apache License 2.0 5 votes vote down vote up
public static File getCurrentWorkspace()
{
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IWorkspaceRoot root = workspace.getRoot();

	IPath location = root.getLocation();
	location.toFile();

	return location.toFile();
}
 
Example 11
Source File: AddProjectNatureTest.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Test Class setup
 *
 * @throws Exception
 *             on error
 */
@BeforeClass
public static void init() throws Exception {
    IProgressMonitor progressMonitor = new NullProgressMonitor();
    IWorkspace workspace = ResourcesPlugin.getWorkspace();

    SWTBotUtils.initialize();

    /* Set up for SWTBot */
    SWTBotPreferences.TIMEOUT = 20000; /* 20 second timeout */
    SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US";
    fLogger.removeAllAppenders();
    fLogger.addAppender(new ConsoleAppender(new SimpleLayout(), ConsoleAppender.SYSTEM_OUT));
    fBot = new SWTWorkbenchBot();

    /* Finish waiting for eclipse to load */
    WaitUtils.waitForJobs();

    // Manually create C project
    fWorkspaceRoot = workspace.getRoot();
    fSomeProject = fWorkspaceRoot.getProject(SOME_PROJECT_NAME);
    fSomeProject.create(progressMonitor);
    fSomeProject.open(progressMonitor);
    IProjectDescription description = fSomeProject.getDescription();
    description.setNatureIds(new String[] { "org.eclipse.cdt.core.cnature" });
    fSomeProject.setDescription(description, null);
    fSomeProject.open(progressMonitor);

    /* set up test trace */
    URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(TRACE_PATH), null);
    URI uri;
    try {
        uri = FileLocator.toFileURL(location).toURI();
        fTestFile = new File(uri);
    } catch (URISyntaxException | IOException e) {
        fail(e.getMessage());
    }
    assumeTrue(fTestFile.exists());

    /* setup timestamp preference */
    IEclipsePreferences defaultPreferences = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
    defaultPreferences.put(ITmfTimePreferencesConstants.DATIME, "MMM d HH:mm:ss");
    defaultPreferences.put(ITmfTimePreferencesConstants.SUBSEC, ITmfTimePreferencesConstants.SUBSEC_NO_FMT);
    TmfTimestampFormat.updateDefaultFormats();
}
 
Example 12
Source File: WorkspaceClassPathFinder.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
private List getExistingEntries( IClasspathEntry[] classpathEntries,IProject project )
{
	ArrayList newClassPath = new ArrayList( );
	for ( int i = 0; i < classpathEntries.length; i++ )
	{
		IClasspathEntry curr = classpathEntries[i];
		if ( curr.getEntryKind( ) == IClasspathEntry.CPE_LIBRARY )
		{
			try
			{
				boolean inWorkSpace = true;
				IWorkspace space = ResourcesPlugin.getWorkspace();
				if (space == null || space.getRoot( ) == null)
				{
					inWorkSpace = false;
				}
					
				IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot( );
				IPath path = curr.getPath( );
				if (root.findMember( path ) == null)
				{
					inWorkSpace = false;
				}
				
				if (inWorkSpace)
				{
					String absPath = getFullPath( path, root.findMember( path ).getProject( ));
				
					URL url = new URL("file:///" + absPath);//$NON-NLS-1$//file:/
					newClassPath.add(url);
				}
				else
				{
					newClassPath.add( curr.getPath( ).toFile( ).toURL( ) );
				}
				
			}
			catch ( MalformedURLException e )
			{
				// DO nothing
			}
		}
	}
	return newClassPath;
}
 
Example 13
Source File: ApplicationWorkbenchAdvisor.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IAdaptable getDefaultPageInput() {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    return workspace.getRoot();
}
 
Example 14
Source File: ProjectExplorerTraceActionsTest.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Test the backward compatibility
 */
@Test
public void testExperimentLinkBackwardCompatibility() {
    /*
     * close the editor for the trace to avoid name conflicts with the one for the
     * experiment
     */
    fBot.closeAllEditors();

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    final IProject project = root.getProject(TRACE_PROJECT_NAME);
    assertTrue(project.exists());
    TmfProjectElement projectElement = TmfProjectRegistry.getProject(project);

    // Get the experiment folder
    TmfExperimentFolder experimentsFolder = projectElement.getExperimentsFolder();
    assertNotNull("Experiment folder should exist", experimentsFolder);
    IFolder experimentsFolderResource = experimentsFolder.getResource();
    String experimentName = "exp";
    IFolder expFolder = experimentsFolderResource.getFolder(experimentName);
    assertFalse(expFolder.exists());

    // Create the experiment
    try {
        expFolder.create(true, true, null);
        IFile file = expFolder.getFile(TRACE_NAME);
        file.createLink(Path.fromOSString(fTestFile.getAbsolutePath()), IResource.REPLACE, new NullProgressMonitor());
    } catch (CoreException e) {
        fail("Failed to create the experiment");
    }

    fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus();
    SWTBotTreeItem experimentsItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectProject(fBot, TRACE_PROJECT_NAME), "Experiments");

    SWTBotTreeItem expItem = SWTBotUtils.getTraceProjectItem(fBot, experimentsItem, "exp");

    // find the trace under the experiment
    expItem.expand();
    expItem.getNode(TRACE_NAME);

    // Open the experiment
    expItem.contextMenu().menu("Open").click();
    fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, experimentName));
}
 
Example 15
Source File: CloneForeignModelHandler.java    From tlaplus with MIT License 4 votes vote down vote up
private TreeMap<String, TreeSet<Model>> buildMap() {
       final Spec currentSpec = ToolboxHandle.getCurrentSpec();
       if (currentSpec == null) {
       	return null;
       }
       
	final IProject specProject = currentSpec.getProject();
	final TreeMap<String, TreeSet<Model>> projectModelMap = new TreeMap<>();
	
	try {
		final IWorkspace iws = ResourcesPlugin.getWorkspace();
		final IWorkspaceRoot root = iws.getRoot();
		final IProject[] projects = root.getProjects();
		
		for (final IProject project : projects) {
			if (!specProject.equals(project)) {
				projectModelMap.put(project.getName(), new TreeSet<>(MODEL_SORTER));
			}
		}
		
		final String currentProjectName = specProject.getName();
		final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
		final ILaunchConfigurationType launchConfigurationType
				= launchManager.getLaunchConfigurationType(TLCModelLaunchDelegate.LAUNCH_CONFIGURATION_TYPE);
		final ILaunchConfiguration[] launchConfigurations
				= launchManager.getLaunchConfigurations(launchConfigurationType);
		for (final ILaunchConfiguration launchConfiguration : launchConfigurations) {
			final String projectName = launchConfiguration.getAttribute(IConfigurationConstants.SPEC_NAME, "-l!D!q_-l!D!q_-l!D!q_");
			if (!projectName.equals(currentProjectName)) {
				final TreeSet<Model> models = projectModelMap.get(projectName);
				
				if (models != null) {
					final Model model = launchConfiguration.getAdapter(Model.class);
					
					if (!model.isSnapshot()) {
						models.add(model);
					}
				} else {
					TLCUIActivator.getDefault().logError("Could not generate model map for [" + projectName + "]!");
				}
			}
		}
	} catch (final CoreException e) {
		TLCUIActivator.getDefault().logError("Building foreign model map.", e);
		
		return null;
	}
	
	return projectModelMap;
}
 
Example 16
Source File: ConvertToJava8RuntimeHandler.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
private static IWorkspaceRoot getWorkspaceRoot() {
  IWorkspace workspace = ResourcesPlugin.getWorkspace();
  return workspace.getRoot();
}
 
Example 17
Source File: FlutterLaunchConfig.java    From dartboard with Eclipse Public License 2.0 4 votes vote down vote up
public IProject getProject(String name) {
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IWorkspaceRoot root = workspace.getRoot();
	return root.getProject(name);
}
 
Example 18
Source File: BaseLaunchConfigTab.java    From dartboard with Eclipse Public License 2.0 4 votes vote down vote up
public IProject[] getProjectsInWorkspace() {
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IWorkspaceRoot root = workspace.getRoot();
	return root.getProjects();
}
 
Example 19
Source File: LaunchConfig.java    From dartboard with Eclipse Public License 2.0 4 votes vote down vote up
public IProject getProject(String name) {
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IWorkspaceRoot root = workspace.getRoot();
	return root.getProject(name);
}