private IContainer findPomXmlBasedir(IContainer dir) { if (dir == null) { return null; } try { // loop upwards through the parents as long as we do not cross the project boundary while (dir.exists() && dir.getProject() != null && dir.getProject() != dir) { // see if pom.xml exists if (dir.getType() == IResource.FOLDER) { IFolder folder = (IFolder) dir; if (folder.findMember(IMavenConstants.POM_FILE_NAME) != null) { return folder; } } else if (dir.getType() == IResource.FILE) { if (((IFile) dir).getName().equals(IMavenConstants.POM_FILE_NAME)) { return dir.getParent(); } } dir = dir.getParent(); } } catch (Exception e) { return dir; } return dir; }
/** * Deletes a set of files from the file system, and also their parent folders if those become * empty during this process. * * @param nameSet set of file paths * @param monitor progress monitor * @throws CoreException if an error occurs */ private void deleteFiles(final Set<IPath> nameSet, IProgressMonitor monitor) throws CoreException { if (nameSet == null || nameSet.isEmpty()) { return; } Set<IContainer> subFolders = new HashSet<IContainer>(); for (IPath filePath : nameSet) { // Generate new path IFile currentFile = project.getFile(filePath); if (currentFile.exists()) { // Retrieve parent folder and store for deletion IContainer folder = currentFile.getParent(); subFolders.add(folder); currentFile.delete(true, monitor); } monitor.worked(1); } // Delete parent folders, if they are empty for (IContainer folder : subFolders) { if (folder.exists() && folder.members().length == 0) { folder.delete(true, monitor); } monitor.worked(1); } }
/* * (non-Javadoc) * * @see core.resources.ICoreResource#seek(core.resources.IResourceLocationRequestor) */ public void lookup(IResourceAcceptor requestor, LookupDepth depth) { String packageName = fRoot.toPackageName(this); IPackageFragment[] fragments = fRoot.getAllPackageFragments(packageName); for (int i = 0; i < fragments.length; i++) { Object[] nonJavaResources = null; try { if (fragments[i].isReadOnly()) { // TODO - is this the correct check for a package in a jar file? nonJavaResources = fragments[i].getNonJavaResources(); } else { IContainer container = (IContainer) fragments[i].getUnderlyingResource(); if (container != null && container.exists()) { IResource[] members = container.members(false); ArrayList<IResource> resultList = new ArrayList<IResource>(); for (int j = 0; j < members.length; j++) { if (members[j] instanceof IFile) resultList.add(members[j]); } nonJavaResources = resultList.toArray(); } } } catch (CoreException e) { TapestryCore.log(e); } if (nonJavaResources == null) continue; for (int j = 0; j < nonJavaResources.length; j++) { IStorage storage = (IStorage) nonJavaResources[j]; ICoreResource loc = new ClasspathResource(fRoot, getPath() + storage.getName()); if (!requestor.accept(loc)) break; } } }
/** * file color changed. reevaluate everything affected by this file TODO: for now only reevaluate * checks in this file */ public void fileColorChanged(FileColorChangedEvent event) { final HashSet<ColoredSourceFile> toCheck = new HashSet<ColoredSourceFile>(); for (IContainer folder : event.getAffectedFolders()) { try { if (folder.exists()) folder.accept( new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { if (resource instanceof IFile) try { toCheck.add(ColoredSourceFile.getColoredSourceFile((IFile) resource)); } catch (FeatureModelNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } }); } catch (CoreException e) { e.printStackTrace(); } } reevaluateFileChecks(toCheck); }
protected void createFolder(IContainer parent) throws CoreException { if (!parent.exists()) { if (!(parent instanceof IFolder)) throw new RuntimeException("IContainer " + notNull(parent) + " does not exist"); createFolder(parent.getParent()); ((IFolder) parent).create(true, false, new NullProgressMonitor()); } }
/** * Creates new folder from project root. The folder name can include relative path as a part of * the name. Nonexistent parent directories are being created. * * @param project - project where to create the folder. * @param name - folder name. * @return folder handle. * @throws CoreException if something goes wrong. */ public static IFolder createFolder(IProject project, String name) throws CoreException { final IPath p = new Path(name); IContainer folder = project; for (String seg : p.segments()) { folder = folder.getFolder(new Path(seg)); if (!folder.exists()) ((IFolder) folder).create(true, true, NULL_MONITOR); } resourcesCreated.add(folder); return (IFolder) folder; }
private void updateReadOnlyPackageFragmentsForCopy( IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName) { IContainer parentFolder = (IContainer) root.resource(); for (int i = 0, length = newFragName.length; i < length; i++) { String subFolderName = newFragName[i]; parentFolder = parentFolder.getFolder(new Path(subFolderName)); sourceFolder = sourceFolder.getFolder(new Path(subFolderName)); if (sourceFolder.exists() && Util.isReadOnly(sourceFolder)) { Util.setReadOnly(parentFolder, true); } } }
public IFile newSource(final IJavaProject it, final String fileName, final String contents) { try { IProject _project = it.getProject(); final IFile result = _project.getFile(("src/" + fileName)); IContainer parent = result.getParent(); while ((!parent.exists())) { ((IFolder) parent).create(true, false, null); } StringInputStream _stringInputStream = new StringInputStream(contents); result.create(_stringInputStream, true, null); return result; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
private void updateReadOnlyPackageFragmentsForMove( IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName, boolean sourceFolderIsReadOnly) { IContainer parentFolder = (IContainer) root.resource(); for (int i = 0, length = newFragName.length; i < length; i++) { String subFolderName = newFragName[i]; parentFolder = parentFolder.getFolder(new Path(subFolderName)); sourceFolder = sourceFolder.getFolder(new Path(subFolderName)); if ((sourceFolder.exists() && Util.isReadOnly(sourceFolder)) || (i == length - 1 && sourceFolderIsReadOnly)) { Util.setReadOnly(parentFolder, true); // the source folder will be deleted anyway (move operation) Util.setReadOnly(sourceFolder, false); } } }
private IModuleResource getWebXmlFile(IProject project, IPath modelDeployDirectory) { // IDE-110 IDE-648 IVirtualFolder webappRoot = CoreUtil.getDocroot(project); if (webappRoot != null) { for (IContainer container : webappRoot.getUnderlyingFolders()) { if (container != null && container.exists()) { IFile webXml = container.getFile(new Path(WEB_XML_PATH)); if (webXml.exists()) { return new ModuleFile( webXml, webXml.getName(), modelDeployDirectory.append(WEB_XML_PATH)); } } } } return null; }
private boolean checkDocrootFileExists(final IPath path) { IVirtualFolder webappRoot = CoreUtil.getDocroot(getTargetProject()); if (webappRoot == null) { return false; } for (IContainer container : webappRoot.getUnderlyingFolders()) { if (container != null && container.exists()) { IFile file = container.getFile(path); if (file.exists()) { return true; } } } return false; }
/** * Moves temporary files out of the build directory, if applicable. A file is considered a * temporary file, if * * <ul> * <li>it had been in the temporary files folder before the build process * <p><b>or</b> * <li>it was created or modified during the build process, and has a temporary file extension * as specified in the preferences * </ul> * * @param excludes set of paths to exclude from moving, e.g. because they are the main output * files * @param monitor progress monitor * @throws CoreException if an error occurs */ private void moveTempFiles(final Set<IPath> excludes, IProgressMonitor monitor) throws CoreException { final IContainer aSourceContainer = getActualSourceContainer(); if (tracking.isInitial() || aSourceContainer == null || !aSourceContainer.exists()) { return; } final boolean markAsDerived = "true" .equals( TexlipseProperties.getProjectProperty( project, TexlipseProperties.MARK_TEMP_DERIVED_PROPERTY)); final String[] tempExts = TexlipsePlugin.getPreferenceArray(TexlipseProperties.TEMP_FILE_EXTS); // Check if there is anything to do if (markAsDerived || tempDir != null) { // First move temporary files, which had been placed into the source folder // just prior to the build; // then check for new temporary files, which need to be moved project .getWorkspace() .run( new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { if (movedFiles != null) { if (excludes != null) { movedFiles.removeAll(excludes); } moveFiles(sourceDir, tempDir, movedFiles, markAsDerived, true, monitor); } final Set<IPath> newTempNames = tracking.getNewTempNames(aSourceContainer, tempExts, format, monitor); if (excludes != null) { newTempNames.removeAll(excludes); } moveFiles(sourceDir, tempDir, newTempNames, markAsDerived, true, monitor); } }, monitor); } }
/** @since 2.5 */ protected void cleanOutput( IBuildContext ctx, OutputConfiguration config, EclipseResourceFileSystemAccess2 access, IProgressMonitor monitor) throws CoreException { final IProject project = ctx.getBuiltProject(); for (IContainer container : getOutputs(project, config)) { if (!container.exists()) { return; } if (config.isCanClearOutputDirectory()) { for (IResource resource : container.members()) { if (!config.isKeepLocalHistory()) { resource.delete(IResource.NONE, monitor); } else if (access == null) { resource.delete(IResource.KEEP_HISTORY, monitor); } else { delete(resource, config, access, monitor); } } } else if (config.isCleanUpDerivedResources()) { List<IFile> resources = derivedResourceMarkers.findDerivedResources(container, null); for (IFile iFile : resources) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (access != null) { access.deleteFile(iFile, config.getName(), monitor); } else { iFile.delete( config.isKeepLocalHistory() ? IResource.KEEP_HISTORY : IResource.NONE, monitor); } } } } }
/** * file color changed. reevaluate everything affected by this file TODO: for now only reevaluate * checks in this file */ public void fileColorChanged(FileColorChangedEvent event) { final HashSet<CLRAnnotatedSourceFile> toCheck = new HashSet<CLRAnnotatedSourceFile>(); for (IContainer folder : event.getAffectedFolders()) { try { if (folder.exists()) folder.accept( new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { if (resource instanceof IFile) toCheck.add( (CLRAnnotatedSourceFile) CLRAnnotatedSourceFile.getColoredJavaSourceFile((IFile) resource)); return true; } }); } catch (CoreException e) { e.printStackTrace(); } } reevaluateFileChecks(toCheck); }
/** * Moves a set of files from the source container to the destination. All files need to be inside * the source container or any of its subfolders. Existing folders are not removed, if left empty. * If source and destination container are identical, files are if applicable only marked as * derived. * * @param source source container * @param dest destination folder (can be null, for only marking files as derived) * @param nameSet set of file paths to move * @param markAsDerived mark files as derived after moving * @param force overwrite exiting files and create subfolders in destination folder, if necessary * @param monitor progress monitor * @return a new set of file paths in their new location. This only includes files which have * actually been moved. * @throws CoreException if an error occurs */ private Set<IPath> moveFiles( final IContainer source, final IContainer dest, final Set<IPath> nameSet, boolean markAsDerived, boolean force, IProgressMonitor monitor) throws CoreException { Set<IPath> newNames = new HashSet<IPath>(); if (nameSet != null && !nameSet.isEmpty()) { IPath sourcePath = source.getProjectRelativePath(); IPath destPath; if (dest != null) { destPath = dest.getProjectRelativePath(); } else { destPath = sourcePath; } boolean moveFiles = !sourcePath.equals(destPath); int sourceSeg = sourcePath.segmentCount(); // Sort paths for running through file system structure incrementally IPath[] sortedNames = nameSet.toArray(new IPath[0]); Arrays.sort( sortedNames, new Comparator<IPath>() { public int compare(IPath o1, IPath o2) { return o1.toString().compareTo(o2.toString()); } }); for (IPath filePath : sortedNames) { if (sourcePath.isPrefixOf(filePath)) { IFile currentFile = project.getFile(filePath); if (moveFiles) { // Generate new path IPath destFilePath = destPath.append(filePath.removeFirstSegments(sourceSeg)); IFile destFile = project.getFile(destFilePath); if (currentFile.exists() && (force || !destFile.exists())) { // Retrieve destination parent folder IContainer destFolder = destFile.getParent(); if (destFolder instanceof IFolder && !destFolder.exists() && force) { // Create destination folder if necessary ((IFolder) destFolder).create(true, true, monitor); if (markAsDerived) { destFolder.setDerived(true); } } if (destFolder.exists()) { // Move file if (destFile.exists() && force) { destFile.delete(true, monitor); } currentFile.move(destFile.getFullPath(), true, monitor); if (markAsDerived && destFile.exists()) { destFile.setDerived(true); } // Store path for later reversal newNames.add(destFilePath); } } } else { if (markAsDerived && currentFile.exists()) { currentFile.setDerived(true); } } monitor.worked(1); } } } return newNames; }
@Override protected String browse(final SapphireRenderingContext context) { final Property property = property(); final List<Path> roots = getBasePaths(); String selectedAbsolutePath = null; final List<String> extensions; if (this.fileExtensionService == null) { extensions = this.staticFileExtensionsList; } else { extensions = this.fileExtensionService.extensions(); } if (enclosed()) { final List<IContainer> baseContainers = new ArrayList<IContainer>(); for (Path path : roots) { final IContainer baseContainer = getWorkspaceContainer(path.toFile()); if (baseContainer != null) { baseContainers.add(baseContainer); } else { break; } } final ITreeContentProvider contentProvider; final ILabelProvider labelProvider; final ViewerComparator viewerComparator; final Object input; if (roots.size() == baseContainers.size()) { // All paths are in the Eclipse Workspace. Use the available content and label // providers. contentProvider = new WorkspaceContentProvider(baseContainers); labelProvider = new WorkbenchLabelProvider(); viewerComparator = new ResourceComparator(); input = ResourcesPlugin.getWorkspace().getRoot(); } else { // At least one of the roots is not in the Eclipse Workspace. Use custom file // system content and label providers. contentProvider = new FileSystemContentProvider(roots); labelProvider = new FileSystemLabelProvider(context); viewerComparator = new FileSystemNodeComparator(); input = new Object(); } final ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(context.getShell(), labelProvider, contentProvider); dialog.setTitle(property.definition().getLabel(false, CapitalizationType.TITLE_STYLE, false)); dialog.setMessage( createBrowseDialogMessage( property.definition().getLabel(true, CapitalizationType.NO_CAPS, false))); dialog.setAllowMultiple(false); dialog.setHelpAvailable(false); dialog.setInput(input); dialog.setComparator(viewerComparator); final Path currentPathAbsolute = convertToAbsolute((Path) ((Value<?>) property).content()); if (currentPathAbsolute != null) { Object initialSelection = null; if (contentProvider instanceof WorkspaceContentProvider) { final URI uri = currentPathAbsolute.toFile().toURI(); final IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot(); final IFile[] files = wsroot.findFilesForLocationURI(uri); if (files.length > 0) { final IFile file = files[0]; if (file.exists()) { initialSelection = file; } } if (initialSelection == null) { final IContainer[] containers = wsroot.findContainersForLocationURI(uri); if (containers.length > 0) { final IContainer container = containers[0]; if (container.exists()) { initialSelection = container; } } } } else { initialSelection = ((FileSystemContentProvider) contentProvider).find(currentPathAbsolute); } if (initialSelection != null) { dialog.setInitialSelection(initialSelection); } } if (this.type == FileSystemResourceType.FILE) { dialog.setValidator(new FileSelectionStatusValidator()); } else if (this.type == FileSystemResourceType.FOLDER) { dialog.addFilter(new ContainersOnlyViewerFilter()); } if (!extensions.isEmpty()) { dialog.addFilter(new ExtensionBasedViewerFilter(extensions)); } if (dialog.open() == Window.OK) { final Object firstResult = dialog.getFirstResult(); if (firstResult instanceof IResource) { selectedAbsolutePath = ((IResource) firstResult).getLocation().toString(); } else { selectedAbsolutePath = ((FileSystemNode) firstResult).getFile().getPath(); } } } else if (this.type == FileSystemResourceType.FOLDER) { final DirectoryDialog dialog = new DirectoryDialog(context.getShell()); dialog.setText( property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false)); dialog.setMessage( createBrowseDialogMessage( property.definition().getLabel(true, CapitalizationType.NO_CAPS, false))); final Value<?> value = (Value<?>) property; final Path path = (Path) value.content(); if (path != null) { dialog.setFilterPath(path.toOSString()); } else if (roots.size() > 0) { dialog.setFilterPath(roots.get(0).toOSString()); } selectedAbsolutePath = dialog.open(); } else { final FileDialog dialog = new FileDialog(context.getShell()); dialog.setText( property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false)); final Value<?> value = (Value<?>) property; final Path path = (Path) value.content(); if (path != null && path.segmentCount() > 1) { dialog.setFilterPath(path.removeLastSegments(1).toOSString()); dialog.setFileName(path.lastSegment()); } else if (roots.size() > 0) { dialog.setFilterPath(roots.get(0).toOSString()); } if (!extensions.isEmpty()) { final StringBuilder buf = new StringBuilder(); for (String extension : extensions) { if (buf.length() > 0) { buf.append(';'); } buf.append("*."); buf.append(extension); } dialog.setFilterExtensions(new String[] {buf.toString()}); } selectedAbsolutePath = dialog.open(); } if (selectedAbsolutePath != null) { final Path relativePath = convertToRelative(new Path(selectedAbsolutePath)); if (relativePath != null) { String result = relativePath.toPortableString(); if (this.includeLeadingSlash) { result = "/" + result; } return result; } } return null; }