Finding currently open files in Eclipse plugin - eclipse

I'm trying to create a plugin that annotates eclipse java projects based on external output. Currently, I'm traversing all of the open projects based on this tutorial: http://www.vogella.de/articles/EclipseJDT/article.html However, I'm looking for a way to get a full list of only the files that are currently open in the java editor. Is there a way or command for me to get that?

//get all active editor references,check if reference is of type java editor
IEditorReference[] ref = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
List<IEditorReference> javaEditors = new ArrayList<IEditorReference>();
for (IEditorReference reference : ref) {
if ("org.eclipse.jdt.ui.CompilationUnitEditor".equals(reference.getId())){
javaEditors.add(reference);
}
}

Related

Using Eclipse's JDT, how do I identify the classpath for a project?

I am writing a plug-in that will generate unit tests for a Java class that is selected in Eclipse's Project Explorer. This plug-in uses a third-party program called Randoop to generate the tests, so I make this happen using ProcessBuilder:
ProcessBuilder builder = new ProcessBuilder(command);
where the command that is passed to the ProcessBuilder is a list of Strings, something like
["java", "-classpath", "path1;path2;etc", "randoop.main.Main", ...]
Within the plug-in I am trying to generate the classpath for Randoop based on the classpath that Eclipse knows about. Here is some of what I have so far:
IClasspathEntry[] resolvedClasspath = javaProject.getResolvedClasspath(true);
for (IClasspathEntry entry : resolvedClasspath) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath outputLocation = entry.getOutputLocation();
if (outputLocation != null) {
buf.append(outputLocation.toString());
}
else {
buf.append(entry.getPath().toString());
}
}
else {
buf.append(entry.getPath().toString());
}
buf.append(CLASSPATH_SEP);
}
It isn't quite right. It seems to specify the library jar files okay, but doesn't do so well with identifying the paths to class files corresponding to CPE_SOURCE entries. For example, I see a classpath entry of /myPkgFragRoot/src/main/java instead of myPkgFragRoot/target/classes.
I seem to have a muddled picture of how Eclipse treats classpaths, so I'm looking for some help. Firstly, I'm wondering if my high-level approach is wrong. It seems like I am writing a large amount of code to generate an incorrect classpath. Is there some simpler way of getting a classpath from an IJavaProject than getting the results of getResolvedClasspath and iterating through them and manipulating the individual entries? Secondly, if there isn't a simpler way, how should I be locating the class files produced by building the project?
If the outputLocation is null, you have to use the default output location javaProject.getOutputLocation() instead of entry.getPath().
See Javadoc of IClasspathEntry.getOutputLocation():
Returns:
the full path [...], or null if using default output folder
If in Project > Properties: Java Build Path tab Source the check box Allow output folders for source folders is not checked, IClasspathEntry::getOutputLocation() will always return null.

How to add templates.xml using plugin?

Editor templates in eclipse can be imported from xml file. Instead of manually importing, wanted to create a plugin. Which will import the templates.xml kept in specified folder at start of the eclipse.
How this can be achieved?
You can use the JFace org.eclipse.jface.text.templates.persistence.TemplateReaderWriter to read a template.xml. Something like:
File file = .... file to read
TemplateReaderWriter reader = new TemplateReaderWriter();
InputStream input = new BufferedInputStream(new FileInputStream(file));
TemplatePersistenceData[] datas = reader.read(input, null);
(code to deal with errors and closing the input left out)
You can then put the data in a TemplateStore:
TemplateStore fTemplateStore = ... store to use
for (TemplatePersistenceData data: datas) {
fTemplateStore.add(data);
}
fTemplateStore.save();
The template store you use depends on which templates you are updating.
For the Java Editor template store you can get the store with
JavaPlugin.getDefault().getTemplateStore();
But the JavaPlugin is not part of the official Eclipse API.
The above code is a simplified version of the import code in org.eclipse.ui.texteditor.templates.TemplatePreferencePage

How to get the list of external tools in eclipse

Eclipse knows external tools (menu run->external tools) and I would like to show the list of external tools on a right click in my view so the user can select a tool which I then execute.
I however simply fail to find the external tools.
The code I have now dumps the commands (and there are plenty) but I do not find the external tools I created.
ICommandService commandService=PlatformUI.getWorkbench().getService(ICommandService.class);
Command[] allCommands = commandService.getDefinedCommands();
for(Command curCommand :allCommands) {
Category cat = curCommand.getCategory();
System.out.print(cat.getName()+" ");
System.out.println(curCommand.getName());
}
Where can I find a list of external tools?
Based on the info of greg I found the following to work in my case.
ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType type = manager.getLaunchConfigurationType("org.eclipse.ui.externaltools.ProgramLaunchConfigurationType"); //$NON-NLS-1$
ILaunchConfiguration[] lcs = manager.getLaunchConfigurations(type);
This works for program launch configurations because I use the key ("org.eclipse.ui.externaltools.ProgramLaunchConfigurationType".
If you do not know which type is your command use getLaunchConfigurationTypes() to find all types and list the names to find the Type you need.
There are plenty.

How to get .java file path to my eclipse plugin

I am developing a eclipse plugin to ease the development using a proprietary version control system.
Right now there is only a command prompt version of the system available for this VCS and its run in terminal. So from my eclipse plugin I want to provide a simple menu options to do the things like check-out and check-in and internally call these commands.
But to run these commands I need to pass the argument 'path' of the selected .java file in the editor/project explorer. How can I get the path of the source file to the plugin?
Get the current workbench page:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
the workbench page implements ISelectionService so you can get the current selection:
ISelection selection = page.getSelection();
this will generally by an IStructuredSelection (but you need to check)
IStructuredSelection sel = (IStructuredSelection)selection;
See if this adapts to an IFile:
Object selObject = sel.getFirstElement(); // or iterate through all the selection elements
IFile file = Platform.getAdapterManager().getAdapter(selObject, IFile.class);
if you get a file the full path is:
String location = file.getLocation().toOSString();
If the current part is an editor then the selection you receive might be a text string. So you need to deal with editors separately:
IWorkbenchPart activePart = page.getActivePart();
if (activePart instanceof IEditorPart)
{
IEditorInput input = ((IEditorPart)activePart).getEditorInput();
if (input instanceof IFileEditorInput)
{
IFile file = ((IFileEditorInput)input).getFile();
...
}
}

How can I create a custom project layout based on another eclipse plugin?

My ultimate goal is to create an eclipse plugin that sets up a PDT project, but with some added builders (and custom build scripts) as well as a specific folder layout (and different folders should be treated as source and some as regular folders).
I've looked at / followed eclipse plugin development tutorials, and ok. I get the gist of creating a wizard that creates a file, but I'm having trouble trying to figure out how to create a project, and more importantly, make that project associated with the PDT (PHP Development Tools) feature.
Answer:
I did stumble upon a solution myself before the answer was given, but it's quite similar.
First, WizardNewProjectCreationPage was used as the first page of my wizard.
Second, on performFinish() I ran the following code:
IProgressMonitor m = new NullProgressMonitor();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(_pageOne.getProjectName());
if (!project.exists())
{
IProjectDescription desc = project.getWorkspace().newProjectDescription(project.getName());
URI projectLocation = _pageOne.getLocationURI();
// desc.setLocationURI(projectLocation);
String[] natures = desc.getNatureIds();
String[] newNatures = new String[natures.length + 1];
System.arraycopy(natures, 0, newNatures, 0, natures.length);
newNatures[natures.length] = PHPNature.ID;
desc.setNatureIds(newNatures);
project.create(desc, m);
project.open(m);
}
how to create a project
Take a look at BasicNewProjectResourceWizard.createNewProject() method.
make that project associated with the PDT (PHP Development Tools) feature
You need to add "org.eclipse.php.core.PHPNature" to the project (that's what Add PHP Support... action does). Use IProjectDescription.setNatureIds().