Search code examples
jvmxtextxtend

Xtext and JVM: Adding Request Method to Request Mapping


I have a problem in Xtext. I need like this:

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String updatePhr(@PathVariable(value = "id") Long id)

But I am getting like this:

@RequestMapping(value = "/create", method = "RequestMethod.POST")

RequestMethod.Post as a string value.

My code is here:

public static String PATHVARIABLE = "org.springframework.web.bind.annotation.PathVariable";

@Inject
private TypesFactory typesFactory;

@Inject
private TypeReferences references;



 def dispatch void infer(Controller element, 
                IJvmDeclaredTypeAcceptor acceptor, 
                boolean isPrelinkingPhase) {
    acceptor.accept(element.toClass( element.fullyQualifiedName )) [ {
                  Method : {
              members += component.toMethod(component.name,component.type) [
              annotations += element.toAnnotationRef(REQUESTMAPPING, "value" -> component.value, "method" -> component.method);        
              documentation = component.documentation
              var i = 1;
              for (p : component.params) {
                val j = i;
                parameters += p.toParameter(p.name, p.parameterType) => [
                    if(component.vars.get(j).isEmpty == false){
        annotations += toAnnotationRef(PATHVARIABLE, "value" -> component.vars.get(j));
        }
    ]
     i++;
              }
              body = component.body
            ]
          }

    }

How to add "@Pathvariable("id")" to parameters.


Solution

  • you are using a JvmStringAnnotationValue and not a JvmEnumAnnotationValue or JvmCustomAnnotationValue

    @Inject
    private TypeReferences references;
    

    and when inferring the annotation

    members += entity.toMethod("create", Void.TYPE.typeRef()) [
        body = ''''''
        annotations += RequestMapping.annotationRef() => [
            val anno = it.annotation
            explicitValues += TypesFactory.eINSTANCE.createJvmStringAnnotationValue => [
                operation = anno.members.filter(JvmOperation).findFirst[simpleName=='value']
                values += "/create"
            ]
            explicitValues += TypesFactory.eINSTANCE.createJvmEnumAnnotationValue => [
                operation = anno.members.filter(JvmOperation).findFirst[simpleName=='method']
    
                values += (references.findDeclaredType(RequestMethod, entity) as JvmEnumerationType).literals.findFirst[simpleName == "POST"]
            ]
        ]
    
    ]
    

    to add to params

            members+=entity.toMethod("doSth", Void.TYPE.typeRef) [
                parameters += entity.toParameter("p1", String.typeRef) => [
                    annotations += "test.MyAnno".annotationRef("id")
                ]
            ]