Java Code Examples for org.eclipse.core.resources.IResource#FOLDER

The following examples show how to use org.eclipse.core.resources.IResource#FOLDER . 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: AddSourceFolderWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Opens a path variable selection dialog
 */
private void handleVariablesButtonPressed() {
	int variableTypes = IResource.FOLDER;
	PathVariableSelectionDialog dialog = new PathVariableSelectionDialog(getShell(), variableTypes);
	dialog.setResource(fParent);
	if (dialog.open() == IDialogConstants.OK_ID) {
		String[] variableNames = (String[]) dialog.getResult();
		if (variableNames != null && variableNames.length == 1) {
			fLinkLocation.setText(variableNames[0]);
			fRootDialogField.setText(new Path(variableNames[0]).lastSegment());
			if (fAdapter != null) {
				fAdapter.dialogFieldChanged(fRootDialogField);
			}
		}
	}
}
 
Example 2
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws InterruptedException {
	if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
		return;



	IResource[] children= null;
	try {
		children= container.members();
	} catch (CoreException exception) {
		// this should never happen because an #isAccessible check is done before #members is invoked
		addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_errorDuringExport, BasicElementLabels.getPathLabel(container.getFullPath(), false)), exception);
	}
	if (children != null) {
		IJavaProject javaProject= JavaCore.create(container.getProject());
		boolean isOnCP= javaProject.isOnClasspath(container);
		for (int i= 0; i < children.length; i++) {
			IResource child= children[i];
			if (isOnCP || !javaProject.isOnClasspath(child) || isInternalJar(child))
				exportElement(child, progressMonitor);
		}
	}
}
 
Example 3
Source File: HostPagePathSelectionDialog.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private static List<IFolder> getSubfolders(IFolder folder) {
  List<IFolder> folders = new ArrayList<IFolder>();

  try {
    for (IResource member : folder.members()) {
      if (member.getType() == IResource.FOLDER) {
        // Filter out derived and hidden folders (anything prefixed with .)
        if (member.isDerived() || member.getName().startsWith(".")) {
          continue;
        }
        folders.add((IFolder) member);
      }
    }
  } catch (CoreException e) {
    GWTPluginLog.logError(e);
  }

  return folders;
}
 
Example 4
Source File: ResourceManager.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static WrappedResource<?, ?> privateCreateWrapping(final VirtualContent<?> parent, final IResource child) {
	if (DEBUG.IS_ON()) {
		DEBUG.OUT("Creation of the wrapped instance of " + child.getName());
	}
	switch (child.getType()) {
		case IResource.FILE:
			if (FileMetaDataProvider.GAML_CT_ID.equals(getContentTypeId((IFile) child))) {
				return new WrappedGamaFile((WrappedContainer<?>) parent, (IFile) child);
			}
			if (child.isLinked()) { return new WrappedLink((WrappedContainer<?>) parent, (IFile) child); }
			return new WrappedFile((WrappedContainer<?>) parent, (IFile) child);
		case IResource.FOLDER:
			return new WrappedFolder((WrappedContainer<?>) parent, (IFolder) child);
		case IResource.PROJECT:
			return new WrappedProject((TopLevelFolder) parent, (IProject) child);
	}
	return null;
}
 
Example 5
Source File: TestsRunner.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static boolean isInteresting(final IProject p) throws CoreException {
	if (p == null || !p.exists() || !p.isAccessible())
		return false;
	// If it is contained in one of the built-in tests projects, return true
	if (p.getDescription().hasNature(WorkbenchHelper.TEST_NATURE))
		return true;
	if (GamaPreferences.Runtime.USER_TESTS.getValue()) {
		// If it is not in user defined projects, return false
		if (p.getDescription().hasNature(WorkbenchHelper.BUILTIN_NATURE))
			return false;
		// We try to find in the project a folder called 'tests'
		final IResource r = p.findMember("tests");
		if (r != null && r.exists() && r.isAccessible() && r.getType() == IResource.FOLDER)
			return true;
	}
	return false;
}
 
Example 6
Source File: ResourceManager.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
boolean processRemoval(final IResource res) {
	boolean update = false;
	switch (res.getType()) {
		case IResource.FILE:
			if (GamlFileExtension.isAny(res.getName())) {
				invalidateModelsCountCache(res.getParent());
				invalidateSeverityCache(res.getParent());
				update = true;
			}
			fileRemoved((IFile) res);
			break;
		case IResource.FOLDER:
			folderRemoved((IFolder) res);
			break;
		case IResource.PROJECT:
			projectRemoved((IProject) res);
			break;
	}

	return update;
}
 
Example 7
Source File: ModuleFile.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns whether a folder is on the public path of this module. The public paths include the
 * paths explicitly declared with <code>&lt;public&gt;</code> tags and all of their descendant
 * sub-folders.
 *
 * @param folder the folder to check
 * @return <code>true</code> if this folder is on a public path, and <code>false</code> otherwise
 */
public boolean isPublicPath(IFolder folder) {
  IFolder[] publicFolders = getFolders(getPublicPaths());

  IContainer moduleContainer = getFile().getParent();
  IContainer container = folder;

  // Walk up the ancestor chain looking for a public path matching this folder
  while (container.getType() == IResource.FOLDER) {
    // If we reach the module's container, we're done searching
    if (container.equals(moduleContainer)) {
      return false;
    }

    for (IFolder publicFolder : publicFolders) {
      if (container.equals(publicFolder)) {
        return true;
      }
    }

    container = container.getParent();
  }

  return false;
}
 
Example 8
Source File: UpdateSynchronizeOperation.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
* This method takes the array of resources to be updated and removes any
* items that have a parent folder that is also being updated, since the
* recursive update of a parent folder will cause the resource to be updated
* anyway.  This will make the update run faster.
* @param resourceArray
* @return
*/
  private IResource[] trimResources(IResource[] resourceArray) {
  	// Get a list of just the folders.
      List<IResource> folders = new ArrayList<IResource>();
      for (int i = 0; i < resourceArray.length; i++) {
          if (resourceArray[i].getType() == IResource.FOLDER || resourceArray[i].getType() == IResource.PROJECT) 
              folders.add(resourceArray[i]);
      }
      
      List<IResource> trimmedList = new ArrayList<IResource>();
      for (int i = 0; i < resourceArray.length; i++) {
          if (!parentIncluded(resourceArray[i], folders))
              trimmedList.add(resourceArray[i]);
      }
      
      IResource[] trimmedArray = new IResource[trimmedList.size()];
trimmedList.toArray(trimmedArray);
return trimmedArray;
  }
 
Example 9
Source File: ResourceOutputPart.java    From depan with Apache License 2.0 5 votes vote down vote up
public String getErrorMsg() {
  IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(
      new Path(getContainerName()));
  String filename = getFilename();
  
  if (getContainerName().length() == 0) {
    return "File container must be specified";
  }
  if (container == null
      || (container.getType()
          & (IResource.PROJECT | IResource.FOLDER)) == 0) {
    return "File container must exist";
  }
  if (!container.isAccessible()) {
    return "Project must be writable";
  }
  if (filename.length() == 0) {
    return "File name must be specified";
  }
  if (filename.replace('\\', '/').indexOf('/', 1) > 0) {
    return "File name cannot include path";
  }
  int dotLoc = filename.lastIndexOf('.');
  if (dotLoc != -1) {
    String ext = filename.substring(dotLoc + 1);
    if (!ext.equalsIgnoreCase(requiredExt)) {
      return "File extension must be \"." + requiredExt + "\"";
    }
  }
  return null;
}
 
Example 10
Source File: Resource.java    From EasyShell with Eclipse Public License 2.0 5 votes vote down vote up
public boolean isDirectory() {
    if (resource != null) {
        if (resource.getType() == IResource.FOLDER) {
            return true;
        } else {
            return false;
        }
    } else {
        if (file.isDirectory()) {
            return true;
        } else {
            return false;
        }
    }
}
 
Example 11
Source File: SearchThread.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Test one resource.
 *
 * @param resource the resource
 */
private void testOneResource(IResource resource) {
  switch (resource.getType()) {
    case IResource.FILE:
      if (resource.getName().toLowerCase().endsWith(".xml")
              // exclude potentially many data files, not descriptors
              && !resource.getName().toLowerCase().endsWith(".txt.xml")
              && (m_fileNameSearch == null || m_fileNameSearch.matcher(resource.getName()).find())) {
        String fileDescriptorRelPath = m_aggregateSection.editor
                .getDescriptorRelativePath(resource.getLocation().toString());
        setStatusMsg(2, "Examining " + getBriefDisplayVersion(fileDescriptorRelPath));
        ResourceSpecifier rs = MultiPageEditor.getDelegateResourceSpecifier((IFile) resource,
                m_componentHeaders);
        // rs == null if wrong kind of descriptor
        if (null == rs)
          return;
        if (!(rs instanceof ResourceCreationSpecifier)) // is a remote descriptor
          if (m_inputTypeSearch != null || m_outputTypeSearch != null)
            return; // don't find remote descriptors when types are wanted

        if (!(rs instanceof ResourceCreationSpecifier) || // is a remote descriptor
                delegateComponentMatchesCapabilityReqs((ResourceCreationSpecifier) rs,
                        m_inputTypeSearch, m_outputTypeSearch)) {
          m_matchingDelegateComponentDescriptors.add(fileDescriptorRelPath);
          m_matchingDelegateComponentDescriptions.add(rs);
        }
      }
      break;
    case IResource.FOLDER:
      getDelegateComponentsByIOTypesBeginningAt((IFolder) resource);
      break;
  }

}
 
Example 12
Source File: ReorgUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static String getName(IResource resource) {
	String resourceLabel= BasicElementLabels.getResourceName(resource);
	switch (resource.getType()){
		case IResource.FILE:
			return Messages.format(RefactoringCoreMessages.ReorgUtils_0, resourceLabel);
		case IResource.FOLDER:
			return Messages.format(RefactoringCoreMessages.ReorgUtils_1, resourceLabel);
		case IResource.PROJECT:
			return Messages.format(RefactoringCoreMessages.ReorgUtils_2, resourceLabel);
		default:
			Assert.isTrue(false);
			return null;
	}
}
 
Example 13
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IPackageFragmentRoot getPackageFragmentRoot(IResource resource, IPath entryPath) {
	switch (resource.getType()) {
		case IResource.FILE:
			return new JarPackageFragmentRoot(resource, this);
		case IResource.FOLDER:
			if (ExternalFoldersManager.isInternalPathForExternalFolder(resource.getFullPath()))
				return new ExternalPackageFragmentRoot(resource, entryPath, this);
			return new PackageFragmentRoot(resource, this);
		case IResource.PROJECT:
			return new PackageFragmentRoot(resource, this);
		default:
			return null;
	}
}
 
Example 14
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a file or folder handle for the source resource as if it were to
 * be created in the destination container.
 *
 * @param destination
 *            destination container
 * @param source
 *            source resource
 * @return IResource file or folder handle, depending on the source type.
 */
IResource createLinkedResourceHandle(IContainer destination, IResource source) {
    IWorkspace workspace = destination.getWorkspace();
    IWorkspaceRoot workspaceRoot = workspace.getRoot();
    IPath linkPath = destination.getFullPath().append(source.getName());
    IResource linkHandle;

    if (source.getType() == IResource.FOLDER) {
        linkHandle = workspaceRoot.getFolder(linkPath);
    } else {
        linkHandle = workspaceRoot.getFile(linkPath);
    }
    return linkHandle;
}
 
Example 15
Source File: PlatformResourceURI.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isDirectory() {
	IResource r = getCachedResource();
	if (r == null) {
		return false;
	}
	int type = r.getType();
	return type == IResource.FOLDER || type == IResource.PROJECT;
}
 
Example 16
Source File: AbstractNewDocumentOutputPart.java    From depan with Apache License 2.0 5 votes vote down vote up
@Override
public String getErrorMsg() {

  // Container validation.
  String containerName = getContainerName();
  if (containerName.length() == 0) {
    return "File container must be specified";
  }
  IResource container =
      WorkspaceTools.buildWorkspaceResource(new Path(containerName));
  if (container == null
      || (container.getType()
          & (IResource.PROJECT | IResource.FOLDER)) == 0) {
    return "File container must exist";
  }
  if (!container.isAccessible()) {
    return "Project must be writable";
  }

  String filename = getFilename();
  if (filename.length() == 0) {
    return "File name must be specified";
  }
  if (filename.replace('\\', '/').indexOf('/', 1) > 0) {
    return "File name cannot include path";
  }
  int dotLoc = filename.lastIndexOf('.');
  if (dotLoc != -1) {
    String ext = filename.substring(dotLoc + 1);
    if (!ext.equalsIgnoreCase(requiredExt)) {
      return "File extension must be \"." + requiredExt + "\"";
    }
  }
  return null;
}
 
Example 17
Source File: ClasspathChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ArrayList determineAffectedPackageFragments(IPath location) throws JavaModelException {
	ArrayList fragments = new ArrayList();

	// see if this will cause any package fragments to be affected
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IResource resource = null;
	if (location != null) {
		resource = workspace.getRoot().findMember(location);
	}
	if (resource != null && resource.getType() == IResource.FOLDER) {
		IFolder folder = (IFolder) resource;
		// only changes if it actually existed
		IClasspathEntry[] classpath = this.project.getExpandedClasspath();
		for (int i = 0; i < classpath.length; i++) {
			IClasspathEntry entry = classpath[i];
			IPath path = classpath[i].getPath();
			if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
				IPackageFragmentRoot[] roots = this.project.computePackageFragmentRoots(classpath[i]);
				PackageFragmentRoot root = (PackageFragmentRoot) roots[0];
				// now the output location becomes a package fragment - along with any subfolders
				ArrayList folders = new ArrayList();
				folders.add(folder);
				collectAllSubfolders(folder, folders);
				Iterator elements = folders.iterator();
				int segments = path.segmentCount();
				while (elements.hasNext()) {
					IFolder f = (IFolder) elements.next();
					IPath relativePath = f.getFullPath().removeFirstSegments(segments);
					String[] pkgName = relativePath.segments();
					IPackageFragment pkg = root.getPackageFragment(pkgName);
					if (!Util.isExcluded(pkg))
						fragments.add(pkg);
				}
			}
		}
	}
	return fragments;
}
 
Example 18
Source File: PackageFragmentRootInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Starting at this folder, create non-java resources for this package fragment root
 * and add them to the non-java resources collection.
 *
 * @exception JavaModelException  The resource associated with this package fragment does not exist
 */
static Object[] computeFolderNonJavaResources(IPackageFragmentRoot root, IContainer folder, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
	IResource[] nonJavaResources = new IResource[5];
	int nonJavaResourcesCounter = 0;
	try {
		IResource[] members = folder.members();
		int length = members.length;
		if (length > 0) {
			// if package fragment root refers to folder in another IProject, then
			// folder.getProject() is different than root.getJavaProject().getProject()
			// use the other java project's options to verify the name
			IJavaProject otherJavaProject = JavaCore.create(folder.getProject());
			String sourceLevel = otherJavaProject.getOption(JavaCore.COMPILER_SOURCE, true);
			String complianceLevel = otherJavaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
			JavaProject javaProject = (JavaProject) root.getJavaProject();
			IClasspathEntry[] classpath = javaProject.getResolvedClasspath();
			nextResource: for (int i = 0; i < length; i++) {
				IResource member = members[i];
				switch (member.getType()) {
					case IResource.FILE :
						String fileName = member.getName();

						// ignore .java files that are not excluded
						if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel) && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
							continue nextResource;
						// ignore .class files
						if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
							continue nextResource;
						// ignore .zip or .jar file on classpath
						if (isClasspathEntry(member.getFullPath(), classpath))
							continue nextResource;
						break;

					case IResource.FOLDER :
						// ignore valid packages or excluded folders that correspond to a nested pkg fragment root
						if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
								&& (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
										|| isClasspathEntry(member.getFullPath(), classpath)))
							continue nextResource;
						break;
				}
				if (nonJavaResources.length == nonJavaResourcesCounter) {
					// resize
					System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
				}
				nonJavaResources[nonJavaResourcesCounter++] = member;
			}
		}
		if (ExternalFoldersManager.isInternalPathForExternalFolder(folder.getFullPath())) {
			IJarEntryResource[] jarEntryResources = new IJarEntryResource[nonJavaResourcesCounter];
			for (int i = 0; i < nonJavaResourcesCounter; i++) {
				jarEntryResources[i] = new NonJavaResource(root, nonJavaResources[i]);
			}
			return jarEntryResources;
		} else if (nonJavaResources.length != nonJavaResourcesCounter) {
			System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
		}
		return nonJavaResources;
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}
}
 
Example 19
Source File: SolcBuilderPreferencePage.java    From uml2solidity with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 
 */
private void validateInput() {
	if (isPropertyPage()) {

		Path srcDir = new Path(sourceDirectory.getStringValue());
		IResource member = project.findMember(srcDir);
		if (member == null)
			member = ResourcesPlugin.getWorkspace().getRoot().findMember(srcDir);
		if (member == null || !member.exists()) {
			setErrorMessage("source directory does not exist");
			return;
		}
		if (member.getType() != IResource.FOLDER) {
			setErrorMessage("source must be a folder");
			return;
		}

		String stringValue = compilerTarget.getStringValue();
		Path ct = new Path(stringValue);
		IResource resource = project.findMember(ct);
		if (resource == null)
			resource = project.findMember(ct.removeLastSegments(1));
		if (resource == null)
			resource = ResourcesPlugin.getWorkspace().getRoot().findMember(ct);
		if (resource == null)
			resource = ResourcesPlugin.getWorkspace().getRoot().findMember(ct.removeLastSegments(1));
		if (resource == null || !resource.exists()) {
			setErrorMessage("target file or dir not found:" + stringValue);
			return;
		}
	}

	String fileName = editor.getStringValue();
	File file = new File(fileName);
	if (!file.exists()) {
		setErrorMessage("The selected compiles does not exitst.");
		return;
	}
	if (!file.canExecute()) {
		setErrorMessage("The selected compiler can not be executed.");
		return;
	}
}
 
Example 20
Source File: SVNLightweightDecorator.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
    * decorate the text label of the given resource.
    * This method assumes that only one thread will be accessing it at a time.
    */
protected void decorateTextLabel(ISVNLocalResource svnResource, LocalResourceStatus status, IDecoration decoration, boolean isDirty) {
	Map bindings = new HashMap(6);

		// if the resource does not have a location then return. This can happen if the resource
		// has been deleted after we where asked to decorate it.
		if (svnResource.getIResource().getLocation() == null) {
			return;
		}
		if (status.isUnversioned())
			return;

		// get the format
		IDecoratorComponent[][] format;
		int type = svnResource.getIResource().getType();
		if (type == IResource.FOLDER) {
			format = folderDecoratorFormat;
		} else if (type == IResource.PROJECT) {
			format = projectDecoratorFormat;
		} else {
			format = fileDecoratorFormat;
		}
           
           // fill the bindings
		if (isDirty & !status.isAdded()) {
			bindings.put(SVNDecoratorConfiguration.DIRTY_FLAG, dirtyFlag);
		}

		if (status.getUrlString() != null) {
			String label = null;
			ISVNRepositoryLocation repository = status.getRepository();
			if (repository != null) {
				label = status.getRepository().getLabel();
			}
		    bindings.put( SVNDecoratorConfiguration.RESOURCE_LABEL, label == null ? status.getUrlString() : label);
   			  
			bindings.put(
				SVNDecoratorConfiguration.RESOURCE_URL,
				Util.unescape(status.getUrlString()));
			
               // short url is the path relative to root url of repository
			SVNUrl repositoryRoot = null;
			if (repository != null) {
				repositoryRoot = repository.getRepositoryRoot();
			}
               if (repositoryRoot != null) {
                   int urlLen =  status.getUrlString().length();
                   int rootLen = repositoryRoot.toString().length()+1;
                   String shortUrl;
                   if (urlLen > rootLen)
                      shortUrl = status.getUrlString().substring(rootLen);
                   else
                      shortUrl = status.getUrlString();
                   bindings.put(
                           SVNDecoratorConfiguration.RESOURCE_URL_SHORT, 
                           Util.unescape(shortUrl));
               }
		}
		
		if (status.isAdded()) {
			bindings.put(SVNDecoratorConfiguration.ADDED_FLAG, addedFlag);
		} else if (SVNStatusKind.EXTERNAL.equals(status.getTextStatus())) {
               bindings.put(SVNDecoratorConfiguration.EXTERNAL_FLAG, externalFlag);
           } else {
			if ((status.getTextStatus() != SVNStatusKind.UNVERSIONED) &&
				(status.getTextStatus() != SVNStatusKind.ADDED)) {
				
				if (status.getLastChangedRevision() != null) {
					bindings.put(
					   SVNDecoratorConfiguration.RESOURCE_REVISION,
					   status.getLastChangedRevision().toString());
				}
				
				if (status.getLastCommitAuthor() != null) {
				    bindings.put(
					   SVNDecoratorConfiguration.RESOURCE_AUTHOR,
					   status.getLastCommitAuthor());
				}
               }				
			if (status.getLastChangedDate() != null) {
                   bindings.put(
				   SVNDecoratorConfiguration.RESOURCE_DATE,
					dateFormat.format(status.getLastChangedDate()));
			}
		}

		SVNDecoratorConfiguration.decorate(decoration, format, bindings);
}