List of usage examples for org.eclipse.jdt.core.dom MethodDeclaration getName
public SimpleName getName()
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.AbstractStateMachineTestStrategy.java
License:Open Source License
protected MethodDeclaration cloneMethodDeclaration(MethodDeclaration declaration) { MethodDeclaration clone = (MethodDeclaration) ASTNode.copySubtree(declaration.getAST(), declaration); clone.setName(declaration.getAST().newSimpleName(declaration.getName().getIdentifier() + "_clone")); return clone; }
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.PathWithUncertaintyTestStrategy.java
License:Open Source License
/** * /*from ww w . j a va2 s .c om*/ * @param state - the state for which we inspect the transitions and generate the test plan * @param rewrite - rewriter used to modify the generated code * @param planMethodDeclaration - the method in which the code must be added * @param parrentPlanBlock - the block of code where the new state code must be added. Can be a method body, the body of an If statement, etc * @param pathTransitions - used to avoid testing cycles and ensure test plan keeps uniqueness on transitions */ private void generatePlanForState(final StateMachineState state, final ASTRewrite rewrite, final MethodDeclaration planMethodDeclaration, final Set<StateMachineStateTransition> pathTransitions) { AST ast = planMethodDeclaration.getAST(); Block parrentPlanBlock = planMethodDeclaration.getBody(); ListRewrite listRewrite = rewrite.getListRewrite(parrentPlanBlock, Block.STATEMENTS_PROPERTY); /** * First we create an abstract method to assert that we have reached current state and we call it * only if the state is not a choice. Choices are "virtual" states that signal splits in transition. * */ { //only create method if not previously created String stateName = state.getName(); String methodName = ASSERT_STATE_LEADING + stateName; if (!generatedAbstractMethods.containsKey(stateName)) { MethodDeclaration method = createAbstractMethodForState(state, planMethodDeclaration.getAST()); generatedAbstractMethods.put(stateName, method); } /** * Call the assert state method to check if we have reached the current state. * For the initial state this assert can also reset the system to initial state. */ { //invoke guard as Assert statement AssertStatement assertStatement = ast.newAssertStatement(); MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(methodName)); assertStatement.setExpression(invocation); parrentPlanBlock.statements().add(assertStatement); // listRewrite.insertFirst(rewrite.createStringPlaceholder("//Call the assert state method to check if we have reached the current state.", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("//For the initial state this assert can also reset the system to initial state.", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(assertStatement, null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); } } /** * If from one state we have multiple triggers, or from a choice we can go to multiple classes * then we generate for each of these transitions paths a separate test plan. * This means we clone the previous method into how many we need */ List<StateMachineStateTransition> transitions = state.getOutTransitions(); //if 1 transition, then we add to same plan //if more, we need separate test plans for each branching if (transitions.isEmpty() && !(state.getVertex() instanceof FinalState)) { //notify user that something is wrong with the model we are converting notifyUser("State \"" + state.getName() + "\"is not final and does not have any transitions. All state machine flows must reach a FinalState."); System.err.println(state.getName() + " is not final and does not have any transitions. All state machine flows must reach a FinalState to be converted in test plans."); } else if (transitions.size() == 1) { StateMachineStateTransition transition = transitions.get(0); //if we have visited this transition, continue if (pathTransitions.contains(transition)) { return; } else { // add transition to visited transitions pathTransitions.add(transition); } // listRewrite.insertLast(rewrite.createStringPlaceholder("//Test transition " + transition.getTransition().getName(), ASTNode.EMPTY_STATEMENT), null); /** * Must assert before any transition that the guard condition is fulfilled */ { //get transition condition (could also be Rule, currently we get only Guard transitions) Constraint guard = transition.getTransition().getGuard(); if (guard != null) { for (Element element : guard.allOwnedElements()) { //currently condition retrieved as plain text that will need to be parsed and evaluated OpaqueExpression expression = (OpaqueExpression) element; for (String body : expression.getBodies()) { if (body.isEmpty()) { notifyUser("Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); System.err.println( "Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); continue; } MethodDeclaration method = createAbstractMethodForGuard(body, ast); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke guard as Assert statement AssertStatement assertStatement = ast.newAssertStatement(); MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); assertStatement.setExpression(invocation); parrentPlanBlock.statements().add(assertStatement); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Assert guard condition for next transition is true", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(assertStatement, null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); } } } } //get all transition triggers List<Trigger> triggers = transition.getTransition().getTriggers(); //for each trigger for (Trigger trigger : triggers) { /** * If we have not created it already, we create an abstract method to invoke the trigger */ { //TODO: update so we do not generate the trigger if it was already generated MethodDeclaration method = createAbstractTriggerInvocation(trigger, planMethodDeclaration.getAST()); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke trigger MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(ast.newExpressionStatement(invocation), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation)); } } if (!(state.getVertex() instanceof FinalState)) { //continue from target state with plan generation StateMachineState targetState = transition.getTargetState(); generatePlanForState(targetState, rewrite, planMethodDeclaration, pathTransitions); } else { if (transition.getTargetState() == null) { notifyUser(state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); System.err.println( state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); } } } else if (transitions.size() > 1) { for (StateMachineStateTransition transition : transitions) { //clone transitions to use clean path for each sub-trees Set<StateMachineStateTransition> transitionsCopy = new HashSet<>(); transitionsCopy.addAll(pathTransitions); //if we have visited this transition, continue if (transitionsCopy.contains(transition)) { continue; } else { // add transition to visited transitions transitionsCopy.add(transition); } //for each transition we do a clone of the plan until now MethodDeclaration transitionMethod = cloneMethodDeclaration(planMethodDeclaration); transitionMethod.setName(ast .newSimpleName(PLAN_METHOD_LEADING + (UUID.randomUUID().toString().replaceAll("\\W", "")))); //shadowing to local parrentPlanBlock parrentPlanBlock = transitionMethod.getBody(); //shadowing to local ListRewrite // listRewrite = rewrite.getListRewrite(transitionMethod.getBody(), Block.STATEMENTS_PROPERTY); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Forcing transition " + transition.getTransition().getName() + " by ensuring guard conditions are met and triggers are invoked.", ASTNode.EMPTY_STATEMENT), null); /** * Must force-set all guard conditions to navigate to this particular execution branch */ { //get transition condition (could also be Rule, currently we get only Guard transitions) //force for the current test the transition condition to true, to enable the system to navigate to expected state Constraint guard = transition.getTransition().getGuard(); if (guard != null) { for (Element element : guard.allOwnedElements()) { //currently condition retrieved as plain text that will need to be parsed and evaluated OpaqueExpression expression = (OpaqueExpression) element; for (String body : expression.getBodies()) { if (body.isEmpty()) { notifyUser("Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); System.err.println("Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); continue; } MethodDeclaration method = createAbstractForceConditionMethod(body, ast); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke method to force guard condition to true MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke method to force guard condition to true: " + body, ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(ast.newExpressionStatement(invocation), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation)); } } } } //get all transition triggers and execute them, like if we had only one transition List<Trigger> triggers = transition.getTransition().getTriggers(); //for each trigger for (Trigger trigger : triggers) { /** * If we have not created it already, we create an abstract method to invoke the trigger */ { //TODO: update so we do not generate the trigger if it was already generated MethodDeclaration method = createAbstractTriggerInvocation(trigger, transitionMethod.getAST()); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke trigger MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(ast.newExpressionStatement(invocation), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation)); } } if (!(state.getVertex() instanceof FinalState)) { //continue from target state with plan generation StateMachineState targetState = transition.getTargetState(); generatePlanForState(targetState, rewrite, transitionMethod, transitionsCopy); } else { if (transition.getTargetState() == null) { notifyUser(state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); System.err.println( state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); } } } } if (state.getVertex() instanceof FinalState) { //store generated method in methods //check and store only if there is at least one transition with an uncertain state boolean hasUncertainty = false; for (StateMachineStateTransition transition : pathTransitions) { //TODO: remove constant and make this efficient //check for all transitions only initial state for uncertainties //as for next transition, the initial will be the target of this one (except for final state) for (Stereotype stereotype : transition.getSourceState().getVertex().getAppliedStereotypes()) { //check if the applied stereotype is InfrastructureLevelUncertainty if (stereotype.getName().equals(INFRASTRUCTURE_UNCERTAINTY_NAME)) { hasUncertainty = true; break; } } } //if does not have any uncertainty on it, do not add it to generated plans if (hasUncertainty) { generatedPlans.put(planMethodDeclaration.getName().toString(), planMethodDeclaration); } } }
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.TransitionCorrectnessTestStrategy.java
License:Open Source License
/** * /*w w w. j a v a 2 s .c o m*/ * @param state - the state for which we inspect the transitions and generate the test plan * @param rewrite - rewriter used to modify the generated code * @param planMethodDeclaration - the method in which the code must be added * @param parrentPlanBlock - the block of code where the new state code must be added. Can be a method body, the body of an If statement, etc * @param pathTransitions - used to avoid testing cycles and ensure test plan keeps uniqueness on transitions */ private void generatePlanForState(final StateMachineState state, final ASTRewrite rewrite, final MethodDeclaration planMethodDeclaration, final Set<StateMachineStateTransition> pathTransitions) { AST ast = planMethodDeclaration.getAST(); Block parrentPlanBlock = planMethodDeclaration.getBody(); ListRewrite listRewrite = rewrite.getListRewrite(parrentPlanBlock, Block.STATEMENTS_PROPERTY); /** * First we create an abstract method to assert that we have reached current state and we call it * only if the state is not a choice. Choices are "virtual" states that signal splits in transition. * */ { //only create method if not previously created String stateName = state.getName(); String methodName = ASSERT_STATE_LEADING + stateName; if (!generatedAbstractMethods.containsKey(stateName)) { MethodDeclaration method = createAbstractMethodForState(state, planMethodDeclaration.getAST()); generatedAbstractMethods.put(stateName, method); } /** * Call the assert state method to check if we have reached the current state. * For the initial state this assert can also reset the system to initial state. */ { //invoke guard as Assert statement AssertStatement assertStatement = ast.newAssertStatement(); MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(methodName)); assertStatement.setExpression(invocation); parrentPlanBlock.statements().add(assertStatement); // listRewrite.insertFirst(rewrite.createStringPlaceholder("//Call the assert state method to check if we have reached the current state.", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("//For the initial state this assert can also reset the system to initial state.", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(assertStatement, null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); } } /** * If from one state we have multiple triggers, or from a choice we can go to multiple classes * then we generate for each of these transitions paths a separate test plan. * This means we clone the previous method into how many we need */ List<StateMachineStateTransition> transitions = state.getOutTransitions(); //if 1 transition, then we add to same plan //if more, we need separate test plans for each branching if (transitions.isEmpty() && !(state.getVertex() instanceof FinalState)) { //notify user that something is wrong with the model we are converting notifyUser("State \"" + state.getName() + "\"is not final and does not have any transitions. All state machine flows must reach a FinalState."); System.err.println(state.getName() + " is not final and does not have any transitions. All state machine flows must reach a FinalState to be converted in test plans."); } else if (transitions.size() == 1) { StateMachineStateTransition transition = transitions.get(0); //if we have visited this transition, continue if (pathTransitions.contains(transition)) { return; } else { // add transition to visited transitions pathTransitions.add(transition); } // listRewrite.insertLast(rewrite.createStringPlaceholder("//Test transition " + transition.getTransition().getName(), ASTNode.EMPTY_STATEMENT), null); /** * Must assert before any transition that the guard condition is fulfilled */ { //get transition condition (could also be Rule, currently we get only Guard transitions) Constraint guard = transition.getTransition().getGuard(); if (guard != null) { for (Element element : guard.allOwnedElements()) { //currently condition retrieved as plain text that will need to be parsed and evaluated OpaqueExpression expression = (OpaqueExpression) element; for (String body : expression.getBodies()) { if (body.isEmpty()) { notifyUser("Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); System.err.println( "Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); continue; } MethodDeclaration method = createAbstractMethodForGuard(body, ast); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke guard as Assert statement AssertStatement assertStatement = ast.newAssertStatement(); MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); assertStatement.setExpression(invocation); parrentPlanBlock.statements().add(assertStatement); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Assert guard condition for next transition is true", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(assertStatement, null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); } } } } //get all transition triggers List<Trigger> triggers = transition.getTransition().getTriggers(); //for each trigger for (Trigger trigger : triggers) { /** * If we have not created it already, we create an abstract method to invoke the trigger */ { //TODO: update so we do not generate the trigger if it was already generated MethodDeclaration method = createAbstractTriggerInvocation(trigger, planMethodDeclaration.getAST()); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke trigger MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(ast.newExpressionStatement(invocation), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation)); } } if (!(state.getVertex() instanceof FinalState)) { //continue from target state with plan generation StateMachineState targetState = transition.getTargetState(); generatePlanForState(targetState, rewrite, planMethodDeclaration, pathTransitions); } else { if (transition.getTargetState() == null) { notifyUser(state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); System.err.println( state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); } } } else if (transitions.size() > 1) { for (StateMachineStateTransition transition : transitions) { //clone transitions to use clean path for each sub-trees //cloning is done here as we are generating different paths for each transition at this point Set<StateMachineStateTransition> transitionsCopy = new HashSet<>(); transitionsCopy.addAll(pathTransitions); //if we have visited this transition, continue if (transitionsCopy.contains(transition)) { continue; } else { // add transition to visited transitions transitionsCopy.add(transition); } //for each transition we do a clone of the plan until now MethodDeclaration transitionMethod = cloneMethodDeclaration(planMethodDeclaration); transitionMethod.setName(ast .newSimpleName(PLAN_METHOD_LEADING + (UUID.randomUUID().toString().replaceAll("\\W", "")))); //shadowing to local parrentPlanBlock parrentPlanBlock = transitionMethod.getBody(); //shadowing to local ListRewrite // listRewrite = rewrite.getListRewrite(transitionMethod.getBody(), Block.STATEMENTS_PROPERTY); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Forcing transition " + transition.getTransition().getName() + " by ensuring guard conditions are met and triggers are invoked.", ASTNode.EMPTY_STATEMENT), null); /** * Must force-set all guard conditions to navigate to this particular execution branch */ { //get transition condition (could also be Rule, currently we get only Guard transitions) //force for the current test the transition condition to true, to enable the system to navigate to expected state Constraint guard = transition.getTransition().getGuard(); if (guard != null) { for (Element element : guard.allOwnedElements()) { //currently condition retrieved as plain text that will need to be parsed and evaluated OpaqueExpression expression = (OpaqueExpression) element; for (String body : expression.getBodies()) { if (body.isEmpty()) { notifyUser("Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); System.err.println("Guard condition for transition " + transition.getTransition().getName() + " from state " + state.getName() + " is empty"); continue; } MethodDeclaration method = createAbstractForceConditionMethod(body, ast); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke method to force guard condition to true MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke method to force guard condition to true: " + body, ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(ast.newExpressionStatement(invocation), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation)); } } } } //get all transition triggers and execute them, like if we had only one transition List<Trigger> triggers = transition.getTransition().getTriggers(); //for each trigger for (Trigger trigger : triggers) { /** * If we have not created it already, we create an abstract method to invoke the trigger */ { //TODO: update so we do not generate the trigger if it was already generated MethodDeclaration method = createAbstractTriggerInvocation(trigger, transitionMethod.getAST()); if (!generatedAbstractMethods.containsKey(method.getName().toString())) { generatedAbstractMethods.put(method.getName().toString(), method); } //invoke trigger MethodInvocation invocation = ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(method.getName().toString())); // listRewrite.insertLast(rewrite.createStringPlaceholder("//Invoke transition trigger", ASTNode.EMPTY_STATEMENT), null); // listRewrite.insertLast(ast.newExpressionStatement(invocation), null); // listRewrite.insertLast(rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT), null); parrentPlanBlock.statements().add(ast.newExpressionStatement(invocation)); } } if (!(state.getVertex() instanceof FinalState)) { //continue from target state with plan generation StateMachineState targetState = transition.getTargetState(); generatePlanForState(targetState, rewrite, transitionMethod, transitionsCopy); } else { if (transition.getTargetState() == null) { notifyUser(state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); System.err.println( state.getName() + " is not final and does not have a target state on transition " + transition.getTransition().getName()); } } } } if (state.getVertex() instanceof FinalState) { //store generated method in methods generatedPlans.put(planMethodDeclaration.getName().toString(), planMethodDeclaration); } }
From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java
License:Open Source License
@Override public boolean visit(MethodDeclaration node) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); }/*w w w .j a v a 2s.co m*/ if (node.getAST().apiLevel() >= JLS3) { printModifiers(node.modifiers()); if (!node.typeParameters().isEmpty()) { this.fBuffer.append("<");//$NON-NLS-1$ for (Iterator<TypeParameter> it = node.typeParameters().iterator(); it.hasNext();) { TypeParameter t = it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(", ");//$NON-NLS-1$ } } this.fBuffer.append("> ");//$NON-NLS-1$ } } if (!node.isConstructor()) { if (node.getReturnType2() != null) { node.getReturnType2().accept(this); } else { // methods really ought to have a return type this.fBuffer.append("void");//$NON-NLS-1$ } this.fBuffer.append(" ");//$NON-NLS-1$ } node.getName().accept(this); this.fBuffer.append("(");//$NON-NLS-1$ if (node.getAST().apiLevel() >= AST.JLS8) { Type receiverType = node.getReceiverType(); if (receiverType != null) { receiverType.accept(this); this.fBuffer.append(' '); SimpleName qualifier = node.getReceiverQualifier(); if (qualifier != null) { qualifier.accept(this); this.fBuffer.append('.'); } this.fBuffer.append("this"); //$NON-NLS-1$ if (node.parameters().size() > 0) { this.fBuffer.append(','); } } } for (Iterator<SingleVariableDeclaration> it = node.parameters().iterator(); it.hasNext();) { SingleVariableDeclaration v = it.next(); v.accept(this); if (it.hasNext()) { this.fBuffer.append(", ");//$NON-NLS-1$ } } this.fBuffer.append(")");//$NON-NLS-1$ if (node.getAST().apiLevel() >= AST.JLS8) { List<Dimension> dimensions = node.extraDimensions(); for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext();) { Dimension e = it.next(); e.accept(this); } } else { for (int i = 0; i < node.getExtraDimensions(); i++) { this.fBuffer.append("[]"); //$NON-NLS-1$ } } List<? extends ASTNode> thrownExceptions = node.getAST().apiLevel() >= AST.JLS8 ? node.thrownExceptionTypes() : getThrownExceptions(node); if (!thrownExceptions.isEmpty()) { this.fBuffer.append(" throws ");//$NON-NLS-1$ for (Iterator<? extends ASTNode> it = thrownExceptions.iterator(); it.hasNext();) { ASTNode n = it.next(); n.accept(this); if (it.hasNext()) { this.fBuffer.append(", ");//$NON-NLS-1$ } } this.fBuffer.append(" ");//$NON-NLS-1$ } if (node.getBody() == null) { this.fBuffer.append(";");//$NON-NLS-1$ } else { node.getBody().accept(this); } return false; }
From source file:boa.datagen.util.Java7Visitor.java
License:Apache License
@Override public boolean visit(MethodDeclaration node) { List<boa.types.Ast.Method> list = methods.peek(); Method.Builder b = Method.newBuilder(); // b.setPosition(pos.build()); if (node.isConstructor()) b.setName("<init>"); else/*from w w w . j a v a2 s . c o m*/ b.setName(node.getName().getFullyQualifiedName()); for (Object m : node.modifiers()) { if (((IExtendedModifier) m).isAnnotation()) ((Annotation) m).accept(this); else ((org.eclipse.jdt.core.dom.Modifier) m).accept(this); b.addModifiers(modifiers.pop()); } boa.types.Ast.Type.Builder tb = boa.types.Ast.Type.newBuilder(); if (node.getReturnType2() != null) { String name = typeName(node.getReturnType2()); for (int i = 0; i < node.getExtraDimensions(); i++) name += "[]"; tb.setName(getIndex(name)); tb.setKind(boa.types.Ast.TypeKind.OTHER); b.setReturnType(tb.build()); } else { tb.setName(getIndex("void")); tb.setKind(boa.types.Ast.TypeKind.OTHER); b.setReturnType(tb.build()); } for (Object t : node.typeParameters()) { boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); String name = ((TypeParameter) t).getName().getFullyQualifiedName(); String bounds = ""; for (Object o : ((TypeParameter) t).typeBounds()) { if (bounds.length() > 0) bounds += " & "; bounds += typeName((org.eclipse.jdt.core.dom.Type) o); } if (bounds.length() > 0) name = name + " extends " + bounds; tp.setName(getIndex(name)); tp.setKind(boa.types.Ast.TypeKind.GENERIC); b.addGenericParameters(tp.build()); } for (Object o : node.parameters()) { SingleVariableDeclaration ex = (SingleVariableDeclaration) o; Variable.Builder vb = Variable.newBuilder(); // vb.setPosition(pos.build()); // FIXME vb.setName(ex.getName().getFullyQualifiedName()); for (Object m : ex.modifiers()) { if (((IExtendedModifier) m).isAnnotation()) ((Annotation) m).accept(this); else ((org.eclipse.jdt.core.dom.Modifier) m).accept(this); vb.addModifiers(modifiers.pop()); } boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); String name = typeName(ex.getType()); for (int i = 0; i < ex.getExtraDimensions(); i++) name += "[]"; if (ex.isVarargs()) name += "..."; tp.setName(getIndex(name)); tp.setKind(boa.types.Ast.TypeKind.OTHER); vb.setVariableType(tp.build()); if (ex.getInitializer() != null) { ex.getInitializer().accept(this); vb.setInitializer(expressions.pop()); } b.addArguments(vb.build()); } for (Object o : node.thrownExceptions()) { boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); tp.setName(getIndex(((Name) o).getFullyQualifiedName())); tp.setKind(boa.types.Ast.TypeKind.CLASS); b.addExceptionTypes(tp.build()); } if (node.getBody() != null) { statements.push(new ArrayList<boa.types.Ast.Statement>()); node.getBody().accept(this); for (boa.types.Ast.Statement s : statements.pop()) b.addStatements(s); } list.add(b.build()); return false; }
From source file:boa.datagen.util.Java8Visitor.java
License:Apache License
@Override public boolean visit(MethodDeclaration node) { List<boa.types.Ast.Method> list = methods.peek(); Method.Builder b = Method.newBuilder(); // b.setPosition(pos.build()); if (node.isConstructor()) b.setName("<init>"); else//w ww.j a v a 2 s . c om b.setName(node.getName().getFullyQualifiedName()); for (Object m : node.modifiers()) { if (((IExtendedModifier) m).isAnnotation()) ((Annotation) m).accept(this); else ((org.eclipse.jdt.core.dom.Modifier) m).accept(this); b.addModifiers(modifiers.pop()); } boa.types.Ast.Type.Builder tb = boa.types.Ast.Type.newBuilder(); if (node.getReturnType2() != null) { String name = typeName(node.getReturnType2()); // FIXME JLS8: Deprecated getExtraDimensions() and added extraDimensions() for (int i = 0; i < node.getExtraDimensions(); i++) name += "[]"; tb.setName(getIndex(name)); tb.setKind(boa.types.Ast.TypeKind.OTHER); b.setReturnType(tb.build()); } else { tb.setName(getIndex("void")); tb.setKind(boa.types.Ast.TypeKind.OTHER); b.setReturnType(tb.build()); } for (Object t : node.typeParameters()) { boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); String name = ((TypeParameter) t).getName().getFullyQualifiedName(); String bounds = ""; for (Object o : ((TypeParameter) t).typeBounds()) { if (bounds.length() > 0) bounds += " & "; bounds += typeName((org.eclipse.jdt.core.dom.Type) o); } if (bounds.length() > 0) name = name + " extends " + bounds; tp.setName(getIndex(name)); tp.setKind(boa.types.Ast.TypeKind.GENERIC); b.addGenericParameters(tp.build()); } if (node.getReceiverType() != null) { Variable.Builder vb = Variable.newBuilder(); // vb.setPosition(pos.build()); // FIXME vb.setName("this"); boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); String name = typeName(node.getReceiverType()); if (node.getReceiverQualifier() != null) name = node.getReceiverQualifier().getFullyQualifiedName() + "." + name; tp.setName(getIndex(name)); tp.setKind(boa.types.Ast.TypeKind.OTHER); // FIXME change to receiver? or something? vb.setVariableType(tp.build()); b.addArguments(vb.build()); } for (Object o : node.parameters()) { SingleVariableDeclaration ex = (SingleVariableDeclaration) o; Variable.Builder vb = Variable.newBuilder(); // vb.setPosition(pos.build()); // FIXME vb.setName(ex.getName().getFullyQualifiedName()); for (Object m : ex.modifiers()) { if (((IExtendedModifier) m).isAnnotation()) ((Annotation) m).accept(this); else ((org.eclipse.jdt.core.dom.Modifier) m).accept(this); vb.addModifiers(modifiers.pop()); } boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); String name = typeName(ex.getType()); // FIXME JLS8: Deprecated getExtraDimensions() and added extraDimensions() for (int i = 0; i < ex.getExtraDimensions(); i++) name += "[]"; if (ex.isVarargs()) name += "..."; tp.setName(getIndex(name)); tp.setKind(boa.types.Ast.TypeKind.OTHER); vb.setVariableType(tp.build()); if (ex.getInitializer() != null) { ex.getInitializer().accept(this); vb.setInitializer(expressions.pop()); } b.addArguments(vb.build()); } for (Object o : node.thrownExceptionTypes()) { boa.types.Ast.Type.Builder tp = boa.types.Ast.Type.newBuilder(); tb.setName(getIndex(typeName((org.eclipse.jdt.core.dom.Type) o))); tp.setKind(boa.types.Ast.TypeKind.CLASS); b.addExceptionTypes(tp.build()); } if (node.getBody() != null) { statements.push(new ArrayList<boa.types.Ast.Statement>()); node.getBody().accept(this); for (boa.types.Ast.Statement s : statements.pop()) b.addStatements(s); } list.add(b.build()); return false; }
From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java
License:Open Source License
private IDSModel processComponent(TypeDeclaration type, ITypeBinding typeBinding, Annotation annotation, IAnnotationBinding annotationBinding, Collection<DSAnnotationProblem> problems) { HashMap<String, Object> params = new HashMap<String, Object>(); for (IMemberValuePairBinding pair : annotationBinding.getDeclaredMemberValuePairs()) { params.put(pair.getName(), pair.getValue()); }//from ww w . j a v a2 s.c o m boolean requiresV12 = false; String implClass = typeBinding.getBinaryName(); String name = implClass; Object value; if ((value = params.get("name")) instanceof String) { //$NON-NLS-1$ name = (String) value; validateComponentName(annotation, name, problems); } Collection<String> services; if ((value = params.get("service")) instanceof Object[]) { //$NON-NLS-1$ Object[] elements = (Object[]) value; services = new LinkedHashSet<String>(elements.length); Map<String, Integer> serviceDuplicates = errorLevel.isNone() ? null : new HashMap<String, Integer>(); for (int i = 0; i < elements.length; ++i) { ITypeBinding serviceType = (ITypeBinding) elements[i]; String serviceName = serviceType.getBinaryName(); if (!errorLevel.isNone()) { if (serviceDuplicates.containsKey(serviceName)) { reportProblem(annotation, "service", i, problems, //$NON-NLS-1$ Messages.AnnotationProcessor_duplicateServiceDeclaration, serviceName); Integer pos = serviceDuplicates.put(serviceName, null); if (pos != null) reportProblem(annotation, "service", pos.intValue(), problems, //$NON-NLS-1$ Messages.AnnotationProcessor_duplicateServiceDeclaration, serviceName); } else { serviceDuplicates.put(serviceName, i); } } services.add(serviceName); validateComponentService(annotation, typeBinding, serviceType, i, problems); } } else { ITypeBinding[] serviceTypes = typeBinding.getInterfaces(); services = new ArrayList<String>(serviceTypes.length); for (int i = 0; i < serviceTypes.length; ++i) { services.add(serviceTypes[i].getBinaryName()); } } String factory = null; if ((value = params.get("factory")) instanceof String) { //$NON-NLS-1$ factory = (String) value; validateComponentFactory(annotation, factory, problems); } Boolean serviceFactory = null; if ((value = params.get("servicefactory")) instanceof Boolean) { //$NON-NLS-1$ serviceFactory = (Boolean) value; } Boolean enabled = null; if ((value = params.get("enabled")) instanceof Boolean) { //$NON-NLS-1$ enabled = (Boolean) value; } Boolean immediate = null; if ((value = params.get("immediate")) instanceof Boolean) { //$NON-NLS-1$ immediate = (Boolean) value; } String[] properties; if ((value = params.get("property")) instanceof Object[]) { //$NON-NLS-1$ Object[] elements = (Object[]) value; ArrayList<String> list = new ArrayList<String>(elements.length); for (int i = 0; i < elements.length; ++i) { if (elements[i] instanceof String) list.add((String) elements[i]); } properties = list.toArray(new String[list.size()]); } else { properties = new String[0]; } String[] propertyFiles; if ((value = params.get("properties")) instanceof Object[]) { //$NON-NLS-1$ Object[] elements = (Object[]) value; ArrayList<String> list = new ArrayList<String>(elements.length); for (int i = 0; i < elements.length; ++i) { if (elements[i] instanceof String) list.add((String) elements[i]); } propertyFiles = list.toArray(new String[list.size()]); validateComponentPropertyFiles(annotation, ((IType) typeBinding.getJavaElement()).getJavaProject().getProject(), propertyFiles, problems); } else { propertyFiles = new String[0]; } String configPolicy = null; if ((value = params.get("configurationPolicy")) instanceof IVariableBinding) { //$NON-NLS-1$ IVariableBinding configPolicyBinding = (IVariableBinding) value; ConfigurationPolicy configPolicyLiteral = ConfigurationPolicy.valueOf(configPolicyBinding.getName()); if (configPolicyLiteral != null) configPolicy = configPolicyLiteral.toString(); } String configPid = null; if ((value = params.get("configurationPid")) instanceof String) { //$NON-NLS-1$ configPid = (String) value; validateComponentConfigPID(annotation, configPid, problems); requiresV12 = true; } DSModel model = new DSModel(new Document(), false); IDSComponent component = model.getDSComponent(); if (name != null) component.setAttributeName(name); if (factory != null) component.setFactory(factory); if (enabled != null) component.setEnabled(enabled.booleanValue()); if (immediate != null) component.setImmediate(immediate.booleanValue()); if (configPolicy != null) component.setConfigurationPolicy(configPolicy); if (configPid != null) component.setXMLAttribute("configuration-pid", configPid); //$NON-NLS-1$ IDSDocumentFactory dsFactory = component.getModel().getFactory(); IDSImplementation impl = dsFactory.createImplementation(); component.setImplementation(impl); impl.setClassName(implClass); if (!services.isEmpty()) { IDSService service = dsFactory.createService(); component.setService(service); for (String serviceName : services) { IDSProvide provide = dsFactory.createProvide(); service.addProvidedService(provide); provide.setInterface(serviceName); } if (serviceFactory != null) service.setServiceFactory(serviceFactory.booleanValue()); } if (properties.length > 0) { HashMap<String, IDSProperty> map = new HashMap<String, IDSProperty>(properties.length); for (int i = 0; i < properties.length; ++i) { String propertyStr = properties[i]; String[] pair = propertyStr.split("=", 2); //$NON-NLS-1$ int colon = pair[0].indexOf(':'); String propertyName, propertyType; if (colon == -1) { propertyName = pair[0]; propertyType = null; } else { propertyName = pair[0].substring(0, colon); propertyType = pair[0].substring(colon + 1); } String propertyValue = pair.length > 1 ? pair[1].trim() : null; IDSProperty property = map.get(propertyName); if (property == null) { // create a new property property = dsFactory.createProperty(); component.addPropertyElement(property); map.put(propertyName, property); property.setPropertyName(propertyName); property.setPropertyType(propertyType); property.setPropertyValue(propertyValue); validateComponentProperty(annotation, propertyName, propertyType, propertyValue, i, problems); } else { // property exists; make it multi-valued String content = property.getPropertyElemBody(); if (content == null) { content = property.getPropertyValue(); property.setPropertyElemBody(content); property.setPropertyValue(null); } if (!errorLevel.isNone()) { String expected = property.getPropertyType() == null || property.getPropertyType().isEmpty() || String.class.getSimpleName().equals(property.getPropertyType()) ? Messages.AnnotationProcessor_stringOrEmpty : property.getPropertyType(); String actual = propertyType == null || String.class.getSimpleName().equals(propertyType) ? Messages.AnnotationProcessor_stringOrEmpty : propertyType; if (!actual.equals(expected)) reportProblem(annotation, "property", i, problems, //$NON-NLS-1$ NLS.bind(Messages.AnnotationProcessor_inconsistentComponentPropertyType, actual, expected), actual); else validateComponentProperty(annotation, propertyName, propertyType, propertyValue, i, problems); } if (propertyValue != null) property.setPropertyElemBody(content + "\n" + pair[1]); //$NON-NLS-1$ } } } if (propertyFiles.length > 0) { for (String propertyFile : propertyFiles) { IDSProperties propertiesElement = dsFactory.createProperties(); component.addPropertiesElement(propertiesElement); propertiesElement.setEntry(propertyFile); } } String activate = null; Annotation activateAnnotation = null; String deactivate = null; Annotation deactivateAnnotation = null; String modified = null; Annotation modifiedAnnotation = null; ArrayList<IDSReference> references = new ArrayList<IDSReference>(); HashMap<String, Annotation> referenceNames = new HashMap<String, Annotation>(); for (MethodDeclaration method : type.getMethods()) { for (Object modifier : method.modifiers()) { if (!(modifier instanceof Annotation)) continue; Annotation methodAnnotation = (Annotation) modifier; IAnnotationBinding methodAnnotationBinding = methodAnnotation.resolveAnnotationBinding(); if (methodAnnotationBinding == null) { if (debug.isDebugging()) debug.trace( String.format("Unable to resolve binding for annotation: %s", methodAnnotation)); //$NON-NLS-1$ continue; } String annotationName = methodAnnotationBinding.getAnnotationType().getQualifiedName(); if (ACTIVATE_ANNOTATION.equals(annotationName)) { if (activate == null) { activate = method.getName().getIdentifier(); activateAnnotation = methodAnnotation; validateLifeCycleMethod(methodAnnotation, "activate", method, problems); //$NON-NLS-1$ } else if (!errorLevel.isNone()) { reportProblem(methodAnnotation, null, problems, Messages.AnnotationProcessor_duplicateActivateMethod, method.getName().getIdentifier()); if (activateAnnotation != null) { reportProblem(activateAnnotation, null, problems, Messages.AnnotationProcessor_duplicateActivateMethod, activate); activateAnnotation = null; } } continue; } if (DEACTIVATE_ANNOTATION.equals(annotationName)) { if (deactivate == null) { deactivate = method.getName().getIdentifier(); deactivateAnnotation = methodAnnotation; validateLifeCycleMethod(methodAnnotation, "deactivate", method, problems); //$NON-NLS-1$ } else if (!errorLevel.isNone()) { reportProblem(methodAnnotation, null, problems, Messages.AnnotationProcessor_duplicateDeactivateMethod, method.getName().getIdentifier()); if (deactivateAnnotation != null) { reportProblem(deactivateAnnotation, null, problems, Messages.AnnotationProcessor_duplicateDeactivateMethod, deactivate); deactivateAnnotation = null; } } continue; } if (MODIFIED_ANNOTATION.equals(annotationName)) { if (modified == null) { modified = method.getName().getIdentifier(); modifiedAnnotation = methodAnnotation; validateLifeCycleMethod(methodAnnotation, "modified", method, problems); //$NON-NLS-1$ } else if (!errorLevel.isNone()) { reportProblem(methodAnnotation, null, problems, Messages.AnnotationProcessor_duplicateModifiedMethod, method.getName().getIdentifier()); if (modifiedAnnotation != null) { reportProblem(modifiedAnnotation, null, problems, Messages.AnnotationProcessor_duplicateModifiedMethod, modified); modifiedAnnotation = null; } } continue; } if (REFERENCE_ANNOTATION.equals(annotationName)) { IMethodBinding methodBinding = method.resolveBinding(); if (methodBinding == null) { if (debug.isDebugging()) debug.trace(String.format("Unable to resolve binding for method: %s", method)); //$NON-NLS-1$ } else { requiresV12 |= processReference(method, methodBinding, methodAnnotation, methodAnnotationBinding, dsFactory, references, referenceNames, problems); } continue; } } } if (activate != null) component.setActivateMethod(activate); if (deactivate != null) component.setDeactivateMethod(deactivate); if (modified != null) component.setModifiedeMethod(modified); if (!references.isEmpty()) { // references must be declared in ascending lexicographical order of their names Collections.sort(references, REF_NAME_COMPARATOR); for (IDSReference reference : references) { component.addReference(reference); } } String xmlns = null; if ((value = params.get("xmlns")) instanceof String) { //$NON-NLS-1$ xmlns = (String) value; validateComponentXMLNS(annotation, xmlns, requiresV12, problems); } else if (requiresV12) { xmlns = NAMESPACE_1_2; } if (xmlns != null) component.setNamespace(xmlns); return model; }
From source file:cc.kave.eclipse.namefactory.visitors.MethodDeclarationVisitor.java
License:Apache License
public MethodDeclaration getMethod(String signature) { for (MethodDeclaration m : methods) { if (!signature.endsWith(")") && m.getName().getIdentifier().equals(signature)) { return m; } else if (getMethodSignature(m).equals(signature)) { return m; }//from w w w . j a va2 s. co m } return null; }
From source file:cc.kave.eclipse.namefactory.visitors.MethodDeclarationVisitor.java
License:Apache License
private String getMethodSignature(MethodDeclaration declaration) { StringBuilder sb = new StringBuilder(); sb.append(declaration.getName().getIdentifier()); sb.append("("); for (Object variable : declaration.parameters()) { SingleVariableDeclaration v = (SingleVariableDeclaration) variable; sb.append(v.resolveBinding().getType().getName()); sb.append(" "); sb.append(v.getName().getIdentifier()); sb.append(", "); }/*www.j a va 2 s.c o m*/ if (sb.toString().endsWith(", ")) { sb.replace(sb.length() - 2, sb.length(), ")"); } else { sb.append(")"); } return sb.toString(); }
From source file:ch.acanda.eclipse.pmd.java.resolution.naming.SuspiciousHashcodeMethodNameQuickFix.java
License:Open Source License
/** * Sets the name of the method to "hashCode". *///w ww. java 2 s. co m @Override protected boolean apply(final MethodDeclaration node) { node.getName().setIdentifier("hashCode"); return true; }