/** * Scans workspace for files that may end up in XtextIndex when given location is processed by the builder. This is * naive filtering based on {@link IndexableFilesDiscoveryUtil#INDEXABLE_FILTERS file extensions}. Symlinks are not * followed. * * @param workspace * to scan * @return collection of indexable locations * @throws CoreException * if scanning of the workspace is not possible. */ public static Collection<String> collectIndexableFiles(IWorkspace workspace) throws CoreException { Set<String> result = new HashSet<>(); workspace.getRoot().accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { if (resource.getType() == IResource.FILE) { IFile file = (IFile) resource; if (INDEXABLE_FILTERS.contains(file.getFileExtension().toLowerCase())) { result.add(file.getFullPath().toString()); } } return true; } }); return result; }
/** * Returns a content provider for the list dialog. It will return all projects in the workspace except the given * project, plus any projects referenced by the given project which do no exist in the workspace. * * @return the content provider that shows the project content */ private IStructuredContentProvider getContentProvider() { return new WorkbenchContentProvider() { @Override public Object[] getChildren(Object o) { if (!(o instanceof IWorkspace)) { return new Object[0]; } // Collect all the projects in the workspace except the given project IProject[] projects = ((IWorkspace) o).getRoot().getProjects(); List<IProject> applicableProjects = Lists.newArrayList(); Optional<? extends IN4JSEclipseProject> projectOpt = null; for (IProject candidate : projects) { projectOpt = n4jsCore.create(candidate); if (projectOpt.isPresent() && projectOpt.get().exists()) { applicableProjects.add(candidate); } } return applicableProjects.toArray(new IProject[applicableProjects.size()]); } }; }
public IProject createProjectPluginResource(String projectName, IProgressMonitor monitor) throws CoreException { IWorkspace myWorkspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot myWorkspaceRoot = myWorkspace.getRoot(); IProject resourceProject = myWorkspaceRoot.getProject(projectName); if (!resourceProject.exists()) { if(myWorkspaceRoot.getLocation().toFile().equals(new Path(Engine.PROJECTS_PATH).toFile())){ logDebug("createProjectPluginResource : project is in the workspace folder"); resourceProject.create(monitor); }else{ logDebug("createProjectPluginResource: project isn't in the workspace folder"); IPath projectPath = new Path(Engine.PROJECTS_PATH + "/" + projectName).makeAbsolute(); IProjectDescription description = myWorkspace.newProjectDescription(projectName); description.setLocation(projectPath); resourceProject.create(description, monitor); } } return resourceProject; }
/** * Set the GW4E Nature to the passed project * * @param project * @return * @throws CoreException */ public static IStatus setGW4ENature(IProject project) throws CoreException { IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); // add our id newNatures[natures.length] = GW4ENature.NATURE_ID; // validate the natures IWorkspace workspace = ResourcesPlugin.getWorkspace(); IStatus status = workspace.validateNatureSet(newNatures); if (status.getCode() == IStatus.OK) { description.setNatureIds(newNatures); project.setDescription(description, null); } return status; }
/** * @return */ protected boolean validateContainer(Problem pb) { if (selectedContainer==null) { pb.raiseProblem(MessageUtil.getString("select_a_folder"), Problem.PROBLEM_RESOURCE_EMPTY); return false; } if (!selectedContainer.exists()) { pb.raiseProblem(MessageUtil.getString("folder_does_not_exists"), Problem.FOLDER_PROJECT_DOES_NOT_EXIST); return false; } IPath path = selectedContainer.getFullPath(); IWorkspace workspace = ResourcesPlugin.getWorkspace(); String projectName = path.segment(0); if (projectName == null || !workspace.getRoot().getProject(projectName).exists()) { pb.raiseProblem(MessageUtil.getString("project_does_not_exist"), Problem.PROBLEM_PROJECT_DOES_NOT_EXIST); return false; } return true; }
private void validateAndConvertOperationField(TransformMapping transformMapping, TypeOperationsOutSocket externalMapping, String componentName) { transformMapping.clear(); for (Object field : externalMapping.getPassThroughFieldOrOperationFieldOrExpressionField()) { if (field instanceof TypeInputField) { if(STAR_PROPERTY.equals(((TypeInputField) field).getName())){ transformMapping.setAllInputFieldsArePassthrough(true); }else{ addPassThroughField((TypeInputField) field, transformMapping); } } else if (field instanceof TypeMapField) { addMapField((TypeMapField) field, transformMapping); } else if (field instanceof TypeOperationField) { addOperationField((TypeOperationField)field, transformMapping, componentName); } else if (field instanceof TypeExpressionField) { addExpressionField((TypeExpressionField) field, transformMapping, componentName); }else if(field instanceof TypeExternalSchema){ String filePath = StringUtils.replace(((TypeExternalSchema)field).getUri(), "../", ""); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IPath relativePath=null; relativePath=workspace.getRoot().getFile(new Path(filePath)).getLocation(); ExternalOperationExpressionUtil.INSTANCE.importOutputFields(relativePath.toFile(), transformMapping, false,Constants.TRANSFORM_DISPLAYNAME); transformMapping.getExternalOutputFieldsData().setExternal(true); transformMapping.getExternalOutputFieldsData().setFilePath(filePath); } } }
private boolean isFilteredByParent() { if ((linkedResourceGroup == null) || linkedResourceGroup.isEnabled()) return false; IPath containerPath = resourceGroup.getContainerFullPath(); if (containerPath == null) return false; String resourceName = resourceGroup.getResource(); if (resourceName == null) return false; if (resourceName.length() > 0) { IPath newFolderPath = containerPath.append(resourceName); IFile newFileHandle = createFileHandle(newFolderPath); IWorkspace workspace = newFileHandle.getWorkspace(); return !workspace.validateFiltered(newFileHandle).isOK(); } return false; }
private void addProjectsToList() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject[] projects = root.getProjects(); for (IProject project : projects){ try { if (project.isNatureEnabled("jasonide.jasonNature")){ projectsList.add(project.getName()); } } catch (CoreException e) { //e.printStackTrace(); //MessageDialog.openError(shell, "CoreException", e.getMessage()); } } }
public IProject createLinkedProject(String projectName, Plugin plugin, IPath linkPath) throws CoreException { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject project = workspace.getRoot().getProject(projectName); IProjectDescription desc = workspace.newProjectDescription(projectName); File file = getFileInPlugin(plugin, linkPath); IPath projectLocation = new Path(file.getAbsolutePath()); if (Platform.getLocation().equals(projectLocation)) projectLocation = null; desc.setLocation(projectLocation); project.create(desc, NULL_MONITOR); if (!project.isOpen()) project.open(NULL_MONITOR); return project; }
private IFile getIFileFromResource() { Resource linkTargetResource = linkTarget.eResource(); if (linkTargetResource == null) { return null; } URI resourceURI = linkTargetResource.getURI(); if (linkTargetResource.getResourceSet() != null && linkTargetResource.getResourceSet().getURIConverter() != null) { resourceURI = linkTargetResource.getResourceSet().getURIConverter().normalize(resourceURI); } if (resourceURI.isPlatformResource()) { String platformString = resourceURI.toPlatformString(true); if (platformString != null) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); return root.getFile(new Path(platformString)); } } return null; }
public static File createFileInPath(String fileName, IPath path){ path = path.append(fileName); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot workspaceRoot = workspace.getRoot(); IFile outputFile = workspaceRoot.getFile(path); File file = new File(outputFile.getLocationURI()); if(!file.exists()) try { if(!file.createNewFile()){ return null; } } catch (IOException e) { e.printStackTrace(); return null; } return file; }
/** * Returns the file object of the feature model * @param featureModel * @return */ private static File getLayoutFile(DwFeatureModelWrapped featureModel){ IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot workspaceRoot = workspace.getRoot(); IFile file = workspaceRoot.getFile(new Path(featureModel.getModel().eResource().getURI().toPlatformString(true))); IPath path = ((IPath)file.getFullPath().clone()).removeFileExtension().addFileExtension("hylayout"); IResource resourceInRuntimeWorkspace = workspaceRoot.findMember(path.toString()); if(resourceInRuntimeWorkspace != null){ return new File(resourceInRuntimeWorkspace.getLocationURI()); }else{ return null; } }
public void testNewSpecHandlerFail() throws InterruptedException, IOException, CoreException { // Create a project (not a specification) that is going to be in the way // of the NewSpecHandler and which will make it fail. final IWorkspace ws = ResourcesPlugin.getWorkspace(); ws.getRoot().getProject("TestNewSpecHandlerFail").create(new NullProgressMonitor()); assertTrue(ws.getRoot().getProject("TestNewSpecHandlerFail").exists()); // Above only creates a project but not a spec. assertNull(Activator.getSpecManager().getSpecByName("TestNewSpecHandlerFail")); // Try to create a spec the Toolbox way which is supposed to fail. final IStatus iStatus = runJob("TestNewSpecHandlerFail"); assertEquals(Status.ERROR, iStatus.getSeverity()); // As a result of the above failed attempt to create a spec // 'TestNewSpecHandlerFail', a spec should appear in the SpecManager // with a file named "Delete me". final Spec spec = Activator.getSpecManager().getSpecByName("TestNewSpecHandlerFail"); assertEquals("Failed to find 'Delete me' spec in ToolboxExplorer", "Delete me", spec.getRootFile().getName()); // Verify that this spec can be deleted and is gone afterwards // (including the dangling project this is all about). Activator.getSpecManager().removeSpec(spec, new NullProgressMonitor(), true); assertNull(Activator.getSpecManager().getSpecByName("TestNewSpecHandlerFail")); assertFalse(ws.getRoot().getProject("TestNewSpecHandlerFail").exists()); }
public static IStatus validateProjectName(final IWorkspace workspace, final String name) { final IStatus status = workspace.validateName(name, IResource.PROJECT); if (!status.isOK()) { return status; } if (name.startsWith(".")) //$NON-NLS-1$ { return new Status( IStatus.ERROR, TFSCommonClientPlugin.PLUGIN_ID, Messages.getString("EclipseProjectInfo.NameStartsWithDotError")); //$NON-NLS-1$ } return Status.OK_STATUS; }
public synchronized void appendText(final String text) { try { ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { // System.out.print(Thread.currentThread().getId() + " : " + message); outFile.appendContents(new ByteArrayInputStream(text.getBytes()), IResource.FORCE, monitor); } }, rule, IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); // if the console output is active, print to it } catch (CoreException e) { TLCActivator.logError("Error writing the TLC process output file for " + model.getName(), e); } }
/** * get the IResource corresponding to the given file. Given file does not * need to exist. * * @param file * @param isDirectory * if true, an IContainer will be returned, otherwise an IFile * will be returned * @return */ public static IResource getResource(File file, boolean isDirectory) { if (file == null) return null; IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot workspaceRoot = workspace.getRoot(); IPath pathEclipse = new Path(file.getAbsolutePath()); IResource resource = null; if (isDirectory) { resource = workspaceRoot.getContainerForLocation(pathEclipse); } else { resource = workspaceRoot.getFileForLocation(pathEclipse); } return resource; }
public Object[] getChildren(Object element) { if (element instanceof IWorkspace) { // check if closed projects should be shown IProject[] allProjects = ((IWorkspace) element).getRoot().getProjects(); if (showClosedProjects) return allProjects; ArrayList accessibleProjects = new ArrayList(); for (int i = 0; i < allProjects.length; i++) { if (allProjects[i].isOpen()) { accessibleProjects.add(allProjects[i]); } } return accessibleProjects.toArray(); } return super.getChildren(element); }
/** * Check if there already is a project under the given name. * @param text */ private void validateProjectName(String text) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IStatus status = workspace.validateName(text, IResource.PROJECT); if (status.isOK()) { if (workspace.getRoot().getProject(text).exists()) { status = createStatus(IStatus.ERROR, TexlipsePlugin.getResourceString("projectWizardNameError")); } attributes.setProjectName(text); } updateStatus(status, projectNameField); }
@Override protected String getErrorMessage() { if (isBlank(dictionaryNameText)) { return "error.translation.dictionary.name.empty"; } final String fileName = dictionaryNameText.getText().trim(); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IStatus result = workspace.validateName(fileName, IResource.FILE); if (!result.isOK()) { return result.getMessage(); } final File file = new File(PreferenceInitializer.getTranslationPath(fileName)); if (file.exists()) { return "error.translation.dictionary.name.duplicated"; } return null; }
public void updateProjects() { WPILibCPPPlugin.logInfo("Updating projects"); // Get the root of the workspace IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); // Get all projects in the workspace IProject[] projects = root.getProjects(); // Loop over all projects for (IProject project : projects) { try { if(project.hasNature("edu.wpi.first.wpilib.plugins.core.nature.FRCProjectNature") && project.hasNature("org.eclipse.cdt.core.ccnature")){ updateVariables(project); } } catch (CoreException e) { WPILibCPPPlugin.logError("Error updating projects.", e); } } }
/** * Destructor */ public void terminate() { IWorkspace ws = ResourcesPlugin.getWorkspace(); ws.removeResourceChangeListener(this); if (this.loadedSpec != null && PreferenceStoreHelper.getInstancePreferenceStore().getBoolean( IPreferenceConstants.I_RESTORE_LAST_SPEC)) { PreferenceStoreHelper.getInstancePreferenceStore().setValue(IPreferenceConstants.I_SPEC_LOADED, this.loadedSpec.getName()); } else { PreferenceStoreHelper.getInstancePreferenceStore().setValue(IPreferenceConstants.I_SPEC_LOADED, ""); } }
@Test public void testInvalidMarkersDeletedWhenProjectOpened() throws Exception { // Given importProjectFromTemplate("testInvalidMarkersDeletedWhenProjectOpened", "bookmarkMarkersTest"); Bookmark bookmark = new Bookmark(new BookmarkId(), ImmutableMap.of(PROP_WORKSPACE_PATH, "/testInvalidMarkersDeletedWhenProjectOpened/file.txt", PROP_LINE_NUMBER, "0")); addBookmark(rootFolderId, bookmark); waitUntil("Cannot find marker", () -> bookmarksMarkers.findMarker(bookmark.getId(), new NullProgressMonitor())); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject project = workspace.getRoot().getProject("testInvalidMarkersDeletedWhenProjectOpened"); project.close(null); deleteBookmark(bookmark.getId()); // When project.open(null); // Then waitUntil("Bookmark marker should be deleted", () -> findBookmarkMarker(bookmark.getId()) == null); }
@Override protected String getErrorMessage() { if (isBlank(this.dictionaryNameText)) { return "error.translation.dictionary.name.empty"; } String fileName = this.dictionaryNameText.getText().trim(); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IStatus result = workspace.validateName(fileName, IResource.FILE); if (!result.isOK()) { return result.getMessage(); } File file = new File(PreferenceInitializer.getTranslationPath(fileName)); if (file.exists()) { return "error.translation.dictionary.name.duplicated"; } return null; }
@Override public void resourceChanged(IResourceChangeEvent event) { if (event.getSource() instanceof IWorkspace) { switch (event.getType()) { case IResourceChangeEvent.POST_CHANGE: try { if (event.getDelta() != null && editor.isActiveOn(event.getResource())) { editor.getPageModel(); } } catch (Exception e) { Log.error("Failed handing post_change of resource", e); } break; } } }
public static IJavaProject getJavaProject(String projectName) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); if (workspace == null) { System.out.println("No workspace"); return null; } IWorkspaceRoot root = workspace.getRoot(); if (root == null) { System.out.println("No workspace root"); return null; } IJavaModel javacore = JavaCore.create(root);// this gets you the java version of the workspace IJavaProject project = null; if (javacore != null) { project = javacore.getJavaProject(projectName); // this returns the specified project } WorkspaceUtilities.javaProject = project; return project; }
/** * Traverses the workspace for CompilationUnits. * * @return the list of all CompilationUnits in the workspace */ public static List<ICompilationUnit> scanForCompilationUnits() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); if (workspace == null) { System.out.println("No workspace"); return null; } IWorkspaceRoot root = workspace.getRoot(); if (root == null) { System.out.println("No workspace root"); return null; } IJavaModel javaModel = JavaCore.create(root); if (javaModel == null) { System.out.println("No Java Model in workspace"); return null; } // Get all CompilationUnits return WorkspaceUtilities.collectCompilationUnits(javaModel); }
private IProject initialize(String projectName) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(projectName); if (!project.exists()) try { project.create(null); if (!project.isOpen()) project.open(null); if (!project.hasNature("org.eclipse.xtext.ui.shared.xtextNature")) { IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { "org.eclipse.xtext.ui.shared.xtextNature" }); project.setDescription(description, null); } } catch (CoreException e) { e.printStackTrace(); } return project; }
private static IProject importProject(File probandsFolder, String projectName, boolean prepareDotProject) throws Exception { File projectSourceFolder = new File(probandsFolder, projectName); if (!projectSourceFolder.exists()) { throw new IllegalArgumentException("proband not found in " + projectSourceFolder); } if (prepareDotProject) { prepareDotProject(projectSourceFolder); } IProgressMonitor monitor = new NullProgressMonitor(); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProjectDescription newProjectDescription = workspace.newProjectDescription(projectName); IProject project = workspace.getRoot().getProject(projectName); project.create(newProjectDescription, monitor); project.open(monitor); if (!project.getLocation().toFile().exists()) { throw new IllegalArgumentException("test project correctly created in " + project.getLocation()); } IOverwriteQuery overwriteQuery = new IOverwriteQuery() { @Override public String queryOverwrite(String file) { return ALL; } }; ImportOperation importOperation = new ImportOperation(project.getFullPath(), projectSourceFolder, FileSystemStructureProvider.INSTANCE, overwriteQuery); importOperation.setCreateContainerStructure(false); importOperation.run(monitor); return project; }
private static void toggleAutobuild(final boolean enabled) { final IWorkspace workspace = getWorkspace(); final IWorkspaceDescription description = workspace.getDescription(); description.setAutoBuilding(enabled); try { LOGGER.info("Turning auto-build " + (enabled ? "on" : "off") + "..."); workspace.setDescription(description); LOGGER.info("Auto-build was successfully turned " + (enabled ? "on" : "off") + "."); } catch (final CoreException e) { throw new RuntimeException("Error while toggling auto-build", e); } }
/** Sets workspace auto-build according to the provided flag. Thrown exceptions are handled by logging. */ private static void setAutobuild(boolean on) { try { final IWorkspace workspace = getWorkspace(); final IWorkspaceDescription description = workspace.getDescription(); description.setAutoBuilding(on); workspace.setDescription(description); } catch (CoreException e) { LOGGER.debug("Organize imports cannot set auto build to " + on + "."); } }
/** * We have to set dynamic dependencies in the project meta data to ensure that the builder is correctly triggered * according to the declared dependencies in the N4JS manifest files. * * @param project * the project to update in respect of its dynamic references. */ public void updateProjectReferencesIfNecessary(final IProject project) { if (project instanceof ExternalProject) { return; // No need to adjust any dynamic references. } try { IProject[] eclipseRequired = project.getDescription().getDynamicReferences(); Set<IProject> currentRequires = Sets.newHashSet(eclipseRequired); final Set<IProject> newRequires = getProjectDependenciesAsSet(project); if (currentRequires.equals(newRequires)) { return; } IWorkspaceRunnable runnable = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { IProjectDescription description = project.getDescription(); IProject[] array = newRequires.toArray(new IProject[newRequires.size()]); description.setDynamicReferences(array); project.setDescription(description, IResource.AVOID_NATURE_CONFIG, monitor); } }; internalWorkspace.getWorkspace().getWorkspace().run(runnable, null /* cannot use a scheduling rule here since this is triggered lazily by the linker */, IWorkspace.AVOID_UPDATE, null); } catch (CoreException e) { // ignore } }
@Override public void dispose() { selectionProvider.removeSelectionChangedListener(selectionChangedListener); selectionProvider = null; final IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.removeResourceChangeListener(openAction); workspace.removeResourceChangeListener(closeAction); workspace.removeResourceChangeListener(closeUnrelatedAction); super.dispose(); }