Example usage for org.eclipse.jdt.core.dom CompilationUnit rewrite

List of usage examples for org.eclipse.jdt.core.dom CompilationUnit rewrite

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom CompilationUnit rewrite.

Prototype

public TextEdit rewrite(IDocument document, Map options) 

Source Link

Document

Converts all modifications recorded for this compilation unit into an object representing the corresponding text edits to the given document containing the original source code for this compilation unit.

Usage

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTQuickFix.java

License:Open Source License

@Override
protected void finishFixingMarkers(final CompilationUnit ast, final IDocument document, final Map<?, ?> options)
        throws BadLocationException {
    ast.rewrite(document, options).apply(document);
}

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTQuickFixTestCase.java

License:Open Source License

private String rewriteAST(final org.eclipse.jface.text.Document document, final CompilationUnit ast)
        throws BadLocationException {
    final TextEdit edit = ast.rewrite(document, getRewriteOptions());
    edit.apply(document);/*from  www. j a  v a  2  s .c  om*/
    return document.get();
}

From source file:com.alex.example.fixlicense.actions.SampleAction.java

License:Open Source License

private void processInlineLicense(IDocument doc) throws Exception {
    CompilationUnit cu = getAST(doc);
    cu.recordModifications();//from w  ww  .j a v a  2 s.co m
    AST ast = cu.getAST();

    if (cu.types().get(0) instanceof TypeDeclaration) {
        TypeDeclaration td = (TypeDeclaration) cu.types().get(0);
        FieldDeclaration[] fd = td.getFields();
        if (fd.length == 0) {
            td.bodyDeclarations().add(0, createLiceseInLineField(ast));
        } else {
            FieldDeclaration firstFd = fd[0];
            VariableDeclarationFragment vdf = (VariableDeclarationFragment) firstFd.fragments().get(0);
            if (vdf.getName().getIdentifier().equals("COPYRIGHT")) {
                td.bodyDeclarations().remove(0);
                td.bodyDeclarations().add(0, createLiceseInLineField(ast));
            } else {
                td.bodyDeclarations().add(0, createLiceseInLineField(ast));
            }
        }
    }

    //record changes
    TextEdit edits = cu.rewrite(doc, null);
    edits.apply(doc);
}

From source file:com.ashigeru.eclipse.util.jdt.internal.ui.handlers.InsertAssertionHandler.java

License:Apache License

private TextEdit createEdit(CompilationUnit ast, MethodDeclaration method, IDocument target) {
    assert ast != null;
    assert method != null;
    assert target != null;
    List<String> objectParams = new ArrayList<String>();
    for (Object o : method.parameters()) {
        SingleVariableDeclaration var = (SingleVariableDeclaration) o;
        if (var.getType().getNodeType() != ASTNode.PRIMITIVE_TYPE) {
            objectParams.add(var.getName().getIdentifier());
        }//www. ja  v a2  s .  c om
    }
    if (objectParams.isEmpty()) {
        return null;
    }
    AST factory = ast.getAST();
    ast.recordModifications();
    List<Statement> toInsert = new ArrayList<Statement>();
    for (String name : objectParams) {
        AssertStatement assertion = createAssertion(factory, name);
        toInsert.add(assertion);
    }

    Block body = method.getBody();
    @SuppressWarnings("unchecked")
    List<Statement> statements = body.statements();

    int offset = 0;
    if (statements.isEmpty() == false) {
        Statement first = statements.get(0);
        int type = first.getNodeType();
        if (type == ASTNode.CONSTRUCTOR_INVOCATION || type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
            offset++;
        }
    }

    statements.addAll(offset, toInsert);

    return ast.rewrite(target, null);
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaFileModelAdapter.java

License:Open Source License

@Override
protected TextEdit rewrite(Document document, Object fileInfo) {
    CompilationUnit cu = (CompilationUnit) fileInfo;
    return cu.rewrite(document, null);
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * @flowerModelElementId _zVs8PpiOEd6aNMdNFvR5WQ
 *///from w  w  w .  j a v a2 s. c  o  m
public static void writeJavafile(CompilationUnit cUnit, IFile file) {
    // TODO ::plus numele packetului?
    String sourceCode = null;
    try {
        Document doc = null;
        if (file.exists())
            doc = new Document(getFileContent(file));
        else
            doc = new Document();

        TextEdit edits = cUnit.rewrite(doc, null);
        edits.apply(doc);
        sourceCode = doc.get();

        if (sourceCode.getBytes().length == 0)
            throw new IllegalArgumentException("java sourcecode.getBytes length = 0 ");
        ByteArrayInputStream bais = new ByteArrayInputStream(sourceCode.getBytes());
        if (!file.exists())
            file.create(bais, true, null);
        else // keep the 3rd flag true! keeps history
            file.setContents(bais, true, true, null);
        bais.close();
    } catch (Exception e) {
        throw new RuntimeException("Could not write Java file: " + file.getFullPath(), e);
    }
}

From source file:com.ecfeed.ui.common.EclipseModelImplementer.java

License:Open Source License

private void saveChanges(CompilationUnit unit, IPath location) throws CoreException {
    ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
    ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(location, LocationKind.LOCATION);
    IDocument document = textFileBuffer.getDocument();
    TextEdit edits = unit.rewrite(document, null);
    try {//from  w ww  . j a va2  s  .  c o  m
        edits.apply(document);
        textFileBuffer.commit(null, false);
        bufferManager.disconnect(location, LocationKind.LOCATION, null);
        refreshWorkspace();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:com.google.devtools.j2cpp.J2ObjC.java

License:Open Source License

/**
 * Removes dead types and methods, declared in a dead code map.
 *
 * @param unit the compilation unit created by ASTParser
 * @param source the Java source used by ASTParser
 * @return the rewritten source//  w w  w  . ja  va 2 s  . c o  m
 * @throws AssertionError if the dead code eliminator makes invalid edits
 */
public static String removeDeadCode(CompilationUnit unit, String source) {
    if (Options.getDeadCodeMap() == null) {
        return source;
    }
    logger.finest("removing dead code");
    new DeadCodeEliminator(Options.getDeadCodeMap()).run(unit);

    Document doc = new Document(source);
    TextEdit edit = unit.rewrite(doc, Options.getCompilerOptions());
    try {
        edit.apply(doc);
    } catch (MalformedTreeException e) {
        throw new AssertionError(e);
    } catch (BadLocationException e) {
        throw new AssertionError(e);
    }
    return doc.get();
}

From source file:com.google.devtools.j2cpp.J2ObjC.java

License:Open Source License

/**
 * Translates a parsed source file, modifying the compilation unit by
 * substituting core Java type and method references with iOS equivalents.
 * For example, <code>java.lang.Object</code> maps to <code>NSObject</code>,
 * and <code>java.lang.String</code> to <code>NSString</code>. The source is
 * also modified to add support for iOS memory management, extract inner
 * classes, etc.//from   w  w w  .  j ava2  s  .co m
 * <p>
 * Note: the returned source file doesn't need to be re-parsed, since the
 * compilation unit already reflects the changes (it's useful, though,
 * for dumping intermediate stages).
 * </p>
 *
 * @param unit the compilation unit created by ASTParser
 * @param source the Java source used by ASTParser
 * @return the rewritten source
 * @throws AssertionError if the translator makes invalid edits
 */
public static String translate(CompilationUnit unit, String source) {

    // Update code that has GWT references.
    new GwtConverter().run(unit);

    // Modify AST to be more compatible with Objective C
    new Rewriter().run(unit);

    // Add auto-boxing conversions.
    new Autoboxer(unit.getAST()).run(unit);

    // Normalize init statements
    new InitializationNormalizer().run(unit);

    // Extract inner and anonymous classes
    new AnonymousClassConverter(unit).run(unit);
    new InnerClassExtractor(unit).run(unit);

    // Translate core Java type use to similar iOS types
    new JavaToIOSTypeConverter().run(unit);
    Map<String, String> methodMappings = Options.getMethodMappings();
    if (methodMappings.isEmpty()) {
        // Method maps are loaded here so tests can call translate() directly.
        loadMappingFiles();
    }
    new JavaToIOSMethodTranslator(unit.getAST(), methodMappings).run(unit);

    // Add dealloc/finalize method(s), if necessary.  This is done
    // after inner class extraction, so that each class releases
    // only its own instance variables.
    new DestructorGenerator().run(unit);

    //    for (Plugin plugin : Options.getPlugins()) {
    //      plugin.processUnit(unit);
    //    }

    // Verify all modified nodes have type bindings
    Types.verifyNode(unit);

    Document doc = new Document(source);
    TextEdit edit = unit.rewrite(doc, Options.getCompilerOptions());
    try {
        edit.apply(doc);
    } catch (MalformedTreeException e) {
        throw new AssertionError(e);
    } catch (BadLocationException e) {
        throw new AssertionError(e);
    }
    return doc.get();
}

From source file:com.google.devtools.j2objc.DeadCodeProcessor.java

License:Apache License

@VisibleForTesting
public static String rewriteSource(String source, CompilationUnit unit, DeadCodeMap deadCodeMap,
        TimeTracker ticker) {//ww  w.j a  va2 s.co  m
    unit.recordModifications();
    new DeadCodeEliminator(deadCodeMap).run(unit);
    ticker.tick("Dead code eliminator pass");

    Document doc = new Document(source);
    TextEdit edit = unit.rewrite(doc, null);
    try {
        edit.apply(doc);
    } catch (MalformedTreeException e) {
        throw new AssertionError(e);
    } catch (BadLocationException e) {
        throw new AssertionError(e);
    }
    String newSource = doc.get();
    ticker.tick("Rewrite source");
    return newSource;
}