3

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.

8
  • 1
    Isn't this simply before you have multiple key bindings for Ctrl+Shift+O? Try unbinding the other one in Preferences, let's see if that helps. Commented Jan 23, 2014 at 8:16
  • Looks like you have two instances of AdGenaratorWizard set as the command handler. Commented Jan 23, 2014 at 8:34
  • thanks guys... @rlegendi I am not sure I can follow you. Unbinding the other one in Preferences in the sense? I haven't used the Ctrl+Shift+O option in preferences, if thats wat you mean... Commented Jan 23, 2014 at 9:13
  • @greg-449 there is only one handler named handler in my code. Commented Jan 23, 2014 at 9:15
  • The handler appears to have been created twice - there is AdGenaratorWizard$1@2b8e2b8e and AdGenaratorWizard$1@25f025f0 Commented Jan 23, 2014 at 9:19

1 Answer 1

6

I was on this for about a week and finally got it working... :)

try {
final IWorkbenchPartSite targetSite = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService()
.getActivePart().getSite();

    if(targetSite!=null){ 
    System.out.println("TargetSite obtained");
    organizeImports(wiProject, targetSite);
    }

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 



public void organizeImports(final IProject project, final IWorkbenchSite targetSite) throws CoreException {
Runnable job = new Runnable() {

@Override
public void run() {
    OrganizeImportsAction org = new OrganizeImportsAction(targetSite);
        try {
          IJavaProject prj = null;
          if (project.hasNature("org.eclipse.jdt.core.javanature")) {
          prj = JavaCore.create(project);
        }

        IStructuredSelection selection = new StructuredSelection(prj);
        org.run(selection);
             } catch (CoreException ce) {
        ce.printStackTrace();
    }

}

};
    this.getShell().getDisplay().syncExec(job);
}
Sign up to request clarification or add additional context in comments.

2 Comments

:) meanwhile where wiProject can be obtained as follows, IProject wiProject = ResourcesPlugin.getWorkspace().getRoot().getProject(myProjectName);
I was doing organize import and other proposals in one shot and facing some issues. This gave me new idea. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.