Search in sources :

Example 11 with AnonymousClassDeclaration

use of org.eclipse.jdt.core.dom.AnonymousClassDeclaration in project che by eclipse.

the class IntroduceFactoryRefactoring method createFactoryMethod.

/**
	 * Creates and returns a new MethodDeclaration that represents the factory method to be used in
	 * place of direct calls to the constructor in question.
	 * 
	 * @param ast An AST used as a factory for various AST nodes
	 * @param ctorBinding binding for the constructor being wrapped
	 * @param unitRewriter the ASTRewrite to be used
	 * @return the new method declaration
	 * @throws CoreException if an exception occurs while accessing its corresponding resource
	 */
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException {
    MethodDeclaration newMethod = ast.newMethodDeclaration();
    SimpleName newMethodName = ast.newSimpleName(fNewMethodName);
    ClassInstanceCreation newCtorCall = ast.newClassInstanceCreation();
    ReturnStatement ret = ast.newReturnStatement();
    Block body = ast.newBlock();
    List<Statement> stmts = body.statements();
    String retTypeName = ctorBinding.getName();
    createFactoryMethodSignature(ast, newMethod);
    newMethod.setName(newMethodName);
    newMethod.setBody(body);
    ITypeBinding declaringClass = fCtorBinding.getDeclaringClass();
    ITypeBinding[] ctorOwnerTypeParameters = declaringClass.getTypeParameters();
    setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);
    newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));
    setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);
    createFactoryMethodConstructorArgs(ast, newCtorCall);
    if (Modifier.isAbstract(declaringClass.getModifiers())) {
        AnonymousClassDeclaration decl = ast.newAnonymousClassDeclaration();
        IMethodBinding[] unimplementedMethods = getUnimplementedMethods(declaringClass);
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
        for (int i = 0; i < unimplementedMethods.length; i++) {
            IMethodBinding unImplementedMethod = unimplementedMethods[i];
            MethodDeclaration newMethodDecl = StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass().getName(), settings, false);
            decl.bodyDeclarations().add(newMethodDecl);
        }
        newCtorCall.setAnonymousClassDeclaration(decl);
    }
    ret.setExpression(newCtorCall);
    stmts.add(ret);
    return newMethod;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block)

Example 12 with AnonymousClassDeclaration

use of org.eclipse.jdt.core.dom.AnonymousClassDeclaration in project che by eclipse.

the class OverrideCompletionProposal method updateReplacementString.

/*
     * @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
     */
@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);
    ImportRewriteContext context;
    if (importRewrite != null) {
        context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);
    } else {
        // create a dummy import rewriter to have one
        importRewrite = StubUtility.createImportRewrite(unit, true);
        context = new // forces that all imports are fully qualified
        ImportRewriteContext() {

            @Override
            public int findInContext(String qualifier, String name, int kind) {
                return RES_NAME_CONFLICT;
            }
        };
    }
    ITypeBinding declaringType = null;
    ChildListPropertyDescriptor descriptor = null;
    ASTNode node = NodeFinder.perform(unit, offset, 1);
    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());
        IMethodBinding methodToOverride = Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
        if (methodToOverride == null && declaringType.isInterface()) {
            //$NON-NLS-1$
            methodToOverride = Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes);
        }
        if (methodToOverride != null) {
            CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
            MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType.getName(), settings, declaringType.isInterface());
            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);
                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;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) StyledString(org.eclipse.jface.viewers.StyledString) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 13 with AnonymousClassDeclaration

use of org.eclipse.jdt.core.dom.AnonymousClassDeclaration in project che by eclipse.

the class NewVariableCorrectionProposal method evaluateFieldModifiers.

private int evaluateFieldModifiers(ASTNode newTypeDecl) {
    if (fSenderBinding.isAnnotation()) {
        return 0;
    }
    if (fSenderBinding.isInterface()) {
        // for interface members copy the modifiers from an existing field
        FieldDeclaration[] fieldDecls = ((TypeDeclaration) newTypeDecl).getFields();
        if (fieldDecls.length > 0) {
            return fieldDecls[0].getModifiers();
        }
        return 0;
    }
    int modifiers = 0;
    if (fVariableKind == CONST_FIELD) {
        modifiers |= Modifier.FINAL | Modifier.STATIC;
    } else {
        ASTNode parent = fOriginalNode.getParent();
        if (parent instanceof QualifiedName) {
            IBinding qualifierBinding = ((QualifiedName) parent).getQualifier().resolveBinding();
            if (qualifierBinding instanceof ITypeBinding) {
                modifiers |= Modifier.STATIC;
            }
        } else if (ASTResolving.isInStaticContext(fOriginalNode)) {
            modifiers |= Modifier.STATIC;
        }
    }
    ASTNode node = ASTResolving.findParentType(fOriginalNode, true);
    if (newTypeDecl.equals(node)) {
        modifiers |= Modifier.PRIVATE;
    } else if (node instanceof AnonymousClassDeclaration) {
        modifiers |= Modifier.PROTECTED;
    } else {
        modifiers |= Modifier.PUBLIC;
    }
    return modifiers;
}
Also used : QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IBinding(org.eclipse.jdt.core.dom.IBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 14 with AnonymousClassDeclaration

use of org.eclipse.jdt.core.dom.AnonymousClassDeclaration in project che by eclipse.

the class AbstractSerialVersionOperation method rewriteAST.

/**
	 * {@inheritDoc}
	 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
    final ASTRewrite rewrite = cuRewrite.getASTRewrite();
    VariableDeclarationFragment fragment = null;
    for (int i = 0; i < fNodes.length; i++) {
        final ASTNode node = fNodes[i];
        final AST ast = node.getAST();
        fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(NAME_FIELD));
        final FieldDeclaration declaration = ast.newFieldDeclaration(fragment);
        declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG));
        declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL));
        if (!addInitializer(fragment, node))
            continue;
        if (fragment.getInitializer() != null) {
            final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite);
            if (node instanceof AbstractTypeDeclaration)
                rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup);
            else if (node instanceof AnonymousClassDeclaration)
                rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
            else if (node instanceof ParameterizedType) {
                final ParameterizedType type = (ParameterizedType) node;
                final ASTNode parent = type.getParent();
                if (parent instanceof ClassInstanceCreation) {
                    final ClassInstanceCreation creation = (ClassInstanceCreation) parent;
                    final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration();
                    if (anonymous != null)
                        rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
                }
            } else
                Assert.isTrue(false);
            addLinkedPositions(rewrite, fragment, positionGroups);
        }
        final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit));
        if (comment != null && comment.length() > 0) {
            final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
            declaration.setJavadoc(doc);
        }
    }
    if (fragment == null)
        return;
    positionGroups.setEndPosition(rewrite.track(fragment));
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 15 with AnonymousClassDeclaration

use of org.eclipse.jdt.core.dom.AnonymousClassDeclaration in project che by eclipse.

the class AddUnimplementedMethodsOperation method getUnimplementedMethods.

private IMethodBinding[] getUnimplementedMethods(ASTNode typeNode) {
    ITypeBinding binding = null;
    boolean implementAbstractsOfInput = false;
    if (typeNode instanceof AnonymousClassDeclaration) {
        AnonymousClassDeclaration decl = (AnonymousClassDeclaration) typeNode;
        binding = decl.resolveBinding();
    } else if (typeNode instanceof AbstractTypeDeclaration) {
        AbstractTypeDeclaration decl = (AbstractTypeDeclaration) typeNode;
        binding = decl.resolveBinding();
    } else if (typeNode instanceof EnumConstantDeclaration) {
        EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) typeNode;
        if (enumConstantDeclaration.getAnonymousClassDeclaration() != null) {
            binding = enumConstantDeclaration.getAnonymousClassDeclaration().resolveBinding();
        } else {
            IVariableBinding varBinding = enumConstantDeclaration.resolveVariable();
            if (varBinding != null) {
                binding = varBinding.getDeclaringClass();
                implementAbstractsOfInput = true;
            }
        }
    }
    if (binding == null)
        return new IMethodBinding[0];
    IMethodBinding[] unimplementedMethods = StubUtility2.getUnimplementedMethods(binding, implementAbstractsOfInput);
    Arrays.sort(unimplementedMethods, new MethodsSourcePositionComparator(binding));
    return unimplementedMethods;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) MethodsSourcePositionComparator(org.eclipse.jdt.internal.corext.util.MethodsSourcePositionComparator) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Aggregations

AnonymousClassDeclaration (org.eclipse.jdt.core.dom.AnonymousClassDeclaration)22 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)17 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)10 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)8 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)7 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)4 ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)4 SimpleName (org.eclipse.jdt.core.dom.SimpleName)4 NotImplementedException (org.autorefactor.util.NotImplementedException)3 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)3 EnumDeclaration (org.eclipse.jdt.core.dom.EnumDeclaration)3 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)3 StructuralPropertyDescriptor (org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)3 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)3 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)3 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)3 CodeGenerationSettings (org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings)3 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)3