Example usage for org.eclipse.jdt.core.dom.rewrite ITrackedNodePosition getStartPosition

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

Introduction

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

Prototype

public int getStartPosition();

Source Link

Document

Returns the original or modified start position of the tracked node depending if called before or after the rewrite is applied.

Usage

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 a  v a 2 s  .  c  o 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);//from   w ww  .j a v a 2  s  . c  o 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.objectteams.otdt.internal.ui.assist.CompletionAdaptor.CreateMethodMappingCompletionProposal.java

License:Open Source License

/** Create a method-binding proposal that, when applied, will change the role-returntype to "void": */
    Proposal makeBeforeAfterBindingProposal(String displayString, Image image,
            final ITrackedNodePosition returnTypePosition, final boolean[] hasAppliedVoidReturn) {
        return new Proposal(displayString, image, 13) {
            @Override/*from w  ww  .j a v  a 2  s  .  c om*/
            public TextEdit computeEdits(int offset, LinkedPosition position, char trigger, int stateMask,
                    LinkedModeModel model) throws CoreException {
                MultiTextEdit edits = new MultiTextEdit();
                if (returnTypePosition != null && !hasAppliedVoidReturn[0])
                    edits.addChild(new ReplaceEdit(returnTypePosition.getStartPosition(),
                            returnTypePosition.getLength(), "void")); //$NON-NLS-1$
                edits.addChild(super.computeEdits(offset, position, trigger, stateMask, model));
                return edits;
            }
        };
    }

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

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override//from  ww  w  .java2 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.PrecedenceProposalSubProcessor.java

License:Open Source License

/**
 * Create the edits for a new precedence declaration.
 * Also add the option to swap the order.
 * If 'useFullStringAlternatives' is true, the two alternatives
 * are provided as two strings comprising a full precedence declaration each.
 * Otherwise the keyword 'precedence' is used as an anchor for a "menu"
 * showing one option: "> Swap Order". 
 * /*from   w w  w .  j  a  va  2 s.c o  m*/
 * @param targetType
 * @param label   display label for this proposal.
 * @param callin1 name of one callin binding
 * @param callin2 name of the other callin binding
 * @param useFullStringAlternatives who to support setting the precedence order.
 * @return the proposal
 */
@SuppressWarnings("unchecked")
private LinkedCorrectionProposal getPrecedenceProposal(TypeDeclaration targetType, String label, String callin1,
        String callin2, boolean isAfter, boolean linkLabel1, boolean linkLabel2) {
    ChildListPropertyDescriptor precedenceProperty;
    if (targetType instanceof RoleTypeDeclaration)
        precedenceProperty = RoleTypeDeclaration.PRECEDENCE_PROPERTY;
    else
        precedenceProperty = TypeDeclaration.PRECEDENCE_PROPERTY;
    ListRewrite listRewrite = this.rewrite.getListRewrite(targetType, precedenceProperty);
    PrecedenceDeclaration newPrecedence = ast.newPrecedenceDeclaration();
    Name element1 = ast.newName(callin1);
    Name element2 = ast.newName(callin2);
    newPrecedence.elements().add(element1);
    newPrecedence.elements().add(element2);
    if (isAfter)
        newPrecedence.setAfter(true);
    listRewrite.insertLast(newPrecedence, null);
    MyLinkedCorrectionProposal proposal = new MyLinkedCorrectionProposal(label, this.cu, this.rewrite, 10,
            ImageManager.getSharedInstance().get(ImageConstants.CALLINBINDING_REPLACE_IMG));

    if (callin1 != null && callin2 != null) {
        if (!linkLabel1 && !linkLabel2) {
            String prefix = isAfter ? "precedence after " : "precedence "; //$NON-NLS-1$ //$NON-NLS-2$
            // setup two alternatives (different order):
            proposal.addLinkedPosition(this.rewrite.track(newPrecedence), false, KEY_PRECEDENCE);
            proposal.addLinkedPositionProposal(KEY_PRECEDENCE, prefix + callin1 + ", " + callin2 + ";", //$NON-NLS-1$ //$NON-NLS-2$ 
                    null);
            proposal.addLinkedPositionProposal(KEY_PRECEDENCE, prefix + callin2 + ", " + callin1 + ";", //$NON-NLS-1$ //$NON-NLS-2$
                    null);
        } else {
            // setup a "menu":
            final ITrackedNodePosition precedencePosition = this.rewrite.track(newPrecedence);
            ITrackedNodePosition swapPosition = new ITrackedNodePosition() {
                public int getLength() {
                    return "precedence".length(); //$NON-NLS-1$
                }

                public int getStartPosition() {
                    return precedencePosition.getStartPosition();
                }
            };
            proposal.addLinkedPosition(swapPosition, false, KEY_PRECEDENCE);
            LinkedProposalPositionGroup positionGroup = proposal.getLinkedProposalModel()
                    .getPositionGroup(KEY_PRECEDENCE, true);
            positionGroup
                    .addProposal(new StringLinkedModeProposal(CorrectionMessages.OTQuickfix_swapordermenu_label,
                            CorrectionMessages.OTQuickfix_swapordermenu_description));
            positionGroup.addProposal(new SwapPrecedencesProposal());

            // prepare elements of this precedence to be linked with the (editable) callin labels.
            if (linkLabel1)
                proposal.addLinkedPosition(this.rewrite.track(element1), false, KEY_LABEL1);
            if (linkLabel2)
                proposal.addLinkedPosition(this.rewrite.track(element2), false, KEY_LABEL2);
        }
    }
    return proposal;
}

From source file:org.jboss.tools.websockets.ui.internal.ca.MethodCompletionProposal.java

License:Open Source License

@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset,
        ImportRewrite importRewrite) throws CoreException, BadLocationException {
    Document recoveredDocument = new Document();
    CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
    if (importRewrite == null) {
        importRewrite = StubUtility.createImportRewrite(unit, true); // create a dummy import rewriter to have one
    }/* w  w w.  j a  v  a  2 s  .co  m*/

    ITypeBinding declaringType = null;
    ChildListPropertyDescriptor descriptor = null;
    ASTNode node = NodeFinder.perform(unit, position, 1);
    if (node instanceof SimpleName || node instanceof Modifier) {
        node = node.getParent();
        if (node instanceof MarkerAnnotation) {
            node = node.getParent();
        }
    }
    if (node instanceof MethodDeclaration || node instanceof FieldDeclaration) {
        node = node.getParent();
    }
    if (node instanceof AnonymousClassDeclaration) {
        declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
        descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
    } else if (node instanceof AbstractTypeDeclaration) {
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
        descriptor = declaration.getBodyDeclarationsProperty();
        declaringType = declaration.resolveBinding();
    }
    if (declaringType != null) {
        ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);

        String delimiter = StubUtility.getLineDelimiterUsed(unit.getTypeRoot());

        StringBuffer content = new StringBuffer();
        if (methodInfo.annotation != null) {
            importRewrite.addImport(methodInfo.annotation);
            int dot = methodInfo.annotation.lastIndexOf('.');
            String simpleName = methodInfo.annotation.substring(dot + 1);
            content.append("@").append(simpleName).append(delimiter); //$NON-NLS-1$
        }
        content.append("public void " + methodInfo.methodName + "("); //$NON-NLS-1$ //$NON-NLS-2$
        boolean first = true;
        for (int i = 0; i < methodInfo.paramTypes.length; i++) {
            String paramType = methodInfo.paramTypes[i];
            if (!first) {
                content.append(", "); //$NON-NLS-1$
            } else {
                first = false;
            }
            importRewrite.addImport(paramType);
            String simpleName = paramType.substring(paramType.lastIndexOf('.') + 1);
            String name = methodInfo.paramNames != null ? methodInfo.paramNames[i]
                    : simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
            content.append(simpleName).append(" ").append(name); //$NON-NLS-1$
        }
        content.append(") {").append(delimiter).append("\t\t"); //$NON-NLS-1$ //$NON-NLS-2$
        String body = StubUtility.getMethodBodyContent(false, fJavaProject, declaringType.getName(),
                declaringType.getName(), "", delimiter); //$NON-NLS-1$
        if (body == null || body.length() == 0) {
            body = delimiter;
        }
        content.append(body);
        content.append("}").append(delimiter); //$NON-NLS-1$

        MethodDeclaration stub = (MethodDeclaration) rewrite.createStringPlaceholder(
                CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, content.toString(), 0,
                        delimiter, unit.getTypeRoot().getJavaProject()),
                ASTNode.METHOD_DECLARATION);

        ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
        rewriter.insertFirst(stub, null);

        ITrackedNodePosition position = rewrite.track(stub);
        try {
            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);
            if (this.position > offset && indent.length() == 0) {
                indent = "\t"; //$NON-NLS-1$
            }
            String replacementString = IndentManipulation.changeIndent(generatedCode, generatedIndent,
                    settings.tabWidth, settings.indentWidth, indent,
                    TextUtilities.getDefaultLineDelimiter(document));
            if (this.position > offset) {
                replacementString = "\t" + replacementString + delimiter; //$NON-NLS-1$
                setReplacementLength(getReplacementLength());
                setReplacementOffset(getReplacementOffset() + this.position - offset);
            } else if (prefixLength > 0) {
                setReplacementLength(getReplacementLength() + prefixLength);
                setReplacementOffset(getReplacementOffset() - prefixLength);
            }
            setReplacementString(replacementString);
        } catch (MalformedTreeException exception) {
            JavaPlugin.log(exception);
        } catch (BadLocationException exception) {
            JavaPlugin.log(exception);
        }
    }
    return true;
}

From source file:org.springframework.ide.eclipse.quickfix.jdt.proposals.AddPathVariableCompletionProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(methodDecl);
    final ASTRewrite astRewrite = ASTRewrite.create(astRoot.getAST());

    AST ast = astRewrite.getAST();//from   w w w.  jav  a 2s . co  m

    String importName = PathVariable.class.getCanonicalName();
    if (!ProposalCalculatorUtil.containsImport(getCompilationUnit(), importName)) {
        ImportRewrite importRewrite = createImportRewrite(astRoot);
        importRewrite.addImport(importName);
    }

    SingleMemberAnnotation annotation = ast.newSingleMemberAnnotation();
    annotation.setTypeName(ast.newSimpleName("PathVariable"));
    StringLiteral pathVariableName = ast.newStringLiteral();
    pathVariableName.setLiteralValue(variable.getVariableName());
    annotation.setValue(pathVariableName);

    astRewrite.getListRewrite(param, SingleVariableDeclaration.MODIFIERS2_PROPERTY).insertFirst(annotation,
            null);

    final ITrackedNodePosition literalPosition = astRewrite.track(variable.getNode());
    addLinkedPosition(new ITrackedNodePosition() {

        public int getStartPosition() {
            return literalPosition.getStartPosition() + variable.getOffsetFromNode();
        }

        public int getLength() {
            return variable.getVariableName().length();
        }
    }, true, "PathVariable");

    addLinkedPosition(new StringLiteralTrackedPosition(astRewrite.track(pathVariableName)), false,
            "PathVariable");

    return astRewrite;
}

From source file:org.springframework.ide.eclipse.quickfix.jdt.proposals.AddRequestMappingCompletionProposal.java

License:Open Source License

private void applyChangeForType(IDocument document, int offset)
        throws MalformedTreeException, JavaModelException, IllegalArgumentException, BadLocationException {
    MultiTextEdit edit = new MultiTextEdit();

    TextEdit importEdit = JdtQuickfixUtils.getTextEditForImport(cu, REQUEST_MAPPING_IMPORT);
    if (importEdit != null) {
        edit.addChild(importEdit);//from  w w  w  . j ava 2 s. c o  m
    }

    ASTRewrite astRewrite = ASTRewrite.create(decl.getAST());
    NormalAnnotation annotation = astRewrite.getAST().newNormalAnnotation();

    annotation.setTypeName(astRewrite.getAST().newSimpleName("RequestMapping"));
    astRewrite.getListRewrite(decl, TypeDeclaration.MODIFIERS2_PROPERTY).insertFirst(annotation, null);

    ITrackedNodePosition tracker = astRewrite.track(annotation.getTypeName());
    edit.addChild(astRewrite.rewriteAST());

    edit.apply(document);

    setReplacementOffset(
            tracker.getStartPosition() + annotation.getTypeName().getFullyQualifiedName().length() + 1);
}

From source file:org.springframework.ide.eclipse.quickfix.jdt.proposals.ClassCompletionProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() throws CoreException {
    setupASTNodes();//from ww  w  .ja v a2 s . c  o  m

    AST ast = annotation.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);

    if (oldLiteral == null) {
        return rewrite;
    }

    SimpleName typeName = ast.newSimpleName(className);
    SimpleType type = ast.newSimpleType(typeName);
    TypeLiteral typeLiteral = ast.newTypeLiteral();
    typeLiteral.setType(type);
    final ITrackedNodePosition newValuePosition = rewrite.track(typeLiteral);

    rewrite.replace(oldLiteral, typeLiteral, null);

    if (packageFragment != null) {
        ImportRewrite importRewrite = createImportRewrite(ASTResolving.findParentCompilationUnit(oldLiteral));
        importRewrite.addImport(packageFragment.getElementName() + "." + className);
    }

    setTrackPosition(new ITrackedNodePosition() {

        public int getStartPosition() {
            return newValuePosition.getStartPosition() + newValuePosition.getLength();
        }

        public int getLength() {
            return 0;
        }
    });

    return rewrite;
}

From source file:org.springframework.ide.eclipse.quickfix.jdt.proposals.PackageNameCompletionProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() throws CoreException {
    setupASTNodes();//from  w  ww  . j av  a  2 s.  c  o  m

    AST ast = annotation.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);

    if (oldLiteral == null) {
        return rewrite;
    }

    StringLiteral newValue = ast.newStringLiteral();
    newValue.setLiteralValue(packageName);
    ITrackedNodePosition newValuePosition = rewrite.track(newValue);

    rewrite.replace(oldLiteral, newValue, null);
    setTrackPosition(new StringLiteralTrackedPosition(newValuePosition,
            newValuePosition.getStartPosition() + 1 + packageName.length(), 0, true));

    return rewrite;
}