/** * Tries and find an Acceleo compiled module (emtl file) corresponding to the given module (mtl * file), then loads it as an EMF resource. * * @param moduleFile The module file of which we seek the compiled version. * @param resourceSet The resource set in which to load the module. * @return The Acceleo compiled module (emtl file) corresponding to the given module (mtl file). * <code>null</code> if none. */ private static Resource getModule(IFile moduleFile, ResourceSet resourceSet) { IFile compiledModule = null; if (IAcceleoConstants.MTL_FILE_EXTENSION.equals(moduleFile.getFileExtension())) { final IProject project = moduleFile.getProject(); if (project != null) { final String compiledName = moduleFile .getFullPath() .removeFileExtension() .addFileExtension(IAcceleoConstants.EMTL_FILE_EXTENSION) .lastSegment(); compiledModule = findChild(project, compiledName); } } Resource module = null; if (compiledModule != null) { String path = compiledModule.getFullPath().toString(); for (Resource resource : resourceSet.getResources()) { if (resource.getURI().toString().equals(path)) { return resource; } } try { module = ModelUtils.load(URI.createPlatformResourceURI(path, true), resourceSet).eResource(); } catch (IOException e) { // FIXME log } } return module; }
private static void deleteMarkersWithCompiledFile(final IProject project, final IFile file) { if (!project.isAccessible()) { return; } try { for (final IMarker m : project.findMarkers(PROBLEM_MARKER, true, IResource.DEPTH_INFINITE)) { final Object source_id = m.getAttribute(IMarker.SOURCE_ID); if (source_id != null && source_id instanceof String && source_id.equals(file.getFullPath().toString())) { try { m.delete(); } catch (final CoreException e) { // not much to do } } } for (final IMarker m : project.findMarkers(TASK_MARKER, true, IResource.DEPTH_INFINITE)) { final Object source_id = m.getAttribute(IMarker.SOURCE_ID); if (source_id != null && source_id instanceof String && source_id.equals(file.getFullPath().toString())) { try { m.delete(); } catch (final CoreException e) { // not much to do } } } } catch (final CoreException e) { // not much to do } }
/** * {@inheritDoc} * * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, * org.eclipse.jface.viewers.IStructuredSelection) */ public void init(IWorkbench iWorkbench, IStructuredSelection iSelection) { this.workbench = iWorkbench; this.selection = iSelection; // load the ecore models from the workspace to ensure that all models are available in the // wizard IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject iProject : projects) { try { if (iProject.isAccessible()) { List<IFile> members = this.members(iProject, IAcceleoConstants.ECORE_FILE_EXTENSION); for (IFile iFile : members) { Map<String, String> dynamicEcorePackagePaths = AcceleoPackageRegistry.INSTANCE.getDynamicEcorePackagePaths(); Collection<String> values = dynamicEcorePackagePaths.values(); boolean contains = values.contains(iFile.getFullPath().toString()); if (!contains) { AcceleoPackageRegistry.INSTANCE.registerEcorePackages( iFile.getFullPath().toString(), AcceleoDynamicMetamodelResourceSetImpl.DYNAMIC_METAMODEL_RESOURCE_SET); } } } } catch (CoreException e) { AcceleoUIActivator.log(e, false); } } }
@Override protected List<? extends ICompletionProposal> computeProposals( final ITextViewer viewer, final int offset) { final IDocument document = viewer.getDocument(); try { final String lineContent = DocumentUtilities.lineContentBeforeCurrentPosition(document, offset); final boolean shouldShowProposal = shouldShowProposals(lineContent, document, offset); if (shouldShowProposal) { final boolean isTsv = assist.isTsvFile(); final Optional<IRegion> region = DocumentUtilities.findLiveCellRegion(document, isTsv, offset); final String prefix = DocumentUtilities.getPrefix(document, region, offset); final String content = region.isPresent() ? document.get(region.get().getOffset(), region.get().getLength()) : ""; final Image image = ImagesManager.getImage(RedImages.getImageForFileWithExtension(".robot")); final List<RedCompletionProposal> proposals = newArrayList(); for (final IFile resourceFile : assist.getResourceFiles()) { final String resourcePath = resourceFile.getFullPath().makeRelative().toString(); if (resourcePath.toLowerCase().startsWith(prefix.toLowerCase())) { final String resourceRelativePath = createCurrentFileRelativePath(resourceFile.getFullPath().makeRelative()); final RedCompletionProposal proposal = RedCompletionBuilder.newProposal() .will(assist.getAcceptanceMode()) .theText(resourceRelativePath) .atOffset(offset - prefix.length()) .givenThatCurrentPrefixIs(prefix) .andWholeContentIs(content) .thenCursorWillStopAtTheEndOfInsertion() .displayedLabelShouldBe(resourcePath) .currentPrefixShouldBeDecorated() .proposalsShouldHaveIcon(image) .create(); proposals.add(proposal); } } return proposals; } return null; } catch (final BadLocationException e) { return null; } }
public void testSingleNonUIThreadUpdatesToEditorDocument() throws Exception { IFile file = getOrCreateFile(PROJECT_NAME + "/" + "testBackgroundChanges.xml"); ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager(); textFileBufferManager.connect( file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor()); ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); final IDocument document = textFileBuffer.getDocument(); document.replace(0, 0, "<?xml encoding=\"UTF-8\" version=\"1.0\"?>\n"); textFileBuffer.commit(new NullProgressMonitor(), true); String testText = document.get() + "<c/><b/><a/>"; final int end = document.getLength(); IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IEditorPart openedEditor = IDE.openEditor(activePage, file); final boolean state[] = new boolean[] {false}; Job changer = new Job("text changer") { protected IStatus run(IProgressMonitor monitor) { try { document.replace(end, 0, "<a/>"); document.replace(end, 0, "<b/>"); document.replace(end, 0, "<c/>"); } catch (Exception e) { return new Status(IStatus.ERROR, SSEUIPlugin.ID, e.getMessage()); } finally { state[0] = true; } return Status.OK_STATUS; } }; changer.setUser(true); changer.setSystem(false); changer.schedule(); while (!state[0]) { openedEditor.getSite().getShell().getDisplay().readAndDispatch(); } String finalText = document.get(); textFileBuffer.commit(new NullProgressMonitor(), true); textFileBufferManager.disconnect( file.getFullPath(), LocationKind.IFILE, new NullProgressMonitor()); activePage.closeEditor(openedEditor, false); assertEquals("Non-UI changes did not apply", testText, finalText); }
@Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (!(obj instanceof BPELModuleDelegate)) return false; BPELModuleDelegate bmd = (BPELModuleDelegate) obj; if (this.getProject() != null && this.getProject().exists() && !this.getProject().equals(bmd.getProject())) { return false; } if (file != null && file.exists() && !(file.getFullPath().equals(bmd.getFile().getFullPath()))) { return false; } if (getId() != null && !getId().equals(bmd.getId())) return false; return true; }
private void checkDirtyFile(RefactoringStatus result, IFile file) { if (!file.exists()) return; ITextFileBuffer buffer = FileBuffers.getTextFileBufferManager() .getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); if (buffer != null && buffer.isDirty()) { String message = RefactoringCoreMessages.DeleteResourcesProcessor_warning_unsaved_file; if (buffer.isStateValidated() && buffer.isSynchronized()) { result.addWarning( Messages.format(message, BasicElementLabels.getPathLabel(file.getFullPath(), false))); } else { result.addFatalError( Messages.format(message, BasicElementLabels.getPathLabel(file.getFullPath(), false))); } } }
/** @generated */ public boolean performFinish() { LinkedList<IFile> affectedFiles = new LinkedList<IFile>(); IFile diagramFile = myFileCreationPage.createNewFile(); de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorUtil.setCharset( diagramFile); affectedFiles.add(diagramFile); URI diagramModelURI = URI.createPlatformResourceURI(diagramFile.getFullPath().toString(), true); ResourceSet resourceSet = myEditingDomain.getResourceSet(); final Resource diagramResource = resourceSet.createResource(diagramModelURI); AbstractTransactionalCommand command = new AbstractTransactionalCommand( myEditingDomain, de.tud.cs.st.vespucci.vespucci_model.diagram.part.Messages .VespucciNewDiagramFileWizard_InitDiagramCommand, affectedFiles) { protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { int diagramVID = de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciVisualIDRegistry .getDiagramVisualID(diagramRootElementSelectionPage.getModelElement()); if (diagramVID != de.tud.cs.st.vespucci.vespucci_model.diagram.edit.parts.ShapesDiagramEditPart .VISUAL_ID) { return CommandResult.newErrorCommandResult( de.tud.cs.st.vespucci.vespucci_model.diagram.part.Messages .VespucciNewDiagramFileWizard_IncorrectRootError); } Diagram diagram = ViewService.createDiagram( diagramRootElementSelectionPage.getModelElement(), de.tud.cs.st.vespucci.vespucci_model.diagram.edit.parts.ShapesDiagramEditPart .MODEL_ID, de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin .DIAGRAM_PREFERENCES_HINT); diagramResource.getContents().add(diagram); diagramResource.getContents().add(diagram.getElement()); return CommandResult.newOKCommandResult(); } }; try { OperationHistoryFactory.getOperationHistory() .execute(command, new NullProgressMonitor(), null); diagramResource.save( de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorUtil .getSaveOptions()); de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorUtil.openDiagram( diagramResource); } catch (ExecutionException e) { de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin.getInstance() .logError("Unable to create model and diagram", e); // $NON-NLS-1$ } catch (IOException ex) { de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin.getInstance() .logError("Save operation failed for: " + diagramModelURI, ex); // $NON-NLS-1$ } catch (PartInitException ex) { de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin.getInstance() .logError("Unable to open editor", ex); // $NON-NLS-1$ } return true; }
public void runTestsObject(Object element) { IResource[] members; try { if (element instanceof IProject) { // if it is a project go deeper if (((IProject) element).isOpen()) { // and it is open log.debug("Calling recursive method for" + ((IProject) element).getFullPath()); members = ((IProject) element).members(); for (int index = 0; index < members.length; index++) this.runTestsObject(members[index]); } } else if (element instanceof IFolder) { // if it is a folder go deeper members = ((IFolder) element).members(); log.debug("Calling recursive method for" + ((IFolder) element).getLocation().toOSString()); for (int index = 0; index < members.length; index++) this.runTestsObject(members[index]); } else if (element instanceof IFile) { // if it is a file IFile ifile = (IFile) element; if (ifile.getFileExtension().equals("rsl")) { log.debug("Calling runTestCasesActiveFile on " + ifile.getFullPath()); RunTestCasesActiveFile.runandprint(ifile); } } else // only projects, folders and rsl files are of interest return; } catch (CoreException e) { log.error(e.getMessage(), e); } }
public IStatus buildLanguage( IProject project, IFile langFile, Map<String, String> overrideProperties, IProgressMonitor monitor) { SDKHelper antHelper = new SDKHelper(this, monitor); try { Map<String, String> properties = new HashMap<String, String>(); if (overrideProperties != null) { properties.putAll(overrideProperties); } String langDirLocation = langFile.getParent().getRawLocation().toOSString(); String langFileName = langFile.getFullPath().removeFileExtension().lastSegment(); properties.put(ISDKConstants.PROPERTY_LANG_DIR, langDirLocation); properties.put(ISDKConstants.PROPERTY_LANG_FILE, langFileName); final IPath buildFile = project.getFile(ISDKConstants.PROJECT_BUILD_XML).getRawLocation(); final String workingDir = getDefaultWorkingDir(buildFile); antHelper.runTarget( buildFile, ISDKConstants.TARGET_BUILD_LANG_CMD, properties, true, workingDir); } catch (Exception e) { return SDKCorePlugin.createErrorStatus(e); } return Status.OK_STATUS; }
public void selectionChanged(IAction action, ISelection selection) { selectedURI = null; selectedFile = null; action.setEnabled(false); if (selection instanceof IStructuredSelection == false || selection.isEmpty()) { return; } try { Object o = ((IStructuredSelection) selection).getFirstElement(); if (o instanceof IFile) { selectedFile = (IFile) ((IStructuredSelection) selection).getFirstElement(); selectedURI = URI.createPlatformResourceURI(selectedFile.getFullPath().toString(), true); } else if (o instanceof EditPart) { EObject e = (EObject) ((EditPart) o).getModel(); if (e.eResource() == null) return; selectedURI = e.eResource().getURI(); selectedFile = ResourceHelper.uriToFile(selectedURI); } else { return; } action.setEnabled(true); } catch (ClassCastException e) { // just catch, do nothing } catch (NullPointerException e) { // just catch, do nothing } }
private ISeamProperty findSeamProperty(IFile file, int start, int end) { if (file == null) return null; IProject project = file.getProject(); if (project == null) return null; ISeamProject seamProject = SeamCorePlugin.getSeamProject(project, true); if (seamProject == null) return null; Set<ISeamComponent> components = seamProject.getComponentsByPath(file.getFullPath()); for (ISeamComponent component : components) { Set<ISeamXmlComponentDeclaration> declarations = component.getXmlDeclarations(); for (ISeamXmlComponentDeclaration declaration : declarations) { Collection<ISeamProperty> properties = declaration.getProperties(); for (ISeamProperty property : properties) { ITextSourceReference location = property.getLocationFor(ISeamXmlComponentDeclaration.NAME); if (location.getStartPosition() <= start && (location.getStartPosition() + location.getLength()) >= end) return property; } } } return null; }
private URI createDiagramFileUri(String diagramName) { URI uri = null; IFolder folder = getProject().getFolder(DIAGRAMS_FOLDER); IFile file = folder.getFile(diagramName); uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true); return uri; }
@Override public StyledString getStyledText(Object element) { if (element instanceof CeylonOutlineNode) { return getStyledLabelFor((Node) ((CeylonOutlineNode) element).getTreeNode()); } else if (element instanceof IFile) { return new StyledString(getLabelForFile((IFile) element)); } else if (element instanceof IProject) { return new StyledString(((IProject) element).getName()); } else if (element instanceof CeylonElement) { CeylonElement ce = (CeylonElement) element; String pkg; if (includePackage()) { pkg = " - " + getPackageLabel(ce.getNode()); } else { pkg = ""; } IFile file = ce.getFile(); String path = file == null ? ce.getVirtualFile().getPath() : file.getFullPath().toString(); return getStyledLabelFor(ce.getNode()) .append(pkg, QUALIFIER_STYLER) .append(" - " + path, COUNTER_STYLER) .append(":" + ce.getLocation(), COUNTER_STYLER); } else if (element instanceof Package) { return new StyledString(getLabel((Package) element), QUALIFIER_STYLER); } else if (element instanceof Module) { return new StyledString(getLabel((Module) element)); } else if (element instanceof Unit) { return new StyledString(((Unit) element).getFilename()); } else { return getStyledLabelFor((Node) element); } }
@Test public void testBuild() throws Exception { IFile sourceFile = testHelper.createFile("test/Test", "package test\nclass Test {}"); assertTrue(sourceFile.exists()); waitForBuild(); IFile targetFile = testHelper.getProject().getFile("/xtend-gen/test/Test.java"); assertTrue(targetFile.exists()); assertFalse(fileIsEmpty(targetFile)); IFile traceFile = testHelper.getProject().getFile("/xtend-gen/test/.Test.java._trace"); assertTrue(traceFile.exists()); assertFalse(fileIsEmpty(traceFile)); IFile classFile = testHelper.getProject().getFile("/bin/test/Test.class"); assertTrue(classFile.exists()); assertFalse(fileIsEmpty(classFile)); List<IPath> traceFiles = traceMarkers.findTraceFiles(sourceFile); assertTrue(traceFiles.contains(traceFile.getFullPath())); sourceFile.delete(true, null); waitForBuild(); cleanBuild(); assertTrue(targetFile.getParent().exists()); assertFalse(targetFile.exists()); assertFalse(traceFile.exists()); assertFalse(classFile.exists()); }
private DiagramRoot getElement(TransactionalEditingDomain editingDomain) { String wrProjectPath = diagramRoot.getProjectPath(); String projectName = wrProjectPath.substring(wrProjectPath.lastIndexOf("/") + 1); String fileName = variativitySelectionPage.getText() + "." + projectName + ProjectPlweb.PLWEB_EXTENSION; IPath filePath = new Path(PathHelper.getProjectFile(projectName, fileName)); IFile fileHandle = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath); URI uri = URI.createPlatformResourceURI(fileHandle.getFullPath().toString(), true); ResourceSet resourceSet = editingDomain.getResourceSet(); EObject element = null; try { Resource resource = resourceSet.getResource(uri, true); element = (EObject) resource.getContents().get(0); } catch (WrappedException ex) { PlwebDiagramEditorPlugin.getInstance() .logError("Unable to load resource: " + uri, ex); // $NON-NLS-1$ } if (element == null || !(element instanceof DiagramRoot)) { MessageDialog.openError( getShell(), Messages.AddProduct_ResourceErrorDialogTitle, Messages.AddProduct_ResourceErrorDialogMessage); return null; } DiagramRoot diagramRoot = (DiagramRoot) element; return diagramRoot; }
/** * Return the IResource instance that matches the specified path. The path is the relative path in * the workspace. If no IResource instance is found that match this path a null is returned. * * @param name the path to the IResource * @return the IResource */ public static IResource findIResourceByPath(final IPath workspacePath) { if (workspacePath == null || workspacePath.isEmpty() || getWorkspace() == null) return null; // Collect all IResources within all IProjects final FileResourceCollectorVisitor visitor = new FileResourceCollectorVisitor(); if (getWorkspace() != null && getWorkspace().getRoot() != null) { final IProject[] projects = getWorkspace().getRoot().getProjects(); for (final IProject project : projects) try { project.accept(visitor); } catch (final CoreException e) { // do nothing } } final IFile[] fileResources = visitor.getFileResources(); for (final IFile fileResource : fileResources) if (fileResource != null) { final IPath path = fileResource.getFullPath(); // Do not process file names staring with '.' since these // are considered reserved for Eclipse specific files if (path.lastSegment().charAt(0) == '.') continue; if (path.equals(workspacePath)) return fileResource; } return null; }
/** https://bugs.eclipse.org/bugs/show_bug.cgi?id=400193 */ @Test public void testSourceRelativeOutput() throws Exception { IProject project = testHelper.getProject(); String srcFolder = "/foo/bar/bug"; JavaProjectSetupUtil.addSourceFolder(JavaCore.create(project), srcFolder); String path = srcFolder + "/Foo.xtend"; String fullFileName = project.getName() + path; IFile sourceFile = testHelper.createFileImpl(fullFileName, "class Foo {}"); assertTrue(sourceFile.exists()); waitForBuild(); IFile generatedFile = project.getFile("foo/bar/xtend-gen/Foo.java"); assertTrue(generatedFile.exists()); IFile traceFile = testHelper.getProject().getFile("foo/bar/xtend-gen/.Foo.java._trace"); assertTrue(traceFile.exists()); IFile classFile = testHelper.getProject().getFile("/bin/Foo.class"); assertTrue(classFile.exists()); List<IPath> traceFiles = traceMarkers.findTraceFiles(sourceFile); assertTrue(traceFiles.contains(traceFile.getFullPath())); sourceFile.delete(false, new NullProgressMonitor()); waitForBuild(); assertFalse(generatedFile.exists()); assertFalse(traceFile.exists()); }
@Override public @NonNull String getInitialContentsAsString( @NonNull IFile newFile, @NonNull AbstractFileDialog dialog) { URI ecoreURI = URI.createPlatformResourceURI(newFile.getFullPath().toString(), true); URI oclInEcoreURI = ecoreURI.trimFileExtension().appendFileExtension("oclinecore"); String initialContentsAsString = super.getInitialContentsAsString(newFile, dialog); @SuppressWarnings("null") OCL ocl = OCL.newInstance(EPackage.Registry.INSTANCE); ResourceSet resourceSet2 = ocl.getResourceSet(); BaseCSResource csResource = ClassUtil.nonNullState((BaseCSResource) resourceSet2.createResource(oclInEcoreURI)); try { ByteArrayInputStream inputStream = new ByteArrayInputStream(initialContentsAsString.getBytes()); csResource.load(inputStream, null); ASResource asResource = ocl.cs2as(csResource); Resource eResource = ocl.as2ecore(asResource, ecoreURI); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); eResource.save(outputStream, null); @SuppressWarnings("null") @NonNull String string = outputStream.toString(); return string; } catch (IOException e) { logger.error("Failed to create " + ecoreURI, e); } return initialContentsAsString; }
protected void handleApplicationBrowseButton() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); AppSelectionDialog dialog = new AppSelectionDialog(getShell(), workspace.getRoot(), new HtmlWebResourceFilter()); dialog.setTitle("Select a HTML page to launch"); dialog.setInitialPattern(".", FilteredItemsSelectionDialog.FULL_SELECTION); // $NON-NLS-1$ IPath path = new Path(htmlText.getText()); if (workspace.validatePath(path.toString(), IResource.FILE).isOK()) { IFile file = workspace.getRoot().getFile(path); if (file != null && file.exists()) { dialog.setInitialSelections(new Object[] {path}); } } dialog.open(); Object[] results = dialog.getResult(); if ((results != null) && (results.length > 0) && (results[0] instanceof IFile)) { IFile file = (IFile) results[0]; String pathStr = file.getFullPath().toPortableString(); htmlText.setText(pathStr); } }
private void writeDotFile(DNodeBP bp, IFile inputFile, String suffix) { String targetPathStr = inputFile.getFullPath().removeFileExtension().toString(); IPath targetPath = new Path(targetPathStr + suffix + ".dot"); ActionHelper.writeFile(targetPath, bp.toDot()); }
@Override public void doSaveAs() { SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell()); saveAsDialog.create(); saveAsDialog.setMessage(EcoreEditorPlugin.INSTANCE.getString("_UI_SaveAs_message")); saveAsDialog.open(); IPath path = saveAsDialog.getResult(); if (path != null) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); if (file != null) { ResourceSet resourceSet = editingDomain.getResourceSet(); Resource currentResource = resourceSet.getResources().get(0); URI newURI = URI.createPlatformResourceURI(file.getFullPath().toString(), true); Resource newResource = resourceSet.createResource(newURI); newResource.getContents().addAll(EcoreUtil.copyAll(currentResource.getContents())); resourceSet.getResources().remove(0); resourceSet.getResources().move(0, newResource); IFileEditorInput modelFile = new FileEditorInput(file); setInputWithNotify(modelFile); setPartName(file.getName()); doSave(getActionBars().getStatusLineManager().getProgressMonitor()); } } }
/** * Creates a compilation unit. * * @exception ModelException if unable to create the compilation unit. */ protected void executeOperation() throws ModelException { try { // beginTask(Messages.operation_createUnitProgress, 2); ModelElementDelta delta = newModelElementDelta(); ISourceModule unit = getSourceModule(); IScriptFolder pkg = (IScriptFolder) getParentElement(); IContainer folder = (IContainer) pkg.getResource(); worked(1); IFile compilationUnitFile = folder.getFile(new Path(fName)); if (compilationUnitFile.exists()) { // update the contents of the existing unit if fForce is true if (force) { IBuffer buffer = unit.getBuffer(); if (buffer == null) return; buffer.setContents(fSource); unit.save(new NullProgressMonitor(), false); resultElements = new IModelElement[] {unit}; if (!Util.isExcluded(unit) && unit.getParent().exists()) { for (int i = 0; i < resultElements.length; i++) { delta.changed(resultElements[i], IModelElementDelta.F_CONTENT); } addDelta(delta); } } else { throw new ModelException( new ModelStatus( IModelStatusConstants.NAME_COLLISION, Messages.bind( Messages.status_nameCollision, compilationUnitFile.getFullPath().toString()))); } } else { try { String encoding = null; try { encoding = folder.getDefaultCharset(); // get folder encoding as file is not accessible } catch (CoreException ce) { // use no encoding } InputStream stream = new ByteArrayInputStream( encoding == null ? fSource.getBytes() : fSource.getBytes(encoding)); createFile(folder, unit.getElementName(), stream, force); resultElements = new IModelElement[] {unit}; if (!Util.isExcluded(unit) && unit.getParent().exists()) { for (int i = 0; i < resultElements.length; i++) { delta.added(resultElements[i]); } addDelta(delta); } } catch (IOException e) { throw new ModelException(e, IModelStatusConstants.IO_EXCEPTION); } } worked(1); } finally { done(); } }
public boolean checkIfFileInTarget(IFile fileToCheck) { String[] strings = selectedListBox.getItems(); int size = selectedListBox.getItemCount(); for (int i = 0; i < size; i++) { if (strings[i].compareTo(fileToCheck.getFullPath().toString()) == 0) return true; } return false; }
/** @return workspace relative pom.xml path or null if pom.xml does not exist */ public String getPomPath() { IFile file = project.getFile(MavenConstants.POM_FILE_NAME); if (file == null) { return null; } return file.getFullPath().toOSString(); }
public boolean visit(IResource r) throws CoreException { if (r.getType() != IResource.FILE) return true; IFile file = (IFile) r; String ext = file.getFullPath().getFileExtension(); if (ext == null) return false; if (KonohaUtil.search(ext, exts)) list.add(file); return false; }
/** * Trigger addition of a resource to an index Note: the actual operation is performed in * background */ public void addSource(IFile resource, IPath containerPath, SourceElementParser parser) { if (RubyCore.getPlugin() == null) return; SearchParticipant participant = BasicSearchEngine.getDefaultSearchParticipant(); SearchDocument document = participant.getDocument(resource.getFullPath().toString()); ((InternalSearchDocument) document).parser = parser; IPath indexLocation = computeIndexLocation(containerPath); scheduleDocumentIndexing(document, containerPath, indexLocation, participant); }
/** * Moves a file to the output directory with a new name. * * @param project the current project * @param sourceFile output file to be moved * @param destDir the destination directory of the file * @param destName the new name of the file * @param monitor progress monitor * @throws CoreException if an error occurs * @return file in the new location */ private static IFile moveFile( IProject project, IFile sourceFile, IContainer destContainer, String destName, IProgressMonitor monitor) throws CoreException { if (sourceFile != null && sourceFile.exists() && destName != null) { final IPath destRelPath = new Path(destName); final IFile dest = destContainer.getFile(destRelPath); if (dest.exists()) { File outFile = new File(sourceFile.getLocationURI()); File destFile = new File(dest.getLocationURI()); try { // Try to move the content instead of deleting the old file // and replace it by the new one. This is better for some // viewers like Sumatrapdf FileOutputStream out = new FileOutputStream(destFile); out.getChannel().tryLock(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(outFile)); byte[] buf = new byte[4096]; int l; while ((l = in.read(buf)) != -1) { out.write(buf, 0, l); } in.close(); out.close(); sourceFile.delete(true, monitor); } catch (IOException e) { // try to delete and move the file dest.delete(true, monitor); sourceFile.move(dest.getFullPath(), true, monitor); } } else { // move the file sourceFile.move(dest.getFullPath(), true, monitor); } monitor.worked(1); return dest; } else { return null; } }
public static IPath getRootPath(RobotFrameworkEditor editor) { IEditorInput input = editor.getEditorInput(); IFile file = null; if (input instanceof IFileEditorInput) { file = ((IFileEditorInput) input).getFile(); return file.getFullPath().removeLastSegments(1); } return null; }
/** Reads the given BPEL file. */ public void read(IFile modelFile, ResourceSet resourceSet) { // TODO: These two lines are a workaround for // https://bugs.eclipse.org/bugs/show_bug.cgi?id=72565 EcorePackage instance = EcorePackage.eINSTANCE; instance.eAdapters(); URI uri = URI.createPlatformResourceURI(modelFile.getFullPath().toString()); processResource = resourceSet.getResource(uri, true); read(processResource, modelFile, resourceSet); }