Search in sources :

Example 6 with OrganizeImportsOperation

use of org.eclipse.jdt.core.manipulation.OrganizeImportsOperation in project eclipse.jdt.ls by eclipse.

the class OrganizeImportsHandler method organizeImports.

public static TextEdit organizeImports(ICompilationUnit unit, Function<ImportSelection[], ImportCandidate[]> chooseImports, IProgressMonitor monitor) {
    if (unit == null) {
        return null;
    }
    CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor);
    if (astRoot == null) {
        return null;
    }
    OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, (TypeNameMatch[][] openChoices, ISourceRange[] ranges) -> {
        List<ImportSelection> selections = new ArrayList<>();
        for (int i = 0; i < openChoices.length; i++) {
            ImportCandidate[] candidates = Stream.of(openChoices[i]).map((choice) -> new ImportCandidate(choice)).toArray(ImportCandidate[]::new);
            Range range = null;
            try {
                range = JDTUtils.toRange(unit, ranges[i].getOffset(), ranges[i].getLength());
            } catch (JavaModelException e) {
                range = JDTUtils.newRange();
            }
            // TODO Sort the ambiguous candidates based on a relevance score.
            selections.add(new ImportSelection(candidates, range));
        }
        ImportCandidate[] chosens = chooseImports.apply(selections.toArray(new ImportSelection[0]));
        if (chosens == null) {
            return null;
        }
        Map<String, TypeNameMatch> typeMaps = new HashMap<>();
        Stream.of(openChoices).flatMap(x -> Arrays.stream(x)).forEach(x -> {
            typeMaps.put(x.getFullyQualifiedName() + "@" + x.hashCode(), x);
        });
        return Stream.of(chosens).filter(chosen -> chosen != null && typeMaps.containsKey(chosen.id)).map(chosen -> typeMaps.get(chosen.id)).toArray(TypeNameMatch[]::new);
    });
    try {
        JobHelpers.waitForJobs(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
        TextEdit edit = op.createTextEdit(null);
        // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=283287
        // and https://github.com/redhat-developer/vscode-java/issues/1472
        TextEdit staticEdit = wrapStaticImports(edit, astRoot, unit);
        if (staticEdit.getChildrenSize() == 0) {
            return null;
        }
        return staticEdit;
    } catch (OperationCanceledException | CoreException e) {
        JavaLanguageServerPlugin.logException("Failed to resolve organize imports source action", e);
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) Signature(org.eclipse.jdt.core.Signature) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) InsertEdit(org.eclipse.text.edits.InsertEdit) JavaModelException(org.eclipse.jdt.core.JavaModelException) HashMap(java.util.HashMap) CoreException(org.eclipse.core.runtime.CoreException) JobHelpers(org.eclipse.jdt.ls.core.internal.JobHelpers) Range(org.eclipse.lsp4j.Range) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ImportReferencesCollector(org.eclipse.jdt.core.manipulation.ImportReferencesCollector) SourceAssistProcessor(org.eclipse.jdt.ls.core.internal.text.correction.SourceAssistProcessor) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) OrganizeImportsOperation(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation) Gson(com.google.gson.Gson) Map(java.util.Map) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) SimilarElementsRequestor(org.eclipse.jdt.ls.core.internal.corrections.SimilarElementsRequestor) Name(org.eclipse.jdt.core.dom.Name) JavaClientConnection(org.eclipse.jdt.ls.core.internal.JavaClientConnection) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) JSONUtility(org.eclipse.jdt.ls.core.internal.JSONUtility) IJavaProject(org.eclipse.jdt.core.IJavaProject) ISourceRange(org.eclipse.jdt.core.ISourceRange) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) CodeStyleConfiguration(org.eclipse.jdt.core.manipulation.CodeStyleConfiguration) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) TextEdit(org.eclipse.text.edits.TextEdit) IBinding(org.eclipse.jdt.core.dom.IBinding) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) JavaModelUtil(org.eclipse.jdt.internal.corext.util.JavaModelUtil) List(java.util.List) Stream(java.util.stream.Stream) CoreASTProvider(org.eclipse.jdt.core.manipulation.CoreASTProvider) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) AST(org.eclipse.jdt.core.dom.AST) DeleteEdit(org.eclipse.text.edits.DeleteEdit) JavaModelException(org.eclipse.jdt.core.JavaModelException) HashMap(java.util.HashMap) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) Range(org.eclipse.lsp4j.Range) ISourceRange(org.eclipse.jdt.core.ISourceRange) OrganizeImportsOperation(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit)

Example 7 with OrganizeImportsOperation

use of org.eclipse.jdt.core.manipulation.OrganizeImportsOperation in project eclipse.jdt.ls by eclipse.

the class SourceAssistProcessor method getOrganizeImportsProposal.

private TextEdit getOrganizeImportsProposal(IInvocationContext context, IProgressMonitor monitor) {
    ICompilationUnit unit = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, null);
    try {
        TextEdit edit = op.createTextEdit(monitor);
        TextEdit staticEdit = OrganizeImportsHandler.wrapStaticImports(edit, astRoot, unit);
        if (staticEdit.getChildrenSize() > 0) {
            return staticEdit;
        }
        return edit;
    } catch (OperationCanceledException | CoreException e) {
        JavaLanguageServerPlugin.logException("Resolve organize imports source action", e);
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) OrganizeImportsOperation(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException)

Example 8 with OrganizeImportsOperation

use of org.eclipse.jdt.core.manipulation.OrganizeImportsOperation in project eclipse.jdt.ls by eclipse.

the class ImportOrganizeTest method test1WithOrder.

@Test
public void test1WithOrder() throws Exception {
    requireJUnitSources();
    ICompilationUnit cu = (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
    assertNotNull("BaseTestRunner.java is missing", cu);
    IPackageFragmentRoot root = (IPackageFragmentRoot) cu.getParent().getParent();
    IPackageFragment pack = root.createPackageFragment("mytest", true, null);
    ICompilationUnit colidingCU = pack.getCompilationUnit("TestListener.java");
    colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
    String[] order = new String[] { "junit", "java.text", "java.io", "java" };
    IChooseImportQuery query = createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
    OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
    TextEdit edit = op.createTextEdit(new NullProgressMonitor());
    IDocument document = new Document(cu.getSource());
    edit.apply(document);
    try {
        cu.becomeWorkingCopy(new NullProgressMonitor());
        cu.getBuffer().setContents(document.get());
        cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
        // @formatter:off
        assertImports(cu, new String[] { "junit.framework.AssertionFailedError", "junit.framework.Test", "junit.framework.TestListener", "junit.framework.TestSuite", "java.text.NumberFormat", "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream", "java.io.FileOutputStream", "java.io.IOException", "java.io.InputStream", "java.io.PrintWriter", "java.io.StringReader", "java.io.StringWriter", "java.lang.reflect.InvocationTargetException", "java.lang.reflect.Method", "java.lang.reflect.Modifier", "java.util.Properties" });
    // @formatter:on
    } finally {
        cu.discardWorkingCopy();
    }
}
Also used : Path(org.eclipse.core.runtime.Path) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) OrganizeImportsOperation(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation) TextEdit(org.eclipse.text.edits.TextEdit) IChooseImportQuery(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation.IChooseImportQuery) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) AbstractMavenBasedTest(org.eclipse.jdt.ls.core.internal.managers.AbstractMavenBasedTest) Test(org.junit.Test)

Aggregations

ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)8 OrganizeImportsOperation (org.eclipse.jdt.core.manipulation.OrganizeImportsOperation)8 TextEdit (org.eclipse.text.edits.TextEdit)8 IDocument (org.eclipse.jface.text.IDocument)6 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)5 CoreException (org.eclipse.core.runtime.CoreException)4 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4 IChooseImportQuery (org.eclipse.jdt.core.manipulation.OrganizeImportsOperation.IChooseImportQuery)4 AbstractMavenBasedTest (org.eclipse.jdt.ls.core.internal.managers.AbstractMavenBasedTest)4 Document (org.eclipse.jface.text.Document)4 Test (org.junit.Test)4 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)2 Path (org.eclipse.core.runtime.Path)2 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)2 Gson (com.google.gson.Gson)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 List (java.util.List)1