@Override public Object[] getChildren(final Object element) { if (workingSetManagerBroker.isWorkingSetTopLevel()) { if (element instanceof IWorkspaceRoot) { final WorkingSetManager manager = workingSetManagerBroker.getActiveManager(); if (manager != null) { return manager.getWorkingSets(); } } else if (element instanceof WorkingSet) { return ((WorkingSet) element).getElements(); } } final Object[] children = super.getChildren(element); if (element instanceof IProject && ((IProject) element).isAccessible()) { return Arrays2.add(children, getVirtualNodes((IProject) element)); } return children; }
private Multimap<String, IProject> initProjectLocation() { final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final IProject[] projects = root.getProjects(); final Multimap<String, IProject> locations = HashMultimap.create(); // initialize the repository paths repositoryPaths = repositoriesProvider.getWorkspaceRepositories().stream() .map(r -> r.getDirectory().getParentFile().toPath()).collect(Collectors.toSet()); for (final IProject project : projects) { if (isRemoteEditNature(project)) { continue; } final String pair = getWorkingSetId(project); locations.put(pair, project); } return locations; }
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; }
public static List<ResourceItem> collectAllWorkspaceFiles(IWorkspaceRoot workspace) { List<ResourceItem> files = new ArrayList<>(); IResourceProxyVisitor visitor = new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() != IResource.FILE) return true; if (proxy.isDerived()) return false; if (proxy.isPhantom()) return false; if (proxy.isHidden()) return false; IFile file = (IFile) proxy.requestResource(); files.add(makeResourceItem(file)); return false; } }; try { IResource[] resources = workspace.members(); for(IResource resource : resources) { if (!resource.getProject().isOpen()) continue; resource.accept(visitor, 0); } } catch (CoreException e) { throw new RuntimeException(e); } return files; }
public CompositeNode getFinalAssemblyDefinition(String name, String containerName) { CompositeNode ret = null; if (containerName != null) { String[] names = StringUtils.split(containerName, "/"); IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = wsRoot.findMember(new Path("/" + names[0])); IPath loc = resource.getLocation(); File file = new File(loc.toOSString() + File.separator + name + ".fassmbl"); try { ret = ParseUtil.getFinalAssemblyNodeFromText(FileUtils.readFileToString(file)); } catch (IOException e) { EclipseUtil.writeStactTraceToConsole(e); } } return ret; }
public LogicalSystemNode getLogicalSystemDefinition(String name, String containerName) { LogicalSystemNode ret = null; if (containerName != null) { String[] names = StringUtils.split(containerName, "/"); IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = wsRoot.findMember(new Path("/" + names[0])); IPath loc = resource.getLocation(); File file = new File(loc.toOSString() + File.separator + name + ".lsys"); try { ret = ParseUtil.getLogicalSystemNodeFromText(FileUtils.readFileToString(file)); } catch (IOException e) { EclipseUtil.writeStactTraceToConsole(e); } } return ret; }
public ComponentImplementationNode getComponentImplementationDefinition(String name, String containerName) { ComponentImplementationNode ret = null; if (containerName != null) { String[] names = StringUtils.split(containerName, "/"); IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = wsRoot.findMember(new Path("/" + names[0])); IPath loc = resource.getLocation(); File file = new File(loc.toOSString() + File.separator + name + ".cimpl"); try { ret = ParseUtil.getComponentImplementationNodeFromText(FileUtils.readFileToString(file)); } catch (IOException e) { EclipseUtil.writeStactTraceToConsole(e); } } return ret; }
@Override public void resourceChanged(IResourceChangeEvent event) { if( event.getType() == IResourceChangeEvent.PRE_BUILD ) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); if( fTouchWorkspace ) { IProject[] projects = root.getProjects(); for( int i = 0; i < projects.length; i++ ) { touchProject(projects[i]); } } else { Iterator<String> iter = fProjectNames.iterator(); while( iter.hasNext() ) { touchProject(root.getProject(iter.next())); } } fTouchWorkspace = false; fProjectNames.clear(); } }
/** * Create a file in a folder with the specified name and content * * @param fullpath * @param filename * @param content * @throws CoreException * @throws InterruptedException */ public static IFile createFileDeleteIfExists(String fullpath, String filename, String content, IProgressMonitor monitor) throws CoreException, InterruptedException { SubMonitor subMonitor = SubMonitor.convert(monitor, 100); subMonitor.setTaskName("Create file delete if it exists " + fullpath); IFile newFile; try { IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot(); IContainer container = (IContainer) wroot.findMember(new Path(fullpath)); newFile = container.getFile(new Path(filename)); if (newFile.exists()) { JDTManager.rename(newFile, new NullProgressMonitor()); newFile.delete(true, new NullProgressMonitor()); } subMonitor.split(30); byte[] source = content.getBytes(Charset.forName("UTF-8")); newFile.create(new ByteArrayInputStream(source), true, new NullProgressMonitor()); subMonitor.split(70); } finally { subMonitor.done(); } return newFile; }
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { copyToPath=getArguments().getDestination().toString(); IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workSpaceRoot.getProject(copyToPath.split("/")[1]); IFolder jobFolder = project.getFolder(copyToPath.substring(copyToPath.indexOf('/', 2))); previousJobFiles=new ArrayList<>(); for (IResource iResource : jobFolder.members()) { if (!(iResource instanceof IFolder)) { IFile iFile = (IFile) iResource; if (iFile.getFileExtension().equalsIgnoreCase(Messages.JOB_EXT)) { previousJobFiles.add(iFile); } } } copiedFileList.add(modifiedResource); return null; }
@Override public void doSaveAs() { String jobId = getActiveProject() + "." + getJobName(); DataViewerUtility.INSTANCE.closeDataViewerWindows(JobManager.INSTANCE.getPreviouslyExecutedJobs().get(jobId)); deleteDebugFiles(jobId); Map<String, String> currentParameterMap = getCurrentParameterMap(); IFile file=opeSaveAsDialog(); saveJob(file,true); IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workSpaceRoot.getProject(getActiveProject()); IFolder paramFolder = project.getFolder(Messages.PARAM); IFile filename=paramFolder.getFile(oldFileName.replace(Messages.JOBEXTENSION,Messages.PROPERTIES_EXTENSION)); copyParameterFile(currentParameterMap,filename); }
/** * Obtient la map Project vers Projet Java du workspace courant. * * @return Map des projets. */ public static JavaProjectMap getProjectMap() { JavaProjectMap projects = new JavaProjectMap(); /* Racine du workspace courant. */ IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); /* Parcourt les projets de la racine. */ for (IProject project : wsRoot.getProjects()) { /* Vérication que le projet est un projet Java accessible. */ if (!project.isAccessible() || !JdtUtils.isJavaProject(project)) { continue; } /* Obtient l'AST du projet. */ IJavaProject javaProject = JavaCore.create(project); projects.put(project, javaProject); } return projects; }
@Override public IEditorInput getEditorInput(Object element) { if (element instanceof ILineBreakpoint) { return new FileEditorInput((IFile) ((ILineBreakpoint) element).getMarker().getResource()); } IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(element.toString())); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile[] files = root.findFilesForLocationURI(fileStore.toURI()); if (files != null) { for (IFile file : files) { if (file.exists()) { return new FileEditorInput(file); } } } return new FileStoreEditorInput(fileStore); }
@Override protected void linkPressed(final HyperlinkEvent event, final EObject project_p, final Session session) { if (project_p instanceof Project) { TransactionalEditingDomain domain = TransactionUtil.getEditingDomain(project_p); domain.getCommandStack().execute(new RecordingCommand(domain) { @Override protected void doExecute() { final Project prj = ((Project) project_p); final Mapping mapping = ToPeriodicDerivation.getOrApply(prj); final DesignModel toBeAnalysedModel = (DesignModel) mapping.getSubLinks().get(0).getUniqueTargetValue("copy"); final URI uri = prj.eResource().getURI(); IPath path = new Path(uri.toPlatformString(true)); final String filename = path.lastSegment().replaceAll(".time4sys", "-report.asciidoc"); path = path.removeLastSegments(1); path = path.append(filename); IWorkspaceRoot wrkspc = ResourcesPlugin.getWorkspace().getRoot(); final IFile output = wrkspc.getFile(path); generateReport(toBeAnalysedModel, output, null); } }); } }
private void doFinish(IPath containerPath, String[] path, IProgressMonitor monitor) throws CoreException { monitor.beginTask("Creating package " + String.join(".", path), path.length); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(containerPath); if (!resource.exists() || !(resource instanceof IContainer)) { throwCoreException("Container \"" + containerPath + "\" does not exist."); } IContainer container = (IContainer) resource; for(int i = 0; i < path.length; i++) { Path p = new Path(path[i]); final IFolder folder = container.getFolder(p); if(!folder.exists()) folder.create(true, false, monitor); container = container.getFolder(p); monitor.worked(1); } }
private static void redirectStandardStreams() throws FileNotFoundException { in = System.in; out = System.out; err = System.err; System.setIn(new ByteArrayInputStream(new byte[0])); boolean isDebug = Boolean.getBoolean("jdt.ls.debug"); if (isDebug) { String id = "jdt.ls-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); File workspaceFile = root.getRawLocation().makeAbsolute().toFile(); File rootFile = new File(workspaceFile, ".metadata"); rootFile.mkdirs(); File outFile = new File(rootFile, ".out-" + id + ".log"); FileOutputStream stdFileOut = new FileOutputStream(outFile); System.setOut(new PrintStream(stdFileOut)); File errFile = new File(rootFile, ".error-" + id + ".log"); FileOutputStream stdFileErr = new FileOutputStream(errFile); System.setErr(new PrintStream(stdFileErr)); } else { System.setOut(new PrintStream(new ByteArrayOutputStream())); System.setErr(new PrintStream(new ByteArrayOutputStream())); } }
public static IJavaProject getJavaProject(final IPath path) { final IJavaProject[] javaProjects = getJavaProjects(); for (final IJavaProject javaProject : javaProjects) { final IPath fullPath = javaProject.getProject().getFullPath(); if (fullPath.equals(path)) { return javaProject; } } final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IContainer container = root.getContainerForLocation(path); if (container != null) { return getJavaProject(container); } container = root.getContainerForLocation(root.getLocation().append(path)); return getJavaProject(container); }
/** * Setup before test. * @throws Exception exception */ @Before public void setUp() throws Exception { String data = "package test_proj;\n\npublic class newClass {\n\n}"; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); project = root.getProject(TestUtils.generateRandomStr(5)); if (!project.exists()) { project.create(null); } if (!project.isOpen()) { project.open(null); } file = project.getFile("test.java"); if (!file.exists()) { byte[] bytes = data.getBytes(); InputStream source = new ByteArrayInputStream(bytes); file.create(source, IResource.NONE, null); } removeMarkers = new RemoveMarkers(); }
private boolean isSourcePath(String path) throws JavaModelException, BackingStoreException { Path pp = new File(instance.getWorkspaceRoot().toString() + File.separator + path).toPath(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (IClasspathEntry entry : project.getRawClasspath()) { if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IResource res = root.findMember(entry.getPath()); if (res != null) { String file = res.getLocation().toOSString(); if (!file.isEmpty() && pp.startsWith(file)) { IPath[] inclusionPatterns = entry.getInclusionPatterns(); if (!matchPatterns(pp, entry.getExclusionPatterns()) && (inclusionPatterns == null || inclusionPatterns.length == 0 || matchPatterns(pp, inclusionPatterns))) { return true; } } } } } return false; }
/** * 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); }
@Test public void testTriggerRespectsAutoBuilding() { XtextBuildTrigger buildTrigger = get(XtextBuildTrigger.class); // auto-build disabled when(workspace.isAutoBuilding()).thenReturn(false); buildTrigger.scheduleFullBuild(); verify(scheduler, never()).scheduleBuildIfNecessary(Matchers.<Iterable<IProject>> any(), Matchers.<IBuildFlag> any()); reset(workspace); reset(scheduler); // auto-build enabled IWorkspaceRoot root = mock(IWorkspaceRoot.class); IProject[] projects = new IProject[0]; when(workspace.isAutoBuilding()).thenReturn(true); when(workspace.getRoot()).thenReturn(root); when(root.getProjects()).thenReturn(projects); buildTrigger.scheduleFullBuild(); verify(scheduler).scheduleBuildIfNecessary(eq(Arrays.asList(projects)), Matchers.<IBuildFlag[]> anyVararg()); }
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 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); } } }
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 updateProjects() { WPILibJavaPlugin.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.jdt.core.javanature")){ updateVariables(project); } else { } } catch (CoreException e) { WPILibJavaPlugin.logError("Error updating projects.", e); } } }
/** * Given a base URI, figure out which {@link IFolder}, if any, it refers to. * * @param baseURI * to find the folder(s) for; must not be {@code null} * @return an array of all folders mapping to that URI, or an empty array if none do. */ private static IContainer[] determineContainersToCheck(final URI baseURI) { Preconditions.checkNotNull(baseURI); IContainer[] result = {}; if (baseURI.isPlatformResource() || baseURI.isFile()) { IWorkspaceRoot workspace = EcorePlugin.getWorkspaceRoot(); if (workspace != null) { if (baseURI.isFile()) { result = workspace.findContainersForLocationURI(java.net.URI.create(baseURI.toString())); } else { // Must be a platform/resource URI IPath platformPath = new Path(baseURI.toPlatformString(true)); IFolder folder = workspace.getFolder(platformPath); if (folder != null) { result = new IContainer[] {folder}; } } } } return result; }
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; }
@Test public void testWorkspaceSettings() throws Exception { Map<String, String> env = new HashMap<>(); Properties sysprops = new Properties(); File file = null; try { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); File rootFile = root.getLocation().toFile(); file = new File(rootFile, "fakeGradleHome"); sysprops.setProperty(GradleProjectImporter.GRADLE_HOME, file.getAbsolutePath()); boolean overrideWorkspaceSettings = GradleProjectImporter.getGradleHomeFile(env, sysprops) != null; assertFalse(overrideWorkspaceSettings); file.mkdir(); file.deleteOnExit(); overrideWorkspaceSettings = GradleProjectImporter.getGradleHomeFile(env, sysprops) != null; assertTrue(overrideWorkspaceSettings); } finally { if (file != null) { file.delete(); } } }
@Override public IResource[] getAllResourcesForLocation( final IPath location, final IWorkspaceRoot root, final boolean mustExist) { IFile[] files = root.findFilesForLocation(location); if (mustExist && files != null) { final List<IFile> existingFiles = new ArrayList<IFile>(); for (int i = 0; i < files.length; i++) { if (files[i].exists()) { existingFiles.add(files[i]); } } files = existingFiles.toArray(new IFile[existingFiles.size()]); } return files; }
@Override public IResource[] getAllResourcesForLocation( final IPath location, final IWorkspaceRoot root, final boolean mustExist) { IContainer[] containers = root.findContainersForLocation(location); if (mustExist && containers != null) { final List<IContainer> existingContainers = new ArrayList<IContainer>(); for (int i = 0; i < containers.length; i++) { if (containers[i].exists()) { existingContainers.add(containers[i]); } } containers = existingContainers.toArray(new IContainer[existingContainers.size()]); } return containers; }
@Override public IResource[] getAllResourcesForLocation( final IPath location, final IWorkspaceRoot root, final boolean mustExist) { if (!mustExist) { throw new IllegalArgumentException("mustExist==false is not compatible with ResourceType.ANY"); //$NON-NLS-1$ } final List<IResource> resources = new ArrayList<IResource>(); resources.addAll(Arrays.asList(FILE.getAllResourcesForLocation(location, root, true))); resources.addAll(Arrays.asList(CONTAINER.getAllResourcesForLocation(location, root, true))); return resources.toArray(new IResource[resources.size()]); }
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; }