org.eclipse.core.resources.IWorkspace Java Examples

The following examples show how to use org.eclipse.core.resources.IWorkspace. 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: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #2
Source File: RenameResourceAction.java    From gama with 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 #3
Source File: MainProjectWizardPage.java    From sarl with 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 #4
Source File: WorkspaceSpecManager.java    From tlaplus with 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 #5
Source File: SyncGraphvizExportHandler.java    From gef with 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 #6
Source File: Repository.java    From bonita-studio with 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 #7
Source File: PythonBaseModelProvider.java    From Pydev with 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 #8
Source File: SpecTest.java    From tlaplus with 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 #9
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 #10
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 #11
Source File: TmfProjectRegistry.java    From tracecompass with 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 #12
Source File: TmfProjectRegistry.java    From tracecompass with 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 #13
Source File: WorkspaceDialog.java    From tmxeditor8 with 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 #14
Source File: TestsPdeAbapGitStagingUtil.java    From ADT_Frontend with 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 #15
Source File: ExportToTranslationDictionaryDialog.java    From ermasterr with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: ExportToTranslationDictionaryDialog.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
@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 #17
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 #18
Source File: JavaReconciler.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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 #19
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 #20
Source File: ProjectConfigurationFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #21
Source File: ReportPlugin.java    From birt with 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 #22
Source File: NewUZProjectWizardPage.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
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 #23
Source File: TmfProjectModelElement.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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
Source File: WizardNewReportCreationPage.java    From birt with 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 #25
Source File: ToolboxExplorerResourceListener.java    From tlaplus with MIT License 5 votes vote down vote up
public void postWorkbenchWindowOpen() {
	// We might have missed events during Toolbox startup when there was
	// a workspace but no UI yet.
	resourceChanged(null);
	
	// update CNF viewers
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(this);
}
 
Example #26
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createPackageHtml(IPackageFragmentRoot root, IProgressMonitor monitor) throws CoreException {
	IWorkspace workspace= ResourcesPlugin.getWorkspace();
	IFolder createdPackage= workspace.getRoot().getFolder(fCreatedPackageFragment.getPath());
	IFile packageHtml= createdPackage.getFile(PACKAGE_HTML_FILENAME);
	String charset= packageHtml.getCharset();
	String content= buildPackageHtmlContent(root, charset);
	try {
		packageHtml.create(new ByteArrayInputStream(content.getBytes(charset)), false, monitor);
	} catch (UnsupportedEncodingException e) {
		String message= "charset " + charset + " not supported by platform"; //$NON-NLS-1$ //$NON-NLS-2$
		throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, message, e));
	}
}
 
Example #27
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 #28
Source File: WebAppMainTab.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the project exists and it uses GWT.
 */
private boolean isValidProject(String projectName, ILaunchConfiguration launchConfig) {
  if (projectName.length() == 0) {
    setErrorMessage("Project was not specified");
    return false;
  }

  IWorkspace workspace = ResourcesPlugin.getWorkspace();
  IStatus status = workspace.validateName(projectName, IResource.PROJECT);
  if (status.isOK()) {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    if (!project.exists()) {
      setErrorMessage(MessageFormat.format(LauncherMessages.JavaMainTab_20, projectName));
      return false;
    }

    if (!project.isOpen()) {
      setErrorMessage(MessageFormat.format(LauncherMessages.JavaMainTab_21, projectName));
      return false;
    }

    boolean isGwtProject = GWTNature.isGWTProject(project);

    if (!isGwtProject) {
      setErrorMessage("Project does not use GWT");
      return false;
    }
  } else {
    setErrorMessage(MessageFormat.format(LauncherMessages.JavaMainTab_19, status.getMessage()));
    return false;
  }

  return true;
}
 
Example #29
Source File: TrimTraceDialog.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private void validateNewTraceName() {

        String newTraceName = fNewElementName.getText();
        TmfCommonProjectElement element = fElement;
        IWorkspace workspace = element.getResource().getWorkspace();
        IStatus nameStatus = workspace.validateName(newTraceName, IResource.FOLDER);

        if ("".equals(newTraceName)) { //$NON-NLS-1$
            updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR,
                    Messages.Dialog_EmptyNameError, null));
            return;
        }

        if (!nameStatus.isOK()) {
            updateStatus(nameStatus);
            return;
        }

        IContainer parentFolder = element.getResource().getParent();
        if (parentFolder.findMember(newTraceName) != null) {
            updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR,
                    Messages.Dialog_ExistingNameError, null));
            return;
        }
        TmfTraceFolder tracesFolderElement = element.getProject().getTracesFolder();
        if (tracesFolderElement != null) {
            IFolder tracesFolder = tracesFolderElement.getResource();
            IPath traceDestinationPath = new Path(newTraceName);
            if (tracesFolder.getFolder(traceDestinationPath).exists()) {
                updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR,
                        Messages.Dialog_ExistingNameError, null));
                return;
            }
        }
        updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); //$NON-NLS-1$
    }
 
Example #30
Source File: SharedStateModule.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public Provider<IWorkspace> provideIWorkspace() {
	return new Provider<IWorkspace>() {
		@Override
		public IWorkspace get() {
			return ResourcesPlugin.getWorkspace();
		}
	};
}