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

The following examples show how to use org.eclipse.core.resources.IWorkspaceRoot#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: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given a base URI, figure out which {@link IFolder}, if any, it refers to.
 *
 * @param baseURI
 *          to find the folder(s) for; must not be {@code null}
 * @return an array of all folders mapping to that URI, or an empty array if none do.
 */
private static IContainer[] determineContainersToCheck(final URI baseURI) {
  Preconditions.checkNotNull(baseURI);
  IContainer[] result = {};
  if (baseURI.isPlatformResource() || baseURI.isFile()) {
    IWorkspaceRoot workspace = EcorePlugin.getWorkspaceRoot();
    if (workspace != null) {
      if (baseURI.isFile()) {
        result = workspace.findContainersForLocationURI(java.net.URI.create(baseURI.toString()));
      } else {
        // Must be a platform/resource URI
        IPath platformPath = new Path(baseURI.toPlatformString(true));
        IFolder folder = workspace.getFolder(platformPath);
        if (folder != null) {
          result = new IContainer[] {folder};
        }
      }
    }
  }
  return result;
}
 
Example 2
Source File: AbstractRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
protected T doImportIResource(final String fileName, final IResource resource) {
    try {
        if (resource instanceof IFile) {
            return importInputStream(fileName, ((IFile) resource).getContents());
        } else if (resource instanceof IFolder) {
            final IPath path = getResource().getFullPath().append(fileName);
            final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            final IFolder targetFolder = root.getFolder(path);
            if (targetFolder.exists()) {
                if (FileActionDialog.overwriteQuestion(fileName)) {
                    targetFolder.delete(true, Repository.NULL_PROGRESS_MONITOR);
                } else {
                    return createRepositoryFileStore(fileName);
                }
            }
            resource.copy(getResource().getFullPath().append(fileName), true, Repository.NULL_PROGRESS_MONITOR);
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return createRepositoryFileStore(fileName);
}
 
Example 3
Source File: RadlCreator.java    From RADL with Apache License 2.0 6 votes vote down vote up
public IFile createRadlFile(String folderName, String serviceName, IProgressMonitor monitor,
    IWorkspaceRoot root) throws CoreException {
  IFolder folder = root.getFolder(new Path(folderName));
  if (!folder.exists()) {
    ensureFolder(monitor, folder);
  }
  final IFile result = folder.getFile(serviceNameToFileName(serviceName));
  try (InputStream stream = getRadlSkeleton(serviceName)) {
    if (result.exists()) {
      result.setContents(stream, true, true, monitor);
    } else {
      result.create(stream, true, monitor);
    }
  } catch (IOException e) { // NOPMD EmptyCatchBlock
  }
  IProjectNature nature = new RadlNature();
  nature.setProject(folder.getProject());
  nature.configure();
  return result;
}
 
Example 4
Source File: AbstractNewModelWizard.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public IResource findContainer(final IProgressMonitor monitor, final String containerName,
		final IWorkspaceRoot root) throws CoreException {
	IResource container = root.findMember(new Path(containerName));
	if (container == null || !container.exists()) {
		final boolean create = MessageDialog.openConfirm(getShell(), "Folder does not exist",
				"Folder \"" + containerName + "\" does not exist. Create it automatically ?");
		if (create) {
			final IFolder folder = root.getFolder(new Path(containerName));
			folder.create(true, true, monitor);
			container = folder;
		} else {
			return null;
		}
	} else if (!(container instanceof IContainer)) {
		MessageDialog.openError(getShell(), "Not a folder", containerName + " is not a folder. Cannot proceed");
		return null;
	}
	return container;
}
 
Example 5
Source File: WebAppUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the project's default output directory to the WAR output directory's
 * WEB-INF/classes folder. If the WAR output directory does not have a WEB-INF
 * directory, this method returns without doing anything.
 *
 * @throws CoreException if there's a problem setting the output directory
 */
public static void setOutputLocationToWebInfClasses(IJavaProject javaProject,
    IProgressMonitor monitor) throws CoreException {
  IProject project = javaProject.getProject();

  IFolder webInfOut = getWebInfOut(project);
  if (!webInfOut.exists()) {
    // If the project has no output <WAR>/WEB-INF directory, don't touch the
    // output location
    return;
  }

  IPath oldOutputPath = javaProject.getOutputLocation();
  IPath outputPath = webInfOut.getFullPath().append("classes");

  if (!outputPath.equals(oldOutputPath)) {
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    // Remove old output location and contents
    IFolder oldOutputFolder = workspaceRoot.getFolder(oldOutputPath);
    if (oldOutputFolder.exists()) {
      try {
        removeOldClassfiles(oldOutputFolder);
      } catch (Exception e) {
        CorePluginLog.logError(e);
      }
    }

    // Create the new output location if necessary
    IFolder outputFolder = workspaceRoot.getFolder(outputPath);
    if (!outputFolder.exists()) {
      // TODO: Could move recreate this in a utilities class
      CoreUtility.createDerivedFolder(outputFolder, true, true, null);
    }

    javaProject.setOutputLocation(outputPath, monitor);
  }
}
 
Example 6
Source File: NewExperimentOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private IFolder createExperiment(String experimentName) {
    IFolder expResource = fExperimentFolderRoot.getResource();
    IWorkspaceRoot workspaceRoot = expResource.getWorkspace().getRoot();
    IPath folderPath = expResource.getFullPath().append(experimentName);
    IFolder folder = workspaceRoot.getFolder(folderPath);
    return folder;
}
 
Example 7
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 8
Source File: DeleteResourceShortcutListener.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
 */
public void resourceChanged(IResourceChangeEvent event) {
    IResourceDelta delta = event.getDelta();

    switch (delta.getKind()) {
    case IResourceDelta.REMOVED:
        break;
    case IResourceDelta.CHANGED:
        List<IConnectionPoint> deleted = new ArrayList<IConnectionPoint>();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

        IConnectionPointManager manager = CoreIOPlugin.getConnectionPointManager();
        IConnectionPoint[] projectShortcuts = manager.getConnectionPointCategory(CATEGORY_ID)
                .getConnectionPoints();
        WorkspaceConnectionPoint connectionPoint;
        for (IConnectionPoint shortcut : projectShortcuts) {
            connectionPoint = (WorkspaceConnectionPoint) shortcut;

            // see if the relative path matches the changed item
            IResourceDelta d = delta.findMember(connectionPoint.getPath());
            if (d != null && d.getKind() == IResourceDelta.REMOVED) {
                if (d.getMovedToPath() == null) {
                	IResource resource = d.getResource();
                	if (!(resource instanceof IProject) && resource.getProject().exists() && !resource.getProject().isOpen())
                	{
                		continue;
                	}
                	// the original container was deleted
                	deleted.add(shortcut);
                } else {
                    // the original container was moved
                    IPath newPath = d.getMovedToPath();
                    IContainer newContainer;
                    if (d.getResource() instanceof IProject) {
                        newContainer = root.getProject(newPath.toString());
                    } else {
                        newContainer = root.getFolder(newPath);
                    }
                    connectionPoint.setResource(newContainer);
                    connectionPoint.setName(newContainer.getName());
                }
            }
        }

        // if the item was deleted, remove it
        for (IConnectionPoint projectShortcut : deleted) {
            manager.removeConnectionPoint(projectShortcut);
        }
        break;
    }
}
 
Example 9
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 10
Source File: CPListElement.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static CPListElement create(Object parent, IClasspathEntry curr, boolean newElement, IJavaProject project) {
	IPath path= curr.getPath();
	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();

	// get the resource
	IResource res= null;
	boolean isMissing= false;
	IPath linkTarget= null;

	switch (curr.getEntryKind()) {
		case IClasspathEntry.CPE_CONTAINER:
			try {
				isMissing= project != null && (JavaCore.getClasspathContainer(path, project) == null);
			} catch (JavaModelException e) {
				isMissing= true;
			}
			break;
		case IClasspathEntry.CPE_VARIABLE:
			IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
			isMissing=  root.findMember(resolvedPath) == null && !resolvedPath.toFile().exists();
			break;
		case IClasspathEntry.CPE_LIBRARY:
			res= root.findMember(path);
			if (res == null) {
				if (!ArchiveFileFilter.isArchivePath(path, true)) {
					if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()
							&& root.getProject(path.segment(0)).exists()) {
						res= root.getFolder(path);
					}
				}

				IPath rawPath= path;
				if (project != null) {
					IPackageFragmentRoot[] roots= project.findPackageFragmentRoots(curr);
					if (roots.length == 1)
						rawPath= roots[0].getPath();
				}
				isMissing= !rawPath.toFile().exists(); // look for external JARs and folders
			} else if (res.isLinked()) {
				linkTarget= res.getLocation();
			}
			break;
		case IClasspathEntry.CPE_SOURCE:
			path= path.removeTrailingSeparator();
			res= root.findMember(path);
			if (res == null) {
				if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
					res= root.getFolder(path);
				}
				isMissing= true;
			} else if (res.isLinked()) {
				linkTarget= res.getLocation();
			}
			break;
		case IClasspathEntry.CPE_PROJECT:
			res= root.findMember(path);
			isMissing= (res == null);
			break;
	}
	CPListElement elem= new CPListElement(parent, project, curr.getEntryKind(), path, newElement, res, linkTarget);
	elem.setExported(curr.isExported());
	elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath());
	elem.setAttribute(OUTPUT, curr.getOutputLocation());
	elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
	elem.setAttribute(INCLUSION, curr.getInclusionPatterns());
	elem.setAttribute(ACCESSRULES, curr.getAccessRules());
	elem.setAttribute(COMBINE_ACCESSRULES, new Boolean(curr.combineAccessRules()));

	IClasspathAttribute[] extraAttributes= curr.getExtraAttributes();
	for (int i= 0; i < extraAttributes.length; i++) {
		IClasspathAttribute attrib= extraAttributes[i];
		CPListElementAttribute attribElem= elem.findAttributeElement(attrib.getName());
		if (attribElem == null) {
			elem.createAttributeElement(attrib.getName(), attrib.getValue(), false);
		} else {
			attribElem.setValue(attrib.getValue());
		}
	}

	elem.setIsMissing(isMissing);
	return elem;
}
 
Example 11
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @param path IPath
 * @return A handle to the package fragment root identified by the given path.
 * This method is handle-only and the element may or may not exist. Returns
 * <code>null</code> if unable to generate a handle from the path (for example,
 * an absolute path that has less than 1 segment. The path may be relative or
 * absolute.
 */
public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
	if (!path.isAbsolute()) {
		path = getPath().append(path);
	}
	int segmentCount = path.segmentCount();
	if (segmentCount == 0) {
		return null;
	}
	if (path.getDevice() != null || JavaModel.getExternalTarget(path, true/*check existence*/) != null) {
		// external path
		return getPackageFragmentRoot0(path);
	}
	IWorkspaceRoot workspaceRoot = this.project.getWorkspace().getRoot();
	IResource resource = workspaceRoot.findMember(path);
	if (resource == null) {
		// resource doesn't exist in workspace
		if (path.getFileExtension() != null) {
			if (!workspaceRoot.getProject(path.segment(0)).exists()) {
				// assume it is an external ZIP archive
				return getPackageFragmentRoot0(path);
			} else {
				// assume it is an internal ZIP archive
				resource = workspaceRoot.getFile(path);
			}
		} else if (segmentCount == 1) {
			// assume it is a project
			String projectName = path.segment(0);
			if (getElementName().equals(projectName)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75814
				// default root
				resource = this.project;
			} else {
				// lib being another project
				resource = workspaceRoot.getProject(projectName);
			}
		} else {
			// assume it is an internal folder
			resource = workspaceRoot.getFolder(path);
		}
	}
	return getPackageFragmentRoot(resource);
}
 
Example 12
Source File: TmfCommonProjectElement.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.0
 */
@Override
protected synchronized void refreshChildren() {
    /* Get the base path to put the resource to */
    IPath tracePath = getResource().getFullPath();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    if (this.getParent() instanceof TmfExperimentElement) {
        return;
    }

    if (TmfTraceType.getTraceType(getTraceType()) == null) {
        if (fViewsElement != null) {
            removeChild(fViewsElement);
            fViewsElement.dispose();
            fViewsElement = null;
        }
        if (fOnDemandAnalysesElement != null) {
            removeChild(fOnDemandAnalysesElement);
            fOnDemandAnalysesElement.dispose();
            fOnDemandAnalysesElement = null;
        }
        if (fReportsElement != null) {
            removeChild(fReportsElement);
            fReportsElement.dispose();
            fReportsElement = null;
        }
        return;
    }
    if (fViewsElement == null) {
        /* Add the "Views" node */
        IFolder viewsNodeRes = root.getFolder(tracePath.append(TmfViewsElement.PATH_ELEMENT));
        fViewsElement = new TmfViewsElement(viewsNodeRes, this);
        addChild(fViewsElement);
    }
    fViewsElement.refreshChildren();

    if (fOnDemandAnalysesElement == null) {
        /* Add the "On-demand Analyses" node */
        IFolder analysesNodeRes = root.getFolder(tracePath.append(TmfOnDemandAnalysesElement.PATH_ELEMENT));
        fOnDemandAnalysesElement = new TmfOnDemandAnalysesElement(analysesNodeRes, this);
        addChild(fOnDemandAnalysesElement);
    }
    fOnDemandAnalysesElement.refreshChildren();

    if (fReportsElement == null) {
        /* Add the "Reports" node */
        IFolder reportsNodeRes = root.getFolder(tracePath.append(TmfReportsElement.PATH_ELEMENT));
        fReportsElement = new TmfReportsElement(reportsNodeRes, this);
        addChild(fReportsElement);
    }
    fReportsElement.refreshChildren();
}
 
Example 13
Source File: UIUtil.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a folder resource given the folder handle.
 * 
 * @param folderHandle
 *            the folder handle to create a folder resource for
 * @param monitor
 *            the progress monitor to show visual progress with
 * @exception CoreException
 *                if the operation fails
 * @exception OperationCanceledException
 *                if the operation is canceled
 */
public static void createFolder( IFolder folderHandle,
		IProgressMonitor monitor ) throws CoreException
{
	try
	{
		// Create the folder resource in the workspace
		// Update: Recursive to create any folders which do not exist
		// already
		if ( !folderHandle.exists( ) )
		{
			IPath path = folderHandle.getFullPath( );
			IWorkspaceRoot root = ResourcesPlugin.getWorkspace( ).getRoot( );
			int numSegments = path.segmentCount( );
			if ( numSegments > 2
					&& !root.getFolder( path.removeLastSegments( 1 ) )
							.exists( ) )
			{
				// If the direct parent of the path doesn't exist, try
				// to create the
				// necessary directories.
				for ( int i = numSegments - 2; i > 0; i-- )
				{
					IFolder folder = root.getFolder( path.removeLastSegments( i ) );
					if ( !folder.exists( ) )
					{
						folder.create( false, true, monitor );
					}
				}
			}
			folderHandle.create( false, true, monitor );
		}
	}
	catch ( CoreException e )
	{
		// If the folder already existed locally, just refresh to get
		// contents
		if ( e.getStatus( ).getCode( ) == IResourceStatus.PATH_OCCUPIED )
			folderHandle.refreshLocal( IResource.DEPTH_INFINITE,
					new SubProgressMonitor( monitor, 500 ) );
		else
			throw e;
	}

	if ( monitor.isCanceled( ) )
		throw new OperationCanceledException( );
}
 
Example 14
Source File: NewLibraryWizardAdapterFactory.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
protected IFolder createFolderHandle( IPath folderPath )
{
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace( )
			.getRoot( );
	return workspaceRoot.getFolder( folderPath );
}
 
Example 15
Source File: ResourceURIConverter.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public IFolder toFolder(URI uri) {
	IWorkspaceRoot root = workspace.getRoot();
	return root.getFolder(new Path(uri.toPlatformString(true)));
}
 
Example 16
Source File: NewLibraryWizard.java    From birt with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a folder resource handle for the folder with the given workspace
 * path. This method does not create the folder resource; this is the
 * responsibility of <code>createFolder</code>.
 * 
 * @param folderPath
 *            the path of the folder resource to create a handle for
 * @return the new folder resource handle
 */
protected IFolder createFolderHandle( IPath folderPath )
{
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace( )
			.getRoot( );
	return workspaceRoot.getFolder( folderPath );
}
 
Example 17
Source File: NewReportWizard.java    From birt with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a folder resource handle for the folder with the given workspace
 * path. This method does not create the folder resource; this is the
 * responsibility of <code>createFolder</code>.
 * 
 * @param folderPath
 *            the path of the folder resource to create a handle for
 * @return the new folder resource handle
 */
protected IFolder createFolderHandle( IPath folderPath )
{
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace( )
			.getRoot( );
	return workspaceRoot.getFolder( folderPath );
}
 
Example 18
Source File: WebAppUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the project default output location
 *
 * @param project
 * @return The absolute path to the resource, check with {@link IResource#exists()}, can be null
 * @throws JavaModelException if unable to find the output location from the project
 */
public static IPath getOutputFolderPath(IJavaProject project) throws JavaModelException {
  IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
  IFolder outputLoc = workspaceRoot.getFolder(project.getOutputLocation());
  return outputLoc.getLocation();
}
 
Example 19
Source File: NewFolderDialogOfHs.java    From translationstudio8 with GNU General Public License v2.0 votes vote down vote up
/**
		 * Creates a folder resource handle for the folder with the given name.
		 * The folder handle is created relative to the container specified during 
		 * object creation. 
		 *
		 * @param folderName the name of the folder resource to create a handle for
		 * @return the new folder resource handle
		 */
		private IFolder createFolderHandle(String folderName) {
			IWorkspaceRoot workspaceRoot = container.getWorkspace().getRoot();
			IPath folderPath = container.getFullPath().append(folderName);
			IFolder folderHandle = workspaceRoot.getFolder(folderPath);

			return folderHandle;
		}