Java Code Examples for org.eclipse.core.resources.IWorkspaceRoot#findMember()

The following examples show how to use org.eclipse.core.resources.IWorkspaceRoot#findMember() . 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: BazelClasspathContainer.java    From eclipse with Apache License 2.0 6 votes vote down vote up
private boolean isSourcePath(String path) throws JavaModelException, BackingStoreException {
  Path pp = new File(instance.getWorkspaceRoot().toString() + File.separator + path).toPath();
  IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
  for (IClasspathEntry entry : project.getRawClasspath()) {
    if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
      IResource res = root.findMember(entry.getPath());
      if (res != null) {
        String file = res.getLocation().toOSString();
        if (!file.isEmpty() && pp.startsWith(file)) {
          IPath[] inclusionPatterns = entry.getInclusionPatterns();
          if (!matchPatterns(pp, entry.getExclusionPatterns()) && (inclusionPatterns == null
              || inclusionPatterns.length == 0 || matchPatterns(pp, inclusionPatterns))) {
            return true;
          }
        }
      }
    }
  }
  return false;
}
 
Example 2
Source File: ClassPathContainer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IAdaptable[] getChildren() {
	List<IAdaptable> list= new ArrayList<IAdaptable>();
	IPackageFragmentRoot[] roots= getPackageFragmentRoots();
	for (int i= 0; i < roots.length; i++) {
		list.add(roots[i]);
	}
	if (fContainer != null) {
		IClasspathEntry[] classpathEntries= fContainer.getClasspathEntries();
		if (classpathEntries == null) {
			// invalid implementation of a classpath container
			JavaPlugin.log(new IllegalArgumentException("Invalid classpath container implementation: getClasspathEntries() returns null. " + fContainer.getPath())); //$NON-NLS-1$
		} else {
			IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
			for (int i= 0; i < classpathEntries.length; i++) {
				IClasspathEntry entry= classpathEntries[i];
				if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
					IResource resource= root.findMember(entry.getPath());
					if (resource instanceof IProject)
						list.add(new RequiredProjectWrapper(this, JavaCore.create((IProject) resource)));
				}
			}
		}
	}
	return list.toArray(new IAdaptable[list.size()]);
}
 
Example 3
Source File: CompilerWorkingDirectoryBlock.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the selected workspace container,or <code>null</code>
 */
public static IContainer getContainer(String path) {
    if (path.length() > 0) {
        IResource res = null;
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        if (path.startsWith("${workspace_loc:")) { //$NON-NLS-1$
            try {
                path = VariableUtils.performStringSubstitution(path, false);
                IPath uriPath = new Path(path).makeAbsolute();
                IContainer[] containers = root.findContainersForLocationURI(URIUtil.toURI(uriPath));
                if (containers.length > 0) {
                    res = containers[0];
                }
            } 
            catch (CoreException e) {
            }
        } 
        else {      
            res = root.findMember(path);
        }
        if (res instanceof IFile) {
            res = ((IFile)res).getParent();
        }
        if (res instanceof IContainer) {
            return (IContainer)res;
        }
    }
    return null;
}
 
Example 4
Source File: ResourceUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a resource for the given absolute or workspace-relative path.
 * <p>
 * If the path has a device (e.g. c:\ on Windows), it will be tried as an
 * absolute path. Otherwise, it is first tried as a workspace-relative path,
 * and failing that an absolute path.
 *
 * @param path the absolute or workspace-relative path to a resource
 * @return the resource, or null
 */
// TODO(tparker): Check against the internal implementation, which was tricky to get right.
public static IResource getResource(IPath path) {
  IResource res = null;
  if (path != null) {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    if (path.getDevice() == null) {
      // try searching relative to the workspace first
      res = root.findMember(path);
    }

    if (res == null) {
      // look for files
      IFile[] files = root.findFilesForLocation(path);
      // Check for accessibility since for directories, the above will return
      // a non-accessible IFile
      if (files.length > 0 && files[0].isAccessible()) {
        res = files[0];
      }
    }

    if (res == null) {
      // look for folders
      IContainer[] containers = root.findContainersForLocation(path);
      if (containers.length > 0) {
        res = containers[0];
      }
    }
  }
  return res;
}
 
Example 5
Source File: AbstractNewDocumentOutputPart.java    From depan with Apache License 2.0 5 votes vote down vote up
@Override
public IFile getOutputFile() throws CoreException {
  IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
  IResource resource = root.findMember(new Path(getContainerName()));
  if (!resource.exists() || !(resource instanceof IContainer)) {
    throwCoreException(
        "Container \"" + getContainerName() + "\" does not exist.");
  }

  IContainer container = (IContainer) resource;
  final IFile file = container.getFile(new Path(getFilename()));
  return file;
}
 
Example 6
Source File: CheckJavaValidatorUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the workspace member.
 *
 * @param name
 *          the name
 * @return the workspace member
 */
private IResource getWorkspaceMember(final String name) {
  IWorkspaceRoot workspaceRoot = EcorePlugin.getWorkspaceRoot();
  if (workspaceRoot == null) {
    return null;
  }
  return workspaceRoot.findMember(new Path(name));
}
 
Example 7
Source File: ResourceUtils.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param relativePath
 *            workspace relative path
 * @return given path if path is not known in workspace
 */
public static IPath relativeToAbsolute(IPath relativePath) {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = root.findMember(relativePath);
    if (resource != null) {
        return resource.getLocation();
    }
    return relativePath;
}
 
Example 8
Source File: BuildPathDialogAccess.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Shows the UI to select new JAR or ZIP archive entries located in the workspace.
 * The dialog returns the selected entries or <code>null</code> if the dialog has
 * been canceled. The dialog does not apply any changes.
 *
 * @param shell The parent shell for the dialog.
 * @param initialSelection The path of the element (container or archive) to initially select or <code>null</code> to not select an entry.
 * @param usedEntries An array of paths that are already on the classpath and therefore should not be
 * selected again.
 * @return Returns the new JAR paths or <code>null</code> if the dialog has
 * been canceled by the user.
 */
public static IPath[] chooseJAREntries(Shell shell, IPath initialSelection, IPath[] usedEntries) {
	if (usedEntries == null) {
		throw new IllegalArgumentException();
	}

	Class<?>[] acceptedClasses= new Class[] { IFile.class };
	TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
	ArrayList<IResource> usedJars= new ArrayList<IResource>(usedEntries.length);
	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
	for (int i= 0; i < usedEntries.length; i++) {
		IResource resource= root.findMember(usedEntries[i]);
		if (resource instanceof IFile) {
			usedJars.add(resource);
		}
	}
	IResource focus= initialSelection != null ? root.findMember(initialSelection) : null;

	FilteredElementTreeSelectionDialog dialog= new FilteredElementTreeSelectionDialog(shell, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
	dialog.setHelpAvailable(false);
	dialog.setValidator(validator);
	dialog.setTitle(NewWizardMessages.BuildPathDialogAccess_JARArchiveDialog_new_title);
	dialog.setMessage(NewWizardMessages.BuildPathDialogAccess_JARArchiveDialog_new_description);
	dialog.setInitialFilter(ArchiveFileFilter.JARZIP_FILTER_STRING);
	dialog.addFilter(new ArchiveFileFilter(usedJars, true, true));
	dialog.setInput(root);
	dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
	dialog.setInitialSelection(focus);

	if (dialog.open() == Window.OK) {
		Object[] elements= dialog.getResult();
		IPath[] res= new IPath[elements.length];
		for (int i= 0; i < res.length; i++) {
			IResource elem= (IResource)elements[i];
			res[i]= elem.getFullPath();
		}
		return res;
	}
	return null;
}
 
Example 9
Source File: NativeLibrariesConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String chooseInternal() {
	String initSelection= fPathField.getText();

	ILabelProvider lp= new WorkbenchLabelProvider();
	ITreeContentProvider cp= new WorkbenchContentProvider();
	Class<?>[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
	TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
	ViewerFilter filter= new TypedViewerFilter(acceptedClasses);

	IResource initSel= null;
	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
	if (initSelection.length() > 0) {
		initSel= root.findMember(new Path(initSelection));
	}
	if (initSel == null) {
		initSel= root.findMember(fEntry.getPath());
	}

	ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(fShell, lp, cp);
	dialog.setAllowMultiple(false);
	dialog.setValidator(validator);
	dialog.addFilter(filter);
	dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
	dialog.setTitle(NewWizardMessages.NativeLibrariesDialog_intfiledialog_title);
	dialog.setMessage(NewWizardMessages.NativeLibrariesDialog_intfiledialog_message);
	dialog.setInput(root);
	dialog.setInitialSelection(initSel);
	dialog.setHelpAvailable(false);
	if (dialog.open() == Window.OK) {
		IResource res= (IResource) dialog.getFirstResult();
		return res.getFullPath().makeRelative().toString();
	}
	return null;
}
 
Example 10
Source File: BazelProjectSupport.java    From eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an Eclipse JDT project into an IntelliJ project view
 */
public static ProjectView getProjectView(IProject project)
    throws BackingStoreException, JavaModelException {
  com.google.devtools.bazel.e4b.projectviews.Builder builder = ProjectView.builder();
  IScopeContext projectScope = new ProjectScope(project);
  Preferences projectNode = projectScope.getNode(Activator.PLUGIN_ID);
  for (String s : projectNode.keys()) {
    if (s.startsWith("buildArgs")) {
      builder.addBuildFlag(projectNode.get(s, ""));
    } else if (s.startsWith("target")) {
      builder.addTarget(projectNode.get(s, ""));
    }
  }

  IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
  for (IClasspathEntry entry : ((IJavaProject) project).getRawClasspath()) {
    switch (entry.getEntryKind()) {
      case IClasspathEntry.CPE_SOURCE:
        IResource res = root.findMember(entry.getPath());
        if (res != null) {
          builder.addDirectory(res.getProjectRelativePath().removeFirstSegments(1).toOSString());
        }
        break;
      case IClasspathEntry.CPE_CONTAINER:
        String path = entry.getPath().toOSString();
        if (path.startsWith(STANDARD_VM_CONTAINER_PREFIX)) {
          builder.setJavaLanguageLevel(
              Integer.parseInt(path.substring(STANDARD_VM_CONTAINER_PREFIX.length())));
        }
        break;
    }
  }
  return builder.build();
}
 
Example 11
Source File: SVNWorkspaceRoot.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
* Returns workspace resource for the given local file system <code>location</code>
* and which is a child of the given <code>parent</code> resource. Returns
* <code>parent</code> if parent's file system location equals to the given
* <code>location</code>. Returns <code>null</code> if <code>parent</code> is the
* workspace root.
*
* Resource does not have to exist in the workspace in which case resource
* type will be determined by the type of the local filesystem object.
*/
  public static IResource getResourceFor(IResource parent, IPath location) {
  	if (parent == null || location == null) {
  		return null;
  	}

  	if (parent instanceof IWorkspaceRoot) {
  		return null;
  	}

  	if (!isManagedBySubclipse(parent.getProject())) {
  		return null;
  	}

  	if (!parent.getLocation().isPrefixOf(location)) {
  		return null;
  	}

int segmentsToRemove = parent.getLocation().segmentCount();
  	IPath fullPath = parent.getFullPath().append(location.removeFirstSegments(segmentsToRemove));

  	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

  	IResource resource = root.findMember(fullPath,true);

  	if (resource != null) {
  		return resource;
  	}

  	if (parent instanceof IFile) {
  		return null;
  	}

if (fullPath.isRoot()) {
	return root;
} else if (fullPath.segmentCount() == 1) {
	return root.getProject(fullPath.segment(0));
}

if (!location.toFile().exists()) {
	if (location.toFile().getName().indexOf(".") == -1) {
		return root.getFolder(fullPath);
	}
}

if (location.toFile().isDirectory()) {
	return root.getFolder(fullPath);
}

return root.getFile(fullPath);
  }
 
Example 12
Source File: ProjectConfigurationFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static List<ICheckConfiguration> getLocalCheckConfigs(Element root, IProject project) {

    List<ICheckConfiguration> configurations = new ArrayList<>();

    List<Element> configElements = root.elements(XMLTags.CHECK_CONFIG_TAG);

    for (Element configEl : configElements) {

      final String name = configEl.attributeValue(XMLTags.NAME_TAG);
      final String description = configEl.attributeValue(XMLTags.DESCRIPTION_TAG);
      String location = configEl.attributeValue(XMLTags.LOCATION_TAG);

      String type = configEl.attributeValue(XMLTags.TYPE_TAG);
      IConfigurationType configType = ConfigurationTypes.getByInternalName(type);

      if (configType instanceof ProjectConfigurationType) {
        // RFE 1420212
        // treat config files relative to *THIS* project
        IWorkspaceRoot workspaceRoot = project.getWorkspace().getRoot();
        // test if the location contains the project name
        if (workspaceRoot.findMember(location) == null) {
          location = project.getFullPath().append(location).toString();
        }
      }

      // get resolvable properties
      List<ResolvableProperty> props = new ArrayList<>();
      List<Element> propertiesElements = configEl.elements(XMLTags.PROPERTY_TAG);
      for (Element propsEl : propertiesElements) {

        ResolvableProperty prop = new ResolvableProperty(propsEl.attributeValue(XMLTags.NAME_TAG),
                propsEl.attributeValue(XMLTags.VALUE_TAG));
        props.add(prop);
      }

      // get additional data
      Map<String, String> additionalData = new HashMap<>();
      List<Element> dataElements = configEl.elements(XMLTags.ADDITIONAL_DATA_TAG);
      for (Element dataEl : dataElements) {

        additionalData.put(dataEl.attributeValue(XMLTags.NAME_TAG),
                dataEl.attributeValue(XMLTags.VALUE_TAG));
      }

      ICheckConfiguration checkConfig = new CheckConfiguration(name, location, description,
              configType, false, props, additionalData);
      configurations.add(checkConfig);
    }

    return configurations;
  }
 
Example 13
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 14
Source File: OutputLocationDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private IContainer chooseOutputLocation() {
	IWorkspaceRoot root= fCurrProject.getWorkspace().getRoot();
	final Class<?>[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
	IProject[] allProjects= root.getProjects();
	ArrayList<IProject> rejectedElements= new ArrayList<IProject>(allProjects.length);
	for (int i= 0; i < allProjects.length; i++) {
		if (!allProjects[i].equals(fCurrProject)) {
			rejectedElements.add(allProjects[i]);
		}
	}
	ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());

	ILabelProvider lp= new WorkbenchLabelProvider();
	ITreeContentProvider cp= new WorkbenchContentProvider();

	IResource initSelection= null;
	if (fOutputLocation != null) {
		initSelection= root.findMember(fOutputLocation);
	}

	FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
	dialog.setTitle(NewWizardMessages.OutputLocationDialog_ChooseOutputFolder_title);

       dialog.setValidator(new ISelectionStatusValidator() {
           ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
           public IStatus validate(Object[] selection) {
               IStatus typedStatus= validator.validate(selection);
               if (!typedStatus.isOK())
                   return typedStatus;
               if (selection[0] instanceof IFolder) {
                   IFolder folder= (IFolder) selection[0];
                   try {
                   	IStatus result= ClasspathModifier.checkSetOutputLocationPrecondition(fEntryToEdit, folder.getFullPath(), fAllowInvalidClasspath, fCPJavaProject);
                   	if (result.getSeverity() == IStatus.ERROR)
                    	return result;
                   } catch (CoreException e) {
                    JavaPlugin.log(e);
                   }
                   return new StatusInfo();
               } else {
               	return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
               }
           }
       });
	dialog.setMessage(NewWizardMessages.OutputLocationDialog_ChooseOutputFolder_description);
	dialog.addFilter(filter);
	dialog.setInput(root);
	dialog.setInitialSelection(initSelection);
	dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));

	if (dialog.open() == Window.OK) {
		return (IContainer)dialog.getFirstResult();
	}
	return null;
}
 
Example 15
Source File: ExclusionInclusionEntryDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ExclusionInclusionEntryDialog(Shell parent, boolean isExclusion, String patternToEdit, List<String> existingPatterns, CPListElement entryToEdit) {
	super(parent);
	fIsExclusion= isExclusion;
	fExistingPatterns= existingPatterns;
	String title, message;
	if (isExclusion) {
		if (patternToEdit == null) {
			title= NewWizardMessages.ExclusionInclusionEntryDialog_exclude_add_title;
		} else {
			title= NewWizardMessages.ExclusionInclusionEntryDialog_exclude_edit_title;
		}
		message= Messages.format(NewWizardMessages.ExclusionInclusionEntryDialog_exclude_pattern_label, BasicElementLabels.getPathLabel(entryToEdit.getPath(), false));
	} else {
		if (patternToEdit == null) {
			title= NewWizardMessages.ExclusionInclusionEntryDialog_include_add_title;
		} else {
			title= NewWizardMessages.ExclusionInclusionEntryDialog_include_edit_title;
		}
		message= Messages.format(NewWizardMessages.ExclusionInclusionEntryDialog_include_pattern_label, BasicElementLabels.getPathLabel(entryToEdit.getPath(), false));
	}
	setTitle(title);
	if (patternToEdit != null) {
		fExistingPatterns.remove(patternToEdit);
	}


	IWorkspaceRoot root= entryToEdit.getJavaProject().getProject().getWorkspace().getRoot();
	IResource res= root.findMember(entryToEdit.getPath());
	if (res instanceof IContainer) {
		fCurrSourceFolder= (IContainer) res;
	}

	fExclusionPatternStatus= new StatusInfo();

	ExclusionPatternAdapter adapter= new ExclusionPatternAdapter();
	fExclusionPatternDialog= new StringButtonDialogField(adapter);
	fExclusionPatternDialog.setLabelText(message);
	fExclusionPatternDialog.setButtonLabel(NewWizardMessages.ExclusionInclusionEntryDialog_pattern_button);
	fExclusionPatternDialog.setDialogFieldListener(adapter);
	fExclusionPatternDialog.enableButton(fCurrSourceFolder != null);

	if (patternToEdit == null) {
		fExclusionPatternDialog.setText(""); //$NON-NLS-1$
	} else {
		fExclusionPatternDialog.setText(patternToEdit.toString());
	}
}
 
Example 16
Source File: AddSourceFolderWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static StatusInfo validatePathName(String str, IContainer parent) {
	StatusInfo result= new StatusInfo();
	result.setOK();

	IPath parentPath= parent.getFullPath();

	if (str.length() == 0) {
		result.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_EnterRootName, BasicElementLabels.getPathLabel(parentPath, false)));
		return result;
	}

	IPath path= parentPath.append(str);

	IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
	IStatus validate= workspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER);
	if (validate.matches(IStatus.ERROR)) {
		result.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidRootName, validate.getMessage()));
		return result;
	}

	IResource res= workspaceRoot.findMember(path);
	if (res != null) {
		if (res.getType() != IResource.FOLDER) {
			result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAFolder);
			return result;
		}
	} else {

		URI parentLocation= parent.getLocationURI();
		if (parentLocation != null) {
			try {
				IFileStore store= EFS.getStore(parentLocation).getChild(str);
				if (store.fetchInfo().exists()) {
					result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase);
					return result;
				}
			} catch (CoreException e) {
				// we couldn't create the file store. Ignore the exception
				// since we can't check if the file exist. Pretend that it
				// doesn't.
			}
		}
	}

	return result;
}
 
Example 17
Source File: ClasspathModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Validate the new entry in the context of the existing entries. Furthermore,
 * check if exclusion filters need to be applied and do so if necessary.
 *
 * If validation was successful, add the new entry to the list of existing entries.
 *
 * @param entry the entry to be validated and added to the list of existing entries.
 * @param existingEntries a list of existing entries representing the build path
 * @param project the Java project
 * @throws CoreException in case that validation fails
 */
private static void validateAndAddEntry(CPListElement entry, List<CPListElement> existingEntries, IJavaProject project) throws CoreException {
	IPath path= entry.getPath();
	IPath projPath= project.getProject().getFullPath();
	IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
	IStatus validate= workspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER);
	StatusInfo rootStatus= new StatusInfo();
	rootStatus.setOK();
	boolean isExternal= isExternalArchiveOrLibrary(entry);
	if (!isExternal && validate.matches(IStatus.ERROR) && !project.getPath().equals(path)) {
		rootStatus.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidRootName, validate.getMessage()));
		throw new CoreException(rootStatus);
	} else {
		if (!isExternal && !project.getPath().equals(path)) {
			IResource res= workspaceRoot.findMember(path);
			if (res != null) {
				if (res.getType() != IResource.FOLDER && res.getType() != IResource.FILE) {
					rootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAFolder);
					throw new CoreException(rootStatus);
				}
			} else {
				URI projLocation= project.getProject().getLocationURI();
				if (projLocation != null) {
					IFileStore store= EFS.getStore(projLocation).getFileStore(path);
					if (store.fetchInfo().exists()) {
						rootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase);
						throw new CoreException(rootStatus);
					}
				}
			}
		}

		for (int i= 0; i < existingEntries.size(); i++) {
			CPListElement curr= existingEntries.get(i);
			if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
				if (path.equals(curr.getPath()) && !project.getPath().equals(path)) {
					rootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExisting);
					throw new CoreException(rootStatus);
				}
			}
		}

		if (!isExternal && !entry.getPath().equals(project.getPath()))
			exclude(entry.getPath(), existingEntries, new ArrayList<CPListElement>(), project, null);

		IPath outputLocation= project.getOutputLocation();
		insertAtEndOfCategory(entry, existingEntries);

		IClasspathEntry[] entries= convert(existingEntries);

		IJavaModelStatus status= JavaConventions.validateClasspath(project, entries, outputLocation);
		if (!status.isOK()) {
			if (outputLocation.equals(projPath)) {
				IStatus status2= JavaConventions.validateClasspath(project, entries, outputLocation);
				if (status2.isOK()) {
					if (project.isOnClasspath(project)) {
						rootStatus.setInfo(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_warning_ReplaceSFandOL, BasicElementLabels.getPathLabel(outputLocation, false)));
					} else {
						rootStatus.setInfo(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_warning_ReplaceOL, BasicElementLabels.getPathLabel(outputLocation, false)));
					}
					return;
				}
			}
			rootStatus.setError(status.getMessage());
			throw new CoreException(rootStatus);
		}

		if (isSourceFolder(project) || project.getPath().equals(path)) {
			rootStatus.setWarning(NewWizardMessages.NewSourceFolderWizardPage_warning_ReplaceSF);
			return;
		}

		rootStatus.setOK();
		return;
	}
}
 
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: RenameResourceAndCloseEditorAction.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
protected IRunnableWithProgress createOperation(final IStatus[] errorStatus) {
	return new IRunnableWithProgress() {
		public void run(IProgressMonitor monitor) {
			IResource[] resources = (IResource[]) getActionResources()
					.toArray(new IResource[getActionResources().size()]);
			// Rename is only valid for a single resource. This has already
			// been validated.
			if (resources.length == 1) {
				// check for overwrite
				IWorkspaceRoot workspaceRoot = resources[0].getWorkspace()
						.getRoot();
				IResource newResource = workspaceRoot.findMember(newPath);
				boolean go = true;
				if (newResource != null) {
					go = checkOverwrite(shellProvider.getShell(), newResource);
				}
				if (go) {
					MoveResourcesOperation op = new MoveResourcesOperation(
							resources[0],
							newPath,
							IDEWorkbenchMessages.RenameResourceAction_operationTitle);
					op.setModelProviderIds(getModelProviderIds());
					try {
						PlatformUI
								.getWorkbench()
								.getOperationSupport()
								.getOperationHistory()
								.execute(
										op,
										monitor,
										WorkspaceUndoUtil
												.getUIInfoAdapter(shellProvider.getShell()));
					} catch (ExecutionException e) {
						if (e.getCause() instanceof CoreException) {
							errorStatus[0] = ((CoreException) e.getCause())
									.getStatus();
						} else {
							errorStatus[0] = new Status(IStatus.ERROR,
									PlatformUI.PLUGIN_ID,
									getProblemsMessage(), e);
						}
					}
				}
			}
		}
	};
}