/** @return the IFile corresponding to the given input, or null if none */ public static IFile getFile(IEditorInput editorInput) { IFile file = null; if (editorInput instanceof IFileEditorInput) { IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput; file = fileEditorInput.getFile(); } else if (editorInput instanceof IPathEditorInput) { IPathEditorInput pathInput = (IPathEditorInput) editorInput; IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); if (wsRoot.getLocation().isPrefixOf(pathInput.getPath())) { file = ResourcesPlugin.getWorkspace().getRoot().getFile(pathInput.getPath()); } else { // Can't get an IFile for an arbitrary file on the file system; return null } } else if (editorInput instanceof IStorageEditorInput) { file = null; // Can't get an IFile for an arbitrary IStorageEditorInput } else if (editorInput instanceof IURIEditorInput) { IURIEditorInput uriEditorInput = (IURIEditorInput) editorInput; IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); URI uri = uriEditorInput.getURI(); String path = uri.getPath(); // Bug 526: uri.getHost() can be null for a local file URL if (uri.getScheme().equals("file") && (uri.getHost() == null || uri.getHost().equals("localhost")) && !path.startsWith(wsRoot.getLocation().toOSString())) { file = wsRoot.getFile(new Path(path)); } } return file; }
@Override public void shouldCorrectlyBuildMultiplePaths() { WorkspaceStorage ws2 = new WorkspaceStorage(new Path(".b"), null); LocalDate date2 = date.minusDays(2); Duration duration2 = duration.withMillis(10000); IFile fileHasNoParentFolder = root.getFile(new Path("/project/file.txt")); ICategory[] categories = {Category.PROJECT, Category.FOLDER, Category.FILE}; List<TreePath> expected = asList( newPath( fileHasParentFolder.getProject(), fileHasParentFolder.getParent(), fileHasParentFolder, duration), newPath(fileHasNoParentFolder.getProject(), fileHasNoParentFolder, duration2)); IFileData data2 = mock(IFileData.class); given(data2.get(IFileData.DATE)).willReturn(date2); given(data2.get(IFileData.DURATION)).willReturn(duration2); given(data2.get(IFileData.FILE)).willReturn(fileHasNoParentFolder); given(data2.get(IFileData.WORKSPACE)).willReturn(ws2); ICategoryProvider provider = mock(ICategoryProvider.class); given(provider.getSelected()).willReturn(asList(categories)); ITreePathBuilder builder = create(provider); IFileDataProvider input = mock(IFileDataProvider.class); given(input.get()).willReturn(asList(data, data2)); List<TreePath> actual = builder.build(input); assertThat(actual.size(), equalTo(expected.size())); assertThat(toString(actual, expected), actual, hasItems(expected.toArray(new TreePath[0]))); }
public IFile getNewModelIFile() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot workspaceRoot = workspace.getRoot(); // IFile newModelFile = (IFile) workspaceRoot.getFileForLocation(newModelPath); IFile newModelFile = (IFile) workspaceRoot.getFile(newModelPath); return newModelFile; }
/** @see org.eclipse.debug.ui.ISourcePresentation#getEditorInput(java.lang.Object) */ public IEditorInput getEditorInput(Object element) { IStorageEditorInput i; AtlStackFrame frame; // String projectName; String fileName; if (element instanceof AtlStackFrame) { frame = (AtlStackFrame) element; if (((AtlDebugTarget) frame.getDebugTarget()).isDisassemblyMode()) return getDisassemblyEditorInput(frame); ILaunchConfiguration configuration = frame.getDebugTarget().getLaunch().getLaunchConfiguration(); try { // TODO Recuperer le nom du fichier sur la stackframe fileName = configuration.getAttribute( AtlLauncherTools.ATLFILENAME, AtlLauncherTools.NULLPARAMETER); IWorkspace wks = ResourcesPlugin.getWorkspace(); IWorkspaceRoot wksroot = wks.getRoot(); i = new FileEditorInput(wksroot.getFile(new Path(fileName))); return i; } catch (CoreException e) { e.printStackTrace(); } } else if (element instanceof AtlBreakpoint) { IMarker marker = ((AtlBreakpoint) element).getMarker(); IFile ifile = (IFile) marker.getResource(); return new FileEditorInput(ifile); } return null; }
public boolean performFinish() { FeatureModel featureModel = new FeatureModel(); featureModel.createDefaultValues(""); Path fullFilePath = new Path(page.fileName.getText()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath rootPath = root.getLocation(); if (rootPath.isPrefixOf(fullFilePath)) { // case: is file in workspace int matchingFirstSegments = rootPath.matchingFirstSegments(fullFilePath); IPath localFilePath = fullFilePath.removeFirstSegments(matchingFirstSegments); String[] segments = localFilePath.segments(); localFilePath = new Path(""); for (String segment : segments) { localFilePath = localFilePath.append(segment); } IFile file = root.getFile(localFilePath); featureModel.initFMComposerExtension(file.getProject()); try { new FeatureModelWriterIFileWrapper(new XmlFeatureModelWriter(featureModel)) .writeToFile(file); file.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { FMUIPlugin.getDefault().logError(e); } open(file); } else { // case: is no file in workspace File file = fullFilePath.toFile(); new XmlFeatureModelWriter(featureModel).writeToFile(file); } return true; }
private boolean init(IValidationContext helper, IReporter reporter, boolean test) { if (!test && disabled) { return false; } if (context == null) { synchronized (reporters) { reporters.add(document); } String[] uris = helper.getURIs(); if (uris.length == 0) { return false; } IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); file = root.getFile(new Path(uris[0])); if (!file.isAccessible()) { return false; } context = new EditorValidationContext(file.getProject(), document); if (context.getValidators().isEmpty()) { return false; } rootProjects = new HashMap<IValidator, IProject>(); for (IValidator validator : context.getValidators()) { Map<IProject, IValidatingProjectSet> projectTree = context.getValidatingProjectTree(validator).getBrunches(); if (!projectTree.isEmpty()) { IProject rootProject = projectTree.keySet().iterator().next(); rootProjects.put(validator, rootProject); } } } return true; }
@Test public void testExternalModification() throws Exception { openPomFile(TEST_POM_POM_XML); // externally replace file contents IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFile(new Path(TEST_POM_POM_XML)); File f = new File(file.getLocation().toOSString()); String text = getEditorText(); assertFalse(text.contains("PASSED")); text = text.replace("Test-Name", "PASSED"); assertTrue(text.contains("PASSED")); setContents(f, text); // reload the file selectProject(PROJECT_NAME).expandNode(PROJECT_NAME).getNode("pom.xml").doubleClick(); bot.shell("File Changed").activate(); bot.button("Yes").click(); bot.sectionWithName("projectSection").expand(); assertTextValue("projectName", "PASSED"); // verify that value changed in xml and in the form selectEditorTab(TAB_POM_XML); String editorText = getEditorText(); assertTrue(editorText, editorText.contains("<name>PASSED</name>")); // XXX verify that value changed on a page haven't been active before }
@Override public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { if (IFile.class.equals(adapter)) { final IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IWorkspaceRoot workspaceRoot = workspace.getRoot(); final IFile file = workspaceRoot.getFile(new Path(reachable.getPath())); return file; } return null; }
public void validate(IValidationContext helper, IReporter reporter) throws ValidationException { /* Added by BC ---- */ // if(true) return; /* end Added by BC ---- */ String[] uris = helper.getURIs(); if (uris.length > 0) { IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); IFile currentFile = null; for (int i = 0; i < uris.length && !reporter.isCancelled(); i++) { currentFile = wsRoot.getFile(new Path(uris[i])); reporter.removeAllMessages(this, currentFile); if (currentFile != null && currentFile.exists()) { if (shouldValidate(currentFile)) { // && fragmentCheck(currentFile)) { int percent = (i * 100) / uris.length + 1; IMessage message = new LocalizedMessage( IMessage.LOW_SEVERITY, percent + "% " + uris[i]); // $NON-NLS-1$ reporter.displaySubtask(this, message); validateFile(currentFile, reporter); } if (DEBUG) { System.out.println("validating: [" + uris[i] + "]"); // $NON-NLS-1$ //$NON-NLS-2$ } } } } else { // if uris[] length 0 -> validate() gets called for each project if (helper instanceof IWorkbenchContext) { IProject project = ((IWorkbenchContext) helper).getProject(); JSFileVisitor visitor = new JSFileVisitor(reporter); try { // collect all jsp files for the project project.accept(visitor, IResource.DEPTH_INFINITE); } catch (CoreException e) { if (DEBUG) { e.printStackTrace(); } } IFile[] files = visitor.getFiles(); for (int i = 0; i < files.length && !reporter.isCancelled(); i++) { int percent = (i * 100) / files.length + 1; IMessage message = new LocalizedMessage( IMessage.LOW_SEVERITY, percent + "% " + files[i].getFullPath().toString()); // $NON-NLS-1$ reporter.displaySubtask(this, message); validateFile(files[i], reporter); if (DEBUG) { System.out.println("validating: [" + files[i] + "]"); // $NON-NLS-1$ //$NON-NLS-2$ } } } } }
protected IEditorPart openBeanEditor(String fileName) throws Exception { copyProjectCreateDocument(fileName); String baseLocation = model.getBaseLocation(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath filePath = new Path(baseLocation); IFile beanFile = root.getFile(filePath); return IDE.openEditor( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), beanFile); }
/** * Recreates the data file from the given input path. In case the given path reflects a temporary * diagram file, it's path is used to recreate the data file, otherwise the given path is simply * made absolute and returned. * * @param inputPath the path to recreate the data file from * @return a file object representing the data file */ public static IFile recreateDataFile(final IPath inputPath) { final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final IProject project = root.getFile(inputPath).getProject(); final int matchingSegments = project.getFullPath().matchingFirstSegments(inputPath); final int totalSegments = inputPath.segmentCount(); final String extension = inputPath.getFileExtension(); IFile result = null; if (totalSegments > matchingSegments) { // it shall be more than just the project IPath resultPath = null; if (ToscaUI.TOSCA_DIAGRAM_FILE_EXTENSION.equals(extension)) { // we got a temporary file here, so rebuild the file of the model from its path String originalExtension = inputPath.segment(matchingSegments); if (originalExtension.startsWith(".")) { // $NON-NLS-1$ originalExtension = originalExtension.substring(1); } final String[] segments = inputPath.segments(); IPath originalPath = project.getFullPath(); for (int index = matchingSegments + 1; index < segments.length; ++index) { originalPath = originalPath.append(segments[index]); } resultPath = originalPath.removeFileExtension().addFileExtension(originalExtension); } else { resultPath = inputPath.makeAbsolute(); } result = root.getFile(resultPath); } return result; }
private IResource createSourceResource(IResourceDelta delta) { IPath sourcePath = delta.getMovedFromPath(); IResource resource = delta.getResource(); IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); switch (resource.getType()) { case IResource.PROJECT: return wsRoot.getProject(sourcePath.segment(0)); case IResource.FOLDER: return wsRoot.getFolder(sourcePath); case IResource.FILE: return wsRoot.getFile(sourcePath); } return null; }
@Before public void setup() { root = ResourcesPlugin.getWorkspace().getRoot(); fileHasParentFolder = root.getFile(new Path("/project/folder/file.txt")); duration = new Duration(100); date = new LocalDate().minusDays(1); ws = new WorkspaceStorage(new Path(".a"), new Path("/a")); data = mock(IFileData.class); given(data.get(IFileData.DATE)).willReturn(date); given(data.get(IFileData.DURATION)).willReturn(duration); given(data.get(IFileData.FILE)).willReturn(fileHasParentFolder); given(data.get(IFileData.WORKSPACE)).willReturn(ws); }
@Override protected void generateGenFile( IWorkflowContext context, EcoreGenerator ecoreGenerator, URI genmodelURI) { // IProject project = (IProject) context.get(PROJECT); // IFile genmodelFile = project.getRoot().getFile(genmodelFileString); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile genmodelFile = root.getFile(new Path(genmodelURI.toPlatformString(true))); MarkerErrorHandler errorHandler = new MarkerErrorHandler(genmodelFile); deleteMarkers(genmodelFile); ecoreGenerator.addErrorHandler(errorHandler); super.generateGenFile(context, ecoreGenerator, genmodelURI); ecoreGenerator.removeErrorHandler(errorHandler); }
/* * (non-Javadoc) Method declared on IElementFactory. */ public IAdaptable createElement(IMemento memento) { // Get the file name. String fileName = memento.getString(TAG_PATH); if (fileName == null) { return null; } // Get a handle to the IFile...which can be a handle // to a resource that does not exist in workspace IWorkspaceRoot root = RemoteResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFile(new Path(fileName)); if (file != null) { return new FileEditorInput(file); } else { return null; } }
public static IPath getAbsolutLibraryPath(final IPath libPath, final IWARProduct product) { IPath result = null; boolean fromTarget = product.isLibraryFromTarget(libPath); if (fromTarget) { String absoluteBridgePath = getServletBridgeAbsolutePath(); if (absoluteBridgePath != null) { if (absoluteBridgePath.indexOf(libPath.toPortableString()) != -1) { result = new Path(absoluteBridgePath); } } } else { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile lib = root.getFile(libPath); result = lib.getLocation(); } return result; }
public IResource[] getResourcesToDelete() { List<IResource> resources = new ArrayList<IResource>(dependencyMap.size()); IPath projectPath = project.getLocation(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (ProjectDependency pd : dependencyMap.keySet()) { if (pd.getDependencyKind() == DependencyKind.Archive) { IPath p = pd.getPath(); if (projectPath.isPrefixOf(p)) { p = p.removeFirstSegments(projectPath.segmentCount() - 1); } IFile f = root.getFile(p); if (f.exists() && project.equals(f.getProject())) { resources.add(f); } } } return resources.toArray(new IResource[0]); }
private String saveICMAssembly(AssemblyInstance assembly) { // configure this RF with the configuration file try { URL url = FileLocator.find(Platform.getBundle("SEI.ArchE.Performance"), new Path("/temp"), null); String tempPathName = FileLocator.resolve(url).getPath(); ResourceSet resourceSet = new ResourceSetImpl(); IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IPath path = new Path(tempPathName + assembly.getName() + ".icm"); IFile xmlFile = workspaceRoot.getFile(path); // Get the URI of the model file URI fileURI = URI.createFileURI(path.toString()); // Create a resource for this file. Resource resource = resourceSet.createResource(fileURI); // Add the assembly to the resource contents resource.getContents().add(assembly); // Save the contents of the resource to the file system. String xmlAssemblyFile = null; try { resource.save(Collections.EMPTY_MAP); } catch (IOException e) { } xmlAssemblyFile = fileURI.toFileString(); return (path.toPortableString()); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return null; // for error }
@Override public InputStream loadFile(Resource resource, String filename) { if (resource == null) return null; URI uri = resource.getURI(); if (uri.isPlatformResource()) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile modelFile = root.getFile(new Path(uri.toPlatformString(false))); IContainer modelParent = modelFile.getParent(); if (modelParent instanceof IFolder) { IFolder modelDir = (IFolder) modelParent; IFile file = modelDir.getFile(filename); try { return file.getContents(); } catch (CoreException e) { LOGGER.warn("Can't handle file '" + filename + "': " + e.getMessage()); } } } LOGGER.warn("Can't find file '" + filename + "' in project"); return null; }
@SuppressWarnings("unchecked") public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType.isAssignableFrom(IHistoryPageSource.class)) { return historyPageSource; } if (IWorkbenchAdapter.class == adapterType) { if (adaptableObject instanceof RepositoryNode) return getRepsitoryNodeWorkbenchAdapter((RepositoryNode) adaptableObject); if (gitModelWorkbenchAdapter == null) gitModelWorkbenchAdapter = new GitModelWorkbenchAdapter(); return gitModelWorkbenchAdapter; } if (adaptableObject instanceof GitModelObject && adapterType == ResourceMapping.class) return GitObjectMapping.create((GitModelObject) adaptableObject); if (adaptableObject instanceof GitModelObject && adapterType == IResource.class) { GitModelObject obj = (GitModelObject) adaptableObject; if (obj instanceof GitModelBlob) { IResource res = root.getFileForLocation(obj.getLocation()); if (res == null) res = root.getFile(obj.getLocation()); return res; } if (obj instanceof GitModelTree) { IResource res = root.getContainerForLocation(obj.getLocation()); if (res == null) res = root.getFolder(obj.getLocation()); return res; } } return null; }
private ISourceContainer getArchiveSourceContainer(String location) throws JavaModelException { IWorkspaceRoot root = PDELaunchingPlugin.getWorkspace().getRoot(); IFile[] containers = root.findFilesForLocationURI(URIUtil.toURI(location)); for (int i = 0; i < containers.length; i++) { IJavaElement element = JavaCore.create(containers[i]); if (element instanceof IPackageFragmentRoot) { IPackageFragmentRoot archive = (IPackageFragmentRoot) element; IPath path = archive.getSourceAttachmentPath(); if (path == null || path.segmentCount() == 0) continue; IPath rootPath = archive.getSourceAttachmentRootPath(); boolean detectRootPath = rootPath != null && rootPath.segmentCount() > 0; IFile archiveFile = root.getFile(path); if (archiveFile.exists()) return new ArchiveSourceContainer(archiveFile, detectRootPath); File file = path.toFile(); if (file.exists()) return new ExternalArchiveSourceContainer(file.getAbsolutePath(), detectRootPath); } } return null; }
/** @generated */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell = getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog = new SaveAsDialog(shell); IFile original = input instanceof IFileEditorInput ? ((IFileEditorInput) input).getFile() : null; if (original != null) { dialog.setOriginalFile(original); } dialog.create(); IDocumentProvider provider = getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message = NLS.bind(Messages.SqlmodelDiagramEditor_SavingDeletedFile, original.getName()); dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Window.CANCEL) { if (progressMonitor != null) { progressMonitor.setCanceled(true); } return; } IPath filePath = dialog.getResult(); if (filePath == null) { if (progressMonitor != null) { progressMonitor.setCanceled(true); } return; } IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IFile file = workspaceRoot.getFile(filePath); final IEditorInput newInput = new FileEditorInput(file); // Check if the editor is already open IEditorMatchingStrategy matchingStrategy = getEditorDescriptor().getEditorMatchingStrategy(); IEditorReference[] editorRefs = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences(); for (int i = 0; i < editorRefs.length; i++) { if (matchingStrategy.matches(editorRefs[i], newInput)) { MessageDialog.openWarning( shell, Messages.SqlmodelDiagramEditor_SaveAsErrorTitle, Messages.SqlmodelDiagramEditor_SaveAsErrorMessage); return; } } boolean success = false; try { provider.aboutToChange(newInput); getDocumentProvider(newInput) .saveDocument( progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); success = true; } catch (CoreException x) { IStatus status = x.getStatus(); if (status == null || status.getSeverity() != IStatus.CANCEL) { ErrorDialog.openError( shell, Messages.SqlmodelDiagramEditor_SaveErrorTitle, Messages.SqlmodelDiagramEditor_SaveErrorMessage, x.getStatus()); } } finally { provider.changed(newInput); if (success) { setInput(newInput); } } if (progressMonitor != null) { progressMonitor.setCanceled(!success); } }
/** @param path absolute path to non-workspace file */ public LocalNonWorkspaceTypedElement(IPath path) { super(ROOT.getFile(path)); this.path = path; exists = path.toFile().exists(); }
private File getFile(URI uri) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile f = root.getFile(new Path(uri.toPlatformString(true))); return f.getLocation().toFile(); }
protected IFile getFile(String fileName, String slot) { String outletPath = getPathes().get(slot); return root.getFile(new Path(outletPath + "/" + fileName)); }