@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 boolean matches(IEditorReference editorRef, IEditorInput input) { // first check that the file being opened is a layout file. if (input instanceof FileEditorInput) { FileEditorInput fileInput = (FileEditorInput) input; // get the IFile object and check it's in one of the layout folders. IFile iFile = fileInput.getFile(); ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(iFile); // if it's a layout, we know check the name of the fileInput against the name of the // file being currently edited by the editor since those are independent of the config. if (resFolder != null && resFolder.getType() == ResourceFolderType.LAYOUT) { try { IEditorInput editorInput = editorRef.getEditorInput(); if (editorInput instanceof FileEditorInput) { FileEditorInput editorFileInput = (FileEditorInput) editorInput; IFile editorIFile = editorFileInput.getFile(); return editorIFile.getProject().equals(iFile.getProject()) && editorIFile.getName().equals(iFile.getName()); } } catch (PartInitException e) { // we do nothing, we'll just return false. } } } return false; }
protected void ensureProjectHasRefactoringEnabled(RefactoringStatus status) throws PreconditionFailure { if (FortranCorePlugin.inTestingMode()) return; HashSet<IFile> filesToBeRemoved = new HashSet<IFile>(); for (IFile f : this.selectedFiles) { if (!PhotranVPG.getInstance().doesProjectHaveRefactoringEnabled(f)) { if (f.getProject() == null) { status.addWarning( Messages.bind( Messages.FortranResourceRefactoring_FileIsNotInAFortranProject, f.getName())); filesToBeRemoved.add(f); } else { status.addWarning( Messages.bind( Messages.FortranResourceRefactoring_AnalysisRefactoringNotEnabled, f.getProject().getName())); filesToBeRemoved.add(f); } } } // Remove files that didn't have Refactoring enabled in their projects this.selectedFiles.removeAll(filesToBeRemoved); }
private Set<Resource> addProjectBuildBundles(Resolver resolver) { if (!Project.BNDFILE.equals(runFile.getName())) return Collections.emptySet(); Set<Resource> result = new HashSet<Resource>(); try { Project model = Workspace.getProject(runFile.getProject().getLocation().toFile()); for (Builder builder : model.getSubBuilders()) { File file = new File(model.getTarget(), builder.getBsn() + ".jar"); if (file.isFile()) { JarInputStream stream = null; try { stream = new JarInputStream(new FileInputStream(file)); Manifest manifest = stream.getManifest(); Resource resource = helper.createResource(manifest.getMainAttributes()); result.add(resource); resolver.add(resource); } catch (IOException e) { Plugin.logError("Error reading project bundle " + file, e); } finally { if (stream != null) stream.close(); } } } } catch (Exception e) { Plugin.logError("Error getting builders for project: " + runFile.getProject(), e); } return result; }
private void processSelection(ExecutionEvent event) { this.desProject = null; ISelection selection = HandlerUtil.getCurrentSelection(event); if (selection instanceof StructuredSelection) { StructuredSelection ss = (StructuredSelection) selection; IProject project = null; List<?> list = ss.toList(); // Check to determine first project for (Object o : list) { if (o instanceof IFile) { IFile file = (IFile) o; if (project == null) { project = file.getProject(); } } } // if we found the project, assign the this.desProject if (project != null) { if (DominoResourcesPlugin.isDominoDesignerProject(project)) { try { this.desProject = DominoResourcesPlugin.getDominoDesignerProject(project); } catch (NsfException e) { SwiperUtil.logError(e.getMessage()); } } } else { // If we can't figure out the project then it is no good return; } // Add files that belong to that project for (Object o : list) { if (o instanceof IFile) { IFile file = (IFile) o; if (file.getProject() == project) { filesTofilter.add(file); } } } } }
/** * Checks if the given <code>file</code> is accessible and its file extension is in the list of * allowed file extensions. */ public final boolean isBeansConfig(IFile file) { if (file.isAccessible() && getAllowedFileExtensions().contains(file.getFileExtension())) { Set<IPath> rootPaths = getRootDirectories(file.getProject()); for (IPath path : rootPaths) { if (path.isPrefixOf(file.getFullPath())) { return locateBeansConfigs(file.getProject(), null).contains(file); } } } return false; }
/** * This method will ensure that the Acceleo project has a dependency with all the project * containing a dynamic metamodels used in the module. * * @param module The Acceleo module * @param inputFile The file in the Acceleo editor */ private void checkDependenciesWithDynamicMetamodels(Module module, IFile inputFile) { List<TypedModel> input = module.getInput(); for (TypedModel typedModel : input) { List<EPackage> takesTypesFrom = typedModel.getTakesTypesFrom(); for (EPackage ePackage : takesTypesFrom) { Map<String, String> dynamicEcorePackagePaths = AcceleoPackageRegistry.INSTANCE.getDynamicEcorePackagePaths(); String packagePath = dynamicEcorePackagePaths.get(ePackage.getNsURI()); if (packagePath == null) { return; } IPath path = new Path(packagePath); IFile metamodelFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path); if (metamodelFile != null && metamodelFile.isAccessible()) { // We have found the "ecore" file for the dynamic metamodel IProject metamodelProject = metamodelFile.getProject(); IProject inputProject = inputFile.getProject(); if (!inputProject.equals(metamodelProject)) { // The dynamic metamodel is not in the project of the generator, let's find if // this dynamic metamodel is in a dependency of the project of the generator. boolean foundProject = false; AcceleoProject acceleoProject = new AcceleoProject(inputProject); List<IProject> recursivelyAccessibleProjects = acceleoProject.getRecursivelyAccessibleProjects(); for (IProject iProject : recursivelyAccessibleProjects) { if (iProject.equals(metamodelProject)) { foundProject = true; } } if (!foundProject) { // The dynamic metamodel is not in a dependency of the current project, log a // warning. try { AcceleoMarkerUtils.createMarkerOnFile( AcceleoMarkerUtils.WARNING_MARKER_ID, inputFile, 0, typedModel.getStartPosition(), typedModel.getEndPosition(), AcceleoUIMessages.getString( "AcceleoCompileOperation.NoDependencyWithDynamicMetamodelProject", //$NON-NLS-1$ metamodelProject.getName(), inputProject.getName())); } catch (CoreException e) { AcceleoUIActivator.log(e, true); } } } } } } }
public String getPropertiesFilePath(IFile sourceXmaFile) { IProject prj = sourceXmaFile.getProject(); IPath p = prj.getLocation(); File f = p.toFile(); String propertiesFile = GenerateJavaFromXMA.getAntPropertiesFilePath(f); if (propertiesFile != null) return propertiesFile; propertiesFile = getResourceFolder(sourceXmaFile.getProject(), GenerateJavaFromXMA.SCRIPT_FOLDER) + GenerateJavaFromXMA.PROPERTIES_FILE; return propertiesFile; }
void checkFile(IResource resource) { if (resource instanceof IFile) { IFile file = (IFile) resource; if (file.getName().endsWith("xfm.xmi")) { String thisUri = resource.getFullPath().toString(); featureModelUri = getFeatureModelUri(file.getProject()); if (thisUri.equals(featureModelUri)) refreshFeatureModel(file.getProject()); } if (file.getName().endsWith(".v")) { builder.deleteMarkers(file); checkFilenameDepenency(file); checkFileContents(file); } if (file.getName().endsWith(".java")) { try { builder.deleteMarkers(file); List<CommentStructure> comments = buildCommentsStructure(loadFile(file)); if (comments.size() > 0) { for (CommentStructure c : comments) { IParseResult result = injector .getInstance(FeaturesParser.class) .parse("FeatureClause", new ByteArrayInputStream(c.clause.getBytes())); if (result.getParseErrors().size() > 0) { String message = ""; for (SyntaxError err : result.getParseErrors()) message += err.getMessage() + "\n"; Exception e = new RuntimeException("parse error: " + message); log.error("error while parsing feature clause", e); } EObject clause = result.getRootASTElement(); if (clause instanceof Feature) { String feature = clause.eGet(clause.eClass().getEStructuralFeature("feature")).toString(); if (!isFeatureDefined(file, feature)) addMarkerIfNotDefined(feature, file, c.line); } else for (EObject e : EcoreUtil2.eAllContentsAsList(clause)) { if (e instanceof Feature || e instanceof Atom) { String feature = e.eGet(e.eClass().getEStructuralFeature("feature")).toString(); if (!isFeatureDefined(file, feature)) addMarkerIfNotDefined(feature, file, c.line); } } } } } catch (ResourceException e) { log.error("error loading file", e); } catch (Throwable e) { log.error("error loading file", e); } } } }
static boolean isInSourceFolder(final IFile file) { if (file == null || !file.isAccessible()) { // throw new IllegalArgumentException(); return false; } boolean result = false; IHaskellProject hsProject = HaskellProjectManager.get(file.getProject()); Set<IPath> sourcePaths = hsProject.getSourcePaths(); for (IPath sourcePath : sourcePaths) { IPath src = file.getProject().getFullPath().append(sourcePath); result |= src.isPrefixOf(file.getFullPath()); } return result; }
protected static String getLineDelimiterPreference(IFile file) { IScopeContext[] scopeContext; if (file != null && file.getProject() != null) { // project preference scopeContext = new IScopeContext[] {new ProjectScope(file.getProject())}; String lineDelimiter = Platform.getPreferencesService() .getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext); if (lineDelimiter != null) return lineDelimiter; } // workspace preference scopeContext = new IScopeContext[] {InstanceScope.INSTANCE}; return Platform.getPreferencesService() .getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext); }
private boolean isDjangoHandledModule( String djangoModulesHandling, IEditorInput input, String lastSegment) { boolean handled = false; if (djangoModulesHandling == PyTitlePreferencesPage.TITLE_EDITOR_DJANGO_MODULES_SHOW_PARENT_AND_DECORATE || djangoModulesHandling == PyTitlePreferencesPage.TITLE_EDITOR_DJANGO_MODULES_DECORATE) { if (input instanceof IFileEditorInput) { IFileEditorInput iFileEditorInput = (IFileEditorInput) input; IFile file = iFileEditorInput.getFile(); IProject project = file.getProject(); try { if (project.hasNature(PythonNature.DJANGO_NATURE_ID)) { if (PyTitlePreferencesPage.isDjangoModuleToDecorate(lastSegment)) { // remove the module name. handled = true; } } } catch (CoreException e) { Log.log(e); } } } return handled; }
@Override public void doSave(IProgressMonitor monitor) { super.doSave(monitor); final ActivitiDiagramEditorInput adei = (ActivitiDiagramEditorInput) getEditorInput(); try { final IFile dataFile = adei.getDataFile(); final String diagramFileString = dataFile.getLocationURI().getPath(); BpmnMemoryModel model = ModelHandler.getModel(EcoreUtil.getURI(getDiagramTypeProvider().getDiagram())); // Save the bpmn diagram file doSaveToBpmn(model, diagramFileString); // Save an image of the diagram doSaveImage(diagramFileString, model); // Refresh the resources in the workspace before invoking export // marshallers, as they may need access to resources dataFile.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); // Invoke export marshallers to produce additional output doInvokeExportMarshallers(model); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } ((BasicCommandStack) getEditingDomain().getCommandStack()).saveIsDone(); updateDirtyState(); }
/** * Convert a file to the EPackage containing a metamodel. * * @param iFile The file that is to be converted to the Epackage. * @return The EPackage containing the metamodel loaded from the file. * @throws CodeGenerationException */ protected EPackage fileToEPack(IFile iFile) throws CodeGenerationException { ResourceSet resSet = new ResourceSetImpl(); resSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap()); URI fileURI = URI.createPlatformResourceURI( "/" + iFile.getProject().getName() + "/" + iFile.getProjectRelativePath().toString(), true); Resource resource = resSet.createResource(fileURI); Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); try { resource.load(options); } catch (IOException e) { throw new CodeGenerationException( "Error while loading resource of File: " + iFile.getName(), e.getCause()); } EList<EObject> sd = resource.getContents(); for (EObject object : sd) { if (object instanceof EPackage) { EPackage ePack = (EPackage) object; pi.setNsURI(ePack.getNsURI()); return ePack; } } return null; }
private void fireEvent() throws ApplicationException { IEditorInput input = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getActiveEditor() .getEditorInput(); IFile ifile = ((IFileEditorInput) input).getFile(); IProject project = ifile.getProject(); String bmFilesDir = ProjectUtil.getBMHomeLocalPath(project); File baseDir = new File(bmFilesDir); String fullPath = baseDir.getAbsolutePath(); CompositeMap bmFiles = getAllBMFiles(baseDir, fullPath); String[] columnProperties = {"name", "fullpath"}; GridViewer gridViewer = new GridViewer( columnProperties, IGridViewer.isColumnPacked | IGridViewer.filterBar | IGridViewer.NoToolBar); gridViewer.setFilterColumn("name"); gridViewer.setData(bmFiles); GridDialog dialog = new GridDialog(new Shell(), gridViewer); if (dialog.open() == Window.OK) { if (dialog.getSelected() != null) { CompositeMap data = dialog.getSelected(); bmselectionsText.setText(data.getString("fullpath")); } } }
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; }
/** * Creates a validator which ensures that the chosen id is not for a layout that is directly or * indirectly including the given layout. Used to avoid cyclic dependencies when offering layouts * to be included within a given file, etc. * * @param file the target file that candidate layouts should not directly or indirectly include * @return a validator which checks whether resource ids are valid or whether they could result in * a cyclic dependency */ public static IInputValidator create(IFile file) { IProject project = file.getProject(); IncludeFinder includeFinder = IncludeFinder.get(project); final Collection<String> invalid = includeFinder.getInvalidIncludes(file); return new CyclicDependencyValidator(invalid); }
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 IResource[] createDependencies(IFile file) { IFile[] depends = new IFile[METADATA_FILES.length]; for (int i = 0; i < METADATA_FILES.length; i++) { depends[i] = file.getProject().getFile(METADATA_FILES[i]); } return depends; }
public static void refactorProjectImportsAndDocLinks( Tree.Declaration node, IFile originalFile, IFile targetFile, CompositeChange change, String originalPackage, String targetPackage) { if (!originalPackage.equals(targetPackage)) { for (PhasedUnit pu : getAllUnits(originalFile.getProject())) { // if (!node.getUnit().equals(pu.getUnit())) { IFile file = ((IFileVirtualFile) pu.getUnitFile()).getFile(); if (!file.equals(originalFile) && !file.equals(targetFile)) { TextFileChange tfc = new TextFileChange("Fix Import", file); tfc.setEdit(new MultiTextEdit()); CompilationUnit rootNode = pu.getCompilationUnit(); refactorImports(node, originalPackage, targetPackage, rootNode, tfc); refactorDocLinks(node, targetPackage, rootNode, tfc); if (tfc.getEdit().hasChildren()) { change.add(tfc); } } // } } } }
@Override public IStatus update() { IFile[] resourcesToProcess = getTargetFiles(getTargetResources()); // The all project of each file shall be updated (In order to see if new files appeared (New // control)) Set<IProject> projects = new HashSet<IProject>(); for (IFile f : resourcesToProcess) { projects.add(f.getProject()); } IProject[] projectsToUpdate = new IProject[projects.size()]; projects.toArray(projectsToUpdate); if (ITracingConstant.UPDATE_TRACING) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Updating projects: ").append("\n"); for (IProject p : projectsToUpdate) { stringBuilder.append(p.getFullPath()).append("\n"); } Tracer.logInfo(stringBuilder.toString()); } CompositeOperation op = UpdateAction.getUpdateOperation(projectsToUpdate, SVNRevision.HEAD); ICancellableOperationWrapper runnable = UIMonitorUtility.doTaskNowDefault(op, false); IActionOperation resultStatus = runnable.getOperation(); return resultStatus.getStatus(); }
/** Retrieves the current {@link IProject} instance based on the currently opened editor. */ public static IProject getCurrentProjectForOpenEditor() { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (activeWorkbenchWindow != null && activeWorkbenchWindow.getActivePage() != null) { IEditorPart p = activeWorkbenchWindow.getActivePage().getActiveEditor(); if (p == null) { IWorkbenchPart activePart = activeWorkbenchWindow.getActivePage().getActivePart(); if (activePart instanceof PropertySheet) { ShowInContext showInContext = ((PropertySheet) activePart).getShowInContext(); if (showInContext instanceof PropertyShowInContext) { IWorkbenchPart part = ((PropertyShowInContext) showInContext).getPart(); if (part instanceof IEditorPart) { p = (IEditorPart) part; } else { JasperReportsPlugin.getDefault() .logWarning("Unable to retrieve the current project for the open editor."); return null; } } } } IEditorInput editorInput = p.getEditorInput(); IFile file = getFile(editorInput); if (file != null) { return file.getProject(); } } return null; }
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; }
public void run(IAction action) { if (this.selection instanceof IStructuredSelection) { for (Iterator<?> iter = ((IStructuredSelection) this.selection).iterator(); iter.hasNext(); ) { Object element = iter.next(); IFile file = null; if (element instanceof IFile) file = (IFile) element; else if (element instanceof IAdaptable) file = (IFile) ((IAdaptable) element).getAdapter(IFile.class); if (file != null) { URI projectLocationURI = file.getProject().getLocationURI(); boolean succesful = false; if (TypeSystemManager.exists(projectLocationURI)) { TypeSystemManager.setEquationFile(projectLocationURI, file); succesful = TypeSystemManager.refreshTypesystem(projectLocationURI); } else { TypeSystem ts = TypeSystemManager.getTypesystem(projectLocationURI, file); succesful = ts.getFirstLayer() != null; } if (succesful) MessageDialog.openInformation( new Shell(), "TypesystemInfo", "Typesystem successfully created."); } } } }
@Override protected void doSetInput(IEditorInput newInput) throws CoreException { // If this editor is for a project file, remove this editor as a property // change listener. if (fProject != null) AutotoolsPropertyManager.getDefault().removeProjectPropertyListener(fProject, this); this.fProject = null; super.doSetInput(newInput); this.input = newInput; if (input instanceof IFileEditorInput) { IFile f = ((IFileEditorInput) input).getFile(); fProject = f.getProject(); // This is a project file. We want to be notified if the Autoconf editor // properties are changed such that the macro versions are changed. AutotoolsPropertyManager.getDefault().addProjectPropertyListener(fProject, this); } getOutlinePage().setInput(input); try { IDocument document = getInputDocument(); setRootElement(reparseDocument(document)); } catch (Exception e) { e.printStackTrace(); } }
/** * @param paths * @return the calculated commit message */ private String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { // special case for merge return commitMessage; } if (amending) return previousCommitMessage; String calculatedCommitMessage = null; Set<IResource> resources = new HashSet<IResource>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } try { ICommitMessageProvider messageProvider = getCommitMessageProvider(); if (messageProvider != null) { IResource[] resourcesArray = resources.toArray(new IResource[0]); calculatedCommitMessage = messageProvider.getMessage(resourcesArray); } } catch (CoreException coreException) { Activator.error(coreException.getLocalizedMessage(), coreException); } if (calculatedCommitMessage != null) return calculatedCommitMessage; else return EMPTY_STRING; }
/** * @see * com.ibm.sse.editor.extensions.hyperlink.IHyperlinkPartitionRecognizer#recognize(org.eclipse.jface.text.IDocument, * com.ibm.sse.editor.extensions.hyperlink.IHyperlinkRegion) */ public boolean recognize(IDocument document, int offset, IHyperlinkRegion region) { StructuredModelWrapper smw = new StructuredModelWrapper(); smw.init(document); try { IFile documentFile = smw.getFile(); if (documentFile == null) { return false; } IProject project = documentFile.getProject(); if (project == null) { return false; } if (EclipseResourceUtil.getModelNature(project) != null) { for (int i = 0; i < JSF_PROJECT_NATURES.length; i++) { if (project.getNature(JSF_PROJECT_NATURES[i]) != null) return true; } return false; } return true; } catch (CoreException x) { JSFExtensionsPlugin.log("", x); // $NON-NLS-1$ return false; } finally { smw.dispose(); } }
/** * Visits the given resource delta that corresponds to a file. * * @param delta The given resource delta * @param file The file concerning by this delta * @return <code>true</code> if the resource delta's children should be visited; <code>false * </code> if they should be skipped. * @exception CoreException if the visit fails for some reason. */ protected boolean visitFile(IResourceDelta delta, IFile currentFile) throws CoreException { // By default, we do not visit the resource delta's children boolean visitChildren = false; final Option<ModelingProject> optionalModelingProject = ModelingProject.asModelingProject(currentFile.getProject()); if (optionalModelingProject.some()) { if (IResourceDelta.REMOVED == delta.getKind()) { if (optionalModelingProject.get().isValid()) { // Check that this IFile is not the main representations // file of this project if (optionalModelingProject.get().isMainRepresentationsFile(currentFile)) { mainRepresentationsFileToDelete.add(currentFile); } } else if (new FileQuery(currentFile).isSessionResourceFile()) { // If the project is not valid and the deleted file is a // representations file, validate the project again. optionalModelingProject .get() .getMainRepresentationsFileURI(new NullProgressMonitor(), true, false); } } else if (IResourceDelta.ADDED == delta.getKind()) { // Check that the corresponding project does not already // have a main representations file if (SiriusUtil.SESSION_RESOURCE_EXTENSION.equals(currentFile.getFileExtension())) { if (optionalModelingProject.get().isValid()) { representationsFileToAddOnValidModelingProject.add(currentFile); } } } } return visitChildren; }
@Override protected String getInitialFileContent(final IFile newFileHandle, final SubMonitor m) { final String lineDelimiter = TextUtil.getLineDelimiter(newFileHandle.getProject()); final IRSourceUnit su = (IRSourceUnit) LTK.getSourceUnitManager() .getSourceUnit( LTK.PERSISTENCE_CONTEXT, newFileHandle, getContentType(newFileHandle), true, m); try { final EvaluatedTemplate data = CodeGeneration.getNewRFileContent(su, lineDelimiter); if (data != null) { fInitialSelection = data.getRegionToSelect(); return data.getContent(); } } catch (final CoreException e) { RUIPlugin.logError( ICommonStatusConstants.INTERNAL_TEMPLATE, "An error occured when applying template to new R script file.", e); //$NON-NLS-1$ } finally { if (su != null) { su.disconnect(m); } } return null; }
public static void openFile(IWorkbenchPage page, IFile destinationFile, byte[] initialContent) { try { if (destinationFile != null) { // TODO: prompt to create the file ? I say no, why would you try the shortcut if you didn't // want it created if (!destinationFile.exists()) { IPath fullPath = destinationFile.getLocation(); if (fullPath.toFile().getParentFile().mkdirs()) { // create Eclipse resource so that the create file doesn't blow chunks destinationFile .getProject() .getFile(destinationFile.getParent().getProjectRelativePath()) .refreshLocal(IFile.DEPTH_ZERO, null); } destinationFile.create(new ByteArrayInputStream(initialContent), false, null); } if (destinationFile.exists()) { IDE.openEditor(page, destinationFile); } } } catch (CoreException e) { String clazz = destinationFile.getName(); System.err.println("OpenCakeFile can not open file: " + clazz); e.printStackTrace(); } }