Example usage for org.eclipse.jdt.core.dom.rewrite ASTRewrite track

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

Introduction

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

Prototype

public final ITrackedNodePosition track(ASTNode node) 

Source Link

Document

Returns an object that tracks the source range of the given node across the rewrite to its AST.

Usage

From source file:com.google.gwt.eclipse.core.markers.quickfixes.ChangeAsyncMethodReturnTypeProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
    AST ast = targetAstRoot.getAST();//from  w  w w .ja  v a2s.co  m
    createImportRewrite(targetAstRoot);

    ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

    // Find the method declaration in the AST we just generated (the one that
    // the AST rewriter is hooked up to).
    MethodDeclaration rewriterAstMethodDecl = JavaASTUtils.findMethodDeclaration(targetAstRoot,
            methodDecl.resolveBinding().getKey());
    if (rewriterAstMethodDecl == null) {
        return null;
    }

    // Set up the list of valid return types
    List<ITypeBinding> validReturnTypeBindings = new ArrayList<ITypeBinding>();
    validReturnTypeBindings.add(ast.resolveWellKnownType("void"));

    IJavaProject javaProject = getCompilationUnit().getJavaProject();
    ITypeBinding requestBinding = JavaASTUtils.resolveType(javaProject, "com.google.gwt.http.client.Request");
    if (requestBinding != null) {
        validReturnTypeBindings.add(requestBinding);
    }
    ITypeBinding requestBuilderBinding = JavaASTUtils.resolveType(javaProject,
            "com.google.gwt.http.client.RequestBuilder");
    if (requestBuilderBinding != null) {
        validReturnTypeBindings.add(requestBuilderBinding);
    }

    // Set default proposal return type
    Type newReturnType = getImportRewrite().addImport(validReturnTypeBindings.get(0), ast);
    rewrite.replace(rewriterAstMethodDecl.getReturnType2(), newReturnType, null);

    // Use linked mode to choose from one of the other valid return types
    String key = "return_type";
    addLinkedPosition(rewrite.track(newReturnType), true, key);
    for (ITypeBinding binding : validReturnTypeBindings) {
        addLinkedPositionProposal(key, binding);
    }

    return rewrite;
}

From source file:com.gowan.plugin.handlers.JUnit3Handler.java

License:Open Source License

/**
 * /*from ww  w.  j a  v  a2 s .  co  m*/
 * @param unit
 * @throws JavaModelException
 */
private void createAST(ICompilationUnit unit) throws JavaModelException {
    CompilationUnit parse = parse(unit);
    JUnit3Visitor visitor = new JUnit3Visitor();
    parse.accept(visitor);

    IDocument doc = new Document(unit.getSource());
    AST ast = parse.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    JUnit3 junit = visitor.getJUnit3();

    TypeDeclaration td = (TypeDeclaration) parse.types().get(0);
    ITrackedNodePosition tdLocation = rewrite.track(td);

    if (junit.getKlass() != null) {
        rewrite.replace(td.getSuperclassType(), null, null);
    } else {
        return; // Skip if the class does not extend junit.framework.TestCase
    }

    //         imports
    ImportDeclaration afterImport = ast.newImportDeclaration();
    afterImport.setName(ast.newName(AFTER));
    ImportDeclaration beforeImport = ast.newImportDeclaration();
    beforeImport.setName(ast.newName(BEFORE));
    ImportDeclaration testImport = ast.newImportDeclaration();
    testImport.setName(ast.newName(TEST));

    ListRewrite lrw = rewrite.getListRewrite(parse, CompilationUnit.IMPORTS_PROPERTY);
    if (junit.getTestCaseImport() != null) {
        lrw.remove(junit.getTestCaseImport(), null);

        lrw.insertLast(afterImport, null);
        lrw.insertLast(beforeImport, null);
        lrw.insertLast(testImport, null);
    }

    if (junit.getSetUp() != null) {
        transformSetUp(ast, rewrite, junit);
    }
    if (junit.getTearDown() != null) {
        transformTearDown(ast, rewrite, junit);
    }
    if (junit.getTest() != null && !junit.getTest().isEmpty()) {
        transformTest(ast, rewrite, junit);
    }

    TextEdit edits = rewrite.rewriteAST(doc, null);

    unit.applyTextEdit(edits, null);

}

From source file:edu.illinois.compositerefactorings.refactorings.copymembertosubtype.CopyMemberToSubtypeRefactoringProcessor.java

License:Open Source License

/**
 * {@link org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor#copyBodyOfPushedDownMethod(ASTRewrite, IMethod, MethodDeclaration, MethodDeclaration, TypeVariableMaplet[])}
 *//*  w  w w . j  av a 2s . co  m*/
private void copyBodyOfPushedDownMethod(ASTRewrite targetRewrite, IMethod method, MethodDeclaration oldMethod,
        MethodDeclaration newMethod, TypeVariableMaplet[] mapping) throws JavaModelException {
    Block body = oldMethod.getBody();
    if (body == null) {
        newMethod.setBody(null);
        return;
    }
    try {
        final IDocument document = new Document(method.getCompilationUnit().getBuffer().getContents());
        final ASTRewrite rewriter = ASTRewrite.create(body.getAST());
        final ITrackedNodePosition position = rewriter.track(body);
        body.accept(new TypeVariableMapper(rewriter, mapping));
        rewriter.rewriteAST(document, getDeclaringType().getCompilationUnit().getJavaProject().getOptions(true))
                .apply(document, TextEdit.NONE);
        String content = document.get(position.getStartPosition(), position.getLength());
        String[] lines = Strings.convertIntoLines(content);
        Strings.trimIndentation(lines, method.getJavaProject(), false);
        content = Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method));
        newMethod.setBody((Block) targetRewrite.createStringPlaceholder(content, ASTNode.BLOCK));
    } catch (MalformedTreeException exception) {
        JavaPlugin.log(exception);
    } catch (BadLocationException exception) {
        JavaPlugin.log(exception);
    }
}

From source file:jmockit.assist.MockMethodCompletionProposal.java

License:Open Source License

private String generateMethodDeclaration(final IDocument document, final Document recoveredDocument,
        final ASTNode node, final ASTRewrite rewrite, final CodeGenerationSettings settings,
        final MethodDeclaration stub) throws BadLocationException {
    ChildListPropertyDescriptor descriptor = getPropDescriptor(node);
    ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
    rewriter.insertFirst(stub, null);/*  ww w .java2s. co  m*/

    ITrackedNodePosition position = rewrite.track(stub);

    rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);

    String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());

    int generatedIndent = IndentManipulation.measureIndentUnits(
            getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
            settings.indentWidth);

    String indent = getIndentAt(document, getReplacementOffset(), settings);
    String methodDeclarationText = IndentManipulation.changeIndent(generatedCode, generatedIndent,
            settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document));

    return methodDeclarationText;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.UnresolvedElementsSubProcessor.java

License:Open Source License

private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot,
        ITypeBinding binding, SimpleName node, boolean isWriteAccess, Collection proposals) {
    int kind = ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
    if (!isWriteAccess) {
        kind |= ScopeAnalyzer.METHODS; // also try to find similar methods
    }//from w  ww  .ja  v a 2  s .  com

    IBinding[] varsAndMethodsInScope = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
    if (varsAndMethodsInScope.length > 0) {
        // avoid corrections like int i= i;
        String otherNameInAssign = null;

        // help with x.getString() -> y.getString()
        String methodSenderName = null;
        String fieldSenderName = null;

        ASTNode parent = node.getParent();
        switch (parent.getNodeType()) {
        case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
            // node must be initializer
            otherNameInAssign = ((VariableDeclarationFragment) parent).getName().getIdentifier();
            break;
        case ASTNode.ASSIGNMENT:
            Assignment assignment = (Assignment) parent;
            if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
                otherNameInAssign = ((SimpleName) assignment.getRightHandSide()).getIdentifier();
            } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
                otherNameInAssign = ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
            }
            break;
        case ASTNode.METHOD_INVOCATION:
            MethodInvocation inv = (MethodInvocation) parent;
            if (inv.getExpression() == node) {
                methodSenderName = inv.getName().getIdentifier();
            }
            break;
        case ASTNode.QUALIFIED_NAME:
            QualifiedName qualName = (QualifiedName) parent;
            if (qualName.getQualifier() == node) {
                fieldSenderName = qualName.getName().getIdentifier();
            }
            break;
        }

        ITypeBinding guessedType = ASTResolving.guessBindingForReference(node);

        ITypeBinding objectBinding = astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
        String identifier = node.getIdentifier();
        boolean isInStaticContext = ASTResolving.isInStaticContext(node);

        loop: for (int i = 0; i < varsAndMethodsInScope.length; i++) {
            IBinding varOrMeth = varsAndMethodsInScope[i];
            if (varOrMeth instanceof IVariableBinding) {
                IVariableBinding curr = (IVariableBinding) varOrMeth;
                String currName = curr.getName();
                if (currName.equals(otherNameInAssign)) {
                    continue loop;
                }
                boolean isFinal = Modifier.isFinal(curr.getModifiers());
                if (isFinal && curr.isField() && isWriteAccess) {
                    continue loop;
                }
                if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
                    continue loop;
                }

                int relevance = 0;
                if (NameMatcher.isSimilarName(currName, identifier)) {
                    relevance += 3; // variable with a similar name than the unresolved variable
                }
                if (currName.equalsIgnoreCase(identifier)) {
                    relevance += 5;
                }
                ITypeBinding varType = curr.getType();
                if (varType != null) {
                    if (guessedType != null && guessedType != objectBinding) { // too many result with object
                        // variable type is compatible with the guessed type
                        if (!isWriteAccess && canAssign(varType, guessedType)
                                || isWriteAccess && canAssign(guessedType, varType)) {
                            relevance += 2; // unresolved variable can be assign to this variable
                        }
                    }
                    if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
                        relevance += 2;
                    }
                    if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
                        relevance += 2;
                    }
                }

                if (relevance > 0) {
                    String label = Messages.format(
                            CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description,
                            currName);
                    proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(),
                            node.getLength(), currName, relevance));
                }
            } else if (varOrMeth instanceof IMethodBinding) {
                IMethodBinding curr = (IMethodBinding) varOrMeth;
                if (!curr.isConstructor() && guessedType != null
                        && canAssign(curr.getReturnType(), guessedType)) {
                    if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
                        AST ast = astRoot.getAST();
                        ASTRewrite rewrite = ASTRewrite.create(ast);
                        /* AJDT 1.7 */
                        String label = Messages.format(
                                CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description,
                                ASTResolving.getMethodSignature(curr)); /* AJDT 1.7 */
                        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, 8,
                                image);
                        proposals.add(proposal);

                        MethodInvocation newInv = ast.newMethodInvocation();
                        newInv.setName(ast.newSimpleName(curr.getName()));
                        ITypeBinding[] parameterTypes = curr.getParameterTypes();
                        for (int k = 0; k < parameterTypes.length; k++) {
                            ASTNode arg = ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
                            newInv.arguments().add(arg);
                            proposal.addLinkedPosition(rewrite.track(arg), false, null);
                        }
                        rewrite.replace(node, newInv, null);
                    }
                }
            }
        }
    }
    if (binding != null && binding.isArray()) {
        String idLength = "length"; //$NON-NLS-1$
        String label = Messages
                .format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
        proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(),
                idLength, 8));
    }
}

From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.CallinRHSCompletionProposal.java

License:Open Source License

@SuppressWarnings("unchecked") // list of method specs from dom.
    @Override/*from  w w w  .j a  v a  2s .  c  om*/
    boolean setupRewrite(ICompilationUnit iCU, ASTRewrite rewrite, ImportRewrite importRewrite,
            ITypeBinding roleBinding, ITypeBinding baseBinding, ASTNode type,
            AbstractMethodMappingDeclaration partialMapping, ChildListPropertyDescriptor bodyProperty)
            throws CoreException {
        if (partialMapping == null || !(partialMapping instanceof CallinMappingDeclaration))
            return false;
        // find base method:
        IMethodBinding method = findMethod(baseBinding, fMethodName, fParamTypes);
        if (method == null)
            return false;
        CallinMappingDeclaration callinMapping = (CallinMappingDeclaration) partialMapping;

        ListRewrite baseSpecsRewrite = rewrite.getListRewrite(partialMapping, BASE_MAPPING_ELEMENTS_PROPERTY);

        int insertPosition = 0;
        if (fLength > 0) {
            // need to remove partial method spec:
            List<MethodSpec> baseSpecs = callinMapping.getBaseMappingElements();
            for (int i = 0; i < baseSpecs.size(); i++) {
                MethodSpec spec = baseSpecs.get(i);
                if (spec.getStartPosition() == fReplaceStart && spec.getLength() == fLength) {
                    baseSpecsRewrite.remove(spec, null);
                    insertPosition = i + 1;
                    break;
                }
            }
        }

        // create and insert:
        boolean hasSignature = callinMapping.getRoleMappingElement().hasSignature();
        MethodSpec spec = OTStubUtility.createMethodSpec(iCU, rewrite, importRewrite, method, hasSignature);
        baseSpecsRewrite.insertAt(spec, insertPosition, null);

        int existingMod = ((CallinMappingDeclaration) partialMapping).getCallinModifier();
        if (existingMod == Modifier.OT_MISSING_MODIFIER) {
            // initial modifier (should match the role method):
            ModifierKeyword defaultKeyword = ModifierKeyword.BEFORE_KEYWORD;
            IMethodMappingBinding mappingBinding = partialMapping.resolveBinding();
            if (mappingBinding != null) {
                IMethodBinding roleMethod = mappingBinding.getRoleMethod();
                if (roleMethod != null && (roleMethod.getModifiers() & ExtraCompilerModifiers.AccCallin) != 0)
                    defaultKeyword = ModifierKeyword.REPLACE_KEYWORD;
                else
                    defaultKeyword = ModifierKeyword.BEFORE_KEYWORD;
            }
            Modifier afterMod = rewrite.getAST().newModifier(defaultKeyword);
            rewrite.set(partialMapping.bindingOperator(), BINDING_MODIFIER_PROPERTY, afterMod, null);

            // other modifiers:
            final ITrackedNodePosition position = rewrite.track(afterMod);
            this.addLinkedPosition(position, false, BINDINGKIND_KEY);
            LinkedProposalPositionGroup group = getLinkedProposalModel().getPositionGroup(BINDINGKIND_KEY, true);
            group.addProposal("before", Images.getImage(CALLINBINDING_BEFORE_IMG), 13); //$NON-NLS-1$
            group.addProposal("replace", Images.getImage(CALLINBINDING_REPLACE_IMG), 13); //$NON-NLS-1$
            group.addProposal("after", Images.getImage(CALLINBINDING_AFTER_IMG), 13); //$NON-NLS-1$
        }
        return true;
    }

From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.CreateMethodMappingCompletionProposal.java

License:Open Source License

/** Overridable, see CalloutToFieldCompletionProposal.
     *  At least baseBinding must be set, roleBinding is optional.
     */// www. ja  va  2s  . c  o m
    boolean setupRewrite(ICompilationUnit iCU, ASTRewrite rewrite, ImportRewrite importRewrite,
            ITypeBinding roleBinding, ITypeBinding baseBinding, ASTNode type,
            AbstractMethodMappingDeclaration partialMapping, ChildListPropertyDescriptor bodyProperty)
            throws CoreException {
        // find base method:
        IMethodBinding method = findMethod(baseBinding, fMethodName, fParamTypes);
        if (method == null)
            return false;

        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
        // create callout:
        AbstractMethodMappingDeclaration stub = this.fIsOnlyCallin
                ? OTStubUtility.createCallin(iCU, rewrite, importRewrite, method, baseBinding.getName(),
                        ModifierKeyword.BEFORE_KEYWORD, settings)
                : OTStubUtility.createCallout(iCU, rewrite, importRewrite, method, baseBinding.getName(), settings);
        if (stub != null) {
            insertStub(rewrite, type, bodyProperty, fReplaceStart, stub);

            MethodSpec roleMethodSpec = (MethodSpec) stub.getRoleMappingElement();

            // return type:
            ITrackedNodePosition returnTypePosition = null;
            ITypeBinding returnType = method.getReturnType();
            final boolean[] hasAppliedVoidReturn = new boolean[1];
            if (!(returnType.isPrimitive() && "void".equals(returnType.getName()))) { //$NON-NLS-1$
                returnTypePosition = rewrite.track(roleMethodSpec.getReturnType2());
                addLinkedPosition(returnTypePosition, true, ROLEMETHODRETURN_KEY);
                LinkedProposalPositionGroup group1 = getLinkedProposalModel().getPositionGroup(ROLEMETHODRETURN_KEY,
                        true);
                group1.addProposal(new MyJavaLinkedModeProposal(iCU, method.getReturnType(), 13));
                group1.addProposal(new Proposal("void", null, 13) { //$NON-NLS-1$
                    @Override
                    public TextEdit computeEdits(int offset, LinkedPosition position, char trigger, int stateMask,
                            LinkedModeModel model) throws CoreException {
                        hasAppliedVoidReturn[0] = true;
                        return super.computeEdits(offset, position, trigger, stateMask, model);
                    }
                });
            }

            // role method name:
            addLinkedPosition(rewrite.track(roleMethodSpec.getName()), false, ROLEMETHODNAME_KEY);

            // argument lifting?
            if (roleBinding != null)
                addLiftingProposals(roleBinding, method, stub, rewrite);

            // binding operator:
            addLinkedPosition(rewrite.track(stub.bindingOperator()), false, BINDINGKIND_KEY);
            LinkedProposalPositionGroup group2 = getLinkedProposalModel().getPositionGroup(BINDINGKIND_KEY, true);
            if (!this.fIsOnlyCallin) {
                String calloutToken = "->"; //$NON-NLS-1$
                if (this.fIsOverride) {
                    calloutToken = "=>"; //$NON-NLS-1$
                    stub.bindingOperator().setBindingKind(MethodBindingOperator.KIND_CALLOUT_OVERRIDE);
                }
                group2.addProposal(calloutToken, Images.getImage(CALLOUTBINDING_IMG), 13);
            }
            group2.addProposal(makeBeforeAfterBindingProposal("<- before", //$NON-NLS-1$
                    Images.getImage(CALLINBINDING_BEFORE_IMG), returnTypePosition, hasAppliedVoidReturn));
            group2.addProposal("<- replace", Images.getImage(CALLINBINDING_REPLACE_IMG), 13); //$NON-NLS-1$
            group2.addProposal(makeBeforeAfterBindingProposal("<- after", Images.getImage(CALLINBINDING_AFTER_IMG), //$NON-NLS-1$
                    returnTypePosition, hasAppliedVoidReturn));
        }
        return true;
    }

From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.CreateMethodMappingCompletionProposal.java

License:Open Source License

/**
     * check whether a given type is played by a role from a given array and create a proposal group containing base and role type. 
     * @param rewrite//from w w  w . j  av  a  2s. c  o m
     * @param positionGroupID 
     * @param roles       available roles in the enclosing team
     * @param type        AST node to investigate
     * @param typeBinding type binding of AST node to investigate
     */
    void addLiftingProposalGroup(ASTRewrite rewrite, String positionGroupID, ITypeBinding[] roles, Type type,
            ITypeBinding typeBinding) {
        for (ITypeBinding roleBinding : roles) {
            if (roleBinding.isSynthRoleIfc())
                continue; // synth ifcs would otherwise cause dupes
            if (typeBinding.equals(roleBinding.getBaseClass())) {
                ITrackedNodePosition argTypePos = rewrite.track(type);
                addLinkedPosition(argTypePos, true, positionGroupID);
                LinkedProposalPositionGroup group = getLinkedProposalModel().getPositionGroup(positionGroupID,
                        true);
                group.addProposal(type.toString(), null, 13);
                group.addProposal(roleBinding.getName(), null, 13);
                break;
            }
        }
    }

From source file:org.eclipse.objectteams.otdt.internal.ui.assist.CompletionAdaptor.OverrideRoleCompletionProposal.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override//from w  ww  . j  a va  2  s.  c  o m
    protected boolean updateReplacementString(IDocument document, char trigger, int offset,
            ImportRewrite importRewrite) throws CoreException, BadLocationException {
        Document recoveredDocument = new Document();
        CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);

        // find enclosing team type:
        ASTNode node = NodeFinder.perform(unit, fReplaceStart, 0);
        while (node != null && !(node instanceof AbstractTypeDeclaration)) {
            node = node.getParent();
        }

        if (node != null) {
            AbstractTypeDeclaration teamDecl = ((AbstractTypeDeclaration) node);

            // create and setup the rewrite:
            AST ast = unit.getAST();
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.setToOTJ();

            // create type
            TypeDeclaration newType = ast.newTypeDeclaration();
            newType.setName(ast.newSimpleName(this.fRoleName));
            newType.setInterface(Flags.isInterface(this.fModifiers));
            newType.setTeam(Flags.isTeam(this.fModifiers));
            // add @Override:
            Annotation overrideAnnotation = ast.newMarkerAnnotation();
            overrideAnnotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
            List modifiers = newType.modifiers();
            modifiers.add(overrideAnnotation);
            // add protected or public
            modifiers.add(ast.newModifier(Flags.isPublic(this.fModifiers) ? ModifierKeyword.PUBLIC_KEYWORD
                    : ModifierKeyword.PROTECTED_KEYWORD));
            // add team keyword?
            if (Flags.isTeam(this.fModifiers))
                modifiers.add(ast.newModifier(ModifierKeyword.TEAM_KEYWORD));

            insertStub(rewrite, teamDecl, teamDecl.getBodyDeclarationsProperty(), this.fReplaceStart, newType);

            // create the replacementString from the rewrite:
            ITrackedNodePosition position = rewrite.track(newType);
            try {
                rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);

                String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
                CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
                int generatedIndent = IndentManipulation.measureIndentUnits(
                        getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth,
                        settings.indentWidth);

                String indent = getIndentAt(document, getReplacementOffset(), settings);
                setReplacementString(
                        IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
                                settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));

            } catch (MalformedTreeException exception) {
                JavaPlugin.log(exception);
            } catch (BadLocationException exception) {
                JavaPlugin.log(exception);
            }
        }
        return true;
    }

From source file:org.eclipse.objectteams.otdt.internal.ui.text.correction.AddMethodMappingSignaturesProposal.java

License:Open Source License

private void addSignatureToCallinBases(ICompilationUnit cu, ASTRewrite rewrite, ImportRewrite imports,
        CallinMappingDeclaration mapping, TextEditGroup editGroup, IMethodBinding roleMethod)
        throws CoreException {
    @SuppressWarnings("unchecked")
    List<MethodSpec> oldBaseSpecs = mapping.getBaseMappingElements();
    ListRewrite baseMethodsRewrite = rewrite.getListRewrite(mapping,
            CallinMappingDeclaration.BASE_MAPPING_ELEMENTS_PROPERTY);
    IMethodMappingBinding mappingBinding = mapping.resolveBinding();
    if (mappingBinding != null) {
        // create proposal from exact methods
        IMethodBinding[] baseMethods = mappingBinding.getBaseMethods();
        for (int i = 0; i < baseMethods.length; i++) {
            IMethodBinding baseMethod = baseMethods[i];
            try {
                MethodSpec newSpec = OTStubUtility.createMethodSpec(cu, rewrite, imports, baseMethod, true);
                baseMethodsRewrite.replace(oldBaseSpecs.get(i), newSpec, editGroup);
            } catch (CoreException e) {
                OTDTUIPlugin.log(e);//from w ww. j a  v a 2 s.  c  o m
            }
        }
    } else {
        ITypeBinding[] roleParameters = roleMethod.getParameterTypes();
        RoleTypeDeclaration role = (RoleTypeDeclaration) mapping.getParent();
        for (int i = 0; i < oldBaseSpecs.size(); i++) {
            MethodSpec oldBaseSpec = oldBaseSpecs.get(i);
            // search matching base methods:
            List<IMethodBinding> matchingBaseMethods = new ArrayList<IMethodBinding>();
            guessBaseMethod(role.resolveBinding(), oldBaseSpec.getName().getIdentifier(), roleParameters, true,
                    matchingBaseMethods);
            if (matchingBaseMethods.size() == 0)
                throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.objectteams.otdt.jdt.ui", //$NON-NLS-1$
                        "Could not find a matching base method")); //$NON-NLS-1$
            try {
                MethodSpec newSpec = OTStubUtility.createMethodSpec(cu, rewrite, imports,
                        matchingBaseMethods.get(0), true);
                baseMethodsRewrite.replace(oldBaseSpecs.get(i), newSpec, editGroup);
                // do we have alternatives to propose?
                if (matchingBaseMethods.size() > 1) {
                    addLinkedPosition(rewrite.track(newSpec), false, KEY_BASEMETHOD);
                    for (IMethodBinding baseMethodBinding : matchingBaseMethods) {
                        MethodSpec bSpec = OTStubUtility.createMethodSpec(cu, rewrite, imports,
                                baseMethodBinding, true);
                        addLinkedPositionProposal(KEY_BASEMETHOD, bSpec.toString(), null);
                    }
                }
            } catch (CoreException e) {
                OTDTUIPlugin.log(e);
            }
        }
    }
}