下面列出了org.eclipse.core.resources.IWorkspace#getRoot ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
}
}
}
/** 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;
}
/**
* 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} });
}
/**
* 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;
}
@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);
}
}
/**
* 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;
}
public static File getCurrentWorkspace()
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IPath location = root.getLocation();
location.toFile();
return location.toFile();
}
@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;
}
/**
* 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;
}
/**
* 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;
}
public IProject getProject(String name) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
return root.getProject(name);
}
public IProject[] getProjectsInWorkspace() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
return root.getProjects();
}
public IProject getProject(String name) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
return root.getProject(name);
}
private static IWorkspaceRoot getWorkspaceRoot() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
return workspace.getRoot();
}
/**
* Copies the resources to the given destination. This method is called
* recursively to merge folders during folder copy.
*
* @param resources
* the resources to copy
* @param destination
* destination to which resources will be copied
* @param subMonitor
* a progress monitor for showing progress and for cancelation
*/
protected void copy(IResource[] resources, IPath destination, IProgressMonitor subMonitor) throws CoreException {
subMonitor.beginTask(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_CopyResourcesTask, resources.length);
for (int i = 0; i < resources.length; i++) {
IResource source = resources[i];
IPath destinationPath = destination.append(source.getName());
IWorkspace workspace = source.getWorkspace();
IWorkspaceRoot workspaceRoot = workspace.getRoot();
IResource existing = workspaceRoot.findMember(destinationPath);
if (source.getType() == IResource.FOLDER && existing != null) {
// the resource is a folder and it exists in the destination,
// copy the
// children of the folder.
if (homogenousResources(source, existing)) {
IResource[] children = ((IContainer) source).members();
copy(children, destinationPath, new SubProgressMonitor(subMonitor, 1));
} else {
// delete the destination folder, copying a linked folder
// over an unlinked one or vice versa. Fixes bug 28772.
delete(existing, new SubProgressMonitor(subMonitor, 0));
source.copy(destinationPath, IResource.SHALLOW, new SubProgressMonitor(subMonitor, 1));
}
} else {
if (existing != null) {
if (homogenousResources(source, existing)) {
copyExisting(source, existing, new SubProgressMonitor(subMonitor, 1));
} else {
// Copying a linked resource over unlinked or vice
// versa.
// Can't use setContents here. Fixes bug 28772.
delete(existing, new SubProgressMonitor(subMonitor, 0));
source.copy(destinationPath, IResource.SHALLOW, new SubProgressMonitor(subMonitor, 1));
}
} else {
source.copy(destinationPath, IResource.SHALLOW, new SubProgressMonitor(subMonitor, 1));
}
if (subMonitor.isCanceled()) {
throw new OperationCanceledException();
}
}
}
}
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;
}
/**
* 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();
}
/**
* 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));
}
@Override
public IAdaptable getDefaultPageInput() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
return workspace.getRoot();
}
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;
}