Java Code Examples for org.eclipse.core.resources.IWorkspace

The following examples show how to use org.eclipse.core.resources.IWorkspace. These examples are extracted from open source projects. 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
@Override
protected String getErrorMessage() {
    if (isBlank(dictionaryNameText)) {
        return "error.translation.dictionary.name.empty";
    }

    final String fileName = dictionaryNameText.getText().trim();

    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IStatus result = workspace.validateName(fileName, IResource.FILE);
    if (!result.isOK()) {
        return result.getMessage();
    }

    final File file = new File(PreferenceInitializer.getTranslationPath(fileName));
    if (file.exists()) {
        return "error.translation.dictionary.name.duplicated";
    }

    return null;
}
 
Example 2
@Override
protected String getErrorMessage() {
	if (isBlank(this.dictionaryNameText)) {
		return "error.translation.dictionary.name.empty";
	}

	String fileName = this.dictionaryNameText.getText().trim();

	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IStatus result = workspace.validateName(fileName, IResource.FILE);
	if (!result.isOK()) {
		return result.getMessage();
	}

	File file = new File(PreferenceInitializer.getTranslationPath(fileName));
	if (file.exists()) {
		return "error.translation.dictionary.name.duplicated";
	}

	return null;
}
 
Example 3
/**
 * Returns a list of projects using this check configuration.
 *
 * @param checkConfig
 *          the check configuration
 * @return the list of projects using this configuration
 * @throws CheckstylePluginException
 *           an unexpected exception occurred
 */
public static List<IProject> getProjectsUsingConfig(ICheckConfiguration checkConfig)
        throws CheckstylePluginException {

  List<IProject> result = new ArrayList<>();

  IWorkspace workspace = ResourcesPlugin.getWorkspace();
  IProject[] projects = workspace.getRoot().getProjects();
  for (int i = 0; (i < projects.length); i++) {
    if (ProjectConfigurationFactory.getConfiguration(projects[i]).isConfigInUse(checkConfig)) {
      result.add(projects[i]);
    }
  }

  return result;
}
 
Example 4
protected boolean validatePage() {
  	canFinish=false;	
  	   getShell().setText(Messages.CREATEPROJECTWIZARD);
      IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();

      String projectFieldContents = getProjectNameFieldValue();
      if (projectFieldContents.equals("")) {
          setErrorMessage(null);
          setMessage(IDEWorkbenchMessages.WizardNewProjectCreationPage_projectNameEmpty);
          return false;
      }

      IStatus nameStatus = workspace.validateName(projectFieldContents,
              IResource.PROJECT);
      if (!nameStatus.isOK()) {
          setErrorMessage(nameStatus.getMessage());
          return false;
      }
     
      IProject handle = getProjectHandle();
      if (handle.exists()) {
          setErrorMessage(IDEWorkbenchMessages.WizardNewProjectCreationPage_projectExistsMessage);
          return false;
      }
return dialogChanged();
  }
 
Example 5
Source Project: ADT_Frontend   Source File: TestsPdeAbapGitStagingUtil.java    License: MIT License 6 votes vote down vote up
protected IProject createDummyAbapProject(String projectName) throws CoreException{
	String destinationId = projectName;
	
	IDestinationDataWritable data = AdtDestinationDataFactory.newDestinationData(destinationId);
	data.setUser("TEST_DUMMY_USER"); 
	data.setClient("777"); 
	data.setLanguage("DE"); 
	data.setPassword("TEST_DUMMY_PW"); 
	
	String projectDestinationId = AdtProjectServiceFactory.createProjectService().createDestinationId(projectName);
	final IDestinationData destinationData = data.getReadOnlyClone(projectDestinationId);
	
	final IAbapProjectService abapProjectService = AdtProjectServiceFactory.createProjectService();
	//IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	final AbapProject[] projects = new AbapProject[1];
	workspace.run(new IWorkspaceRunnable() {
		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			projects[0] = (AbapProject) abapProjectService.createAbapProject(projectName, destinationData, monitor);
		}
	}, new NullProgressMonitor());
	return projects[0].getProject();
}
 
Example 6
Source Project: tracecompass   Source File: TmfProjectRegistry.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get the project model element for a project resource
 * @param aProject the project resource
 * @param force a flag controlling whether a new project should be created if it doesn't exist
 * @return the project model element
 */
public static synchronized TmfProjectElement getProject(IProject aProject, boolean force) {
    IProject project = aProject;
    if (TmfProjectElement.showProjectRoot(project)) {
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IProject shadowProject = workspace.getRoot().getProject(TmfProjectModelHelper.getShadowProjectName(project.getName()));
        if (shadowProject.exists()) {
            project = shadowProject;
        }
    }
    TmfProjectElement element = registry.get(project);
    if (element == null && force) {
        element = new TmfProjectElement(project.getName(), project, null);
        registry.put(project, element);
        // force the model to be populated
        element.refreshChildren();
    }
    return element;
}
 
Example 7
/**
 * 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 8
Source Project: Pydev   Source File: PyCodeCoverageView.java    License: 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 9
Source Project: tlaplus   Source File: SpecTest.java    License: MIT License 6 votes vote down vote up
private void createDelete(final String specName, boolean forget) throws IOException, CoreException {
	// Create...
	final File tempFile = File.createTempFile(specName, TLAConstants.Files.TLA_EXTENSION);
	final Spec spec = Spec.createNewSpec("TestCreateDeleteSpec", tempFile.getAbsolutePath(), false, new NullProgressMonitor());
	final IProject project = spec.getProject();
	
	final WorkspaceSpecManager wsm = new WorkspaceSpecManager(new NullProgressMonitor());
	wsm.removeSpec(spec, new NullProgressMonitor(), forget);
	
	// Make sure that the project has been deleted.
	assertFalse(project.exists());
	final IWorkspace ws = ResourcesPlugin.getWorkspace();
	for (final IProject aProject : ws.getRoot().getProjects()) {
		assertNotSame(project.getName(), aProject.getName());
	}
	
	Spec mostRecentlyOpenedSpec = wsm.getMostRecentlyOpenedSpec();
	assertNull(mostRecentlyOpenedSpec != null ? mostRecentlyOpenedSpec.getName() : "", mostRecentlyOpenedSpec);
}
 
Example 10
Source Project: bonita-studio   Source File: Repository.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Repository(final IWorkspace workspace,
        final IProject project,
        final ExtensionContextInjectionFactory extensionContextInjectionFactory,
        final JDTTypeHierarchyManager jdtTypeHierarchyManager,
        final ProjectManifestFactory projectManifestFactory,
        final ProjectClasspathFactory bonitaBPMProjectClasspath,
        final boolean migrationEnabled) {
    this.workspace = workspace;
    this.project = project;
    this.jdtTypeHierarchyManager = jdtTypeHierarchyManager;
    this.migrationEnabled = migrationEnabled;
    this.extensionContextInjectionFactory = extensionContextInjectionFactory;
    this.projectManifestFactory = projectManifestFactory;
    this.bonitaBPMProjectClasspath = bonitaBPMProjectClasspath;
    this.projectFileListener = createProjectFileChangeListener();
}
 
Example 11
Source Project: tlaplus   Source File: WorkspaceSpecManager.java    License: MIT License 6 votes vote down vote up
/**
 * Destructor
 */
public void terminate()
{
    IWorkspace ws = ResourcesPlugin.getWorkspace();
    ws.removeResourceChangeListener(this);
    if (this.loadedSpec != null
            && PreferenceStoreHelper.getInstancePreferenceStore().getBoolean(
                    IPreferenceConstants.I_RESTORE_LAST_SPEC))
    {
        PreferenceStoreHelper.getInstancePreferenceStore().setValue(IPreferenceConstants.I_SPEC_LOADED,
                this.loadedSpec.getName());
    } else
    {
        PreferenceStoreHelper.getInstancePreferenceStore().setValue(IPreferenceConstants.I_SPEC_LOADED, "");
    }

}
 
Example 12
Source Project: tracecompass   Source File: TmfProjectRegistry.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static void handleParentProjectRefresh(IProject project) {
    Job job = Job.createSystem("TmfProjectRegistry.handleParentProjectRefresh Job", monitor -> { //$NON-NLS-1$
        if (!project.exists() || !project.isOpen()) {
            return;
        }
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IProject shadowProject = workspace.getRoot().getProject(TmfProjectModelHelper.getShadowProjectName(project.getName()));
        if (shadowProject.exists()) {
            try {
                shadowProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
            } catch (CoreException e) {
                Activator.getDefault().logError("Error refeshing shadow project " + shadowProject.getName(), e); //$NON-NLS-1$
            }
        }
    });
    job.schedule();
}
 
Example 13
Source Project: gama   Source File: RenameResourceAction.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the new name to be given to the target resource.
 *
 * @return java.lang.String
 * @param resource
 *            the resource to query status on
 */
protected String queryNewResourceName(final IResource resource) {
	final IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
	final IPath prefix = resource.getFullPath().removeLastSegments(1);
	final IInputValidator validator = string -> {
		if (resource.getName().equals(string)) {
			return IDEWorkbenchMessages.RenameResourceAction_nameMustBeDifferent;
		}
		final IStatus status = workspace.validateName(string, resource.getType());
		if (!status.isOK()) { return status.getMessage(); }
		if (workspace.getRoot().exists(prefix.append(string))) {
			return IDEWorkbenchMessages.RenameResourceAction_nameExists;
		}
		return null;
	};

	final InputDialog dialog =
			new InputDialog(WorkbenchHelper.getShell(), IDEWorkbenchMessages.RenameResourceAction_inputDialogTitle,
					IDEWorkbenchMessages.RenameResourceAction_inputDialogMessage, resource.getName(), validator);
	dialog.setBlockOnOpen(true);
	final int result = dialog.open();
	if (result == Window.OK) { return dialog.getValue(); }
	return null;
}
 
Example 14
Source Project: sarl   Source File: MainProjectWizardPage.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("synthetic-access")
@Override
public void update(Observable observable, Object arg) {
	try {
		final IWorkspace workspace = JavaPlugin.getWorkspace();
		final String name = MainProjectWizardPage.this.nameGroup.getName();
		checkProjectName(workspace, name);
		final IProject handle = checkProjectExist(workspace, name);
		final String location = MainProjectWizardPage.this.locationGroup.getLocation().toOSString();
		final IPath projectPath = checkLocationSyntax(location);
		validateLocation(workspace, handle, projectPath);

		setErrorMessage(null);
		setMessage(null);
		setPageComplete(true);

	} catch (ValidationException e) {
		setMessage(e.getMessage());
		setErrorMessage(e.getErrorMessage());
		setPageComplete(false);
	}
}
 
Example 15
Source Project: tmxeditor8   Source File: WorkspaceDialog.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object[] getChildren(Object element) {
	if (element instanceof IWorkspace) {
		// check if closed projects should be shown
		IProject[] allProjects = ((IWorkspace) element).getRoot().getProjects();
		if (showClosedProjects) {
			return allProjects;
		}

		ArrayList<IProject> accessibleProjects = new ArrayList<IProject>();
		for (int i = 0; i < allProjects.length; i++) {
			if (allProjects[i].isOpen()) {
				accessibleProjects.add(allProjects[i]);
			}
		}
		return accessibleProjects.toArray();
	}

	return super.getChildren(element);
}
 
Example 16
Source Project: birt   Source File: WizardNewReportCreationPage.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private boolean isInValidFilePath() {
	String fn = getFileName();

	IPath resourcePath;
	if (!fn.endsWith("." + fileExtension)) //$NON-NLS-1$
	{
		resourcePath = getContainerFullPath().append(
				getFileName() + "." + fileExtension); //$NON-NLS-1$
	} else
		resourcePath = getContainerFullPath().append(getFileName());

	IWorkspace workspace = ResourcesPlugin.getWorkspace();

	IStatus result = workspace.validatePath(resourcePath
			.removeFileExtension().toString(), IResource.FOLDER);

	if (!result.isOK()) {
		setErrorMessage(result.getMessage());
		return true;
	}

	return false;
}
 
Example 17
Source Project: birt   Source File: ReportPlugin.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return the cheat sheet property preference, stored in the workbench root
 */
public static boolean readCheatSheetPreference( )
{
	IWorkspace workspace = ResourcesPlugin.getWorkspace( );
	try
	{
		String property = workspace.getRoot( )
				.getPersistentProperty( new QualifiedName( "org.eclipse.birt.property", //$NON-NLS-1$
						"showCheatSheet" ) ); //$NON-NLS-1$
		if ( property != null )
			return Boolean.valueOf( property ).booleanValue( );
	}
	catch ( CoreException e )
	{
		logger.log( Level.SEVERE, e.getMessage( ), e );
	}
	return true;
}
 
Example 18
Source Project: tracecompass   Source File: ResourceUtilTest.java    License: 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 19
Source Project: Pydev   Source File: PythonBaseModelProvider.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param newWorkingSet
 */
private IWorkspace[] getWorkspaces(IWorkingSet newWorkingSet) {
    IAdaptable[] elements = newWorkingSet.getElements();
    HashSet<IWorkspace> set = new HashSet<IWorkspace>();

    for (IAdaptable adaptable : elements) {
        IResource adapter = adaptable.getAdapter(IResource.class);
        if (adapter != null) {
            IWorkspace workspace = adapter.getWorkspace();
            set.add(workspace);
        } else {
            Log.log("Was not expecting that IWorkingSet adaptable didn't return anything...");
        }
    }
    return set.toArray(new IWorkspace[0]);
}
 
Example 20
/**
 * Returns a new name for a copy of the resource at the given path in the
 * given workspace. This name is determined automatically.
 *
 * @param originalName
 *            the full path of the resource
 * @param workspace
 *            the workspace
 * @return the new full path for the copy
 */
static IPath getAutoNewNameFor(IPath originalName, IWorkspace workspace) {
    int counter = 1;
    String resourceName = originalName.lastSegment();
    IPath leadupSegment = originalName.removeLastSegments(1);

    while (true) {
        String nameSegment;

        if (counter > 1) {
            nameSegment = NLS.bind("Copy ({0}) of {1}",
                    counter, resourceName);
        } else {
            nameSegment = NLS.bind("Copy of {0}", resourceName);
        }

        IPath pathToTry = leadupSegment.append(nameSegment);

        if (!workspace.getRoot().exists(pathToTry)) {
            return pathToTry;
        }

        counter++;
    }
}
 
Example 21
@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 22
Source Project: gef   Source File: SyncGraphvizExportHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(final IResourceDelta delta) {
	IResource resource = delta.getResource();
	if (resource.getType() == IResource.FILE
			&& ((IFile) resource).getName().endsWith(EXTENSION)) {
		try {
			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			if (!workspace.isTreeLocked()) {
				IFile file = (IFile) resource;
				workspace.run(new DotExportRunnable(file), null);
			}
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
	return true;
}
 
Example 23
/**
 * Returns the trace specific supplementary folder under the project's
 * supplementary folder. Its parent folders will be created if they don't exist.
 * If createFolder is true, the returned folder will be created, otherwise it
 * may not exist.
 *
 * @param supplFolderPath
 *            folder path relative to the project's supplementary folder
 * @param createFolder
 *            if true, the returned folder will be created
 * @param progressMonitor
 *            the progress monitor
 * @return the trace specific supplementary folder
 * @since 4.0
 */
public IFolder prepareTraceSupplementaryFolder(String supplFolderPath, boolean createFolder, IProgressMonitor progressMonitor) {
    SubMonitor subMonitor = SubMonitor.convert(progressMonitor);
    IFolder folder = getTraceSupplementaryFolder(supplFolderPath);
    IFolder propertiesFolder = folder.getFolder(TmfCommonConstants.TRACE_PROPERTIES_FOLDER);
    if ((createFolder && propertiesFolder.exists() && propertiesFolder.isHidden()) ||
            (!createFolder && folder.getParent().exists())) {
        return folder;
    }
    try {
        ICoreRunnable runnable = monitor -> {
            if (createFolder) {
                TraceUtils.createFolder(propertiesFolder, monitor);
                propertiesFolder.setHidden(true);
            } else {
                TraceUtils.createFolder((IFolder) folder.getParent(), monitor);
            }
        };
        ResourcesPlugin.getWorkspace().run(runnable, folder.getProject(), IWorkspace.AVOID_UPDATE, subMonitor);
    } catch (CoreException e) {
        Activator.getDefault().logError("Error creating supplementary folder " + folder.getFullPath(), e); //$NON-NLS-1$
    }
    return folder;
}
 
Example 24
@Override
public void uninstall() {

	IWorkbenchPartSite site= fTextEditor.getSite();
	IWorkbenchWindow window= site.getWorkbenchWindow();
	window.getPartService().removePartListener(fPartListener);
	fPartListener= null;

	Shell shell= window.getShell();
	if (shell != null && !shell.isDisposed())
		shell.removeShellListener(fActivationListener);
	fActivationListener= null;

	JavaCore.removeElementChangedListener(fJavaElementChangedListener);
	fJavaElementChangedListener= null;

	IWorkspace workspace= JavaPlugin.getWorkspace();
	workspace.removeResourceChangeListener(fResourceChangeListener);
	fResourceChangeListener= null;

	JavaPlugin.getDefault().getCombinedPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
	fPropertyChangeListener= null;

	super.uninstall();
}
 
Example 25
Source Project: birt   Source File: BirtWizardUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check folder if exist. If not, create it.
 * 
 * @param project
 * @param webContentFolder
 * @param folderName
 */
private static void checkFolder( IProject project, String webContentFolder,
		String folderName )
{
	if ( folderName == null )
		return;

	try
	{
		File file = new File( folderName );
		if ( file != null )
		{
			if ( file.exists( ) )
				return;

			if ( file.isAbsolute( ) )
			{
				// create absolute folder
				file.mkdir( );
			}
			else
			{
				// create folder in web content folder
				final IWorkspace ws = ResourcesPlugin.getWorkspace( );
				final IPath pjPath = project.getFullPath( );

				IPath configPath = pjPath.append( webContentFolder );
				IPath path = configPath.append( folderName );
				BirtWizardUtil.mkdirs( ws.getRoot( ).getFolder( path ) );
			}
		}
	}
	catch ( Exception e )
	{
		Logger.logException( Logger.WARNING, e );
	}
}
 
Example 26
private MarkerManager()
{
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(new IResourceChangeListener()
	{
		public void resourceChanged(IResourceChangeEvent event)
		{
			handleResourceChanged();
		}
	}, IResourceChangeEvent.PRE_BUILD);
}
 
Example 27
Source Project: APICloud-Studio   Source File: BuildUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Synchronous run of a builder with the given name on the given project.
 * 
 * @param project
 * @param kind
 *            See {@link IncrementalProjectBuilder} for the available types.
 * @param builderName
 * @param args
 * @param monitor
 * @return A status indicating if the build succeeded or failed
 */
public static IStatus syncBuild(IProject project, int kind, String builderName, Map args, IProgressMonitor monitor)
{
	try
	{
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		BuildManager buildManager = ((Workspace) workspace).getBuildManager();
		return buildManager.build(new BuildConfiguration(project), kind, builderName, args, monitor);
	}
	catch (IllegalStateException e)
	{
		return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error while getting the Workspace", e); //$NON-NLS-1$
	}
}
 
Example 28
Source Project: n4js   Source File: ProjectTestsUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Imports a project by reference into the workspace
 *
 * @return the created project
 */
public static IProject importProjectNotCopy(IWorkspace workspace, File rootFolder, IProgressMonitor progressMonitor)
		throws CoreException {
	IPath path = new org.eclipse.core.runtime.Path(new File(rootFolder, "_project").getAbsolutePath());
	IProjectDescription desc = workspace.loadProjectDescription(path);
	IProject project = workspace.getRoot().getProject(desc.getName());
	project.create(desc, progressMonitor);
	project.open(progressMonitor);
	return project;
}
 
Example 29
Source Project: tlaplus   Source File: ResourceHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Retrieves the project handle
 * @param name name of the project
 * @return a project handle
 */
public static IProject getProject(String name)
{
    if (name == null)
    {
        return null;
    }
    IWorkspace ws = ResourcesPlugin.getWorkspace();
    IProject project = ws.getRoot().getProject(name);

    return project;
}
 
Example 30
Source Project: n4js   Source File: ProjectStateChangeListener.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void resourceChanged(final IResourceChangeEvent event) {
	IWorkspace workspace = getWorkspace();
	if (workspace != null) {
		if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
			try {
				final Set<IProject> affectedProjects = Sets.newLinkedHashSet();
				event.getDelta().accept(projectCollector(affectedProjects));
				if (!affectedProjects.isEmpty()) {
					ToBeBuilt toBeBuilt = new ToBeBuilt();
					Set<URI> toBeUpdated = toBeBuilt.getToBeUpdated();
					Set<String> projectNames = new LinkedHashSet<>();
					for (IProject project : affectedProjects) {
						IFile file = project.getFile(N4JSGlobals.PACKAGE_JSON);
						if (file.exists()) {
							projectNames.add(project.getName());
							toBeUpdated.add(URI.createPlatformResourceURI(file.getFullPath().toString(), true));
						}

					}
					packageJsonQueue.enqueue(projectNames, toBeBuilt, false);
					syncIndexJob.schedule();
				}
			} catch (CoreException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
	}
	super.resourceChanged(event);
}