List of usage examples for org.eclipse.jdt.core.dom MethodDeclaration getAST
public final AST getAST()
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
/** * // w w w . ja 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 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
/** * /* www .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); }/*from w ww .ja va 2 s. c om*/ 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:br.com.objectos.way.core.code.jdt.MethodDeclarationWriter.java
License:Apache License
MethodDeclarationWriter(MethodDeclaration method) { ast = method.getAST(); this.method = method; }
From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java
License:Open Source License
private boolean processReference(MethodDeclaration method, IMethodBinding methodBinding, Annotation annotation, IAnnotationBinding annotationBinding, IDSDocumentFactory factory, Collection<IDSReference> collector, Map<String, Annotation> names, Collection<DSAnnotationProblem> problems) { HashMap<String, Object> params = new HashMap<String, Object>(); for (IMemberValuePairBinding pair : annotationBinding.getDeclaredMemberValuePairs()) { params.put(pair.getName(), pair.getValue()); }/* w w w . j av a 2 s .c o m*/ boolean requiresV12 = false; ITypeBinding[] argTypes = methodBinding.getParameterTypes(); ITypeBinding serviceType; Object value; if ((value = params.get("service")) instanceof ITypeBinding) { //$NON-NLS-1$ serviceType = (ITypeBinding) value; if (!errorLevel.isNone() && argTypes.length > 0) { ITypeBinding[] typeArgs; if (!(ServiceReference.class.getName().equals(argTypes[0].getErasure().getQualifiedName()) && ((typeArgs = argTypes[0].getTypeArguments()).length == 0 || serviceType.isAssignmentCompatible(typeArgs[0]))) && !serviceType.isAssignmentCompatible(argTypes[0])) reportProblem(annotation, "service", problems, //$NON-NLS-1$ NLS.bind(Messages.AnnotationProcessor_invalidReferenceService, argTypes[0].getName(), serviceType.getName()), serviceType.getName()); } } else if (argTypes.length > 0) { if (ServiceReference.class.getName().equals(argTypes[0].getErasure().getQualifiedName())) { ITypeBinding[] typeArgs = argTypes[0].getTypeArguments(); if (typeArgs.length > 0) serviceType = typeArgs[0]; else serviceType = null; } else { serviceType = argTypes[0].isPrimitive() ? getObjectType(method.getAST(), argTypes[0]) : argTypes[0]; } } else { serviceType = null; } if (serviceType == null) { reportProblem(annotation, null, problems, Messages.AnnotationProcessor_invalidReferenceServiceUnknown); serviceType = method.getAST().resolveWellKnownType(Object.class.getName()); } validateReferenceBindMethod(annotation, serviceType, methodBinding, problems); String service = serviceType == null ? null : serviceType.getBinaryName(); String methodName = methodBinding.getName(); String name; if ((value = params.get("name")) instanceof String) { //$NON-NLS-1$ name = (String) value; } else if (methodName.startsWith("bind")) { //$NON-NLS-1$ name = methodName.substring("bind".length()); //$NON-NLS-1$ } else if (methodName.startsWith("set")) { //$NON-NLS-1$ name = methodName.substring("set".length()); //$NON-NLS-1$ } else if (methodName.startsWith("add")) { //$NON-NLS-1$ name = methodName.substring("add".length()); //$NON-NLS-1$ } else { name = methodName; } if (!errorLevel.isNone()) { if (names.containsKey(name)) { reportProblem(annotation, "name", problems, //$NON-NLS-1$ NLS.bind(Messages.AnnotationProcessor_duplicateReferenceName, name), name); Annotation duplicate = names.put(name, null); if (duplicate != null) reportProblem(duplicate, "name", problems, //$NON-NLS-1$ NLS.bind(Messages.AnnotationProcessor_duplicateReferenceName, name), name); } else { names.put(name, annotation); } } String cardinality = null; if ((value = params.get("cardinality")) instanceof IVariableBinding) { //$NON-NLS-1$ IVariableBinding cardinalityBinding = (IVariableBinding) value; ReferenceCardinality cardinalityLiteral = ReferenceCardinality.valueOf(cardinalityBinding.getName()); if (cardinalityLiteral != null) cardinality = cardinalityLiteral.toString(); } String policy = null; if ((value = params.get("policy")) instanceof IVariableBinding) { //$NON-NLS-1$ IVariableBinding policyBinding = (IVariableBinding) value; ReferencePolicy policyLiteral = ReferencePolicy.valueOf(policyBinding.getName()); if (policyLiteral != null) policy = policyLiteral.toString(); } String target = null; if ((value = params.get("target")) instanceof String) { //$NON-NLS-1$ target = (String) value; validateReferenceTarget(annotation, target, problems); } String unbind; if ((value = params.get("unbind")) instanceof String) { //$NON-NLS-1$ String unbindValue = (String) value; if ("-".equals(unbindValue)) { //$NON-NLS-1$ unbind = null; } else { unbind = unbindValue; if (!errorLevel.isNone() && serviceType != null) { IMethodBinding unbindMethod = findReferenceMethod(methodBinding.getDeclaringClass(), serviceType, unbind); if (unbindMethod == null) reportProblem(annotation, "unbind", problems, //$NON-NLS-1$ NLS.bind(Messages.AnnotationProcessor_invalidReferenceUnbind, unbind), unbind); } } } else if (serviceType != null) { String unbindCandidate; if (methodName.startsWith("add")) { //$NON-NLS-1$ unbindCandidate = "remove" + methodName.substring("add".length()); //$NON-NLS-1$ //$NON-NLS-2$ } else { unbindCandidate = "un" + methodName; //$NON-NLS-1$ } IMethodBinding unbindMethod = findReferenceMethod(methodBinding.getDeclaringClass(), serviceType, unbindCandidate); if (unbindMethod == null) unbind = null; else unbind = unbindMethod.getName(); } else { unbind = null; } String policyOption = null; if ((value = params.get("policyOption")) instanceof IVariableBinding) { //$NON-NLS-1$ IVariableBinding policyOptionBinding = (IVariableBinding) value; ReferencePolicyOption policyOptionLiteral = ReferencePolicyOption .valueOf(policyOptionBinding.getName()); if (policyOptionLiteral != null) { policyOption = policyOptionLiteral.toString(); requiresV12 = true; } } String updated; if ((value = params.get("updated")) instanceof String) { //$NON-NLS-1$ String updatedValue = (String) value; if ("-".equals(updatedValue)) { //$NON-NLS-1$ updated = null; } else { updated = updatedValue; if (!errorLevel.isNone() && serviceType != null) { IMethodBinding updatedMethod = findReferenceMethod(methodBinding.getDeclaringClass(), serviceType, updated); if (updatedMethod == null) reportProblem(annotation, "updated", problems, //$NON-NLS-1$ NLS.bind(Messages.AnnotationProcessor_invalidReferenceUpdated, updated), updated); } } requiresV12 = true; } else if (serviceType != null) { String updatedCandidate; if (methodName.startsWith("bind")) { //$NON-NLS-1$ updatedCandidate = "updated" + methodName.substring("bind".length()); //$NON-NLS-1$ //$NON-NLS-2$ } else if (methodName.startsWith("set")) { //$NON-NLS-1$ updatedCandidate = "updated" + methodName.substring("set".length()); //$NON-NLS-1$ //$NON-NLS-2$ } else if (methodName.startsWith("add")) { //$NON-NLS-1$ updatedCandidate = "updated" + methodName.substring("add".length()); //$NON-NLS-1$ //$NON-NLS-2$ } else { updatedCandidate = "updated" + methodName; //$NON-NLS-1$ } IMethodBinding updatedMethod = findReferenceMethod(methodBinding.getDeclaringClass(), serviceType, updatedCandidate); if (updatedMethod == null) updated = null; else updated = updatedMethod.getName(); } else { updated = null; } IDSReference reference = factory.createReference(); collector.add(reference); reference.setReferenceBind(methodName); if (name != null) reference.setReferenceName(name); if (service != null) reference.setReferenceInterface(service); if (cardinality != null) reference.setReferenceCardinality(cardinality); if (policy != null) reference.setReferencePolicy(policy); if (target != null) reference.setReferenceTarget(target); if (unbind != null) reference.setReferenceUnbind(unbind); if (policyOption != null) reference.setXMLAttribute("policy-option", policyOption); //$NON-NLS-1$ if (updated != null) reference.setXMLAttribute("updated", updated); //$NON-NLS-1$ return requiresV12; }
From source file:coloredide.utils.CopiedNaiveASTFlattener.java
License:Open Source License
public boolean visit(MethodDeclaration node) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); }//from w w w .j a v a2 s . c om printIndent(); hook_beforeVisitMethodDeclaration(node); if (node.getAST().apiLevel() >= AST.JLS3) { printModifiers(node.modifiers()); if (!node.typeParameters().isEmpty()) { this.buffer.append("<");//$NON-NLS-1$ for (Iterator it = node.typeParameters().iterator(); it.hasNext();) { TypeParameter t = (TypeParameter) it.next(); t.accept(this); if (it.hasNext()) { this.buffer.append(",");//$NON-NLS-1$ } } this.buffer.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.buffer.append("void");//$NON-NLS-1$ } this.buffer.append(" ");//$NON-NLS-1$ } node.getName().accept(this); this.buffer.append("(");//$NON-NLS-1$ for (Iterator it = node.parameters().iterator(); it.hasNext();) { SingleVariableDeclaration v = (SingleVariableDeclaration) it.next(); v.accept(this); if (it.hasNext()) { this.buffer.append(",");//$NON-NLS-1$ } } this.buffer.append(")");//$NON-NLS-1$ for (int i = 0; i < node.getExtraDimensions(); i++) { this.buffer.append("[]"); //$NON-NLS-1$ } if (!node.thrownExceptions().isEmpty()) { this.buffer.append(" throws ");//$NON-NLS-1$ for (Iterator it = node.thrownExceptions().iterator(); it.hasNext();) { Name n = (Name) it.next(); n.accept(this); if (it.hasNext()) { this.buffer.append(", ");//$NON-NLS-1$ } } this.buffer.append(" ");//$NON-NLS-1$ } if (node.getBody() == null) { this.buffer.append(";\n");//$NON-NLS-1$ } else { node.getBody().accept(this); } return false; }
From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaOperationModelAdapter.java
License:Open Source License
@Override public void setValueFeatureValue(Object element, Object feature, Object value) { if (CodeSyncPackage.eINSTANCE.getCodeSyncElement_Name().equals(feature)) { MethodDeclaration method = getMethodDeclaration(element); String name = (String) value; int index = name.indexOf("("); if (index == -1) { index = name.length();// ww w. j a v a2 s . c om } name = name.substring(0, index); method.setName(method.getAST().newSimpleName(name)); } if (AstCacheCodePackage.eINSTANCE.getTypedElement_Type().equals(feature)) { MethodDeclaration method = getMethodDeclaration(element); Type type = getTypeFromString(method.getAST(), (String) value); method.setReturnType2(type); } super.setValueFeatureValue(element, feature, value); }
From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaOperationModelAdapter.java
License:Open Source License
@Override public Object createChildOnContainmentFeature(Object element, Object feature, Object correspondingChild) { if (AstCacheCodePackage.eINSTANCE.getOperation_Parameters().equals(feature)) { MethodDeclaration method = (MethodDeclaration) element; AST ast = method.getAST(); SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration(); method.parameters().add(parameter); return parameter; }//from w w w . ja va 2s. c o m return super.createChildOnContainmentFeature(element, feature, correspondingChild); }
From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaMethod.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*w ww. j a va 2 s .co 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); } }