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

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

Introduction

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

Prototype

public int getLength();

Source Link

Document

Returns the original or modified length 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  om
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);// w  ww  .j  a  va2s. 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// w w w. jav  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// www  . jav  a 2s .  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.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
    }/*from   w  w  w  .ja  v  a 2s  .c  o 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.ClassCompletionProposal.java

License:Open Source License

@Override
protected ASTRewrite getRewrite() throws CoreException {
    setupASTNodes();//from   w w w . j  av  a  2  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;
}