Search in sources :

Example 66 with TextEdit

use of org.eclipse.text.edits.TextEdit in project liferay-ide by liferay.

the class NewLiferayModuleProjectOpMethods method addProperties.

@SuppressWarnings("unchecked")
public static boolean addProperties(File dest, List<String> properties) throws Exception {
    if (ListUtil.isEmpty(properties)) {
        return false;
    }
    try {
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        String readContents = FileUtil.readContents(dest, true);
        parser.setSource(readContents.toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setResolveBindings(true);
        CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
        cu.recordModifications();
        Document document = new Document(new String(readContents));
        cu.accept(new ASTVisitor() {

            @Override
            public boolean visit(NormalAnnotation node) {
                String qualifiedName = node.getTypeName().getFullyQualifiedName();
                if (qualifiedName.equals("Component")) {
                    ASTRewrite rewrite = ASTRewrite.create(cu.getAST());
                    AST ast = cu.getAST();
                    List<ASTNode> values = node.values();
                    boolean hasProperty = false;
                    for (ASTNode astNode : values) {
                        if (astNode instanceof MemberValuePair) {
                            MemberValuePair pairNode = (MemberValuePair) astNode;
                            String fullQualifiedName = pairNode.getName().getFullyQualifiedName();
                            if (fullQualifiedName.equals("property")) {
                                Expression express = pairNode.getValue();
                                if (express instanceof ArrayInitializer) {
                                    ListRewrite lrw = rewrite.getListRewrite(express, ArrayInitializer.EXPRESSIONS_PROPERTY);
                                    ArrayInitializer initializer = (ArrayInitializer) express;
                                    List<ASTNode> expressions = initializer.expressions();
                                    ASTNode propertyNode = null;
                                    for (int i = properties.size() - 1; i >= 0; i--) {
                                        StringLiteral stringLiteral = ast.newStringLiteral();
                                        stringLiteral.setLiteralValue(properties.get(i));
                                        if (ListUtil.isNotEmpty(expressions)) {
                                            propertyNode = expressions.get(expressions.size() - 1);
                                            lrw.insertAfter(stringLiteral, propertyNode, null);
                                        } else {
                                            lrw.insertFirst(stringLiteral, null);
                                        }
                                    }
                                }
                                hasProperty = true;
                            }
                        }
                    }
                    if (hasProperty == false) {
                        ListRewrite clrw = rewrite.getListRewrite(node, NormalAnnotation.VALUES_PROPERTY);
                        ASTNode lastNode = values.get(values.size() - 1);
                        ArrayInitializer newArrayInitializer = ast.newArrayInitializer();
                        MemberValuePair propertyMemberValuePair = ast.newMemberValuePair();
                        propertyMemberValuePair.setName(ast.newSimpleName("property"));
                        propertyMemberValuePair.setValue(newArrayInitializer);
                        clrw.insertBefore(propertyMemberValuePair, lastNode, null);
                        ListRewrite newLrw = rewrite.getListRewrite(newArrayInitializer, ArrayInitializer.EXPRESSIONS_PROPERTY);
                        for (String property : properties) {
                            StringLiteral stringLiteral = ast.newStringLiteral();
                            stringLiteral.setLiteralValue(property);
                            newLrw.insertAt(stringLiteral, 0, null);
                        }
                    }
                    try (OutputStream fos = Files.newOutputStream(dest.toPath())) {
                        TextEdit edits = rewrite.rewriteAST(document, null);
                        edits.apply(document);
                        fos.write(document.get().getBytes());
                        fos.flush();
                    } catch (Exception e) {
                        ProjectCore.logError(e);
                    }
                }
                return super.visit(node);
            }
        });
        return true;
    } catch (Exception e) {
        ProjectCore.logError("error when adding properties to " + dest.getAbsolutePath(), e);
        return false;
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) AST(org.eclipse.jdt.core.dom.AST) OutputStream(java.io.OutputStream) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) MemberValuePair(org.eclipse.jdt.core.dom.MemberValuePair) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) Expression(org.eclipse.jdt.core.dom.Expression) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ArrayList(java.util.ArrayList) List(java.util.List) ElementList(org.eclipse.sapphire.ElementList) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 67 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class OrganizeImportsCommand method organizeImportsInCompilationUnit.

public void organizeImportsInCompilationUnit(ICompilationUnit unit, WorkspaceEdit rootEdit) {
    try {
        InnovationContext context = new InnovationContext(unit, 0, unit.getBuffer().getLength() - 1);
        CUCorrectionProposal proposal = new CUCorrectionProposal("OrganizeImports", unit, IProposalRelevance.ORGANIZE_IMPORTS) {

            @Override
            protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
                CompilationUnit astRoot = context.getASTRoot();
                OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, null);
                editRoot.addChild(op.createTextEdit(null));
            }
        };
        addWorkspaceEdit(unit, proposal, rootEdit);
    } catch (CoreException e) {
        JavaLanguageServerPlugin.logException("Problem organize imports ", e);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) OrganizeImportsOperation(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation) CUCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.CUCorrectionProposal) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) InnovationContext(org.eclipse.jdt.ls.core.internal.corrections.InnovationContext) IDocument(org.eclipse.jface.text.IDocument)

Example 68 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class CompletionProposalReplacementProvider method addImports.

/**
 * Adds imports collected by importRewrite to item
 * @param item
 */
private void addImports(List<org.eclipse.lsp4j.TextEdit> additionalEdits) {
    if (this.importRewrite != null) {
        try {
            TextEdit edit = this.importRewrite.rewriteImports(new NullProgressMonitor());
            TextEditConverter converter = new TextEditConverter(this.compilationUnit, edit);
            additionalEdits.addAll(converter.convert());
        } catch (CoreException e) {
            JavaLanguageServerPlugin.logException("Error adding imports", e);
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) TextEditConverter(org.eclipse.jdt.ls.core.internal.TextEditConverter)

Example 69 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class ImportOrganizeTest method testStaticImports1.

@Test
public void testStaticImports1() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
    StringBuilder buf = new StringBuilder();
    buf.append("package pack1;\n");
    buf.append("\n");
    buf.append("import static java.lang.System.out;\n");
    buf.append("\n");
    buf.append("public class C {\n");
    buf.append("    public int foo() {\n");
    buf.append("        out.print(File.separator);\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("C.java", buf.toString(), false, null);
    String[] order = new String[] { "java", "pack", "#java" };
    IChooseImportQuery query = createQuery("C", new String[] {}, new int[] {});
    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());
        buf = new StringBuilder();
        buf.append("package pack1;\n");
        buf.append("\n");
        buf.append("import java.io.File;\n");
        buf.append("\n");
        buf.append("import static java.lang.System.out;\n");
        buf.append("\n");
        buf.append("public class C {\n");
        buf.append("    public int foo() {\n");
        buf.append("        out.print(File.separator);\n");
        buf.append("    }\n");
        buf.append("}\n");
        assertTrue(cu.getSource().equals(buf.toString()));
    } finally {
        cu.discardWorkingCopy();
    }
}
Also used : 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) AbstractMavenBasedTest(org.eclipse.jdt.ls.core.internal.managers.AbstractMavenBasedTest) Test(org.junit.Test)

Example 70 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class ImportOrganizeTest method testStaticImports2.

@Test
public void testStaticImports2() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
    StringBuilder buf = new StringBuilder();
    buf.append("package pack1;\n");
    buf.append("\n");
    buf.append("import static java.io.File.*;\n");
    buf.append("\n");
    buf.append("public class C {\n");
    buf.append("    public String foo() {\n");
    buf.append("        return pathSeparator + separator + File.separator;\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("C.java", buf.toString(), false, null);
    String[] order = new String[] { "#java.io.File", "java", "pack" };
    IChooseImportQuery query = createQuery("C", new String[] {}, new int[] {});
    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());
        buf = new StringBuilder();
        buf.append("package pack1;\n");
        buf.append("\n");
        buf.append("import static java.io.File.pathSeparator;\n");
        buf.append("import static java.io.File.separator;\n");
        buf.append("\n");
        buf.append("import java.io.File;\n");
        buf.append("\n");
        buf.append("public class C {\n");
        buf.append("    public String foo() {\n");
        buf.append("        return pathSeparator + separator + File.separator;\n");
        buf.append("    }\n");
        buf.append("}\n");
        assertTrue(cu.getSource().equals(buf.toString()));
    } finally {
        cu.discardWorkingCopy();
    }
}
Also used : 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) AbstractMavenBasedTest(org.eclipse.jdt.ls.core.internal.managers.AbstractMavenBasedTest) Test(org.junit.Test)

Aggregations

TextEdit (org.eclipse.text.edits.TextEdit)190 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)113 Test (org.junit.Test)49 IDocument (org.eclipse.jface.text.IDocument)48 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)48 BadLocationException (org.eclipse.jface.text.BadLocationException)34 Document (org.eclipse.jface.text.Document)33 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)32 UndoEdit (org.eclipse.text.edits.UndoEdit)26 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)23 InsertEdit (org.eclipse.text.edits.InsertEdit)22 CoreException (org.eclipse.core.runtime.CoreException)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)19 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)19 DeleteEdit (org.eclipse.text.edits.DeleteEdit)17 MoveSourceEdit (org.eclipse.text.edits.MoveSourceEdit)16 ArrayList (java.util.ArrayList)15 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)15 MoveTargetEdit (org.eclipse.text.edits.MoveTargetEdit)15 TextEditGroup (org.eclipse.text.edits.TextEditGroup)15