Java Code Examples for org.eclipse.core.resources.ResourcesPlugin#getWorkspace()

The following examples show how to use org.eclipse.core.resources.ResourcesPlugin#getWorkspace() . 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: PyCodeCoverageView.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run() {
    ContainerSelectionDialog dialog = new ContainerSelectionDialog(getSite().getShell(), null, false,
            "Choose folder to be analyzed in the code-coverage");
    dialog.showClosedProjects(false);
    if (dialog.open() != Window.OK) {
        return;
    }
    Object[] objects = dialog.getResult();
    if (objects.length == 1) { //only one folder can be selected
        if (objects[0] instanceof IPath) {
            IPath p = (IPath) objects[0];

            IWorkspace w = ResourcesPlugin.getWorkspace();
            IContainer folderForLocation = (IContainer) w.getRoot().findMember(p);
            setSelectedContainer(folderForLocation);
        }
    }
}
 
Example 2
Source File: ProjectTestsUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new workspace project with the given project location in the probands folder (cf.
 * {@code probandsName}).
 *
 * Creates a new workspace project with name {@code workspaceName}. Note that the project folder (based on the given
 * project location) and the project name may differ.
 *
 * Does not copy the proband resources into the workspaces, but keeps the project files at the given location (cf.
 * create new project with non-default location outside of workspace)
 *
 * @throws CoreException
 *             If the project creation does not succeed.
 */
public static IProject createProjectWithLocation(File probandsFolder, String projectLocationFolder,
		String workspaceName) throws CoreException {
	File projectSourceFolder = new File(probandsFolder, projectLocationFolder);
	if (!projectSourceFolder.exists()) {
		throw new IllegalArgumentException("proband not found in " + projectSourceFolder);
	}
	prepareDotProject(projectSourceFolder);

	IProgressMonitor monitor = new NullProgressMonitor();
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IProject project = workspace.getRoot().getProject(workspaceName);

	workspace.run((mon) -> {
		IProjectDescription newProjectDescription = workspace.newProjectDescription(workspaceName);
		final IPath absoluteProjectPath = new org.eclipse.core.runtime.Path(projectSourceFolder.getAbsolutePath());
		newProjectDescription.setLocation(absoluteProjectPath);
		project.create(newProjectDescription, mon);
		project.open(mon);
	}, monitor);

	return project;

}
 
Example 3
Source File: DefaultTemplateProjectCreator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, projectFactories.size());
	try {
		IWorkbench workbench = PlatformUI.getWorkbench();
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		for (ProjectFactory projectFactory : projectFactories) {
			projectFactory.setWorkbench(workbench);
			projectFactory.setWorkspace(workspace);
			projectFactory.createProject(subMonitor, null);
			subMonitor.worked(1);
		}
	} finally {
		subMonitor.done();
	}
}
 
Example 4
Source File: InternalBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static void setAutoBuild(boolean b) {
	System.out.println("Setting auto-build to " + b);

	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	try {
		IWorkspaceDescription desc = workspace.getDescription();
		desc.setAutoBuilding(b);
		workspace.setDescription(desc);
	} catch (CoreException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: AbstractGWTPluginTestCase.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static File createFile(IPath workspaceRelativeAbsPathOfFile, String contents) throws CoreException {
  // TODO: Convert to ResouceUtils.createFile
  Workspace workspace = (Workspace) ResourcesPlugin.getWorkspace();
  File file = (File) workspace.newResource(workspaceRelativeAbsPathOfFile, IResource.FILE);
  ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contents.getBytes());
  file.create(byteArrayInputStream, false, null);
  JobsUtilities.waitForIdle();
  return file;
}
 
Example 6
Source File: BuilderUtils.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean setAutoBuilding(boolean state) throws CoreException {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceDescription desc = workspace.getDescription();
    boolean isAutoBuilding = desc.isAutoBuilding();
    if (isAutoBuilding != state) {
        desc.setAutoBuilding(state);
        workspace.setDescription(desc);
    }
    return isAutoBuilding;
}
 
Example 7
Source File: EclipseProjectImporter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void importDir(java.nio.file.Path dir, IProgressMonitor m) {
	SubMonitor monitor = SubMonitor.convert(m, 4);
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IPath dotProjectPath = new Path(dir.resolve(DESCRIPTION_FILE_NAME).toAbsolutePath().toString());
	IProjectDescription descriptor;
	try {
		descriptor = workspace.loadProjectDescription(dotProjectPath);
		String name = descriptor.getName();
		if (!descriptor.hasNature(JavaCore.NATURE_ID)) {
			return;
		}
		IProject project = workspace.getRoot().getProject(name);
		if (project.exists()) {
			IPath existingProjectPath = project.getLocation();
			existingProjectPath = fixDevice(existingProjectPath);
			dotProjectPath = fixDevice(dotProjectPath);
			if (existingProjectPath.equals(dotProjectPath.removeLastSegments(1))) {
				project.open(IResource.NONE, monitor.newChild(1));
				project.refreshLocal(IResource.DEPTH_INFINITE, monitor.newChild(1));
				return;
			} else {
				project = findUniqueProject(workspace, name);
				descriptor.setName(project.getName());
			}
		}
		project.create(descriptor, monitor.newChild(1));
		project.open(IResource.NONE, monitor.newChild(1));
	} catch (CoreException e) {
		JavaLanguageServerPlugin.log(e.getStatus());
		throw new RuntimeException(e);
	} finally {
		monitor.done();
	}
}
 
Example 8
Source File: CreateAppEngineWtpProject.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(IProgressMonitor monitor) throws InvocationTargetException, CoreException {
  IWorkspace workspace = ResourcesPlugin.getWorkspace();
  IProject newProject = config.getProject();
  URI location = config.getEclipseProjectLocationUri();

  String name = newProject.getName();
  IProjectDescription description = workspace.newProjectDescription(name);
  description.setLocationURI(location);

  String operationLabel = getDescription();
  SubMonitor subMonitor = SubMonitor.convert(monitor, operationLabel, 120);
  CreateProjectOperation operation = new CreateProjectOperation(description, operationLabel);
  try {
    operation.execute(subMonitor.newChild(10), uiInfoAdapter);
    mostImportant = createAndConfigureProjectContent(newProject, config, subMonitor.newChild(80));
  } catch (ExecutionException ex) {
    throw new InvocationTargetException(ex);
  }

  IFacetedProject facetedProject = ProjectFacetsManager.create(
      newProject, true /* convertIfNecessary */, subMonitor.newChild(5));
  addAppEngineFacet(facetedProject, subMonitor.newChild(6));

  addAdditionalDependencies(newProject, config, subMonitor.newChild(20));

  fixTestSourceDirectorySettings(newProject, subMonitor.newChild(5));
}
 
Example 9
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validates that the given source resources can be copied to the
 * destination as decided by the VCM provider.
 *
 * @param destination
 *            copy destination
 * @param sourceResources
 *            source resources
 * @return <code>true</code> all files passed validation or there were no
 *         files to validate. <code>false</code> one or more files did not
 *         pass validation.
 */
private boolean validateEdit(IContainer destination, IResource[] sourceResources) {
    ArrayList<IFile> copyFiles = new ArrayList<IFile>();

    collectExistingReadonlyFiles(destination.getFullPath(), sourceResources, copyFiles);
    if (copyFiles.size() > 0) {
        IFile[] files = copyFiles.toArray(new IFile[copyFiles.size()]);
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IStatus status = workspace.validateEdit(files, messageShell);

        canceled = status.isOK() == false;
        return status.isOK();
    }
    return true;
}
 
Example 10
Source File: ProjectActionGroup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void dispose() {
	fSelectionProvider.removeSelectionChangedListener(fSelectionChangedListener);
	fSelectionProvider= null;

	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.removeResourceChangeListener(fOpenAction);
	workspace.removeResourceChangeListener(fCloseAction);
	workspace.removeResourceChangeListener(fCloseUnrelatedAction);
	super.dispose();
}
 
Example 11
Source File: SootRunner.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
private static Collection<String> applicationClassPath(final IJavaProject javaProject) {
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	try {
		final List<String> urls = new ArrayList<>();
		final URI uriString = workspace.getRoot().getFile(javaProject.getOutputLocation()).getLocationURI();
		urls.add(new File(uriString).getAbsolutePath());
		return urls;
	}
	catch (final Exception e) {
		Activator.getDefault().logError(e, "Error building project classpath");
		return Lists.newArrayList();
	}
}
 
Example 12
Source File: ResourceUtils.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
public static void scheduleWorkspaceRunnable(final IWorkspaceRunnable operation, String jobCaption, boolean user) throws CoreException {
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	scheduleWorkspaceRunnable(operation, workspace.getRoot(), jobCaption, user);
}
 
Example 13
Source File: NewFolderAction.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the new name to be given to the target resource.
 * 
 * @param container
 *            the container to query status on
 * @return the new name to be given to the target resource.
 */
private String queryNewResourceName( final File container )
{
	final IWorkspace workspace = ResourcesPlugin.getWorkspace( );

	IInputValidator validator = new IInputValidator( ) {

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.jface.dialogs.IInputValidator#isValid(java.lang.String)
		 */
		public String isValid( String string )
		{
			if ( string == null || string.length( ) <= 0 )
			{
				return Messages.getString( "NewFolderAction.emptyName" ); //$NON-NLS-1$
			}

			File newPath = new File( container, string );

			if ( newPath.exists( ) )
			{
				return Messages.getString( "NewFolderAction.nameExists" ); //$NON-NLS-1$
			}

			IStatus status = workspace.validateName( newPath.getName( ),
					IResource.FOLDER );

			if ( !status.isOK( ) )
			{
				return status.getMessage( );
			}
			return null;
		}
	};

	InputDialog dialog = new InputDialog( getShell( ),
			Messages.getString( "NewFolderAction.inputDialogTitle" ), //$NON-NLS-1$
			Messages.getString( "NewFolderAction.inputDialogMessage" ), //$NON-NLS-1$
			"", //$NON-NLS-1$
			validator );

	dialog.setBlockOnOpen( true );
	int result = dialog.open( );
	if ( result == Window.OK )
	{
		return dialog.getValue( );
	}
	return null;
}
 
Example 14
Source File: WorkspaceSpecManager.java    From tlaplus with MIT License 4 votes vote down vote up
/**
 * Constructor
 */
public WorkspaceSpecManager(final IProgressMonitor monitor)
{
    // initialize the spec life cycle manager
    lifecycleManager = new SpecLifecycleManager();

    final IWorkspace ws = ResourcesPlugin.getWorkspace();

    final String specLoadedName = PreferenceStoreHelper.getInstancePreferenceStore().getString(
            IPreferenceConstants.I_SPEC_LOADED);

    final IProject[] projects = ws.getRoot().getProjects();
    try
    {

        for (int i = 0; i < projects.length; i++)
        {
            // changed from projects[i].isAccessible()
            final IProject project = projects[i];
if (project.isOpen())
            {
                if (project.hasNature(TLANature.ID))
                {
		// Refresh the project in case the actual on-disk
		// representation and the cached Eclipse representation
		// have diverged. This can happen when e.g. another
		// Toolbox opens the project or the files get manually
		// edited. Without calling refresh, code down below 
                	// might throw exceptions due to out-of-sync problems.  
                	project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                    
                	final Spec spec = new Spec(project);
                    // Added by LL on 12 Apr 2011
                    // If spec.rootFile = null, then this is a bad spec. So
                    // we should report it and not perform addSpec(spec).  It
                    // would be nice if we could report it to the user, but
                    // it seems to be impossible to popup a window at this point
                    // in the code.
                    if (spec.getRootFile() == null)
                    {
                        Activator.getDefault().logError("The bad spec is: `" + project.getName() + "'", null);
                    } else
                    {
                        // This to threw a null pointer exception for Tom, probably causing the abortion
                        // of the Toolbox start. But it started on the next attempt.  Should we catch the
                        // and perhaps report the bad spec?
                        addSpec(spec);
                    }
                    
                    // load the spec if found
                    if (spec.getName().equals(specLoadedName))
                    {
                        this.setSpecLoaded(spec);
                    }
                }
            } else
            {
                // DELETE closed projects
                project.delete(IResource.FORCE | IResource.ALWAYS_DELETE_PROJECT_CONTENT, monitor);
            }
        }

        if (specLoadedName != null && !specLoadedName.equals("") && this.loadedSpec == null)
        {
            // there was a spec loaded but it was not found
            // explicit un-set it
            setSpecLoaded(null);
        }

    } catch (CoreException e)
    {
        Activator.getDefault().logError("Error initializing specification workspace", e);
    }

    ws.addResourceChangeListener(this);
    
    Platform.getAdapterManager().registerAdapters(this, IProject.class);
}
 
Example 15
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 16
Source File: SootPlugin.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns the workspace instance.
 */
public static IWorkspace getWorkspace() {
	return ResourcesPlugin.getWorkspace();
}
 
Example 17
Source File: WorkbenchNavigatorPlugin.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return the workspace instance.
 */
public static IWorkspace getWorkspace() {
	return ResourcesPlugin.getWorkspace();
}
 
Example 18
Source File: IDEReportClasspathResolver.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
private List<String> getAllClassPathFromEntries(List<IClasspathEntry> list)
{
	List<String> retValue = new ArrayList();
	IWorkspace space = ResourcesPlugin.getWorkspace( );
	IWorkspaceRoot root = space.getRoot( );
	
	
	for (int i=0; i<list.size( ); i++)
	{
		IClasspathEntry curr = list.get( i );
		boolean inWorkSpace = true;
		
		if ( space == null || space.getRoot( ) == null )
		{
			inWorkSpace = false;
		}

		IPath path = curr.getPath( );
		if (curr.getEntryKind( ) == IClasspathEntry.CPE_VARIABLE)
		{
			path = JavaCore.getClasspathVariable( path.segment( 0 ) );
		}
		else
		{
			path = JavaCore.getResolvedClasspathEntry( curr ).getPath( );
		}
		
		if (curr.getEntryKind( ) == IClasspathEntry.CPE_PROJECT)
		{
			if (root.findMember( path ) instanceof IProject)
			{
				List<String> strs = getProjectClasspath( (IProject)root.findMember( path ),false, true );
				for (int j=0; j<strs.size( ); j++)
				{
					addToList( retValue, strs.get( j ) );
				}
			}
		}
		else
		{
			if ( root.findMember( path ) == null )
			{
				inWorkSpace = false;
			}

			if ( inWorkSpace )
			{
				String absPath = getFullPath( path,
						root.findMember( path ).getProject( ) );

				//retValue.add( absPath );
				addToList( retValue, absPath );
			}
			else
			{
				//retValue.add( path.toFile( ).getAbsolutePath( ));
				addToList( retValue, path.toFile( ).getAbsolutePath( ) );
			}
		}
	
		//strs.add( JavaCore.getResolvedClasspathEntry( entry ).getPath( ).toFile( ).getAbsolutePath( ) );
	}
	return retValue;
}
 
Example 19
Source File: ProjectHelper.java    From eclipse-extras with Eclipse Public License 1.0 4 votes vote down vote up
private IProjectDescription createProjectDescription() {
  IWorkspace workspace = ResourcesPlugin.getWorkspace();
  IProjectDescription result = workspace.newProjectDescription( projectName );
  result.setLocation( projectLocation );
  return result;
}
 
Example 20
Source File: JgPlugin.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the workspace instance.
 *
 * @return the workspace
 */
public static IWorkspace getWorkspace() {
  return ResourcesPlugin.getWorkspace();
}