Java Code Examples for org.eclipse.core.resources.IContainer#getFolder()

The following examples show how to use org.eclipse.core.resources.IContainer#getFolder() . 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: ProjectCustomizer.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a folder, if it does not exist, in a given container
 * 
 * @param container
 *          an IContainer
 * @param folderName
 *          The folder name
 * @return the handle (IFolder) to the folder
 * @throws PearException
 *           If a problem occurs
 */
public static IFolder createFolder(IContainer container, String folderName) throws PearException {
  try {
    IFolder folder = container.getFolder(new Path(folderName));
    // If the folder does not exist, create and return, failure returns null
    if (!folder.exists()) {
      folder.create(true, true, null);
      return folder;
    } else {
      // return what already exisited
      return folder;
    }
  } catch (Throwable e) {
    PearException subEx = new PearException("folderName could not be created properly.", e);
    throw subEx;
  }
}
 
Example 2
Source File: GetContainers.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets an IContainer inside a container given a path in the filesystem (resolves the full path of the container and
 * checks if the location given is under it).
 * @param mustExist 
 */
public static final IContainer getContainerInContainer(IPath location, IContainer container, boolean mustExist) {
    IPath projectLocation = container.getLocation();
    if (projectLocation != null && projectLocation.isPrefixOf(location)) {
        int segmentsToRemove = projectLocation.segmentCount();
        IPath removeFirstSegments = location.removeFirstSegments(segmentsToRemove);
        if (removeFirstSegments.segmentCount() == 0) {
            return container; //I.e.: equal to container
        }
        IContainer file = container.getFolder(removeFirstSegments);
        if (!mustExist || file.exists()) {
            return file;
        }
    }
    return null;
}
 
Example 3
Source File: RecipeHelper.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public static void processFile ( final IContainer parent, final Definition definition, final Profile profile, final IProgressMonitor monitor ) throws Exception
{
    monitor.beginTask ( makeJobLabel ( definition, profile ), 100 );

    final IFolder output = parent.getFolder ( new Path ( "output" ) ); //$NON-NLS-1$
    if ( output.exists () )
    {
        output.delete ( true, new SubProgressMonitor ( monitor, 9 ) );
    }
    output.create ( true, true, new SubProgressMonitor ( monitor, 1 ) );

    final Builder builder = new Builder ( definition, profile );
    final Recipe recipe = builder.build ();

    try
    {
        final Map<String, Object> initialContent = new HashMap<String, Object> ();
        initialContent.put ( "output", output ); //$NON-NLS-1$

        recipe.execute ( initialContent, new SubProgressMonitor ( monitor, 90 ) );
    }
    finally
    {
        monitor.done ();
    }
}
 
Example 4
Source File: ResourceUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Create the components of the provided folder as required. Assumes the containing project
 * already exists.
 *
 * @param folder the path to be created if it does not already exist
 * @param monitor may be {@code null}
 * @throws CoreException on error
 */
public static void createFolders(IContainer folder, IProgressMonitor monitor)
    throws CoreException {

  IPath path = folder.getProjectRelativePath();
  IContainer current = folder.getProject();
  SubMonitor progress = SubMonitor.convert(monitor, path.segmentCount());
  for (String segment : path.segments()) {
    IFolder child = current.getFolder(new Path(segment));
    if (!child.exists()) {
      child.create(true, true, progress.newChild(1));
    } else {
      progress.worked(1);
    }
    current = child;
  }
}
 
Example 5
Source File: DerivedResourceCleanerJob.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected IStatus cleanUpDerivedResources(IProgressMonitor monitor, IProject project) throws CoreException, OperationCanceledException {
	if (monitor.isCanceled()) {
		return Status.CANCEL_STATUS;
	}
	if (shouldBeProcessed(project)) {
		IContainer container = project;
		if (folderNameToClean != null)
			container = container.getFolder(new Path(folderNameToClean));
		for (IFile derivedFile : derivedResourceMarkers.findDerivedResources(container, null)) {
			derivedFile.delete(true, monitor);
			if (monitor.isCanceled()) {
				return Status.CANCEL_STATUS;
			}
		}
	}
	return Status.OK_STATUS;
}
 
Example 6
Source File: PythonPackageWizard.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the complete package path given by the user (all filled with __init__) 
 * and returns the last __init__ module created.
 */
public static IFile createPackage(IProgressMonitor monitor, IContainer validatedSourceFolder, String packageName)
        throws CoreException {
    IFile lastFile = null;
    if (validatedSourceFolder == null) {
        return null;
    }
    IContainer parent = validatedSourceFolder;
    for (String packagePart : StringUtils.dotSplit(packageName)) {
        IFolder folder = parent.getFolder(new Path(packagePart));
        if (!folder.exists()) {
            folder.create(true, true, monitor);
        }
        parent = folder;
        IFile file = parent.getFile(new Path("__init__"
                + FileTypesPreferences.getDefaultDottedPythonExtension()));
        if (!file.exists()) {
            file.create(new ByteArrayInputStream(new byte[0]), true, monitor);
        }
        lastFile = file;
    }

    return lastFile;
}
 
Example 7
Source File: ModuleSpecifierSelectionDialog.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates all non-existing segments of the given path.
 *
 * @param path
 *            The path to create
 * @param parent
 *            The container in which the path should be created in
 * @param monitor
 *            A progress monitor. May be {@code null}
 *
 * @return The folder specified by the path
 */
private IContainer createFolderPath(IPath path, IContainer parent, IProgressMonitor monitor) {
	IContainer activeContainer = parent;

	if (null != monitor) {
		monitor.beginTask("Creating folders", path.segmentCount());
	}

	for (String segment : path.segments()) {
		IFolder folderToCreate = activeContainer.getFolder(new Path(segment));
		try {
			if (!folderToCreate.exists()) {
				createFolder(segment, activeContainer, monitor);
			}
			if (null != monitor) {
				monitor.worked(1);
			}
			activeContainer = folderToCreate;
		} catch (CoreException e) {
			LOGGER.error("Failed to create module folders.", e);
			MessageDialog.open(MessageDialog.ERROR, getShell(),
					FAILED_TO_CREATE_FOLDER_TITLE, String.format(FAILED_TO_CREATE_FOLDER_MESSAGE,
							folderToCreate.getFullPath().toString(), e.getMessage()),
					SWT.NONE);
			break;
		}
	}
	return activeContainer;
}
 
Example 8
Source File: CordovaProjectConfigurator.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean shouldBeAnEclipseProject(IContainer container, IProgressMonitor monitor) {
	// TODO share code with CanConvertToHybridTester
       boolean configExist = false;
       for(IPath path: PlatformConstants.CONFIG_PATHS){
           IFile config = container.getFile(path);
           if(config.exists()){
               configExist = true;
               break;
           }
       }
       IFolder wwwFile = container.getFolder(new Path(PlatformConstants.DIR_WWW));
       return configExist && wwwFile.exists();
}
 
Example 9
Source File: ProjectStub.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFile getFile(IPath path) {
    String[] segments = path.segments();
    int segmentCount = path.segmentCount();
    IContainer container = this;
    for (int i = 0; i < segmentCount - i; i++) {
        container = container.getFolder(new Path(segments[i]));
    }
    if (container != this) {
        return container.getFile(new Path(segments[segmentCount - 1]));
    }

    throw new RuntimeException("Finish implementing");
}
 
Example 10
Source File: ResourceUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the folder specified by projectRelativeFolderPath, and all parent
 * folders, if they do not already exist.
 *
 * @param project
 * @param projectRelativeFolderPath
 * @throws CoreException
 */
public static void createFolderStructure(IProject project,
    IPath projectRelativeFolderPath) throws CoreException {

  IContainer curContainer = project;

  for (String pathSegment : projectRelativeFolderPath.segments()) {
    curContainer = curContainer.getFolder(new Path(pathSegment));
    createFolderIfNonExistent((IFolder) curContainer,
        new NullProgressMonitor());
  }
}
 
Example 11
Source File: ProjectHelper.java    From eclipse-extras with Eclipse Public License 1.0 5 votes vote down vote up
public IFolder createFolder( String name ) throws CoreException {
  initializeProject();
  String[] segments = new Path( name ).segments();
  IContainer container = project;
  for( String segment : segments ) {
    IFolder newFolder = container.getFolder( new Path( segment ) );
    if( !newFolder.exists() ) {
      newFolder.create( true, true, newProgressMonitor() );
    }
    container = newFolder;
  }
  return project.getFolder( new Path( name ) );
}
 
Example 12
Source File: AbstractResouceWizardPage.java    From depan with Apache License 2.0 5 votes vote down vote up
protected IContainer getResourceContainer(
    ResourceContainer container) {
  IContainer resources = WorkspaceTools.guessContainer(selection);
  if (resources != null) {
    return resources.getFolder(container.getPath());
  }
  return null;
}
 
Example 13
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Imports resources from <code>bundleSourcePath</code> to
 * <code>importTarget</code>.
 *
 * @param importTarget
 *            the parent container
 * @param bundleSourcePath
 *            the path to a folder containing resources
 *
 * @throws CoreException
 *             import failed
 * @throws IOException
 *             import failed
 */
public static void importResources(IContainer importTarget, Bundle bundle, String bundleSourcePath) throws CoreException,
        IOException {
    Enumeration<?> entryPaths = bundle.getEntryPaths(bundleSourcePath);
    while (entryPaths.hasMoreElements()) {
        String path = (String) entryPaths.nextElement();
        IPath name = new Path(path.substring(bundleSourcePath.length()));
        if (path.endsWith("/.svn/")) {
            continue; // Ignore SVN folders
        } else if (path.endsWith("/")) {
            IFolder folder = importTarget.getFolder(name);
            if (folder.exists()) {
                folder.delete(true, null);
            }
            folder.create(true, true, null);
            importResources(folder, bundle, path);
        } else {
            URL url = bundle.getEntry(path);
            IFile file = importTarget.getFile(name);
            if (!file.exists()) {
                file.create(url.openStream(), true, null);
            } else {
                file.setContents(url.openStream(), true, false, null);
            }
        }
    }
}
 
Example 14
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IResource getRefactoredResource(IResource element) {
	IFolder packageFolder= (IFolder) fPackage.getResource();
	if (packageFolder == null) {
		return element;
	}

	IContainer newPackageFolder= (IContainer) getNewPackage().getResource();

	if (packageFolder.equals(element)) {
		return newPackageFolder;
	}

	IPath packagePath= packageFolder.getProjectRelativePath();
	IPath elementPath= element.getProjectRelativePath();

	if (packagePath.isPrefixOf(elementPath)) {
		if (fRenameSubpackages || (element instanceof IFile && packageFolder.equals(element.getParent()))) {
			IPath pathInPackage= elementPath.removeFirstSegments(packagePath.segmentCount());
			if (element instanceof IFile) {
				return newPackageFolder.getFile(pathInPackage);
			} else {
				return newPackageFolder.getFolder(pathInPackage);
			}
		}
	}
	return element;
}
 
Example 15
Source File: ClientTemplate.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void addResource ( final IProject project, final String name, final InputStream stream, final IProgressMonitor monitor ) throws CoreException
{
    try
    {
        final String[] toks = name.split ( "\\/" ); //$NON-NLS-1$
        IContainer container = project;
        for ( int i = 0; i < toks.length - 1; i++ )
        {
            final IFolder folder = container.getFolder ( new Path ( toks[i] ) );
            if ( !folder.exists () )
            {
                folder.create ( true, true, null );
            }
            container = folder;
        }
        final IFile file = project.getFile ( name );
        if ( file.exists () )
        {
            file.setContents ( stream, IResource.FORCE, monitor );
        }
        else
        {
            file.create ( stream, true, monitor );
        }
    }
    finally
    {
        try
        {
            stream.close ();
        }
        catch ( final IOException e )
        {
        }
    }
    monitor.done ();
}
 
Example 16
Source File: ProjectStub.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFile getFile(IPath path) {
    String[] segments = path.segments();
    int segmentCount = path.segmentCount();
    IContainer container = this;
    for (int i = 0; i < segmentCount - i; i++) {
        container = container.getFolder(new Path(segments[i]));
    }
    if (container != this) {
        return container.getFile(new Path(segments[segmentCount - 1]));
    }

    throw new RuntimeException("Finish implementing");
}
 
Example 17
Source File: SaveLoadConfig.java    From depan with Apache License 2.0 4 votes vote down vote up
public IFile getNewResourceFile(IContainer proj) {
  IPath treePath = getContainer().getPath();
  IFolder root = proj.getFolder(treePath);
  return root.getFile(getBaseNameExt());
}
 
Example 18
Source File: NewProjectWizard.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This creates the project in the workspace.
 *
 * @param description
 * @param projectHandle
 * @param monitor
 * @throws CoreException
 * @throws OperationCanceledException
 */
void createProject(final IProjectDescription description, final IProject proj, final boolean isTest,
		final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	try {

		final SubMonitor m = SubMonitor.convert(monitor, "", 2000);
		proj.create(description, m.split(1000));

		if (monitor.isCanceled()) { throw new OperationCanceledException(); }
		proj.open(m.split(1000));

		WorkspaceModelsManager.setValuesProjectDescription(proj, false, false, isTest, null);

		/*
		 * We now have the project and we can do more things with it before updating the perspective.
		 */
		final IContainer container = proj;

		/* Add the models folder */
		final IFolder modelFolder = container.getFolder(new Path("models"));
		modelFolder.create(true, true, monitor);

		/* Add the includes folder */
		final IFolder incFolder = container.getFolder(new Path("includes"));
		incFolder.create(true, true, monitor);

		/* Add the images folder */
		if (isTest) {
			final IFolder imFolder = container.getFolder(new Path("tests"));
			imFolder.create(true, true, monitor);
		}

	} catch (final CoreException ioe) {
		final IStatus status =
				new Status(IStatus.ERROR, "ProjectWizard", IStatus.OK, ioe.getLocalizedMessage(), null);
		throw new CoreException(status);
	} finally {
		monitor.done();
		ResourceManager.getInstance().reveal(proj.getFolder(isTest ? "tests" : "models"));
	}
}
 
Example 19
Source File: ProjectCreator.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
public static IFolder createFolder(IContainer parent, String projectName) throws CoreException {
	IFolder folder = parent.getFolder(new Path(projectName));
	folder.create(true, true, new NullProgressMonitor());
	return folder;
}
 
Example 20
Source File: PyRenameResourceChange.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Change perform(IProgressMonitor pm) throws CoreException {
    try {
        pm.beginTask(getName(), 1);

        IResource resource = getResource();
        long currentStamp = resource.getModificationStamp();
        IContainer destination = target != null ? target : getDestination(resource, fInitialName, fNewName, pm);

        IResource[] createdFiles = createDestination(destination);

        IPath newPath;
        boolean copyChildrenInsteadOfMove = false;
        if (resource.getType() == IResource.FILE) {
            //Renaming file
            newPath = destination.getFullPath().append(FullRepIterable.getLastPart(fNewName) + ".py");
        } else {
            //Renaming folder
            newPath = destination.getFullPath().append(FullRepIterable.getLastPart(fNewName));

            IPath fullPath = resource.getFullPath();
            if (fullPath.isPrefixOf(newPath)) {
                copyChildrenInsteadOfMove = true;
            }
        }

        if (copyChildrenInsteadOfMove) {
            IContainer container = (IContainer) resource;
            IResource[] members = container.members(true); //Note: get the members before creating the target.
            IFolder folder = container.getFolder(new Path(newPath.lastSegment()));
            IFile initFile = container.getFile(new Path("__init__.py"));

            folder.create(IResource.NONE, true, null);
            createdFiles = ArrayUtils.concatArrays(createdFiles, new IResource[] { folder });

            for (IResource member : members) {
                member.move(newPath.append(member.getFullPath().lastSegment()), IResource.SHALLOW, pm);
            }
            initFile.create(new ByteArrayInputStream(new byte[0]), IResource.NONE, null);

        } else {
            //simple move
            resource.move(newPath, IResource.SHALLOW, pm);
        }

        if (fStampToRestore != IResource.NULL_STAMP) {
            IResource newResource = ResourcesPlugin.getWorkspace().getRoot().findMember(newPath);
            newResource.revertModificationStamp(fStampToRestore);
        }

        for (IResource r : this.fCreatedFiles) {
            r.delete(true, null);
        }

        //The undo command
        return new PyRenameResourceChange(newPath, fNewName, fInitialName, fComment, currentStamp, createdFiles);
    } finally {
        pm.done();
    }
}