All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ovirt.api.metamodel.tool.JaxrsGenerator Maven / Gradle / Ivy

/*
Copyright (c) 2015 Red Hat, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.ovirt.api.metamodel.tool;

import static java.util.stream.Collectors.joining;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.ovirt.api.metamodel.concepts.ListType;
import org.ovirt.api.metamodel.concepts.Locator;
import org.ovirt.api.metamodel.concepts.Method;
import org.ovirt.api.metamodel.concepts.Model;
import org.ovirt.api.metamodel.concepts.Name;
import org.ovirt.api.metamodel.concepts.NameParser;
import org.ovirt.api.metamodel.concepts.Parameter;
import org.ovirt.api.metamodel.concepts.Service;
import org.ovirt.api.metamodel.concepts.StructType;
import org.ovirt.api.metamodel.concepts.Type;
import org.ovirt.api.metamodel.tool.util.JaxrsGeneratorUtils;

/**
 * This class takes a model and generates the corresponding JAX-RS resource interfaces.
 */
@ApplicationScoped
public class JaxrsGenerator extends JavaGenerator {
    // The content types supported by all the resources, and thus added to the @Produces and @Consumes annotations:
    private static final String[] MEDIA_TYPES = {
        "ApiMediaType.APPLICATION_XML",
        "ApiMediaType.APPLICATION_JSON",
    };

    // List of JAX-RS interfaces that support asynchronous creation:
    private static final Set ASYNCHRONOUS = new HashSet<>();

    private static void addAsyncronous(String name) {
        ASYNCHRONOUS.add(NameParser.parseUsingCase(name));
    }

    static {
        addAsyncronous("Disk");
        addAsyncronous("InstanceType");
        addAsyncronous("InstanceTypeNic");
        addAsyncronous("InstanceTypeWatchdog");
        addAsyncronous("Snapshot");
        addAsyncronous("StorageDomainContentDisk");
        addAsyncronous("Template");
        addAsyncronous("TemplateCdrom");
        addAsyncronous("TemplateDisk");
        addAsyncronous("TemplateNic");
        addAsyncronous("TemplateWatchdog");
        addAsyncronous("Vm");
        addAsyncronous("VmCdrom");
        addAsyncronous("VmDisk");
        addAsyncronous("VmNic");
        addAsyncronous("VmPool");
        addAsyncronous("VmWatchdog");
    }

    // Reference to the object that calculates names for XML schema types and for Java classes generated by the JAXB
    // compiler from the XML schema:
    @Inject private SchemaNames schemaNames;

    // Reference to the object that implements the rules to generate names for Java concepts:
    @Inject private JavaPackages javaPackages;
    @Inject private JavaNames javaNames;
    @Inject private JaxrsNames jaxrsNames;
    @Inject private Names names;
    @Inject private JaxrsGeneratorUtils jaxrsGeneratorUtils;

    public void generate(Model model) {
        model.getServices().forEach(this::generateInterface);
    }

    private void addMethod(String returnType, String methodNameWithArgs, Object ... args) {
        javaBuffer.addLine("default public %s %s {", returnType, String.format(methodNameWithArgs, args));
        javaBuffer.addLine(  "throw new UnsupportedOperationException();");
        javaBuffer.addLine("}");
    }

    private void addResponseReturnMethod(String methodNameWithArgs, Object ... args) {
        addMethod("Response", methodNameWithArgs, args);
    }

    private void generateInterface(Service service) {
        // Get the Java name of the interface:
        JavaClassName interfaceName = jaxrsNames.getInterfaceName(service);

        // Prepare the buffer:
        javaBuffer = new JavaClassBuffer();
        javaBuffer.setClassName(interfaceName);
        generateInterfaceSource(service, interfaceName);
        try {
            javaBuffer.write(outDir);
        }
        catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    private void generateInterfaceSource(Service service, JavaClassName interfaceName) {
        // Generate the imports:
        javaBuffer.addImport(Produces.class);
        javaBuffer.addImport(javaPackages.getJaxrsPackageName(), "ApiMediaType");

        // Calculate the "extends" clause of the interface declaration:
        List extendsList = new ArrayList<>();
        Service base = service.getBase();
        if (base != null) {
            JavaClassName baseInterfaceName = jaxrsNames.getInterfaceName(base);
            javaBuffer.addImport(baseInterfaceName);
            extendsList.add(baseInterfaceName.getSimpleName());
        }
        if (ASYNCHRONOUS.contains(service.getName())) {
            javaBuffer.addImport(javaPackages.getJaxrsPackageName(), "AsynchronouslyCreatedResource");
            extendsList.add("AsynchronouslyCreatedResource");
        }
        String extendsClause = extendsList.isEmpty()? "": "extends " + String.join(", ", extendsList);

        //add import statement for of the auto-generated 'helper' class for this service
        JavaClassName helperClassName = jaxrsNames.getHelperName(service);
        javaBuffer.addImport(helperClassName);

        // Check if this is the root of the tree of services:
        boolean isRoot = service == service.getModel().getRoot();

        // Generate the interface declaration:
        generateDoc(service);
        if (isRoot) {
            javaBuffer.addImport(Path.class);
            javaBuffer.addLine("@Path(\"/\")");
        }
        javaBuffer.addLine("@Produces({ %s })", generateMediaTypes());
        javaBuffer.addLine(
            "public interface %s %s {",
            interfaceName.getSimpleName(),
            extendsClause
        );

        // The root service needs this additional that can't be represented in the model:
        if (isRoot) {
            javaBuffer.addImport(HEAD.class);
            javaBuffer.addImport(Response.class);
            javaBuffer.addLine("@HEAD");
            javaBuffer.addLine("Response head();");
            javaBuffer.addLine();
        }

        // Generate the methods:
        List methods = service.getDeclaredMethods();
        Map> baseMethods = jaxrsGeneratorUtils.getBaseMethodsMap(methods);
        methods.forEach(x -> generateMethod(x, helperClassName, baseMethods));

        // Generate 'follow()' method (should exist in all interfaces).
        generateFollowMethod();

        // Generate the resource locators:
        List locators = service.getDeclaredLocators();
        locators.forEach(x -> generateLocator(x));

        // Find all the action methods and generate the action resource locator:
        List actions = new ArrayList<>();
        for (Method method : service.getMethods()) {
            if (method.isAction()) {
                actions.add(method);
            }
        }
        if (!actions.isEmpty()) {
            generateActionLocator(actions);
        }

        javaBuffer.addLine("}");
    }

    private void generateFollowMethod() {
        javaBuffer.addImport(javaPackages.getXjcPackageName(), "ActionableResource");
        javaBuffer.addLine("default public void follow (ActionableResource entity) {");
        javaBuffer.addLine("}");
        javaBuffer.addLine();
    }

    private void generateActionLocator(List actions) {
        // Generate the imports:
        javaBuffer.addImport(Path.class);
        javaBuffer.addImport(PathParam.class);
        javaBuffer.addImport(javaPackages.getJaxrsPackageName(), "ActionResource");

        // Generate the method:
        javaBuffer.addLine(
            "@Path(\"{action: (?:%s)}/{oid}\")",
            actions.stream().map(Method::getName).map(jaxrsNames::getActionPath).sorted().collect(joining("|"))
        );
        javaBuffer.addLine(
            "ActionResource getActionResource(@PathParam(\"action\") String action, @PathParam(\"oid\") String oid);"
        );

        javaBuffer.addLine();
    }

    private void generateMethod(Method method, JavaClassName helperClassName, Map> baseMethods) {
        Name name = method.getName();
        if (JaxrsGeneratorUtils.ADD.equals(name)) {
            generateAddMethod(method, helperClassName, baseMethods);
        }
        else if (JaxrsGeneratorUtils.GET.equals(name)) {
            generateGetMethod(method);
        }
        else if (JaxrsGeneratorUtils.LIST.equals(name)) {
            generateListMethod(method);
        }
        else if (JaxrsGeneratorUtils.REMOVE.equals(name)) {
            generateRemoveMethod(method);
        }
        else if (JaxrsGeneratorUtils.UPDATE.equals(name)) {
            generateUpdateMethod(method, helperClassName, baseMethods);
        }
        else if (jaxrsGeneratorUtils.isAddSignature(method)) {
            generateAddSignature(method);
        }
        else if (jaxrsGeneratorUtils.isUpdateSignature(method)) {
            generateUpdateSignature(method);
        }
        else if (jaxrsGeneratorUtils.isActionSignature(method)) {
            generateActionSignature(method);
        }
        else {//other options exhausted; must be an action
            generateActionMethod(method, helperClassName, baseMethods);
        }
    }

    private void generateActionSignature(Method method) {
        generateDoc(method);
        javaBuffer.addImport(Response.class);
        javaBuffer.addImport(javaPackages.getXjcPackageName(), "Action");
        Name methodName = new Name(method.getBase().getName());
        methodName.addWords(method.getName().getWords());
        javaBuffer.addLine("default public Response %s(Action action) {", jaxrsNames.getMethodName(methodName));
        javaBuffer.addLine("throw new UnsupportedOperationException();");
        javaBuffer.addLine("}");
    }

    private void generateUpdateSignature(Method method) {
        generateDoc(method);
        // Find the main parameter of the method, as this is the only one that appears in the JAX-RS interfaces, the
        // rest of the methods are extracted explicitly by the implementation:
        Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method);
        if (mainParameter == null) {
            throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter");
        }

        // Calculate the Java type of the main parameter:
        Type mainType = mainParameter.getType();
        JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType);
        String methodName = javaNames.getJavaMemberStyleName(names.concatenate(method.getBase().getName(), method.getName()));
        javaBuffer.addLine(
            "default public %s " + methodName + "(%s %s) {",
            mainTypeReference.getText(),
            mainTypeReference.getText(),
            javaNames.getJavaMemberStyleName(mainParameter.getName()));
        javaBuffer.addLine("throw new UnsupportedOperationException();");
        javaBuffer.addLine("}");
    }

    private void generateAddSignature(Method method) {
        generateDoc(method);
        // Find the main parameter of the method, as this is the only one that appears in the JAX-RS interfaces, the
        // rest of the methods are extracted explicitly by the implementation:
        Parameter mainParameter = jaxrsGeneratorUtils.getMainAddParameter(method);
        if (mainParameter == null) {
            throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter");
        }
        // Calculate the Java type of the main parameter:
        Type mainType = mainParameter.getType();
        JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType);
        javaBuffer.addImports(mainTypeReference.getImports());
        String parameterName = javaNames.getJavaMemberStyleName(mainParameter.getName());
        String methodName = javaNames.getJavaMemberStyleName(names.concatenate(method.getBase().getName(), method.getName()));
        javaBuffer.addLine("default public Response %s(%s %s) {", methodName, mainTypeReference.getText(), parameterName);
        javaBuffer.addLine("throw new UnsupportedOperationException();");
        javaBuffer.addLine("}");
        javaBuffer.addLine();
    }

    private void generateAddMethod(Method method, JavaClassName helperClassName, Map> baseMethods) {
        // Find the main parameter of the method, as this is the only one that appears in the JAX-RS interfaces, the
        // rest of the methods are extracted explicitly by the implementation:
        Parameter mainParameter = jaxrsGeneratorUtils.getMainAddParameter(method);
        if (mainParameter == null) {
            throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter");
        }

        // Calculate the Java type of the main parameter:
        Type mainType = mainParameter.getType();
        JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType);

        // Generate the imports:
        javaBuffer.addImport(Consumes.class);
        javaBuffer.addImport(POST.class);
        javaBuffer.addImport(Response.class);
        javaBuffer.addImports(mainTypeReference.getImports());

        // Generate the method:
        generateDoc(method);
        javaBuffer.addLine("@POST");
        javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes());
        String parameterName = javaNames.getJavaMemberStyleName(mainParameter.getName());
        if (baseMethods.containsKey(method)) {
            javaBuffer.addLine("default public Response add(%s %s) {", mainTypeReference.getText(), parameterName);
            Set signatures = baseMethods.get(method);
            if (signatures!=null && mandatoryAttributeExists(signatures)) {
                writeHelperInvocation(helperClassName, parameterName, method.getName());
            }
            else {
                javaBuffer.addLine("throw new UnsupportedOperationException();");
                //add log message - signatures with only 'optional' attributes indicate bad input
            }
            javaBuffer.addLine("}");
        }
        else {
            //generate doAdd() method
            if (method.isMandatoryAttributeExists()) {
                javaBuffer.addLine("default public Response doAdd(%s %s) {", mainTypeReference.getText(), parameterName);
                javaBuffer.addLine(helperClassName.getSimpleName() + ".validateAdd(" + parameterName + ");");
                javaBuffer.addLine("return add(" + parameterName + ");");
                javaBuffer.addLine("}");
            }
            javaBuffer.addLine("");
            //generate add() method
            addResponseReturnMethod("add(%s %s)", mainTypeReference.getText(),
                    javaNames.getJavaMemberStyleName(mainParameter.getName()));
        }
        javaBuffer.addLine();
    }

    private void writeHelperInvocation(JavaClassName helperClassName, String parameterName, Name methodName) {
        javaBuffer.addImport(InvocationTargetException.class);
        String helperMethodName = "get" + javaNames.getJavaClassStyleName(methodName) + "Signature";
        javaBuffer.addLine("try {");
        javaBuffer.addLine("return (Response)(" + helperClassName.getSimpleName() + "." + helperMethodName + "(" + parameterName
                + ").invoke(this, " + parameterName + "));");
        javaBuffer.addLine("}");
        javaBuffer.addLine("catch(InvocationTargetException e) {");
        javaBuffer.addLine("throw (RuntimeException)e.getTargetException();");
        javaBuffer.addLine("}");
        javaBuffer.addLine("catch(IllegalAccessException | NoSuchMethodException | SecurityException e) {");
        javaBuffer.addLine("throw new IllegalStateException(\"Failed to find or invoke API method. The failure is in auto-generated code and indicates a bug in the JAX-RS intrafaces generation process\", e);");
        javaBuffer.addLine("}");
    }

    private void generateGetMethod(Method method) {
        Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method);
        if (mainParameter == null) {
            throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter");
        }

        // Most "Get" methods return the type that is declared in the model, but the root resource needs to return
        // "Response", because it has to be able to return the type declared in the model and also the XML schema and
        // the RSDL.
        Service service = method.getDeclaringService();
        boolean isRoot = service == service.getModel().getRoot();
        javaBuffer.addImport(GET.class);
        javaBuffer.addLine("@GET");
        if (isRoot)  {
            javaBuffer.addImport(Response.class);
            addResponseReturnMethod("get()");
        }
        else {
            Type mainType = mainParameter.getType();
            JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType);
            javaBuffer.addImports(mainTypeReference.getImports());
            //add doGet() method with default implementation
            generateDoGetMethod(mainParameter, mainTypeReference);
            generateDoc(method);
            javaBuffer.addLine();
            //add get() method
            addMethod(mainTypeReference.getText(), "get()");
        }

        javaBuffer.addLine();
    }

    private void generateDoGetMethod(Parameter mainParameter, JavaTypeReference mainTypeReference) {
        String parameterName = javaNames.getJavaMemberStyleName(mainParameter.getName());
        javaBuffer.addLine("default public %s doGet() {", mainTypeReference.getText());
        javaBuffer.addLine("%s %s = get();", mainTypeReference.getText(), parameterName);
        javaBuffer.addLine("follow(%s);", parameterName);
        javaBuffer.addLine("return %s;", parameterName);
        javaBuffer.addLine("}");
    }

    private void generateListMethod(Method method) {
        // Find the main parameter of the method, as this is the only one that appears in the JAX-RS interfaces, the
        // rest of the methods are extracted explicitly by the implementation:
        Parameter mainParameter = method.getParameters().stream()
            .filter(x -> x.getType() instanceof ListType)
            .findFirst()
            .orElse(null);
        if (mainParameter == null) {
            throw new IllegalStateException("Method \"" + method + "\" doesn't have any list parameter");
        }

        // Calculate the Java type of the main parameter:
        Type mainType = mainParameter.getType();
        JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType);

        // Generate the imports:
        javaBuffer.addImport(GET.class);
        javaBuffer.addImports(mainTypeReference.getImports());

        // Generate the method:
        javaBuffer.addLine("@GET");

        // Generate doList() method:
        generateDoListMethod(mainParameter, mainTypeReference);
        generateDoc(method);
        addMethod(mainTypeReference.getText(), "list()");
        javaBuffer.addLine();
    }

    private void generateDoListMethod(Parameter mainParameter, JavaTypeReference mainTypeReference) {
        String parameterName = javaNames.getJavaMemberStyleName(mainParameter.getName());
        javaBuffer.addLine("default public %s doList() {", mainTypeReference.getText());
        javaBuffer.addLine("%s %s = list();", mainTypeReference.getText(), parameterName);
        javaBuffer.addLine("follow(%s);", parameterName);
        javaBuffer.addLine("return %s;", parameterName);
        javaBuffer.addLine("}");
    }

    private void generateRemoveMethod(Method method) {
        // Generate the imports:
        javaBuffer.addImport(DELETE.class);
        javaBuffer.addImport(Response.class);

        // The remove methods that have structured parameters (currently only the method that removes a set of Gluster
        // bricks) need to receive an "Action" to carry those parameters.
        // TODO: Fix this renaming that method to "RemoveBricks" or something similar.
        boolean needsAction = method.parameters()
            .map(Parameter::getType)
            .anyMatch(x -> x instanceof StructType || x instanceof ListType);
        generateDoc(method);
        javaBuffer.addLine("@DELETE");
        if (needsAction) {
            javaBuffer.addImport(javaPackages.getXjcPackageName(), "Action");
            addResponseReturnMethod("remove(Action action)");
        }
        else {
            addResponseReturnMethod("remove()");
        }

        javaBuffer.addLine();
    }

    private void generateUpdateMethod(Method method, JavaClassName helperClassName, Map> baseMethods) {
        // Find the main parameter of the method, as this is the only one that appears in the JAX-RS interfaces, the
        // rest of the methods are extracted explicitly by the implementation:
        Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method);
        if (mainParameter == null) {
            throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter");
        }

        // Calculate the Java type of the main parameter:
        Type mainType = mainParameter.getType();
        JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType);

        // Generate the imports:
        javaBuffer.addImport(Consumes.class);
        javaBuffer.addImport(PUT.class);
        javaBuffer.addImports(mainTypeReference.getImports());

        // Generate the method:
        generateDoc(method);
        javaBuffer.addLine("@PUT");
        javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes());
        String parameterName = javaNames.getJavaMemberStyleName(mainParameter.getName());
        if (baseMethods.containsKey(method)) {
            javaBuffer.addLine("default %s update(%s %s) {",
                    mainTypeReference.getText(),
                    mainTypeReference.getText(),
                    parameterName);
            Set signatures = baseMethods.get(method);
            if (signatures!=null && mandatoryAttributeExists(signatures)) {
                writeHelperInvocation(helperClassName, parameterName, method.getName());
            }
            else {
                javaBuffer.addLine("throw new UnsupportedOperationException();");
                //add log message - signatures with only 'optional' attributes indicate bad input
            }
            javaBuffer.addLine("}");
        } else {
            //generate doUpdate() method
            if (method.isMandatoryAttributeExists()) {
                javaBuffer.addLine("default %s doUpdate(%s %s) {",
                        mainTypeReference.getText(),
                        mainTypeReference.getText(),
                        parameterName);
                javaBuffer.addLine(helperClassName.getSimpleName() + ".validateUpdate(" + parameterName + ");");
                javaBuffer.addLine("return update(" + parameterName + ");");
                javaBuffer.addLine("}");
            }
            //generate update() method
            addMethod(mainTypeReference.getText(), "update(%s %s)",
                mainTypeReference.getText(),
                javaNames.getJavaMemberStyleName(mainParameter.getName()));
        }
        javaBuffer.addLine();
    }

    private void generateActionMethod(Method method, JavaClassName helperClassName, Map> baseMethods) {
        // Generate the imports:
        javaBuffer.addImport(Consumes.class);
        javaBuffer.addImport(POST.class);
        javaBuffer.addImport(Path.class);
        javaBuffer.addImport(Response.class);
        javaBuffer.addImport(javaPackages.getXjcPackageName(), "Action");
        javaBuffer.addImport(javaPackages.getXjcPackageName(), "Actionable");

        // Generate the method:
        generateDoc(method);
        javaBuffer.addLine("@POST");
        javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes());
        javaBuffer.addLine("@Actionable");
        javaBuffer.addLine(
            "@Path(\"%s\")",
            jaxrsNames.getActionPath(method.getName())
        );
        String methodName = jaxrsNames.getMethodName(method.getName());
        if (baseMethods.containsKey(method)) {
            javaBuffer.addLine("default Response %s(Action action) {", methodName);
            Set signatures = baseMethods.get(method);
            if (signatures!=null && mandatoryAttributeExists(signatures)) {
                writeHelperInvocation(helperClassName, "action", method.getName());
            }
            else {
                javaBuffer.addLine("throw new UnsupportedOperationException();");
                //add log message - signatures with only 'optional' attributes indicate bad input.
            }
            javaBuffer.addLine("}");
        } else {
            //generate do() method
            if (method.isMandatoryAttributeExists()) {
                javaBuffer.addLine("default Response %s(Action action) {", "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1));
                javaBuffer.addLine(helperClassName.getSimpleName() + ".validate" + getActionValidationMethodName(methodName) + "(action);");
                javaBuffer.addLine("return " + methodName + "(action);");
                javaBuffer.addLine("}");
            }
            javaBuffer.addLine("");
            //generate () method
            addResponseReturnMethod(jaxrsNames.getMethodName(method.getName()) + "(Action action)");
        }
        javaBuffer.addLine();
    }

    private boolean mandatoryAttributeExists(Set methods) {
        for (Method method : methods) {
            if (method.isMandatoryAttributeExists()) {
                return true;
            }
        }
        return false;
    }

    private String getActionValidationMethodName(String methodName) {
        if (methodName.matches("{1}do[A-Z].*")) {
            return methodName.substring(2, 3).toUpperCase() + methodName.substring(3);
        } else {
            return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
        }
    }
    private void generateLocator(Locator locator) {
        if (locator.getParameters().isEmpty()) {
            generateParameterlessLocator(locator);
        }
        else {
            generateParameterizedLocator(locator);
        }
    }

    private void generateParameterizedLocator(Locator locator) {
        // Calculate the Java name of the service located by the given locator:
        JavaClassName interfaceName = jaxrsNames.getInterfaceName(locator.getService());

        // Generate the imports:
        javaBuffer.addImport(Path.class);
        javaBuffer.addImport(PathParam.class);
        javaBuffer.addImport(interfaceName);

        // Generate the locator method:
        generateDoc(locator);
        javaBuffer.addLine("@Path(\"{id}\")");
        javaBuffer.addLine(
            "%s get%sResource(@PathParam(\"id\") String id);",
            interfaceName.getSimpleName(),
            javaNames.getJavaClassStyleName(locator.getName())
        );

        javaBuffer.addLine();
    }

    private void generateParameterlessLocator(Locator locator) {
        // Calculate the Java name of the service located by the given locator:
        JavaClassName interfaceName = jaxrsNames.getInterfaceName(locator.getService());

        // Generate the imports:
        javaBuffer.addImport(Path.class);
        javaBuffer.addImport(PathParam.class);
        javaBuffer.addImport(interfaceName);

        // Generate the locator method:
        generateDoc(locator);
        javaBuffer.addLine(
            "@Path(\"%s\")",
            jaxrsNames.getActionPath(locator.getName())
        );
        javaBuffer.addLine(
            "%s get%sResource();",
            interfaceName.getSimpleName(),
            javaNames.getJavaClassStyleName(locator.getName())
        );

        javaBuffer.addLine();
    }

    private String generateMediaTypes() {
        return String.join(", ", MEDIA_TYPES);
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy