/** * Generates assembler classes if the API returns more than one object. * * @param resources * @param templateGroup */ private void generateModelClassesForInput( List<Resource> resources, StringTemplateGroup templateGroup) { List<String> generatedClasses = new ArrayList<String>(); for (Resource resource : resources) { if (resource.getEndPoints() != null) { for (Endpoint endpoint : resource.getEndPoints()) { if (endpoint.getOperations() != null) { for (EndpointOperation operation : endpoint.getOperations()) { ResourceMethod method = operation.generateMethod( endpoint, resource, dataTypeMappingProvider, nameGenerator); if (method.getInputModel() != null) { Model model = method.getInputModel(); if (model != null) { if (!generatedClasses.contains(model.getName())) { List<String> imports = new ArrayList<String>(); imports.addAll(this.config.getDefaultModelImports()); for (ModelField param : model.getFields()) { param.setName(reservedWordMapper.translate(param.getName())); for (String importDef : param .getFieldDefinition( this.getDataTypeMappingProvider(), config, nameGenerator) .getImportDefinitions()) { if (!imports.contains(importDef)) { imports.add(importDef); } } } StringTemplate template = templateGroup.getInstanceOf(MODEL_OBJECT_TEMPLATE); template.setAttribute("fields", model.getFields()); template.setAttribute("imports", imports); template.setAttribute("extends", config.getDefaultModelBaseClass()); template.setAttribute( "annotationPackageName", languageConfig.getAnnotationPackageName()); template.setAttribute("className", model.getGenratedClassName()); template.setAttribute(PACKAGE_NAME, config.getModelPackageName()); File aFile = new File( languageConfig.getModelClassLocation() + model.getGenratedClassName() + languageConfig.getClassFileExtension()); writeFile(aFile, template.toString(), "Input model class"); generatedClasses.add(model.getName()); } } } } } } } } }
/** * @param progressMonitor * @param uriMappings * @param resource * @param methodsStack * @throws CoreException */ private void resolveResourcesUriMappings( final Resource resource, final String uriTemplateFragment, final Map<ResolvedUriMapping, Stack<ResourceMethod>> uriMappings, final Stack<ResourceMethod> methodsStack, final IProgressMonitor progressMonitor) throws CoreException { // resource resourceMethods and subresources resourceMethods are treated the same way for (ResourceMethod resourceMethod : resource.getAllMethods()) { String uriPathTemplate = resolveURIPathTemplate(uriTemplateFragment, resource, resourceMethod); MediaTypeCapabilities mediaTypeCapabilities = resolveMediaTypeCapabilities(resource, resourceMethod); UriMapping resourceUriMapping = resourceMethod.getUriMapping(); ResolvedUriMapping uriMapping = new ResolvedUriMapping( resourceUriMapping.getHTTPMethod(), uriPathTemplate, resourceUriMapping.getQueryParams(), mediaTypeCapabilities); @SuppressWarnings("unchecked") Stack<ResourceMethod> stack = (Stack<ResourceMethod>) methodsStack.clone(); stack.add(resourceMethod); uriMappings.put(uriMapping, stack); } // TODO : verify support chain of subresource locators // TODO : stack resourceMethods and detect+prevent cycles for (ResourceMethod resourceMethod : resource.getSubresourceLocators()) { String uriPathTemplate = resolveURIPathTemplate(uriTemplateFragment, resource, resourceMethod); IType returnType = resourceMethod.getReturnType(); if (returnType == null) { continue; } ITypeHierarchy subresourceTypeHierarchy = JdtUtils.resolveTypeHierarchy(returnType, false, progressMonitor); for (IType subresourceType : subresourceTypeHierarchy.getSubtypes(returnType)) { Resource subresource = getByType(subresourceType); if (subresource != null && !subresource.isRootResource()) { @SuppressWarnings("unchecked") Stack<ResourceMethod> stack = (Stack<ResourceMethod>) methodsStack.clone(); stack.add(resourceMethod); resolveResourcesUriMappings( subresource, uriPathTemplate, uriMappings, stack, progressMonitor); } } } }
public ResourceClassBuilder buildMethod() { if (method.resourceClass.getClazz().isAnonymousClass()) { method.getMethod().setAccessible(true); } resourceClassBuilder.resourceMethods.add(method); return resourceClassBuilder; }
private static final MediaTypeCapabilities resolveMediaTypeCapabilities( final Resource resource, final ResourceMethod resourceMethod) { MediaTypeCapabilities resourceMediaTypeCapabilities = resource.getMediaTypeCapabilities(); MediaTypeCapabilities methodMediaTypeCapabilities = resourceMethod.getUriMapping().getMediaTypeCapabilities(); MediaTypeCapabilities mediaTypeCapabilities = new MediaTypeCapabilities(); if (!methodMediaTypeCapabilities.getConsumedMimeTypes().isEmpty()) { mediaTypeCapabilities.setConsumedMimeTypes( methodMediaTypeCapabilities.getConsumedMimeTypes()); } else if (!resourceMediaTypeCapabilities.getConsumedMimeTypes().isEmpty()) { mediaTypeCapabilities.setConsumedMimeTypes( resourceMediaTypeCapabilities.getConsumedMimeTypes()); } else { // leave empty collection // mediaTypeCapabilities.setConsumedMimeTypes(Arrays.asList("*/*")); } if (!methodMediaTypeCapabilities.getProducedMimeTypes().isEmpty()) { mediaTypeCapabilities.setProducedMimeTypes( methodMediaTypeCapabilities.getProducedMimeTypes()); } else if (!resourceMediaTypeCapabilities.getProducedMimeTypes().isEmpty()) { mediaTypeCapabilities.setProducedMimeTypes( resourceMediaTypeCapabilities.getProducedMimeTypes()); } else { // leave empty collection // mediaTypeCapabilities.setProducedMimeTypes(Arrays.asList("*/*")); } return mediaTypeCapabilities; }
/** * Generates one API class for each resource and each end point in the resource is translated as * method. * * @param resources * @param templateGroup */ private void generateAPIClasses(List<Resource> resources, StringTemplateGroup templateGroup) { for (Resource resource : resources) { try { List<ResourceMethod> methods = new ArrayList<ResourceMethod>(); List<String> imports = new ArrayList<String>(); imports.addAll(this.config.getDefaultServiceImports()); methods = resource.generateMethods( resource, dataTypeMappingProvider, nameGenerator, languageConfig); StringTemplate template = templateGroup.getInstanceOf(API_OBJECT_TEMPLATE); String className = resource.generateClassName(nameGenerator); if (className != null) { List<ResourceMethod> filteredMethods = new ArrayList<ResourceMethod>(); for (ResourceMethod method : methods) { if (!this.getCodeGenRulesProvider().isMethodIgnored(className, method.getName())) { filteredMethods.add(method); } } template.setAttribute("imports", imports); template.setAttribute(PACKAGE_NAME, config.getApiPackageName()); template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName()); template.setAttribute("modelPackageName", config.getModelPackageName()); template.setAttribute("exceptionPackageName", languageConfig.getExceptionPackageName()); template.setAttribute("resource", className); template.setAttribute("methods", filteredMethods); template.setAttribute("extends", config.getServiceBaseClass(className)); File aFile = new File( languageConfig.getResourceClassLocation() + resource.generateClassName(nameGenerator) + languageConfig.getClassFileExtension()); writeFile(aFile, template.toString(), "API Classes"); } } catch (RuntimeException t) { System.out.println( "Failed generating api class for the resource : " + resource.getResourcePath()); throw t; } } }
@Override protected void doWithMethodDocument(MethodDocument document, Method method) { ResourceMethod rm = method.getAnnotation(ResourceMethod.class); if (rm == null) { throw new IllegalArgumentException( "Can't generate document unless method is annotated with @ResourceMethod"); } MethodParamProcessor mpp = new MethodParamProcessor(); mpp.processAnnotations(method, document); // --- Process TGIRest annotations ResourceMethod resourceMethod = method.getAnnotation(ResourceMethod.class); if (resourceMethod != null) { document.setDescription(resourceMethod.description()); document.setResponseErrors(getResponseErrors(resourceMethod)); // Parse examples. document.setExampleDocuments(getExampleDocuments(resourceMethod)); } }
/** * Gets the error documentation for the resource method annotation. * * @param resourceMethod Endpoint method to document. * @return a list of ResponseErrors in the parameter */ List<ResponseError> getResponseErrors(ResourceMethod resourceMethod) { if (null == resourceMethod) return Collections.emptyList(); final Collection<ResponseError> errors = Collections2.transform( Arrays.asList(resourceMethod.errors()), new Function<MethodError, ResponseError>() { @Override public ResponseError apply(MethodError from) { return new ResponseError(from.status().getStatusCode(), from.cause()); } }); return ImmutableList.copyOf(errors); }
// FIXME : include method parameters if annotated with @QueryParam private static final String resolveURIPathTemplate( final String uriTemplateFragment, final Resource resource, final ResourceMethod resourceMethod) { StringBuffer uriTemplateBuffer = new StringBuffer(uriTemplateFragment); String resourceUriPathTemplate = resource.getUriPathTemplate(); String methodUriPathTemplate = resourceMethod.getUriMapping().getUriPathTemplateFragment(); if (resourceUriPathTemplate != null) { uriTemplateBuffer.append("/").append(resourceUriPathTemplate); } if (methodUriPathTemplate != null) { uriTemplateBuffer.append("/").append(methodUriPathTemplate); } return uriTemplateBuffer .toString() .replaceAll("/\\*", "/") .replaceAll("///", "/") .replaceAll("//", "/"); }
List<ApiExampleDocument> getExampleDocuments(ResourceMethod method) { if (null == method) return Collections.emptyList(); final Collection<ApiExampleDocument> documents = Collections2.transform( Arrays.asList(method.examples()), new Function<ApiCallExample, ApiExampleDocument>() { @Override public ApiExampleDocument apply(ApiCallExample apiCallExample) { return new ApiExampleDocument( apiCallExample.title(), apiCallExample.description(), apiCallExample.input(), apiCallExample.contentType(), apiCallExample.output(), apiCallExample.accepts()); } }); return ImmutableList.copyOf(documents); }
public ResourceMethodBuilder consumes(String... consumes) { MediaType[] types = new MediaType[consumes.length]; for (int i = 0; i < consumes.length; i++) types[i] = MediaType.valueOf(consumes[i]); method.consumes = types; return this; }
public ResourceMethodBuilder consumes(MediaType... consumes) { method.consumes = consumes; return this; }
public ResourceMethodBuilder produces(String... produces) { MediaType[] types = new MediaType[produces.length]; for (int i = 0; i < produces.length; i++) types[i] = MediaType.valueOf(produces[i]); method.produces = types; return this; }
public ResourceMethodBuilder produces(MediaType... produces) { method.produces = produces; return this; }
private void generateOutputWrappers(List<Resource> resources, StringTemplateGroup templateGroup) { List<String> generatedClasses = new ArrayList<String>(); StringTemplate template = templateGroup.getInstanceOf(WRAPPER_OBJECT_TEMPLATE); if (template == null) { System.out.println("WrapperObject template not found to generate output wrappers"); return; } for (Resource resource : resources) { if (resource.getEndPoints() != null) { for (Endpoint endpoint : resource.getEndPoints()) { if (endpoint.getOperations() != null) { for (EndpointOperation operation : endpoint.getOperations()) { ResourceMethod method = operation.generateMethod( endpoint, resource, dataTypeMappingProvider, nameGenerator); if (codeGenRulesProvider.isModelIgnored( nameGenerator.applyMethodNamingPolicy(method.getReturnClassName()))) { continue; } if (method.getListWrapperModel() != null) { Model model = method.getListWrapperModel(); method.setReturnClassName(model.getName()); if (model != null) { if (!generatedClasses.contains(model.getName())) { List<String> imports = new ArrayList<String>(); imports.addAll(this.config.getDefaultModelImports()); for (ModelField param : model.getFields()) { for (String importDef : param .getFieldDefinition( this.getDataTypeMappingProvider(), config, nameGenerator) .getImportDefinitions()) { if (!imports.contains(importDef)) { imports.add(importDef); } } } template = templateGroup.getInstanceOf(WRAPPER_OBJECT_TEMPLATE); template.setAttribute("fields", model.getFields()); template.setAttribute("imports", imports); template.setAttribute("extends", config.getDefaultModelBaseClass()); template.setAttribute( "annotationPackageName", languageConfig.getAnnotationPackageName()); template.setAttribute("className", model.getGenratedClassName()); template.setAttribute(PACKAGE_NAME, config.getModelPackageName()); File aFile = new File( languageConfig.getModelClassLocation() + model.getGenratedClassName() + languageConfig.getClassFileExtension()); writeFile(aFile, template.toString(), "List wrapper model class"); generatedClasses.add(model.getName()); } } } } } } } } }
public URI method(Consumer<R> methodInvocation) { Invocation invocation = invocationCaptor.capture(methodInvocation); ResourceMethod method = new ResourceMethod(invocation.getMethod()); return method.uriFromArguments(invocation.getArguments(), resourceUri.clone()); }