Java Code Examples for org.eclipse.core.resources.IResource#getFullPath()

The following examples show how to use org.eclipse.core.resources.IResource#getFullPath() . 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: ResourceMoveTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void performMove(final IContainer theDestination, final IResource... theResources) {
  try {
    MoveResourcesDescriptor _moveResourcesDescriptor = new MoveResourcesDescriptor();
    final Procedure1<MoveResourcesDescriptor> _function = (MoveResourcesDescriptor it) -> {
      final Function1<IResource, IPath> _function_1 = (IResource it_1) -> {
        return it_1.getFullPath();
      };
      it.setResourcePathsToMove(((IPath[])Conversions.unwrapArray(ListExtensions.<IResource, IPath>map(((List<IResource>)Conversions.doWrapArray(theResources)), _function_1), IPath.class)));
      it.setDestinationPath(theDestination.getFullPath());
    };
    MoveResourcesDescriptor _doubleArrow = ObjectExtensions.<MoveResourcesDescriptor>operator_doubleArrow(_moveResourcesDescriptor, _function);
    this.performRefactoring(_doubleArrow);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 2
Source File: Auditor.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private IDocument connectFileBuffer(IResource resource) {

      if (!(resource instanceof IFile)) {
        return null;
      }

      IDocument document = null;

      try {
        IPath path = resource.getFullPath();
        mFileBufferManager.connect(path, new NullProgressMonitor());

        mConnectedFileBufferPaths.add(path);
        document = mFileBufferManager.getTextFileBuffer(path).getDocument();
      } catch (CoreException e) {
        CheckstyleLog.log(e);
      }
      return document;
    }
 
Example 3
Source File: JarEntryLocator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @return a URI for the given jarEntry, can be <code>null</code>.
 */
public URI getURI(IPackageFragmentRoot root, IJarEntryResource jarEntry, TraversalState state) {
	if (root.isArchive()) {
		URI jarURI = JarEntryURIHelper.getUriForPackageFragmentRoot(root);
		URI storageURI = URI.createURI(jarEntry.getFullPath().toString());
		return createJarURI(root.isArchive(), jarURI, storageURI);
	} else if (root instanceof ExternalPackageFragmentRoot) {
		IResource resource = ((ExternalPackageFragmentRoot) root).resource();
		IPath result = resource.getFullPath();
		for(int i = 1; i < state.getParents().size(); i++) {
			Object obj = state.getParents().get(i);
			if (obj instanceof IPackageFragment) {
				result = result.append(new Path(((IPackageFragment) obj).getElementName().replace('.', '/')));
			} else if (obj instanceof IJarEntryResource) {
				result = result.append(((IJarEntryResource) obj).getName());
			}
		}
		result = result.append(jarEntry.getName());
		return URI.createPlatformResourceURI(result.toString(), true);			
	} else {
		throw new IllegalStateException("Unexpeced root type: " + root.getClass().getName());
	}
}
 
Example 4
Source File: SARLProposalProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static String extractProjectPath(IPath fileWorkspacePath, IJavaProject javaProject) {
	if (javaProject != null && javaProject.exists() && javaProject.isOpen()) {
		try {
			for (final IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
				if (!root.isArchive() && !root.isExternal()) {
					final IResource resource = root.getResource();
					if (resource != null) {
						final IPath sourceFolderPath = resource.getFullPath();
						if (sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
							final IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
							return claspathRelativePath.removeLastSegments(1)
									.toString().replace("/", "."); //$NON-NLS-1$//$NON-NLS-2$
						}
					}
				}
			}
		} catch (JavaModelException e) {
			Logger.getLogger(SARLProposalProvider.class).error(e.getLocalizedMessage(), e);
		}
	}
	return null;
}
 
Example 5
Source File: EclipseBuildSupport.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean isBuildFile(IResource resource) {
	if (resource == null || resource.getProject() == null) {
		return false;
	}
	IProject project = resource.getProject();
	for (String file : files) {
		if (resource.equals(project.getFile(file))) {
			return true;
		}
	}
	IPath path = resource.getFullPath();
	for (String folder : folders) {
		IPath folderPath = project.getFolder(folder).getFullPath();
		if (folderPath.isPrefixOf(path)) {
			return true;
		}
	}
	return false;
}
 
Example 6
Source File: SynchronizerSyncInfoCache.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
synchronized protected void removeRecursiveFromPendingCache(IResource resource)
{
	IPath fullPath = resource.getFullPath();
	for (Iterator iter = pendingCacheWrites.keySet().iterator(); iter.hasNext();) {
		if (fullPath.isPrefixOf(((IResource) iter.next()).getFullPath())) {
			iter.remove();
		}
	}			
}
 
Example 7
Source File: ResourcePickerDialog.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
@Override
public void copyValuesFromGUI() {
  if (resourcesUI.getSelectionCount() > 0) {
    pickedResource = (IResource)resourcesUI.getSelection()[0].getData();
    IPath ipath = (null == pickedResource) ? null : pickedResource.getFullPath();
    result = (null == ipath ||
    		      (2 > ipath.segmentCount())) // project name alone cant be given to getFile
    	 ? null 
       : new IFile[] {TAEConfiguratorPlugin.getWorkspace().getRoot().getFile(ipath)};        
  }
}
 
Example 8
Source File: BuildPathDialogAccess.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IPath[] internalChooseFolderEntry(Shell shell, IPath initialSelection, IPath[] usedEntries, String title, String message) {
	Class<?>[] acceptedClasses= new Class[] { IProject.class, IFolder.class };

	ArrayList<IResource> usedContainers= new ArrayList<IResource>(usedEntries.length);
	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
	for (int i= 0; i < usedEntries.length; i++) {
		IResource resource= root.findMember(usedEntries[i]);
		if (resource instanceof IContainer) {
			usedContainers.add(resource);
		}
	}

	IResource focus= initialSelection != null ? root.findMember(initialSelection) : null;
	Object[] used= usedContainers.toArray();

	MultipleFolderSelectionDialog dialog= new MultipleFolderSelectionDialog(shell, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
	dialog.setExisting(used);
	dialog.setTitle(title);
	dialog.setMessage(message);
	dialog.setHelpAvailable(false);
	dialog.addFilter(new TypedViewerFilter(acceptedClasses, used));
	dialog.setInput(root);
	dialog.setInitialFocus(focus);

	if (dialog.open() == Window.OK) {
		Object[] elements= dialog.getResult();
		IPath[] res= new IPath[elements.length];
		for (int i= 0; i < res.length; i++) {
			IResource elem= (IResource) elements[i];
			res[i]= elem.getFullPath();
		}
		return res;
	}
	return null;
}
 
Example 9
Source File: StandardImportAndReadSmokeTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a temporary archive from the specified resource.
 */
private static String createArchive(IResource sourceResource) throws URISyntaxException {
    IPath exportedPath = sourceResource.getFullPath();

    SWTBotTreeItem traceFilesProject = SWTBotUtils.selectProject(fBot, TRACE_PROJECT_NAME);
    traceFilesProject.contextMenu("Export...").click();

    SWTBotShell activeShell = fBot.shell("Export").activate();
    SWTBotTree exportWizardsTree = fBot.tree();
    SWTBotTreeItem treeItem = SWTBotUtils.getTreeItem(fBot, exportWizardsTree, "General", "Archive File");
    treeItem.select();
    fBot.button("Next >").click();
    fBot.button("&Deselect All").click();
    try {
        String resolveLinkedResLabel = "Resolve and export linked resources";
        fBot.waitUntil(Conditions.waitForWidget(withMnemonic(resolveLinkedResLabel)), 100);
        fBot.checkBox(resolveLinkedResLabel).select();
    } catch (TimeoutException e) {
        // Ignore, doesn't exist pre-4.6M5
    }

    if (sourceResource instanceof IFile) {
        String[] folderPath = exportedPath.removeLastSegments(1).segments();
        String fileName = exportedPath.lastSegment();
        SWTBotImportWizardUtils.selectFile(fBot, fileName, folderPath);
    } else {
        selectFolder(exportedPath.segments());
    }

    String workspacePath = URIUtil.toFile(URIUtil.fromString(System.getProperty("osgi.instance.area"))).getAbsolutePath();
    final String archiveDestinationPath = workspacePath + File.separator + TRACE_PROJECT_NAME + File.separator + GENERATED_ARCHIVE_NAME;
    fBot.comboBox().setText(archiveDestinationPath);
    fBot.button("&Finish").click();
    fBot.waitUntil(Conditions.shellCloses(activeShell), IMPORT_TIME_OUT);
    return archiveDestinationPath;
}
 
Example 10
Source File: ArchiveFileExportOperation2.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and returns the string that should be used as the name of the entry in the archive.
 * @param exportResource
 *            the resource to export
 * @param leadupDepth
 *            the number of resource levels to be included in the path including the resourse itself.
 */
private String createDestinationName(int leadupDepth, IResource exportResource) {
	IPath fullPath = exportResource.getFullPath();
	if (createLeadupStructure) {
		return fullPath.makeRelative().toString();
	}
	return fullPath.removeFirstSegments(fullPath.segmentCount() - leadupDepth).toString();
}
 
Example 11
Source File: SourceAttachmentCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateSourceAttachmentFromProjectJar() throws Exception {
	IResource source = project.findMember("foo-sources.jar");
	assertNotNull(source);
	IPath sourcePath = source.getLocation();
	SourceAttachmentAttribute attributes = new SourceAttachmentAttribute(null, sourcePath.toOSString(), "UTF-8");
	SourceAttachmentRequest request = new SourceAttachmentRequest(classFileUri, attributes);
	String arguments = new Gson().toJson(request, SourceAttachmentRequest.class);
	SourceAttachmentResult updateResult = SourceAttachmentCommand.updateSourceAttachment(Arrays.asList(arguments), new NullProgressMonitor());
	assertNotNull(updateResult);
	assertNull(updateResult.errorMessage);

	// Verify the source is attached to the classfile.
	IClassFile classfile = JDTUtils.resolveClassFile(classFileUri);
	IBuffer buffer = classfile.getBuffer();
	assertNotNull(buffer);
	assertTrue(buffer.getContents().indexOf("return sum;") >= 0);

	// Verify whether project inside jar attachment is saved with project relative path.
	IJavaProject javaProject = JavaCore.create(project);
	IPath relativePath = source.getFullPath();
	IPath absolutePath = source.getLocation();
	for (IClasspathEntry entry : javaProject.getRawClasspath()) {
		if (Objects.equals("foo.jar", entry.getPath().lastSegment())) {
			assertNotNull(entry.getSourceAttachmentPath());
			assertEquals(relativePath, entry.getSourceAttachmentPath());
			assertNotEquals(absolutePath, entry.getSourceAttachmentPath());
			break;
		}
	}
}
 
Example 12
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();
    }
}
 
Example 13
Source File: ConvertJavaCode.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private void handleException(String message, Throwable e, IResource file) throws ExecutionException {
	throw new ExecutionException(message + (file != null ? (" " + file.getFullPath()) : ""), e);
}
 
Example 14
Source File: PathWithLocationType.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
public PathWithLocationType(IResource res) {
    this(res.getFullPath(), null, LocationType.WORKSPACE);
}
 
Example 15
Source File: DeleteChangeCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static Change createDeleteChange(IResource resource) {
	Assert.isTrue(! (resource instanceof IWorkspaceRoot));//cannot be done
	Assert.isTrue(! (resource instanceof IProject)); //project deletion is handled by the workbench
	return new DeleteResourceChange(resource.getFullPath(), true);
}
 
Example 16
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean contains(IResource resource) {

		IClasspathEntry[] classpath;
		IPath output;
		try {
			classpath = getResolvedClasspath();
			output = getOutputLocation();
		} catch (JavaModelException e) {
			return false;
		}

		IPath fullPath = resource.getFullPath();
		IPath innerMostOutput = output.isPrefixOf(fullPath) ? output : null;
		IClasspathEntry innerMostEntry = null;
		ExternalFoldersManager foldersManager = JavaModelManager.getExternalManager();
		for (int j = 0, cpLength = classpath.length; j < cpLength; j++) {
			IClasspathEntry entry = classpath[j];

			IPath entryPath = entry.getPath();
			if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
				IResource linkedFolder = foldersManager.getFolder(entryPath);
				if (linkedFolder != null)
					entryPath = linkedFolder.getFullPath();
			}
			if ((innerMostEntry == null || innerMostEntry.getPath().isPrefixOf(entryPath))
					&& entryPath.isPrefixOf(fullPath)) {
				innerMostEntry = entry;
			}
			IPath entryOutput = classpath[j].getOutputLocation();
			if (entryOutput != null && entryOutput.isPrefixOf(fullPath)) {
				innerMostOutput = entryOutput;
			}
		}
		if (innerMostEntry != null) {
			// special case prj==src and nested output location
			if (innerMostOutput != null && innerMostOutput.segmentCount() > 1 // output isn't project
					&& innerMostEntry.getPath().segmentCount() == 1) { // 1 segment must be project name
				return false;
			}
			if  (resource instanceof IFolder) {
				 // folders are always included in src/lib entries
				 return true;
			}
			switch (innerMostEntry.getEntryKind()) {
				case IClasspathEntry.CPE_SOURCE:
					// .class files are not visible in source folders
					return !org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(fullPath.lastSegment());
				case IClasspathEntry.CPE_LIBRARY:
					// .java files are not visible in library folders
					return !org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(fullPath.lastSegment());
			}
		}
		if (innerMostOutput != null) {
			return false;
		}
		return true;
	}
 
Example 17
Source File: IDEClassPathBlock.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean performApply( )
{
	String value = ""; //$NON-NLS-1$
	List list = fLibrariesList.getElements( );

	for ( int i = 0; i < list.size( ); i++ )
	{
		StringBuffer entryScript = new StringBuffer( );
		IDECPListElement element = (IDECPListElement) list.get( i );
		int type = getType( element );
		if ( type == UNKNOW_TYPE )
		{
			continue;
		}
		IClasspathEntry entry = element.getClasspathEntry( );
		if ( entry == null )
		{
			continue;
		}
		entryScript.append( entry.getEntryKind( ) );
		entryScript.append( TYPE_SEPARATOR );
		entryScript.append( type );
		entryScript.append( TYPE_SEPARATOR );
		IResource resource = element.getResource( );
		IPath path;
		if ( resource == null )
		{
			path = element.getPath( );
		}
		else
		{
			path = resource.getFullPath( );
		}
		entryScript.append( path );
		if ( i != list.size( ) - 1 )
		{
			entryScript.append( ENTRY_SEPARATOR );
		}
		value = value + entryScript.toString( );
	}

	setValue( PREF_CLASSPATH, value );
	return super.performApply( );
}
 
Example 18
Source File: SetMainFileAction.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
    * 
 */
public void run(IAction action) {
    
    IResource file = ((FileEditorInput)editor.getEditorInput()).getFile();
    IProject project = file.getProject();
    
       //load settings, if changed on disk
       if (TexlipseProperties.isProjectPropertiesFileChanged(project)) {
           TexlipseProperties.loadProjectProperties(project);
       }
       
       // check that there is an output format property
       String format = TexlipseProperties.getProjectProperty(project, TexlipseProperties.OUTPUT_FORMAT);
       if (format == null || format.length() == 0) {
           TexlipseProperties.setProjectProperty(project, TexlipseProperties.OUTPUT_FORMAT, TexlipsePlugin.getPreference(TexlipseProperties.OUTPUT_FORMAT));
       }
       
       // check that there is a builder number
       String builderNum = TexlipseProperties.getProjectProperty(project, TexlipseProperties.BUILDER_NUMBER);
       if (builderNum == null || builderNum.length() == 0) {
           TexlipseProperties.setProjectProperty(project, TexlipseProperties.BUILDER_NUMBER, TexlipsePlugin.getPreference(TexlipseProperties.BUILDER_NUMBER));
       }
       
    String name = file.getName();
       IPath path = file.getFullPath();
       
       IResource currentMainFile = TexlipseProperties.getProjectSourceFile(project);
       // check if this is already the main file
       if (currentMainFile != null && path.equals(currentMainFile.getFullPath())) {
           return;
       }
       
       // set main file
    TexlipseProperties.setProjectProperty(project, TexlipseProperties.MAINFILE_PROPERTY, name);
    
       // set output files
    String output = name.substring(0, name.lastIndexOf('.')+1) + format;
    TexlipseProperties.setProjectProperty(project, TexlipseProperties.OUTPUTFILE_PROPERTY, output);

       // set source directory
    String dir = path.removeFirstSegments(1).removeLastSegments(1).toString();
       TexlipseProperties.setProjectProperty(project, TexlipseProperties.SOURCE_DIR_PROPERTY, dir);
       
       // make sure there is output directory setting
       String oldOut = TexlipseProperties.getProjectProperty(project, TexlipseProperties.OUTPUT_DIR_PROPERTY);
       if (oldOut == null) {
           TexlipseProperties.setProjectProperty(project, TexlipseProperties.OUTPUT_DIR_PROPERTY, dir);
       }
       
       // make sure there is temp directory setting
       String oldTmp = TexlipseProperties.getProjectProperty(project, TexlipseProperties.TEMP_DIR_PROPERTY);
       if (oldTmp == null) {
           TexlipseProperties.setProjectProperty(project, TexlipseProperties.TEMP_DIR_PROPERTY, dir);
       }

       //save settings to file
       TexlipseProperties.saveProjectProperties(project);
}
 
Example 19
Source File: LibrariesWorkbookPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private CPListElement newCPLibraryElement(IResource res) {
	return new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res);
}
 
Example 20
Source File: RefactoringFileBuffers.java    From eclipse.jdt.ls with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Connects to and acquires a text file buffer for the specified compilation unit.
 * <p>
 * All text file buffers acquired by a call to {@link RefactoringFileBuffers#acquire(ICompilationUnit)}
 * must be released using {@link RefactoringFileBuffers#release(ICompilationUnit)}.
 * </p>
 *
 * @param unit the compilation unit to acquire a text file buffer for
 * @return the text file buffer, or <code>null</code> if no buffer could be acquired
 * @throws CoreException if no buffer could be acquired
 */
public static ITextFileBuffer acquire(final ICompilationUnit unit) throws CoreException {
	Assert.isNotNull(unit);
	final IResource resource= unit.getResource();
	if (resource != null && resource.getType() == IResource.FILE) {
		final IPath path= resource.getFullPath();
		FileBuffers.getTextFileBufferManager().connect(path, LocationKind.IFILE, new NullProgressMonitor());
		return FileBuffers.getTextFileBufferManager().getTextFileBuffer(path, LocationKind.IFILE);
	}
	return null;
}