Java Code Examples for org.eclipse.core.resources.IFolder#createLink()

The following examples show how to use org.eclipse.core.resources.IFolder#createLink() . 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: BazelProjectSupport.java    From eclipse with Apache License 2.0 6 votes vote down vote up
private static void createClasspath(IPath root, List<String> paths, IJavaProject javaProject,
    int javaLanguageLevel) throws CoreException {
  String name = root.lastSegment();
  IFolder base = javaProject.getProject().getFolder(name);
  if (!base.isLinked()) {
    base.createLink(root, IResource.NONE, null);
  }
  List<IClasspathEntry> list = new LinkedList<>();
  for (String path : paths) {
    IPath workspacePath = base.getFullPath().append(path);
    list.add(JavaCore.newSourceEntry(workspacePath));
  }
  list.add(JavaCore.newContainerEntry(new Path(BazelClasspathContainer.CONTAINER_NAME)));

  list.add(
      JavaCore.newContainerEntry(new Path(STANDARD_VM_CONTAINER_PREFIX + javaLanguageLevel)));
  IClasspathEntry[] newClasspath = list.toArray(new IClasspathEntry[0]);
  javaProject.setRawClasspath(newClasspath, null);
}
 
Example 2
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static IProject createInvisibleProjectIfNotExist(IPath workspaceRoot) throws OperationCanceledException, CoreException {
	String invisibleProjectName = ProjectUtils.getWorkspaceInvisibleProjectName(workspaceRoot);
	IProject invisibleProject = ResourcesPlugin.getWorkspace().getRoot().getProject(invisibleProjectName);
	if (!invisibleProject.exists()) {
		ProjectsManager.createJavaProject(invisibleProject, null, null, "bin", null);
		// Link the workspace root to the invisible project.
		IFolder workspaceLinkFolder = invisibleProject.getFolder(ProjectUtils.WORKSPACE_LINK);
		if (!workspaceLinkFolder.isLinked()) {
			try {
				JDTUtils.createFolders(workspaceLinkFolder.getParent(), null);
				workspaceLinkFolder.createLink(workspaceRoot.toFile().toURI(), IResource.REPLACE, null);
			} catch (CoreException e) {
				invisibleProject.delete(true, null);
				throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID,
						Messages.format("Failed to create linked resource from ''{0}'' to the invisible project ''{1}''.", new String[] { workspaceRoot.toString(), invisibleProjectName }), e));
			}
		}
	}

	return invisibleProject;
}
 
Example 3
Source File: TracePackageExportOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a linked resource in the specified folder
 *
 * @param exportFolder the folder that will contain the linked resource
 * @param res the resource to export
 * @throws CoreException when createLink fails
 * @return the created linked resource
 */
private static IResource createExportResource(IFolder exportFolder, IResource res) throws CoreException {
    IResource ret = null;
    // Note: The resources cannot be HIDDEN or else they are ignored by ArchiveFileExportOperation
    if (res instanceof IFolder) {
        IFolder folder = exportFolder.getFolder(res.getName());
        folder.createLink(res.getLocationURI(), IResource.REPLACE, null);
        ret = folder;
    } else if (res instanceof IFile) {
        IFile file = exportFolder.getFile(res.getName());
        if (!file.exists()) {
            file.createLink(res.getLocationURI(), IResource.NONE, null);
        }
        ret = file;
    }
    return ret;
}
 
Example 4
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Configures the classpath of the project before refactoring.
 *
 * @param project
 *            the java project
 * @param root
 *            the package fragment root to refactor
 * @param folder
 *            the temporary source folder
 * @param monitor
 *            the progress monitor to use
 * @throws IllegalStateException
 *             if the plugin state location does not exist
 * @throws CoreException
 *             if an error occurs while configuring the class path
 */
private static void configureClasspath(final IJavaProject project, final IPackageFragmentRoot root, final IFolder folder, final IProgressMonitor monitor) throws IllegalStateException, CoreException {
	try {
		monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 200);
		final IClasspathEntry entry= root.getRawClasspathEntry();
		final IClasspathEntry[] entries= project.getRawClasspath();
		final List<IClasspathEntry> list= new ArrayList<IClasspathEntry>();
		list.addAll(Arrays.asList(entries));
		final IFileStore store= EFS.getLocalFileSystem().getStore(JavaPlugin.getDefault().getStateLocation().append(STUB_FOLDER).append(project.getElementName()));
		if (store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists())
			store.delete(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
		store.mkdir(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
		folder.createLink(store.toURI(), IResource.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
		addExclusionPatterns(list, folder.getFullPath());
		for (int index= 0; index < entries.length; index++) {
			if (entries[index].equals(entry))
				list.add(index, JavaCore.newSourceEntry(folder.getFullPath()));
		}
		project.setRawClasspath(list.toArray(new IClasspathEntry[list.size()]), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
	} finally {
		monitor.done();
	}
}
 
Example 5
Source File: StandardImportAndReadSmokeTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a temporary archive containing a nested archive. For example,
 * testtraces.zip/synctraces.tar.gz can be used to test a nested archive.
 */
private static String createNestedArchive() throws IOException, CoreException, URISyntaxException {
    // Link to the test traces folder. We use a link so that we can safely
    // delete the entire project when we are done.
    IProject project = getProjectResource();
    String canonicalPath = new File(TRACE_FOLDER_PARENT_PATH).getCanonicalPath();
    IFolder folder = project.getFolder(TRACE_FOLDER_PARENT_NAME);
    folder.createLink(new Path(canonicalPath), IResource.REPLACE, null);
    IFile file = folder.getFile(ARCHIVE_FILE_NAME);
    String archivePath = createArchive(file);
    folder.delete(true, null);
    return archivePath;
}
 
Example 6
Source File: ImportHandler.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private static void initializeTraceResource(final LttngRelaydConnectionInfo connectionInfo, final String tracePath, final IProject project) throws CoreException, TmfTraceImportException {
    final TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true);
    final TmfTraceFolder tracesFolder = projectElement.getTracesFolder();
    if (tracesFolder != null) {
        IFolder folder = tracesFolder.getResource();
        IFolder traceFolder = folder.getFolder(connectionInfo.getSessionName());
        Path location = new Path(tracePath);
        IStatus result = ResourcesPlugin.getWorkspace().validateLinkLocation(folder, location);
        if (result.isOK()) {
            traceFolder.createLink(location, IResource.REPLACE, new NullProgressMonitor());
        } else {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, result.getMessage()));
        }

        TraceTypeHelper selectedTraceType = TmfTraceTypeUIUtils.selectTraceType(location.toOSString(), null, null);
        // No trace type was determined.
        TmfTraceTypeUIUtils.setTraceType(traceFolder, selectedTraceType);

        TmfTraceElement found = null;
        final List<TmfTraceElement> traces = tracesFolder.getTraces();
        for (TmfTraceElement candidate : traces) {
            if (candidate.getName().equals(connectionInfo.getSessionName())) {
                found = candidate;
            }
        }

        if (found == null) {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_LiveTraceElementError));
        }

        // Properties used to be able to reopen a trace in live mode
        traceFolder.setPersistentProperty(CtfConstants.LIVE_HOST, connectionInfo.getHost());
        traceFolder.setPersistentProperty(CtfConstants.LIVE_PORT, Integer.toString(connectionInfo.getPort()));
        traceFolder.setPersistentProperty(CtfConstants.LIVE_SESSION_NAME, connectionInfo.getSessionName());

        final TmfTraceElement finalTrace = found;
        Display.getDefault().syncExec(() -> TmfOpenTraceHelper.openFromElement(finalTrace));
    }
}
 
Example 7
Source File: ExternalFoldersManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IFolder createLinkFolder(IPath externalFolderPath, boolean refreshIfExistAlready,
								IProject externalFoldersProject, IProgressMonitor monitor) throws CoreException {
	
	IFolder result = addFolder(externalFolderPath, externalFoldersProject, false);
	if (!result.exists())
		result.createLink(externalFolderPath, IResource.ALLOW_MISSING_LOCAL, monitor);
	else if (refreshIfExistAlready)
		result.refreshLocal(IResource.DEPTH_INFINITE,  monitor);
	return result;
}
 
Example 8
Source File: ExternalResourceManager.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
private static final IStatus linkDirectory(IProject p, final IFolder externalsFolder, File directory, IProgressMonitor monitor, boolean filterOutSubfolders) throws CoreException {
	IWorkspace workspace = ResourceUtils.getWorkspace();
	if (workspace == null){
		return Status.OK_STATUS;
	}
	List<File> parts = ResourceUtils.getParts(directory);
	IFolder folder = externalsFolder;
	for (int i = 0; i < parts.size() - 1; i++) {
		File part = parts.get(i);
		folder = folder.getFolder(getName(part));
		if (!folder.exists()) {
			folder.create(IResource.FORCE | IResource.VIRTUAL, true, monitor);
			ResourceUtils.setAbsolutePathOfLinkedResourceAttribute(folder, part.getAbsolutePath());
			ResourceUtils.setSyntheticResourceAttribute(folder);
		}
	}
	
	IFolder linkedFolder = folder.getFolder(directory.getName());
	
	if (linkedFolder.exists() && (linkedFolder.isVirtual() || linkedFolder.getLocation() == null)) { 
		// linkedFolder can be only linked or virtual folder (by the precondition of this method).
		// It can be virtual folder (linkedFolder.getLocation() === null) if lookup directory was added and it was not linked before. 
		
		linkedFolder.delete(true, monitor);
	}
	if (!linkedFolder.exists()){
		Path path = new Path(directory.getAbsolutePath());
		IStatus validateLinkLocationStatus = workspace.validateLinkLocation(linkedFolder, path);
		if (!JavaUtils.areFlagsSet(validateLinkLocationStatus.getSeverity(), IStatus.ERROR | IStatus.CANCEL)){
			linkedFolder.createLink(path, IResource.NONE, monitor);
			if (filterOutSubfolders) {
				ResourceUtils.applyRegexFilter(linkedFolder, IResourceFilterDescription.EXCLUDE_ALL | IResourceFilterDescription.FOLDERS, ".*", monitor); //$NON-NLS-1$
			}
			ResourceUtils.setAbsolutePathOfLinkedResourceAttribute(linkedFolder, directory.getAbsolutePath());
			ResourceUtils.refreshLocalSync(folder);
		}
		
		return validateLinkLocationStatus;
	}
	
	return Status.OK_STATUS;
}
 
Example 9
Source File: PythonExistingSourceFolderWizard.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected IFile doCreateNew(IProgressMonitor monitor) throws CoreException {
    IProject project = filePage.getValidatedProject();
    String name = filePage.getValidatedName();
    IPath source = filePage.getSourceToLink();
    if (project == null || !project.exists()) {
        throw new RuntimeException("The project selected does not exist in the workspace.");
    }
    IPythonPathNature pathNature = PythonNature.getPythonPathNature(project);
    if (pathNature == null) {
        IPythonNature nature = PythonNature.addNature(project, monitor, null, null, null, null, null);
        pathNature = nature.getPythonPathNature();
        if (pathNature == null) {
            throw new RuntimeException("Unable to add the nature to the seleted project.");
        }
    }
    if (source == null || !source.toFile().exists()) {
        throw new RuntimeException("The source to link to, " + source.toString() + ", does not exist.");
    }
    IFolder folder = project.getFolder(name);
    if (!folder.exists()) {
        folder.createLink(source, IResource.BACKGROUND_REFRESH, monitor);
    }
    String newPath = folder.getFullPath().toString();

    String curr = pathNature.getProjectSourcePath(true);
    if (curr == null) {
        curr = "";
    }
    if (curr.endsWith("|")) {
        curr = curr.substring(0, curr.length() - 1);
    }
    String newPathRel = PyStructureConfigHelpers.convertToProjectRelativePath(
            project.getFullPath().toString(), newPath);
    if (curr.length() > 0) {
        //there is already some path
        Set<String> projectSourcePathSet = pathNature.getProjectSourcePathSet(true);
        if (!projectSourcePathSet.contains(newPath)) {
            //only add to the path if it doesn't already contain the new path
            curr += "|" + newPathRel;
        }
    } else {
        //there is still no other path
        curr = newPathRel;
    }
    pathNature.setProjectSourcePath(curr);
    PythonNature.getPythonNature(project).rebuildPath();
    return null;
}