I have built an eclipse plugin, which would generate a new Java project with new classes.
Once the classes are generated, the plugin must traverse through each class and do an automatic "organize imports" action (It must be done programmatically - not by Eclipse SaveAction option).
I have tried a code segment for doing the same.
public void organizeImports(IProject iProj) {
try {
IPackageFragment[] packages = JavaCore.create(iProj)
.getPackageFragments();
for (IPackageFragment mypackage : packages) {
if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
for (ICompilationUnit currentCompilationUnit : mypackage
.getCompilationUnits()) {
try {
System.out.println("CompilationUnit: " + currentCompilationUnit);
IEditorPart editorPart = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().activate(editorPart);
final IHandlerService handlerService = (IHandlerService) PlatformUI
.getWorkbench().getService(
IHandlerService.class);
IHandler handler = new AbstractHandler() {
public Object execute(ExecutionEvent event)
throws ExecutionException {
System.out.println("Inside execute");
return null;
}
};
handlerService
.activateHandler(
"org.eclipse.jdt.ui.edit.text.java.organize.imports",
handler);
handlerService
.executeCommand(
"org.eclipse.jdt.ui.edit.text.java.organize.imports",
null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
Now it makes imports successfully for few classes, while for others it throws something like this
MESSAGE A handler conflict occurred.
This may disable some commands.!MESSAGE Conflict for 'org.eclipse.jdt.ui.edit.text.java.organize.imports':
HandlerActivation(commandId=org.eclipse.jdt.ui.edit.text.java.organize.imports,
handler=com.plugin.generator.wizard.AdGenaratorWizard$1@2b8e2b8e,expression=,sourcePriority=0)
HandlerActivation(commandId=org.eclipse.jdt.ui.edit.text.java.organize.imports,
handler=com.plugin.generator.wizard.AdGenaratorWizard$1@25f025f0,expression=,sourcePriority=0)
If you try to understand what exactly happens, supposing you would like to do a manual Organize Imports using "Ctrl+Shift+O", sometimes eclipse would prompt you with a window asking for selecting import statements to choose among similar packages. (For eg: Choose either "org.eclipse.ui.commands" OR "org.eclipse.core.commands") Now thats why the above said error message occurs.
When I try to run organize imports automatically through my code, it gets into a conflict of which import to choose and returns exception.
So is there any way to handle that? Hope u understand what exactly happens. Please suggest how I can do that.
Ctrl+Shift+O? Try unbinding the other one in Preferences, let's see if that helps.AdGenaratorWizardset as the command handler.handlerin my code.AdGenaratorWizard$1@2b8e2b8eandAdGenaratorWizard$1@25f025f0