Example usage for org.eclipse.jdt.core.dom MethodDeclaration getParent

List of usage examples for org.eclipse.jdt.core.dom MethodDeclaration getParent

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom MethodDeclaration getParent.

Prototype

public final ASTNode getParent() 

Source Link

Document

Returns this node's parent node, or null if this is the root node.

Usage

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaMethod.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w  w w.j a va  2s .c o  m*/
protected void setASTFeatureValue(EStructuralFeature feature, MethodDeclaration astElement, Object value)
        throws CodeSyncException {
    if (astElement == null)
        throw new IllegalArgumentException("astElement null ");
    AST ast = astElement.getAST();

    switch (feature.getFeatureID()) {
    case UMLPackage.NAMED_ELEMENT__NAME:
        if (value == null)
            throw new IllegalArgumentException("setting name to null value ");
        astElement.setName(ast.newSimpleName((String) value));
        break;
    case UMLPackage.OPERATION__TYPE:
        parentForwardJavaClass_OwnedMethods.parentForwardJavaType.parentForwardJavaSrcDir_Files
                .createImportDeclarationIfNeeded((Type) value);
        String modelReturnType = value == null ? null : ((Type) value).getName();
        if (!astElement.isConstructor()) {
            TypeDeclaration parent = (TypeDeclaration) astElement.getParent();
            if (value == null
                    && astElement.getName().getIdentifier().equals(parent.getName().getIdentifier())) {
                // transform this method to constructor
                astElement.setConstructor(true);
            } else //if null value => return void type
                astElement.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, modelReturnType, true));
        } else if (value != null) {
            // transforming from constructor to ordinary method
            astElement.setConstructor(false);
            astElement.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, modelReturnType, true));
        }
        break;
    case UMLPackage.BEHAVIORAL_FEATURE__OWNED_PARAMETER:
        astElement.parameters().clear();
        for (Parameter par : (List<Parameter>) value)
            if (par.getDirection().equals(ParameterDirectionKind.IN_LITERAL)) {
                parentForwardJavaClass_OwnedMethods.parentForwardJavaType.parentForwardJavaSrcDir_Files
                        .createImportDeclarationIfNeeded(par.getType());

                SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
                String paramName = par.getName();
                String paramType = par.getType() == null ? null : par.getType().getName();
                if (paramName == null)
                    throw new IllegalArgumentException("Parameter name is null: " + par);
                variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, paramType, true));
                try {
                    variableDeclaration.setName(ast.newSimpleName(paramName));
                } catch (IllegalArgumentException e) {
                    throw new CodeSyncException("Invalid Parameter Name: \"" + paramName
                            + "\" on java operation: " + astElement.getName() + "()", e);
                }
                astElement.parameters().add(variableDeclaration);
            }
        break;
    case UMLPackage.BEHAVIORAL_FEATURE__IS_ABSTRACT:
        JavaSyncUtils.updateModifierFromModelToJavaClass(astElement, (Boolean) value,
                JavaSyncUtils.MODIFIER_ABSTRACT);
        break;
    case UMLPackage.ELEMENT__EANNOTATIONS:
        List<EAnnotation> annotations = (List<EAnnotation>) value;
        for (EAnnotation annot : annotations) {
            // search for a template method annotation
            if (annot.getSource().equals("TemplateMethod") && annot.getDetails().containsKey("id")) {
                String bodyContent = JetTemplateFactory.INSTANCE
                        .invokeOperationJetTemplate(annot.getEModelElement(), annot.getDetails().get("id"));
                if (annot.getDetails().containsKey("comment")) { // if it must contain also the template comment
                    String commentLine = JetTemplateFactory.INSTANCE.invokeOperationJetTemplate(
                            annot.getEModelElement(), annot.getDetails().get("comment"));
                    JavaSyncUtils.generateBodyWithCommentForMethod(astElement, bodyContent, commentLine);
                } else { // add only content to method
                    JavaSyncUtils.generateBodyForMethod(astElement, bodyContent);
                }
                // remove annotation; it doesn't need to be synchronized
                annotations.remove(annot);
                break;
            }
        }
        break;
    default:
        super.setASTFeatureValue(feature, astElement, value);
    }
}

From source file:com.google.devtools.j2cpp.translate.GwtConverter.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    @SuppressWarnings("unchecked")
    List<IExtendedModifier> modifiers = node.modifiers();
    if (hasAnnotation(GwtIncompatible.class, modifiers)) {
        // Remove method from its declaring class.
        ASTNode parent = node.getParent();
        if (parent instanceof TypeDeclarationStatement) {
            parent = ((TypeDeclarationStatement) parent).getDeclaration();
        }//from w w w.  jav a  2s  . c  o m
        if (parent instanceof AbstractTypeDeclaration) {
            ((AbstractTypeDeclaration) parent).bodyDeclarations().remove(node);
        } else if (parent instanceof AnonymousClassDeclaration) {
            ((AnonymousClassDeclaration) parent).bodyDeclarations().remove(node);
        } else {
            throw new AssertionError("unknown parent type: " + parent.getClass().getSimpleName());
        }
    }
    return true;
}

From source file:com.halware.nakedide.eclipse.ext.outline.NakedObjectMember.java

License:Open Source License

public NakedObjectMember(ICompilationUnit compilationUnit, String memberName,
        MethodDeclaration methodDeclaration, MemberType memberType, Map<String, IMethod> methodsByName) {
    super(compilationUnit, methodDeclaration);
    this.memberName = memberName;
    this.memberType = memberType;
    parent = (TypeDeclaration) methodDeclaration.getParent();
    this.methodsByName = methodsByName;
}

From source file:com.kodebeagle.javaparser.MethodInvocationResolver.java

License:Apache License

private void addMethodDoc(MethodDeclaration node) {
    if (node.getJavadoc() != null && node.getParent() instanceof AbstractTypeDeclaration) {
        String typeName = ((AbstractTypeDeclaration) node.getParent()).getName().getFullyQualifiedName();
        String fullTypeName = currentPackage + "." + removeSpecialSymbols(typeName);
        TypeJavadoc typeJavadoc = typeJavadocs.get(fullTypeName);
        if (typeJavadoc != null) {
            typeJavadoc.getMethodJavadocs().add(
                    new MethodJavadoc(node.getName().getFullyQualifiedName(), node.getJavadoc().toString()));
        }//w ww .ja v a  2 s. c  om
    }
}

From source file:de.fkoeberle.autocommit.message.java.factories.AddedMethodCMF.java

License:Open Source License

@Override
public String createMessage() throws IOException {
    BodyDeclaration addedDeclaration = singleAddedBodyDeclarationView.getAddedDeclaration();
    if (!(addedDeclaration instanceof MethodDeclaration)) {
        return null;
    }//from  w  ww  .  ja va 2  s  .co  m
    MethodDeclaration addedMethod = (MethodDeclaration) addedDeclaration;

    AbstractTypeDeclaration type = (AbstractTypeDeclaration) (addedMethod.getParent());

    String fullTypeName = TypeUtil.fullTypeNameOf(type);
    String methodName = TypeUtil.nameOfMethod(addedMethod);
    String parameterTypes = TypeUtil.parameterTypesOf(addedMethod);
    String typeName = TypeUtil.nameOf(type);
    CommitMessageTemplate message;
    if (addedMethod.isConstructor()) {
        message = addedConstructorMessage;
    } else {

        message = addedMethodMessage;
    }

    return message.createMessageWithArgs(fullTypeName, methodName, parameterTypes, typeName);
}

From source file:de.ovgu.cide.export.physical.ahead.ast.JakClassRefinement.java

License:Open Source License

/**
 * adds a refinement for a given original method. if the method belongs to
 * an inner class the method is added to the according inner class
 * refinement//  w w w .j ava  2 s . c o m
 * 
 * @param method
 * @param copiedMethod
 */
public void addRefinementForMethod(MethodDeclaration originalMethod, MethodDeclaration refinement) {

    assert originalMethod.getParent() instanceof TypeDeclaration;
    // toplevel class
    if (originalMethod.getParent().getParent() instanceof CompilationUnit)
        this.addRefinement(refinement);
    else {// inner class
        assert originalMethod.getParent().getParent() instanceof TypeDeclaration;
        assert originalMethod.getParent().getParent().getParent() instanceof CompilationUnit;
        TypeDeclaration innerClass = (TypeDeclaration) originalMethod.getParent();
        JakClassRefinement innerClassRefinement = getInnerClassRefinement(innerClass);
        innerClassRefinement.addRefinement(refinement);
    }

}

From source file:de.ovgu.cide.export.physical.ahead.MethodObjectHelper.java

License:Open Source License

public static TypeDeclaration moveMethodToMethodObject(MethodDeclaration method,
        RefactoringColorManager colorManager, boolean isStatic) {
    debug_numberOfMessageObjects++;/*from w  w  w  .java2  s.c om*/

    AST ast = method.getAST();
    assert method.getParent() instanceof TypeDeclaration;
    TypeDeclaration containingClass = (TypeDeclaration) method.getParent();

    String moName = getMethodObjectName(containingClass, method);
    // System.out.println(moName);
    boolean isSourceMethodStatic = isMethodStatic(method);
    if (isStatic && !isSourceMethodStatic)
        makeThisAccessExplicit(method);

    // create inner class and execute method
    TypeDeclaration methodObjectClass = ast.newTypeDeclaration();
    methodObjectClass.setName(ast.newSimpleName(moName));
    if (isStatic) {
        Modifier staticModifier = ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD);
        methodObjectClass.modifiers().add(staticModifier);

    }

    MethodDeclaration executeMethod = ast.newMethodDeclaration();
    executeMethod.setName(ast.newSimpleName("execute"));
    executeMethod.setReturnType2((Type) ASTNode.copySubtree(ast, method.getReturnType2()));
    executeMethod.thrownExceptions().addAll(ASTNode.copySubtrees(ast, method.thrownExceptions()));

    methodObjectClass.bodyDeclarations().add(executeMethod);
    containingClass.bodyDeclarations().add(methodObjectClass);

    createConstructor(methodObjectClass, method, isStatic && !isSourceMethodStatic);

    // move body to MO
    Block oldMethodBody = method.getBody();
    Block newMethodBody = ast.newBlock();
    method.setBody(newMethodBody);

    executeMethod.setBody(oldMethodBody);

    if (isStatic && !isSourceMethodStatic)
        changeThisAccessToField(oldMethodBody);

    // call method object
    ClassInstanceCreation moConstructorCall = ast.newClassInstanceCreation();
    moConstructorCall.setType(ast.newSimpleType(ast.newSimpleName(moName)));
    addParamters(moConstructorCall, method, isStatic && !isSourceMethodStatic);
    MethodInvocation moCall = ast.newMethodInvocation();
    moCall.setExpression(moConstructorCall);
    moCall.setName(ast.newSimpleName("execute"));
    if (RefactoringUtils.isVoid(method.getReturnType2())) {
        newMethodBody.statements().add(ast.newExpressionStatement(moCall));
    } else {
        ReturnStatement returnStmt = ast.newReturnStatement();
        returnStmt.setExpression(moCall);
        newMethodBody.statements().add(returnStmt);
    }

    // adjustColors
    colorManager.setColors(methodObjectClass, colorManager.getOwnColors(method));

    moveLocalVariableDeclarationsToFields(executeMethod, methodObjectClass, colorManager);

    addMethodObjectAnnotation(methodObjectClass);

    return methodObjectClass;
}

From source file:de.ovgu.cide.export.physical.ahead.RefactoringUtils.java

License:Open Source License

public static boolean canRefactorStatementsBeforeAfter(MethodDeclaration method, List<Statement> refactorFirst,
        List<Statement> refactorLast, RefactoringColorManager colorManager, Set<IFeature> derivative) {
    if (!(method.getParent() instanceof TypeDeclaration))
        return false;
    if (!(method.getParent().getParent() instanceof CompilationUnit))
        if (!MethodObjectHelper.isMethodObjectClass((TypeDeclaration) method.getParent()))
            return false;

    if (refactorFirst.size() == 0 && refactorLast.size() == 0)
        return false;
    // check that there are no variables defined (otherwise just do not
    // refactor this, but wait for hook methods)
    if (refactorLast.size() > 0) {
        LocalVariableAnalyzer lva = new LocalVariableAnalyzer(method, refactorLast, refactorFirst,
                colorManager);// www. j  a v  a2s.  c o  m
        lva.setIgnoreMethodParameters(true);
        lva.execute();
        if (lva.getParameters().size() > 0)
            return false;
    }
    // cannot refactor first statements in constructor, only the end
    if (method.isConstructor())
        if (refactorFirst.size() > 0 && !refactorFirst.equals(method.getBody().statements()))
            return false;
    // check that these statements do not contain exceptions to the subtree
    // rule
    if (containsSubtreeRuleException(refactorFirst, colorManager, derivative)
            || containsSubtreeRuleException(refactorLast, colorManager, derivative))
        return false;

    return true;
}

From source file:de.ovgu.cide.export.physical.ahead.validator.LocalVariableTmp.java

License:Open Source License

private void count(MethodDeclaration method, String varName) {
    counter++;/*from   www .j  av  a  2s  .  com*/
    System.out.println(
            "Local variable conflict: " + counter + " (in " + ((TypeDeclaration) method.getParent()).getName()
                    + "." + method.getName().toString() + ":" + varName + ")");
}

From source file:edu.cmu.cs.crystal.cfg.eclipse.EclipseCFG.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    EclipseCFGNode method = nodeMap.get(node);
    EclipseCFGNode implicitCatch;/*from  www .jav a2  s . co m*/

    excpReturns = new HashMap<ITypeBinding, EclipseCFGNode>();

    undeclExit = new EclipseCFGNode(null);
    createEdge(undeclExit, method);
    undeclExit.setName("(error)");
    exceptionMap.pushCatch(undeclExit, node.getAST().resolveWellKnownType("java.lang.Throwable"));

    for (Name name : (List<Name>) node.thrownExceptions()) {
        implicitCatch = new EclipseCFGNode(null);
        createEdge(implicitCatch, method);
        implicitCatch.setName("(throws)");
        exceptionMap.pushCatch(implicitCatch, (ITypeBinding) name.resolveBinding());
        excpReturns.put(name.resolveTypeBinding(), implicitCatch);
    }

    uberReturn = new EclipseCFGNode(null);
    uberReturn.setName("(uber-return)");
    createEdge(uberReturn, method);

    if (node.isConstructor()) {
        TypeDeclaration type = (TypeDeclaration) node.getParent();
        for (FieldDeclaration field : type.getFields()) {
            if (!Modifier.isStatic(field.getModifiers()))
                field.accept(this);
        }
    }

    // visit the statements individually.
    // we'll need to put them together by hand later so we can insert the
    // field decls
    // into constructors.
    for (ASTNode param : (List<ASTNode>) node.parameters())
        param.accept(this);
    if (node.getBody() != null)
        for (ASTNode stmt : (List<ASTNode>) node.getBody().statements())
            stmt.accept(this);

    return false;
}