Search in sources :

Example 46 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project eclipse.jdt.ls by eclipse.

the class SurroundWithTryCatchRefactoring method createTryCatchStatement.

private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter) throws CoreException {
    List<Statement> result = new ArrayList<>(1);
    TryStatement tryStatement = getAST().newTryStatement();
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite);
    if (!fIsMultiCatch) {
        for (int i = 0; i < exceptions.length; i++) {
            ITypeBinding exception = exceptions[i];
            CatchClause catchClause = getAST().newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
            String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
            String name = fScope.createName(varName, false);
            decl.setName(getAST().newSimpleName(name));
            Type type = fImportRewrite.addImport(exception, getAST(), context, TypeLocation.EXCEPTION);
            decl.setType(type);
            catchClause.setException(decl);
            Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter);
            if (st != null) {
                catchClause.getBody().statements().add(st);
            }
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(decl.getType()), i == 0);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + i, true).addPosition(fRewriter.track(decl.getName()), false);
        }
    } else {
        List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions);
        CatchClause catchClause = getAST().newCatchClause();
        SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
        String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
        String name = fScope.createName(varName, false);
        decl.setName(getAST().newSimpleName(name));
        UnionType unionType = getAST().newUnionType();
        List<Type> types = unionType.types();
        int i = 0;
        for (ITypeBinding exception : filteredExceptions) {
            Type type = fImportRewrite.addImport(exception, getAST(), context, TypeLocation.EXCEPTION);
            types.add(type);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(type), i == 0);
            i++;
        }
        decl.setType(unionType);
        catchClause.setException(decl);
        fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + 0, true).addPosition(fRewriter.track(decl.getName()), false);
        // $NON-NLS-1$
        Statement st = getCatchBody("Exception", name, lineDelimiter);
        if (st != null) {
            catchClause.getBody().statements().add(st);
        }
        tryStatement.catchClauses().add(catchClause);
    }
    List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements();
    ListRewrite statements = fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
    boolean selectedNodeRemoved = false;
    ASTNode expressionStatement = null;
    for (int i = 0; i < fSelectedNodes.length; i++) {
        ASTNode node = fSelectedNodes[i];
        if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
            AST ast = getAST();
            VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
            // Create a copy and remove the initializer
            VariableDeclarationStatement copy = (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement);
            List<IExtendedModifier> modifiers = copy.modifiers();
            for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) {
                IExtendedModifier modifier = iter.next();
                if (modifier.isModifier() && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) {
                    iter.remove();
                }
            }
            List<VariableDeclarationFragment> fragments = copy.fragments();
            for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                VariableDeclarationFragment fragment = iter.next();
                fragment.setInitializer(null);
            }
            CompilationUnit root = (CompilationUnit) statement.getRoot();
            int extendedStart = root.getExtendedStartPosition(statement);
            // we have a leading comment and the comment is covered by the selection
            if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) {
                String commentToken = buffer.getText(extendedStart, statement.getStartPosition() - extendedStart);
                commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
                Type type = statement.getType();
                String typeName = buffer.getText(type.getStartPosition(), type.getLength());
                copy.setType((Type) fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
            }
            result.add(copy);
            // convert the fragments into expression statements
            fragments = statement.fragments();
            if (!fragments.isEmpty()) {
                List<ExpressionStatement> newExpressionStatements = new ArrayList<>();
                for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                    VariableDeclarationFragment fragment = iter.next();
                    Expression initializer = fragment.getInitializer();
                    if (initializer != null) {
                        Assignment assignment = ast.newAssignment();
                        assignment.setLeftHandSide((Expression) fRewriter.createCopyTarget(fragment.getName()));
                        assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer));
                        newExpressionStatements.add(ast.newExpressionStatement(assignment));
                    }
                }
                if (!newExpressionStatements.isEmpty()) {
                    if (fSelectedNodes.length == 1) {
                        expressionStatement = fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
                    } else {
                        fRewriter.replace(statement, fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])), null);
                    }
                } else {
                    fRewriter.remove(statement, null);
                    selectedNodeRemoved = true;
                }
            } else {
                fRewriter.remove(statement, null);
                selectedNodeRemoved = true;
            }
        }
    }
    result.add(tryStatement);
    ASTNode replacementNode;
    if (result.size() == 1) {
        replacementNode = result.get(0);
    } else {
        replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()]));
    }
    if (fSelectedNodes.length == 1) {
        ASTNode selectedNode = fSelectedNodes[0];
        if (selectedNode instanceof MethodReference) {
            MethodReference methodReference = (MethodReference) selectedNode;
            IMethodBinding functionalMethod = QuickAssistProcessor.getFunctionalMethodForMethodReference(methodReference);
            // functionalMethod is non-null and non-generic. See ExceptionAnalyzer.handleMethodReference(MethodReference node).
            Assert.isTrue(functionalMethod != null && !functionalMethod.isGenericMethod());
            LambdaExpression lambda = QuickAssistProcessor.convertMethodRefernceToLambda(methodReference, functionalMethod, fRootNode, fRewriter, null, true);
            ASTNode statementInBlock = (ASTNode) ((Block) lambda.getBody()).statements().get(0);
            fRewriter.replace(statementInBlock, replacementNode, null);
            statements.insertLast(statementInBlock, null);
            return;
        }
        LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(selectedNode);
        if (enclosingLambda != null && selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY && enclosingLambda.resolveMethodBinding() != null) {
            QuickAssistProcessor.changeLambdaBodyToBlock(enclosingLambda, getAST(), fRewriter);
            Block blockBody = (Block) fRewriter.get(enclosingLambda, LambdaExpression.BODY_PROPERTY);
            ASTNode statementInBlock = (ASTNode) blockBody.statements().get(0);
            fRewriter.replace(statementInBlock, replacementNode, null);
            statements.insertLast(statementInBlock, null);
            return;
        }
        if (expressionStatement != null) {
            statements.insertLast(expressionStatement, null);
        } else {
            if (!selectedNodeRemoved) {
                statements.insertLast(fRewriter.createMoveTarget(selectedNode), null);
            }
        }
        fRewriter.replace(selectedNode, replacementNode, null);
    } else {
        ListRewrite source = fRewriter.getListRewrite(fSelectedNodes[0].getParent(), (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent());
        ASTNode toMove = source.createMoveTarget(fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null);
        statements.insertLast(toMove, null);
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Assignment(org.eclipse.jdt.core.dom.Assignment) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) Block(org.eclipse.jdt.core.dom.Block) MethodReference(org.eclipse.jdt.core.dom.MethodReference) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 47 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project eclipse.jdt.ls by eclipse.

the class ChangeMethodSignatureProposal method modifyParameters.

private void modifyParameters(ASTRewrite rewrite, MethodDeclaration methodDecl) {
    AST ast = methodDecl.getAST();
    ArrayList<String> usedNames = new ArrayList<>();
    boolean hasCreatedVariables = false;
    IVariableBinding[] declaredFields = fSenderBinding.getDeclaringClass().getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        // avoid to take parameter names that are equal to field names
        usedNames.add(declaredFields[i].getName());
    }
    ImportRewrite imports = getImportRewrite();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(methodDecl, imports);
    ListRewrite listRewrite = rewrite.getListRewrite(methodDecl, MethodDeclaration.PARAMETERS_PROPERTY);
    // old parameters
    List<SingleVariableDeclaration> parameters = methodDecl.parameters();
    // index over the oldParameters
    int k = 0;
    for (int i = 0; i < fParameterChanges.length; i++) {
        ChangeDescription curr = fParameterChanges[i];
        if (curr == null) {
            SingleVariableDeclaration oldParam = parameters.get(k);
            usedNames.add(oldParam.getName().getIdentifier());
            k++;
        } else if (curr instanceof InsertDescription) {
            InsertDescription desc = (InsertDescription) curr;
            SingleVariableDeclaration newNode = ast.newSingleVariableDeclaration();
            newNode.setType(imports.addImport(desc.type, ast, context, TypeLocation.PARAMETER));
            // $NON-NLS-1$
            newNode.setName(ast.newSimpleName("x"));
            // remember to set name later
            desc.resultingParamName = new SimpleName[] { newNode.getName() };
            desc.resultingParamType = newNode.getType();
            hasCreatedVariables = true;
            listRewrite.insertAt(newNode, i, null);
            Javadoc javadoc = methodDecl.getJavadoc();
            if (javadoc != null) {
                TagElement newTagElement = ast.newTagElement();
                newTagElement.setTagName(TagElement.TAG_PARAM);
                // $NON-NLS-1$
                SimpleName arg = ast.newSimpleName("x");
                newTagElement.fragments().add(arg);
                insertParamTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), parameters, k, newTagElement);
                // set the name later
                desc.resultingTagArg = arg;
            } else {
                desc.resultingTagArg = null;
            }
        } else if (curr instanceof RemoveDescription) {
            SingleVariableDeclaration decl = parameters.get(k);
            listRewrite.remove(decl, null);
            k++;
            TagElement tagNode = findParamTag(methodDecl, decl);
            if (tagNode != null) {
                rewrite.remove(tagNode, null);
            }
        } else if (curr instanceof EditDescription) {
            EditDescription desc = (EditDescription) curr;
            ITypeBinding newTypeBinding = desc.type;
            SingleVariableDeclaration decl = parameters.get(k);
            if (k == parameters.size() - 1 && i == fParameterChanges.length - 1 && decl.isVarargs() && newTypeBinding.isArray()) {
                // stick with varargs if it was before
                newTypeBinding = newTypeBinding.getElementType();
            } else {
                rewrite.set(decl, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.FALSE, null);
            }
            Type newType = imports.addImport(newTypeBinding, ast, context, TypeLocation.PARAMETER);
            rewrite.replace(decl.getType(), newType, null);
            DimensionRewrite.removeAllChildren(decl, SingleVariableDeclaration.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null);
            TypeAnnotationRewrite.removePureTypeAnnotations(decl, SingleVariableDeclaration.MODIFIERS2_PROPERTY, rewrite, null);
            IBinding binding = decl.getName().resolveBinding();
            if (binding != null) {
                SimpleName[] names = LinkedNodeFinder.findByBinding(decl.getRoot(), binding);
                SimpleName[] newNames = new SimpleName[names.length];
                for (int j = 0; j < names.length; j++) {
                    // $NON-NLS-1$  // name will be set later
                    SimpleName newName = ast.newSimpleName("x");
                    newNames[j] = newName;
                    rewrite.replace(names[j], newName, null);
                }
                desc.resultingParamName = newNames;
            } else {
                // $NON-NLS-1$  // name will be set later
                SimpleName newName = ast.newSimpleName("x");
                rewrite.replace(decl.getName(), newName, null);
                // remember to set name later
                desc.resultingParamName = new SimpleName[] { newName };
            }
            desc.resultingParamType = newType;
            desc.orginalName = decl.getName().getIdentifier();
            hasCreatedVariables = true;
            k++;
            TagElement tagNode = findParamTag(methodDecl, decl);
            if (tagNode != null) {
                List<? extends ASTNode> fragments = tagNode.fragments();
                if (!fragments.isEmpty()) {
                    // $NON-NLS-1$
                    SimpleName arg = ast.newSimpleName("x");
                    rewrite.replace(fragments.get(0), arg, null);
                    desc.resultingTagArg = arg;
                }
            }
        } else if (curr instanceof SwapDescription) {
            SingleVariableDeclaration decl1 = parameters.get(k);
            SingleVariableDeclaration decl2 = parameters.get(((SwapDescription) curr).index);
            rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null);
            rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null);
            usedNames.add(decl1.getName().getIdentifier());
            k++;
            TagElement tagNode1 = findParamTag(methodDecl, decl1);
            TagElement tagNode2 = findParamTag(methodDecl, decl2);
            if (tagNode1 != null && tagNode2 != null) {
                rewrite.replace(tagNode1, rewrite.createCopyTarget(tagNode2), null);
                rewrite.replace(tagNode2, rewrite.createCopyTarget(tagNode1), null);
            }
        }
    }
    if (!hasCreatedVariables) {
        return;
    }
    if (methodDecl.getBody() != null) {
        // avoid take a name of a local variable inside
        CompilationUnit root = (CompilationUnit) methodDecl.getRoot();
        IBinding[] bindings = (new ScopeAnalyzer(root)).getDeclarationsAfter(methodDecl.getBody().getStartPosition(), ScopeAnalyzer.VARIABLES);
        for (int i = 0; i < bindings.length; i++) {
            usedNames.add(bindings[i].getName());
        }
    }
    fixupNames(rewrite, usedNames);
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) TagElement(org.eclipse.jdt.core.dom.TagElement) ArrayList(java.util.ArrayList) List(java.util.List) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer)

Example 48 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project eclipse.jdt.ls by eclipse.

the class ChangeMethodSignatureProposal method insertParamTag.

private TagElement insertParamTag(ListRewrite tagRewriter, List<SingleVariableDeclaration> parameters, int currentIndex, TagElement newTagElement) {
    HashSet<String> previousNames = new HashSet<>();
    for (int n = 0; n < currentIndex; n++) {
        SingleVariableDeclaration var = parameters.get(n);
        previousNames.add(var.getName().getIdentifier());
    }
    JavadocTagsSubProcessor.insertTag(tagRewriter, newTagElement, previousNames);
    return newTagElement;
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) HashSet(java.util.HashSet)

Example 49 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project eclipse.jdt.ls by eclipse.

the class UnusedCodeFix method hasSideEffect.

private static boolean hasSideEffect(SimpleName reference) {
    ASTNode parent = reference.getParent();
    while (parent instanceof QualifiedName) {
        parent = parent.getParent();
    }
    if (parent instanceof FieldAccess) {
        parent = parent.getParent();
    }
    ASTNode node = null;
    int nameParentType = parent.getNodeType();
    if (nameParentType == ASTNode.ASSIGNMENT) {
        Assignment assignment = (Assignment) parent;
        node = assignment.getRightHandSide();
    } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
        SingleVariableDeclaration decl = (SingleVariableDeclaration) parent;
        node = decl.getInitializer();
        if (node == null) {
            return false;
        }
    } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        node = parent;
    } else {
        return false;
    }
    ArrayList<Expression> sideEffects = new ArrayList<>();
    node.accept(new SideEffectFinder(sideEffects));
    return sideEffects.size() > 0;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 50 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration in project jbosstools-hibernate by jbosstools.

the class ProcessEntityInfo method visit.

@SuppressWarnings("unchecked")
public boolean visit(TypeDeclaration node) {
    ITypeBinding typeBinding = node.resolveBinding();
    String nodeName = typeBinding == null ? null : typeBinding.getBinaryName();
    if (nodeName == null) {
        return false;
    }
    entityInfo = entityInfos.getEntityInfo(nodeName);
    if (entityInfo == null) {
        return false;
    }
    if (entityInfo.isAddMappedSuperclassFlag()) {
        MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation();
        matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_MAPPEDSUPERCLASS));
        ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.MODIFIERS2_PROPERTY);
        lrw.insertFirst(matd, null);
    }
    if (entityInfo.isAddEntityFlag()) {
        MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation();
        matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_ENTITY));
        ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.MODIFIERS2_PROPERTY);
        lrw.insertFirst(matd, null);
    }
    /**
     * /
     *		if (!entityInfo.isImplicitConstructorFlag() && !entityInfo.isDefaultConstructorFlag() &&
     *				entityInfo.isAddSerializableInterfaceFlag()) {
     *			// add serializable interface
     *			SimpleName sn = null;
     *			//if (!entityInfo.isAddSerializableInterfaceImportFlag()) {
     *				sn = rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_SERIALIZABLE);
     *			//}
     *			//else {
     *			//	sn = rewriter.getAST().newSimpleName(JPAConst.IMPORT_SERIALIZABLE);
     *			//}
     *			SimpleType st = rewriter.getAST().newSimpleType(sn);
     *			ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
     *			lrw.insertFirst(st, null);
     *			// add "private static final long serialVersionUID = 1L;"
     *			// ...
     *		}
     *		/*
     */
    if (!entityInfo.isImplicitConstructorFlag() && !entityInfo.isDefaultConstructorFlag() && entityInfo.isAddSerializableInterfaceFlag()) {
        MethodDeclaration md = rewriter.getAST().newMethodDeclaration();
        md.setConstructor(true);
        Modifier modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
        md.modifiers().add(modifier);
        Block body = rewriter.getAST().newBlock();
        md.setBody(body);
        SimpleName sn = rewriter.getAST().newSimpleName(entityInfo.getName());
        md.setName(sn);
        ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        List<?> list = lrw.getOriginalList();
        MethodDeclaration insertBeforeNode = null;
        Iterator<?> it = list.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            if (obj instanceof MethodDeclaration) {
                insertBeforeNode = (MethodDeclaration) obj;
                break;
            }
        }
        if (insertBeforeNode == null) {
            lrw.insertLast(md, null);
        } else {
            lrw.insertBefore(md, insertBeforeNode, null);
        }
    }
    if (enableOptLock && entityInfo.isAddVersionFlag() && !entityInfo.hasVersionAnnotation()) {
        // add property "version", add getter/setter getVersion/setVersion,
        // add annotation for the property or for the getter
        // 
        // $NON-NLS-1$
        final String version = "version";
        // $NON-NLS-1$
        final String versionType = "Integer";
        // 
        VariableDeclarationFragment vdFragment = rewriter.getAST().newVariableDeclarationFragment();
        SimpleName variableName = rewriter.getAST().newSimpleName(version);
        vdFragment.setName(variableName);
        FieldDeclaration fieldVersion = rewriter.getAST().newFieldDeclaration(vdFragment);
        Modifier modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD);
        fieldVersion.modifiers().add(modifier);
        Name typeName = rewriter.getAST().newName(versionType);
        SimpleType type = rewriter.getAST().newSimpleType(typeName);
        fieldVersion.setType(type);
        // 
        MethodDeclaration mdGetter = rewriter.getAST().newMethodDeclaration();
        modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
        mdGetter.modifiers().add(modifier);
        Block body = rewriter.getAST().newBlock();
        ReturnStatement returnVersion = rewriter.getAST().newReturnStatement();
        variableName = rewriter.getAST().newSimpleName(version);
        returnVersion.setExpression(variableName);
        body.statements().add(returnVersion);
        mdGetter.setBody(body);
        // $NON-NLS-1$
        SimpleName sn = rewriter.getAST().newSimpleName("getVersion");
        mdGetter.setName(sn);
        typeName = rewriter.getAST().newName(versionType);
        type = rewriter.getAST().newSimpleType(typeName);
        mdGetter.setReturnType2(type);
        // 
        MethodDeclaration mdSetter = rewriter.getAST().newMethodDeclaration();
        modifier = rewriter.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
        mdSetter.modifiers().add(modifier);
        body = rewriter.getAST().newBlock();
        Assignment assignment = rewriter.getAST().newAssignment();
        FieldAccess fieldAccess = rewriter.getAST().newFieldAccess();
        ThisExpression thisExpression = rewriter.getAST().newThisExpression();
        fieldAccess.setExpression(thisExpression);
        variableName = rewriter.getAST().newSimpleName(version);
        fieldAccess.setName(variableName);
        assignment.setLeftHandSide(fieldAccess);
        variableName = rewriter.getAST().newSimpleName(version);
        assignment.setRightHandSide(variableName);
        ExpressionStatement expressionStatement = rewriter.getAST().newExpressionStatement(assignment);
        body.statements().add(expressionStatement);
        mdSetter.setBody(body);
        // $NON-NLS-1$
        sn = rewriter.getAST().newSimpleName("setVersion");
        mdSetter.setName(sn);
        SingleVariableDeclaration svd = rewriter.getAST().newSingleVariableDeclaration();
        variableName = rewriter.getAST().newSimpleName(version);
        svd.setName(variableName);
        typeName = rewriter.getAST().newName(versionType);
        type = rewriter.getAST().newSimpleType(typeName);
        svd.setType(type);
        mdSetter.parameters().add(svd);
        // 
        ListRewrite lrw = rewriter.getListRewrite(node, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        if (entityInfo.getVersionFieldGetter() != FieldGetterType.FIELD && entityInfo.getVersionFieldGetter() != FieldGetterType.FIELD_GETTER) {
            lrw.insertLast(fieldVersion, null);
        }
        if (entityInfo.getVersionFieldGetter() != FieldGetterType.GETTER && entityInfo.getVersionFieldGetter() != FieldGetterType.FIELD_GETTER) {
            lrw.insertLast(mdGetter, null);
            lrw.insertLast(mdSetter, null);
        }
        if (annotationStyle == AnnotStyle.FIELDS) {
            MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation();
            matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_VERSION));
            lrw = rewriter.getListRewrite(fieldVersion, FieldDeclaration.MODIFIERS2_PROPERTY);
            lrw.insertFirst(matd, null);
        } else if (annotationStyle == AnnotStyle.GETTERS) {
            MarkerAnnotation matd = rewriter.getAST().newMarkerAnnotation();
            matd.setTypeName(rewriter.getAST().newSimpleName(JPAConst.ANNOTATION_VERSION));
            lrw = rewriter.getListRewrite(mdGetter, MethodDeclaration.MODIFIERS2_PROPERTY);
            lrw.insertFirst(matd, null);
        }
    }
    return true;
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Assignment(org.eclipse.jdt.core.dom.Assignment) SimpleType(org.eclipse.jdt.core.dom.SimpleType) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) Modifier(org.eclipse.jdt.core.dom.Modifier)

Aggregations

SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)124 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)41 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)39 Type (org.eclipse.jdt.core.dom.Type)37 Block (org.eclipse.jdt.core.dom.Block)35 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 AST (org.eclipse.jdt.core.dom.AST)32 ArrayList (java.util.ArrayList)29 List (java.util.List)27 SimpleName (org.eclipse.jdt.core.dom.SimpleName)27 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)27 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)26 Expression (org.eclipse.jdt.core.dom.Expression)22 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)20 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)18 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)18 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)17 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)16 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)16 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)16