uma
uma

Reputation: 327

Java Imports Programmatically

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.

Upvotes: 3

Views: 1198

Answers (1)

uma
uma

Reputation: 327

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);
}

Upvotes: 6

Related Questions