|
| 1 | +package de.vogella.jdt.addclasspath.handlers; |
| 2 | + |
| 3 | +import org.eclipse.core.commands.AbstractHandler; |
| 4 | +import org.eclipse.core.commands.ExecutionEvent; |
| 5 | +import org.eclipse.core.commands.ExecutionException; |
| 6 | +import org.eclipse.core.resources.IProject; |
| 7 | +import org.eclipse.core.resources.IWorkspace; |
| 8 | +import org.eclipse.core.resources.IWorkspaceRoot; |
| 9 | +import org.eclipse.core.resources.ResourcesPlugin; |
| 10 | +import org.eclipse.core.runtime.CoreException; |
| 11 | +import org.eclipse.core.runtime.Path; |
| 12 | +import org.eclipse.jdt.core.IClasspathEntry; |
| 13 | +import org.eclipse.jdt.core.IJavaProject; |
| 14 | +import org.eclipse.jdt.core.JavaCore; |
| 15 | + |
| 16 | +public class SampleHandler extends AbstractHandler { |
| 17 | + |
| 18 | + public Object execute(ExecutionEvent event) throws ExecutionException { |
| 19 | + IWorkspace workspace = ResourcesPlugin.getWorkspace(); |
| 20 | + IWorkspaceRoot root = workspace.getRoot(); |
| 21 | + // Get all projects in the workspace |
| 22 | + IProject[] projects = root.getProjects(); |
| 23 | + // Loop over all projects |
| 24 | + for (IProject project : projects) { |
| 25 | + try { |
| 26 | + // Only work on open projects with the Java nature |
| 27 | + if (project.isOpen() |
| 28 | + && project |
| 29 | + .isNatureEnabled("org.eclipse.jdt.core.javanature")) { |
| 30 | + |
| 31 | + IJavaProject javaProject = JavaCore.create(project); |
| 32 | + IClasspathEntry[] entries = javaProject.getRawClasspath(); |
| 33 | + IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1]; |
| 34 | + |
| 35 | + System.arraycopy(entries, 0, newEntries, 0, entries.length); |
| 36 | + |
| 37 | + // add a new entry using the path to the container |
| 38 | + Path junitPath = new Path( |
| 39 | + "org.eclipse.jdt.junit.JUNIT_CONTAINER/4"); |
| 40 | + IClasspathEntry junitEntry = JavaCore |
| 41 | + .newContainerEntry(junitPath); |
| 42 | + newEntries[entries.length] = JavaCore |
| 43 | + .newContainerEntry(junitEntry.getPath()); |
| 44 | + javaProject.setRawClasspath(newEntries, null); |
| 45 | + } |
| 46 | + } catch (CoreException e) { |
| 47 | + e.printStackTrace(); |
| 48 | + } |
| 49 | + } |
| 50 | + return null; |
| 51 | + } |
| 52 | +} |
0 commit comments