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

The following examples show how to use org.eclipse.core.resources.IFile#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: Model.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses all files into a list of models.
 * 
 * @param files
 * @return list of models
 */
public static Iterable<Model> parseYaml(Iterable<IFile> files, final CompositeSchema schema) {
    if (files == null) {
        return Arrays.asList();
    }

    final List<Model> models = new ArrayList<>();
    for (IFile file : files) {
        Model model = new Model(schema, file.getFullPath());
        try {
            reader(model).readValue(file.getLocationURI().toURL());
        } catch (IllegalArgumentException | IOException e) {
            e.printStackTrace();
            continue;
        }

        models.add(model);
    }
    return models; 
}
 
Example 2
Source File: XmlSourceValidatorTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetProject() throws CoreException {
  IProject project = dynamicWebProject.getProject();
  IFile file = project.getFile("testdata.xml");
  file.create(ValidationTestUtils.stringToInputStream(APPLICATION_XML), 0, null);

  IDocument document = ValidationTestUtils.getDocument(file);

  IncrementalHelper helper = new IncrementalHelper(document, project);
  IPath path = file.getFullPath();
  helper.setURI(path.toString());

  IProject testProject = XmlSourceValidator.getProject(helper);
  assertNotNull(testProject);
  assertEquals(project, testProject);
}
 
Example 3
Source File: XbaseHoverDocumentationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean handleDocRoot(TagElement node) {
	if (!TagElement.TAG_DOCROOT.equals(node.getTagName()))
		return false;
	URI uri = EcoreUtil.getURI(context);
	if (uri.isPlatformResource()) {
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.toPlatformString(true)));
		IPath fullPath = file.getFullPath();
		IProject project = file.getProject();
		if (project.exists() && project.isOpen()) {
			for (IContainer f : sourceFolderProvider.getSourceFolders(project)) {
				if (f.getFullPath().isPrefixOf(fullPath)) {
					IPath location = f.getLocation();
					if (location != null) {
						buffer.append(location.toFile().toURI().toASCIIString());
						return true;
					}
				}
			}
		}
	}
	return true;
}
 
Example 4
Source File: XtendUIValidator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isInSourceFolder(IJavaProject javaProject, IFile resource) {
	IPath path = resource.getFullPath();
	IClasspathEntry[] classpath;
	try {
		classpath = javaProject.getResolvedClasspath(true);
	} catch(JavaModelException e){
		return false; // not a Java project
	}
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
			IPath entryPath = entry.getPath();
			if (entryPath.isPrefixOf(path)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 5
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Reads the content of the IFile.
 * 
 * @param file the file whose content has to be read
 * @return the content of the file
 * @throws CoreException if the file could not be successfully connected or disconnected
 */
private static String getIFileContent(IFile file) throws CoreException {
	String content= null;
	ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
	IPath fullPath= file.getFullPath();
	manager.connect(fullPath, LocationKind.IFILE, null);
	try {
		ITextFileBuffer buffer= manager.getTextFileBuffer(fullPath, LocationKind.IFILE);
		if (buffer != null) {
			content= buffer.getDocument().get();
		}
	} finally {
		manager.disconnect(fullPath, LocationKind.IFILE, null);
	}

	return content;
}
 
Example 6
Source File: RebuildAffectedResourcesTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void assertHasErrors(final IFile file, final String msgPart) {
  try {
    final IMarker[] findMarkers = file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
    for (final IMarker iMarker : findMarkers) {
      if (((MarkerUtilities.getSeverity(iMarker) == IMarker.SEVERITY_ERROR) && MarkerUtilities.getMessage(iMarker).contains(msgPart))) {
        return;
      }
    }
    IPath _fullPath = file.getFullPath();
    String _plus = ((("Expected an error marker containing \'" + msgPart) + "\' on ") + _fullPath);
    String _plus_1 = (_plus + " but found ");
    final Function1<IMarker, String> _function = (IMarker it) -> {
      return MarkerUtilities.getMessage(it);
    };
    String _join = IterableExtensions.join(ListExtensions.<IMarker, String>map(((List<IMarker>)Conversions.doWrapArray(findMarkers)), _function), ",");
    String _plus_2 = (_plus_1 + _join);
    Assert.fail(_plus_2);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 7
Source File: WorkingCopyOwnerProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWorkingCopyOwner_01() {
  try {
    final IFile file = this.unrelatedProject.getFile("src/foo/MyClass.xtend");
    IPath _fullPath = file.getFullPath();
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo");
    _builder.newLine();
    _builder.append("class MyClass {");
    _builder.newLine();
    _builder.append("\t");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    IResourcesSetupUtil.createFile(_fullPath, _builder.toString());
    IResourcesSetupUtil.waitForBuild();
    Assert.assertNull("no source expected as, xtend file is in unrelated project", this.newWorkingCopyOwner().findSource("MyClass", "foo"));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 8
Source File: JsonRpcHelpers.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns an {@link IDocument} for the given {@link IFile}.
 *
 * @param file an {@link IFile}
 * @return a document with the contents of the file,
 * or <code>null</code> if the file can not be opened.
 */
public static IDocument toDocument(IFile file) {
	if (file != null && file.isAccessible()) {
		IPath path = file.getFullPath();
		ITextFileBufferManager fileBufferManager = FileBuffers.getTextFileBufferManager();
		LocationKind kind = LocationKind.IFILE;
		try {
			fileBufferManager.connect(path, kind, new NullProgressMonitor());
			ITextFileBuffer fileBuffer = fileBufferManager.getTextFileBuffer(path, kind);
			if (fileBuffer != null) {
				return fileBuffer.getDocument();
			}
		} catch (CoreException e) {
			JavaLanguageServerPlugin.logException("Failed to convert "+ file +"  to an IDocument", e);
		} finally {
			try {
				fileBufferManager.disconnect(path, kind, new NullProgressMonitor());
			} catch (CoreException slurp) {
				//Don't care
			}
		}
	}
	return null;
}
 
Example 9
Source File: RenameRefactoringProcessor.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
private Change createRenameModuleFileChange(IFile ifile, String newName, RefactoringChangeContext refactoringChangeContext) {
	IFile renamedIFile = getRenamedAbsoluteFile(ifile, newName);
	if (ResourceUtils.equals(renamedIFile, ifile)) {
		return null;
	}
	
	final RenameResourceDescriptor descriptor= (RenameResourceDescriptor) RefactoringCore.getRefactoringContribution(RenameResourceDescriptor.ID).createDescriptor();
	descriptor.setProject(ifile.getProject().getName());
	descriptor.setDescription(Messages.RenameRefactoringProcessor_RenameModule);
	descriptor.setComment(""); //$NON-NLS-1$
	descriptor.setFlags(RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE);
	descriptor.setResourcePath(ifile.getFullPath());
	descriptor.setNewName(newName);
	descriptor.setUpdateReferences(true);
	
	IPath conflictingResourcePath = null;
	if (renamedIFile.exists()) {
		conflictingResourcePath = renamedIFile.getFullPath();
		refactoringChangeContext.registerFileDelete(ResourceUtils.getAbsoluteFile(renamedIFile));
	}
	XdsRenameResourceChange resourceChange = new XdsRenameResourceChange(ifile.getFullPath(), conflictingResourcePath, newName);
	resourceChange.setDescriptor(new RefactoringChangeDescriptor(descriptor));
	
	return resourceChange;
}
 
Example 10
Source File: CleanUpPostSaveListener.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private long getDocumentStamp(IFile file, IProgressMonitor monitor) throws CoreException {
 final ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
 final IPath path= file.getFullPath();

 monitor.beginTask("", 2); //$NON-NLS-1$

 ITextFileBuffer buffer= null;
 try {
 	manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
  buffer= manager.getTextFileBuffer(path, LocationKind.IFILE);
	    IDocument document= buffer.getDocument();

	    if (document instanceof IDocumentExtension4) {
			return ((IDocumentExtension4)document).getModificationStamp();
		} else {
			return file.getModificationStamp();
		}
 } finally {
 	if (buffer != null)
 		manager.disconnect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
 	monitor.done();
 }
}
 
Example 11
Source File: XtendFileRenameParticipant.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected List<? extends IRenameElementContext> createRenameElementContexts(Object element) {
	if(super.getNewName().endsWith(".xtend")) {
		IFile file = (IFile) element;
		final IPath filePath = file.getFullPath();
		final IPath newPath = file.getFullPath().removeLastSegments(1).append(getNewName() + ".xtend");
		String className = trimFileExtension(file.getName());
		if(className != null) {
			ResourceSet resourceSet = resourceSetProvider.get(file.getProject());
			URI resourceURI = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
			Resource resource = resourceSet.getResource(resourceURI, true);
			if (resource != null && !resource.getContents().isEmpty()) {
				for (XtendTypeDeclaration type : EcoreUtil2.eAllOfType(resource.getContents().get(0), XtendTypeDeclaration.class)) {
					if (equal(className, type.getName())) {
						IRenameElementContext renameElementContext = renameContextFactory.createRenameElementContext(type, null, null,
								(XtextResource) resource);
						if(renameElementContext instanceof IChangeRedirector.Aware) 
							((IChangeRedirector.Aware) renameElementContext).setChangeRedirector(new IChangeRedirector() {
								@Override
								public IPath getRedirectedPath(IPath source) {
									return source.equals(filePath) ? newPath : source;
								}
								
							});
						return singletonList(renameElementContext);
					}
				}
			}
		}
	}
	return super.createRenameElementContexts(element);
}
 
Example 12
Source File: WorkspaceTools.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure that we have a file extension on the file name.
 * 
 * @param savePath Initial save path from user
 * @return valid IFile with an extension.
 */
public static IFile calcFileWithExt(IFile saveFile, String ext) {
  IPath savePath = saveFile.getFullPath();
  String saveExt = savePath.getFileExtension();
  if (null == saveExt) {
    savePath = savePath.addFileExtension(ext);
  } else if (!saveExt.equals(ext)) {
    savePath = savePath.addFileExtension(ext);
  }
  return buildResourceFile(savePath);
}
 
Example 13
Source File: SarlClassPathDetector.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Visit the given SARL compilation unit.
 *
 * @param sfile the compilation unit.
 */
protected void visitSarlCompilationUnit(IFile sfile) {
	final IPath path = sfile.getFullPath();
	final IPath sourceFolder = findSarlSourceFolder(path);
	if (sourceFolder != null) {
		addToMap(this.sourceFolders, sourceFolder,
				path.removeFirstSegments(sourceFolder.segmentCount()));
	}
}
 
Example 14
Source File: AbstractExportHandler.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
private void addXLFFile(IFile file) {
	if (!fileSet.contains(file.getFullPath())) {// 防止又选项目,又选文件夹,又选文件
		IPath path = file.getFullPath();
		if (path.segment(1).equals(XLF)) {// 必须存放在 XLIFF 中(should check??)
			if (file.getFileExtension() != null && CommonFunction.validXlfExtension(file.getFileExtension())) {
				fileSet.add(file.toString());
				XliffBean bean = getXlfBean(file);
				if (bean != null) {
					config.addXlfBean(file.getProject(), bean);
				}
			}
		}
	}
}
 
Example 15
Source File: DeletePackageFragmentRootChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static String getFileContents(IFile file) throws CoreException {
	ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
	IPath path= file.getFullPath();
	manager.connect(path, LocationKind.IFILE, new NullProgressMonitor());
	try {
		return manager.getTextFileBuffer(path, LocationKind.IFILE).getDocument().get();
	} finally {
		manager.disconnect(path, LocationKind.IFILE, new NullProgressMonitor());
	}
}
 
Example 16
Source File: XmlSourceValidatorTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFile() throws CoreException {
  IProject project = dynamicWebProject.getProject();
  IFile file = project.getFile("testdata.xml");
  file.create(ValidationTestUtils.stringToInputStream(APPLICATION_XML), 0, null);

  assertTrue(file.exists());

  IPath path = file.getFullPath();
  IFile testFile = XmlSourceValidator.getFile(path.toString());

  assertNotNull(testFile);
  assertEquals(file, testFile);
}
 
Example 17
Source File: GamlEditorDragAndDropHandler.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private String obtainRelativePath(final IFile file) {
	final IPath path = file.getFullPath();
	final IPath editorFile = new Path(editor.getURI().toPlatformString(true)).removeLastSegments(1);
	final IPath newRelativePath = path.makeRelativeTo(editorFile);
	final String name = newRelativePath.toString();
	return name;
}
 
Example 18
Source File: TexDocumentProvider.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Does the same as super.createDocument(Object), except this also adds
 * latex nature to the project containing the given document.
 */
public IDocument getDocument(Object element) {
    IDocument doc = super.getDocument(element);
    
    // add latex nature to project holding this latex file
    // this way we also get latex builder to any project that has latex files
    if (element instanceof FileEditorInput) {
        IFile file = (IFile) ((FileEditorInput)element).getAdapter(IFile.class);
        if (file != null) {
            
            IProject project = file.getProject();
            try {
                if (!project.hasNature(TexlipseNature.NATURE_ID)) {
                    TexlipseProjectCreationOperation.addProjectNature(project, new NullProgressMonitor());
                } else if (TexlipseProperties.getProjectProperty(project, TexlipseProperties.OUTPUT_FORMAT) == null) {
                    // this is needed for imported projects
                    TexlipseNature n = new TexlipseNature();
                    // the nature is not added, just configured
                    n.setProject(project);
                    // this will cause the builder to be added, if not already there
                    n.configure();
                }
            } catch (CoreException e) {
                return doc;
            }
            
            // output format might not yet be set
            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));
                TexlipseProperties.setProjectProperty(project, TexlipseProperties.BUILDER_NUMBER, TexlipsePlugin.getPreference(TexlipseProperties.BUILDER_NUMBER));
                TexlipseProperties.setProjectProperty(project, TexlipseProperties.MARK_TEMP_DERIVED_PROPERTY, "true");
                TexlipseProperties.setProjectProperty(project, TexlipseProperties.MARK_OUTPUT_DERIVED_PROPERTY, "true");
                
                String name = file.getName();
                TexlipseProperties.setProjectProperty(project, TexlipseProperties.MAINFILE_PROPERTY, name);
                String output = name.substring(0, name.lastIndexOf('.')+1) + TexlipsePlugin.getPreference(TexlipseProperties.OUTPUT_FORMAT);
                TexlipseProperties.setProjectProperty(project, TexlipseProperties.OUTPUTFILE_PROPERTY, output);
                
                IPath path = file.getFullPath();
                String dir = path.removeFirstSegments(1).removeLastSegments(1).toString();
                if (dir.length() > 0) {
                    TexlipseProperties.setProjectProperty(project, TexlipseProperties.SOURCE_DIR_PROPERTY, dir);
                    TexlipseProperties.setProjectProperty(project, TexlipseProperties.OUTPUT_DIR_PROPERTY, dir);
                    TexlipseProperties.setProjectProperty(project, TexlipseProperties.TEMP_DIR_PROPERTY, dir);
                }
            }
        }
    }
    
    return doc;
}
 
Example 19
Source File: UserLibraryPreferencePage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private CPListElement[] doOpenExternalJarFileDialog(CPListElement existing, Object parent) {
	String lastUsedPath;
	if (existing != null) {
		lastUsedPath= existing.getPath().removeLastSegments(1).toOSString();
	} else {
		lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
		if (lastUsedPath == null) {
			lastUsedPath= ""; //$NON-NLS-1$
		}
	}
	String title= (existing == null) ? PreferencesMessages.UserLibraryPreferencePage_browsejar_new_title : PreferencesMessages.UserLibraryPreferencePage_browsejar_edit_title;

	FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE);
	dialog.setText(title);
	dialog.setFilterExtensions(ArchiveFileFilter.ALL_ARCHIVES_FILTER_EXTENSIONS);
	dialog.setFilterPath(lastUsedPath);
	if (existing != null) {
		dialog.setFileName(existing.getPath().lastSegment());
	}

	String res= dialog.open();
	if (res == null) {
		return null;
	}
	String[] fileNames= dialog.getFileNames();
	int nChosen= fileNames.length;

	IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();

	IPath filterPath= Path.fromOSString(dialog.getFilterPath());
	CPListElement[] elems= new CPListElement[nChosen];
	for (int i= 0; i < nChosen; i++) {
		IPath path= filterPath.append(fileNames[i]).makeAbsolute();

		IFile file= root.getFileForLocation(path); // support internal JARs: bug 133191
		if (file != null) {
			path= file.getFullPath();
		}

		CPListElement curr= new CPListElement(parent, null, IClasspathEntry.CPE_LIBRARY, path, file);
		curr.setAttribute(CPListElement.SOURCEATTACHMENT, BuildPathSupport.guessSourceAttachment(curr));
		curr.setAttribute(CPListElement.JAVADOC, BuildPathSupport.guessJavadocLocation(curr));
		elems[i]= curr;
	}
	fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath());

	return elems;
}
 
Example 20
Source File: EclipseResourceFileSystemAccess2.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @throws CoreException
 *             if something unexpected happens during resource access
 * @throws IOException
 *             if serialization of the trace data fails
 * @since 2.3
 */
protected void updateTraceInformation(IFile traceFile, CharSequence contents, boolean derived)
		throws CoreException, IOException {
	if (contents instanceof ITraceRegionProvider) {
		try {
			AbstractTraceRegion traceRegion = ((ITraceRegionProvider) contents).getTraceRegion();
			if (sourceTraces == null) {
				sourceTraces = HashMultimap.create();
			}
			IPath tracePath = traceFile.getFullPath();
			Iterator<AbstractTraceRegion> iterator = traceRegion.treeIterator();
			while (iterator.hasNext()) {
				AbstractTraceRegion region = iterator.next();
				for (ILocationData location : region.getAssociatedLocations()) {
					SourceRelativeURI path = location.getSrcRelativePath();
					if (path != null) {
						sourceTraces.put(path, tracePath);
					}
				}
			}
			class AccessibleOutputStream extends ByteArrayOutputStream {
				byte[] internalBuffer() {
					return buf;
				}

				int internalLength() {
					return count;
				}
			}
			AccessibleOutputStream data = new AccessibleOutputStream();
			traceSerializer.writeTraceRegionTo(traceRegion, data);
			// avoid copying the byte array
			InputStream input = new ByteArrayInputStream(data.internalBuffer(), 0, data.internalLength());
			if (traceFile.exists()) {
				traceFile.setContents(input, true, false, monitor);
			} else {
				traceFile.create(input, true, monitor);
			}
			setDerived(traceFile, derived);
			return;
		} catch (TraceNotFoundException e) {
			// ok
		}
	}
	if (traceFile.exists()) {
		traceFile.delete(IResource.FORCE, monitor);
	}
}