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

templates.decorator.spring.controller.class.vm Maven / Gradle / Ivy

The newest version!
#parse( "${include}/header.include.vm" )
#parse("${include}/generic.include.vm")
#set ( $interfaceName      = "${sourceinfo.interfaceClass.simpleName}")
#set ( $className          ="${interfaceName}SpringController")
#set ( $sourceinfo.generatePackage = $pkg )
$codewriter.setCurrentJavaFilename("$pkg", "${className}.java")
## 读取源码注释
#set ($interfaceDoc    = $JavadocReader.read(${sourceinfo.interfaceClass}))
#set(  $tmp = $sourceinfo.importedList.remove("IOException"))
## 生成参数封装类名
#macro(argsClass)$TOOL.toClassName($method.name)${sourceinfo.methodSuffix($method)}Args#end
/**
 * decorator pattern 装饰者模式代理{@link #typeName(${sourceinfo.interfaceClass})}接口
* 将{@link #typeName(${sourceinfo.interfaceClass})}实例封装为一个spring controler
* $GENERAED_BY
* */ ${sourceinfo.backupImportedList()}## ${sourceinfo.rebuildImportedList($methods,false,false,true)}## package $pkg; #outputImports() #if($config.useCommonResponse) import static com.gitee.l0km.com4j.basex.web.DefaultResponseFactory.loadResponseFactory; import com.gitee.l0km.com4j.basex.web.Response; import com.gitee.l0km.com4j.basex.web.ResponseFactory; import com.gitee.l0km.com4j.basex.web.TranformValueException; #else import java.io.PrintWriter; import java.io.StringWriter; import java.util.ServiceLoader; import java.util.Iterator; #end###if($config.useCommonResponse) #if($config.timecost) import com.gitee.l0km.aocache.annotations.AoTimecost; #end###if($config.timecost) #if($config.withDelegateMethod) import com.gitee.l0km.codegen.annotations.DelegateMethod; #end import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import io.swagger.annotations.*; $!{interfaceDoc.getClassComment()}## @RestController("instanceOf${className}") @Api(value="${interfaceName}",tags={"${interfaceName} Controller"}) public class ${className} { private static final Logger logger = LoggerFactory.getLogger(${className}.class); #if($config.withV1Compatibility) private static InstanceSupplier instanceSupplier = getInstanceSupplier(); #end public static final ResponseFactory responseFactory = loadResponseFactory(); @Autowired#if($config.withV1Compatibility)(required = false)#end @Qualifier("${interfaceName}SpringInstance") private ${interfaceName} delegate; @Value("${${className}.logError:true}") private boolean logError = true ; @Value("${${className}.trace:true}") private boolean trace = true ; public ${className}() { } /** * @return 返回被装饰的{@link #typeName(${sourceinfo.interfaceClass})}实例 */ public #typeName(${sourceinfo.interfaceClass}) delegate() { #if($config.withV1Compatibility) if(instanceSupplier != null){ return Objects.requireNonNull(instanceSupplier.instanceOf${interfaceName}(),"${interfaceName} instance is null"); } #end return Objects.requireNonNull(delegate,"${interfaceName} instance is null"); } #set($methodCount = 0 ) #foreach ($method in $TOOL.sortBySignature($methods)) #set($methodCount= $methodCount + 1 ) #set ($methodDoc = $!{interfaceDoc.getMethodDoc($method.delegate())}) #set($firstLinePrefix = "") #set($deprecated = $method.deprecated || $!{interfaceDoc.isDeprecated($methodDoc)}) #if($deprecated) #set($firstLinePrefix = "【废弃方法】") #end #set($httpMethod=${sourceinfo.requestMethodOf($method,"POST")}) #set($paramPrefix = "") // port-$methodCount #if($deprecated) @SuppressWarnings("deprecation") #end @ResponseBody @RequestMapping(value = "${sourceinfo.portPrefix}${method.name}${sourceinfo.methodSuffix($method)}", method = RequestMethod.${sourceinfo.requestMethodOf($method,"POST")}${sourceinfo.appendProducesIfNoempty($method)}) @ApiOperation(value = "${firstLinePrefix}$TOOL.firstLine($!{interfaceDoc.commentTextOf($method.delegate())},true)", notes = $TOOL.asJavaString($!{interfaceDoc.commentTextOf($method.delegate())}," \n", true),httpMethod="${sourceinfo.requestMethodOf($method,"POST")}") #if($config.timecost && !${sourceinfo.withAnnotation($method,"com.gitee.l0km.aocache.annotations.AoTimecost")}) @AoTimecost #end###if($config.timecost) #if($config.withDelegateMethod) @DelegateMethod( #if($sourceinfo.imported(${config.implClass})) delegateType = #typeName(${config.implClass}).class, #else delegateTypeName = "${config.implClassName}", #end name = "$method.name"#if(${method.parameterTypes.size()}>0), parameterTypes={#join($method.parameterTypes '#typeName($e).class' ',')}, parameterNames={#join($method.parameterNames '"$e"' ',')}#end) #end ## 如果有方法注解(Annotation)则复制方法注解 #if(!${sourceinfo.annotationOf($method).empty}) ${sourceinfo.annoationCodeOf($method," ")} #end #if($httpMethod == "POST" || $httpMethod == "PUT") #set($paramname = "args") #set($paramPrefix = "$paramname.") public Response ${method.name}(#if($method.parameters.size() > 0) @Validated @RequestBody #argsClass() $paramname#end) #elseif($httpMethod == "GET" || $httpMethod == "DELETE") #if($method.parameters.size() > 0) @ApiImplicitParams({ #foreach( $param in $method.parameters ) @ApiImplicitParam(name = "$param.name", value =$TOOL.asJavaString($!{interfaceDoc.parameterCommentOf($method.delegate(),$param.name)}," \n", true) ,required =${sourceinfo.isRequired($param)} ,dataType="$TOOL.swaggerDataType(${param.type})",paramType = "query"$!{sourceinfo.defaultValueCodeOf($param,",")})#if( $velocityCount < $method.parameters.size() ),#end #end###foreach( $param in $method.parameters ) }) #end###if($method.parameters.size() > 0) public Response ${method.name}(#if($method.parameters.size() > 0) #join($method.parameters '@Validated @RequestParam(required =${sourceinfo.isRequired($e)}$!{sourceinfo.defaultValueCodeOf($e,",")}) #typeName($sourceinfo.actualTypeOf($e)) $e.name' ',')#end) #else /////// INVALID httpMethod=$httpMethod /////////// #end { Response response = responseFactory.createResponse(); response.delegate(delegate()); try{ #if($TOOL.isVoid($method.returnType)) delegate().${method.name}(#join($method.parameters '$paramPrefix$e.name' ',')); #if(${sourceinfo.needResponse($method)}) response.onComplete(); #else return null; #end #elseif($sourceinfo.isIsLocalMethod($method)) response.onComplete(false); #else response.onComplete(delegate().${method.name}(#join($method.parameters '$paramPrefix$e.name' ','))); #end } catch(Exception e){ if(!(e instanceof TranformValueException)){ if(trace) logger.error(e.getMessage(),e); else if(logError){ logger.error(e.getMessage()); } } response.onError(e); } return response; } #end##foreach #set($methodCount = 0 ) #foreach ($method in $TOOL.sortBySignature($methods)) #set($methodCount= $methodCount + 1 ) #set ($methodDoc = $!{interfaceDoc.getMethodDoc($method.delegate())}) #set($httpMethod=${sourceinfo.requestMethodOf($method,"POST")}) #if($httpMethod == "POST" || $httpMethod == "PUT") #if($method.parameters.size() > 0) /** * argClass-$methodCount
* wrap arguments for method {@link #${method.name}(#argsClass())} */ @ApiModel("${className}${esc.d}#argsClass()") public static class #argsClass(){ #foreach( $param in $method.parameters ) ## 如果有参数注解(Annotation)则复制参数注解 #if(!${sourceinfo.annotationOf($param).empty}) ${sourceinfo.annoationCodeOf($param," ")} #end @ApiModelProperty(value =$TOOL.asJavaString($!{interfaceDoc.parameterCommentOf($method.delegate(),$param.name)}," \n", true) ,required=${sourceinfo.isRequired($param)} ,dataType="$TOOL.swaggerDataType(${param.type})") public #typeName($sourceinfo.actualTypeOf($param)) $param.name; #end###foreach( $param in $method.parameters ) } #end###if($method.parameters.size() > 0) #end###if($httpMethod == "POST") #end###foreach ($method in $TOOL.sortBySignature($methods)) #if($config.withV1Compatibility) /** * 获取{@link #typeName(${sourceinfo.interfaceClass})}实例的接口, * 用于应用层SPI方式提供{@link #typeName(${sourceinfo.interfaceClass})}实例 * @author guyadong * */ public static interface InstanceSupplier{ #typeName(${sourceinfo.interfaceClass}) instanceOf${interfaceName}(); } /** * SPI(Service Provider Interface)机制加载 {@link InstanceSupplier}实例,没有找到则返回{@code null}, * 返回{@link InstanceSupplier}提供的{@link #typeName(${sourceinfo.interfaceClass})}实例 * @return 返回{@link #typeName(${sourceinfo.interfaceClass})}实例 */ private static final InstanceSupplier getInstanceSupplier() { /* SPI(Service Provider Interface)机制加载 {@link InstanceSupplier}实例,没有找到则抛出异常 */ ServiceLoader providers = ServiceLoader.load(InstanceSupplier.class); Iterator itor = providers.iterator(); return itor.hasNext() ? itor.next() : null; } /** * @param instanceSupplier 要设置的 instanceSupplier */ public static void setInstanceSupplier(InstanceSupplier instanceSupplier) { ${className}.instanceSupplier = instanceSupplier; } #end #if(!$config.useCommonResponse) /** * SPI(Service Provider Interface)加载{@link ResponseFactory}接口实例, * 没有找到则返回{@link DefaultResponseFactory}实例 * @return 返回{@link ResponseFactory}实例 */ private static final ResponseFactory loadResponseFactory() { ServiceLoader providers = ServiceLoader.load(ResponseFactory.class); Iterator itor = providers.iterator(); return itor.hasNext() ? itor.next() : new DefaultResponseFactory(); } /** * web响应数据接口 * @author guyadong * */ public static interface Response{ /** * 接口方法调用成功 * @param result 调用返回值 */ void onComplete(Object result); /** * 接口方法调用成功,调用方法返回类型为void */ void onComplete(); /** * 接口方法调用抛出异常 * @param e 异常 */ void onError(Exception e); /** * 设置调用代理对象实例 * @param delegate */ void delegate(Object delegate); } /** * 获取{@link Response}接口实例的工厂类接口 * @author guyadong * */ public static interface ResponseFactory{ /** * @return 返回新的{@link Response}接口实例 */ Response createResponse(); } /** * {@link Response}默认实现 * @author guyadong * */ public static class DefaultResponse implements Response{ private static boolean outStrackTrace = false; private boolean success; /** RPC调用的返回值 */ private Object result; /** 异常信息 */ private String errorMessage; /** 异常堆栈信息 */ private String stackTrace; @Override public void onComplete(Object result) { this.success = true; this.result = result; } @Override public void onComplete() { onComplete(null); } @Override public void onError(Exception e) { if(e instanceof TranformValueException){ onComplete((((TranformValueException)e).getResult())); return ; } success = false; errorMessage = e.getMessage(); if(errorMessage == null){ errorMessage = e.getClass().getSimpleName(); } if(outStrackTrace){ StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); stackTrace = writer.toString(); } } @Override public void delegate(Object delegate) { } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getStackTrace() { return stackTrace; } public void setStackTrace(String stackTrace) { this.stackTrace = stackTrace; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DefaultResponse [success="); builder.append(success); builder.append(", "); if (result != null) { builder.append("result="); builder.append(result); builder.append(", "); } if (errorMessage != null) { builder.append("errorMessage="); builder.append(errorMessage); builder.append(", "); } if (stackTrace != null) { builder.append("stackTrace="); builder.append(stackTrace); } builder.append("]"); return builder.toString(); } /** * 开启输出堆栈信息(默认为不开启)
* 开发时为了调试需要获取详细的异常堆栈信息可以开启 */ public static void enableStrackTrace() { outStrackTrace = true; } } /** * {@link ResponseFactory}接口默认实现 * @author guyadong * */ public static class DefaultResponseFactory implements ResponseFactory{ @Override public Response createResponse() { return new DefaultResponse(); } } /** * 通过异常传递正常返回值 * @author guyadong * */ public class TranformValueException extends RuntimeException { private static final long serialVersionUID = 3098148044189108183L; /** * 传递的正常返回值 */ private Object result; public TranformValueException(Object result) { super(); this.result = result; } /** * 正常返回值 */ public Object getResult() { return result; } } #end###if(!$config.useCommonResponse) public static String DESCRIPTION = $TOOL.asJavaString($interfaceDoc.commentText()," \n", true); public String getDescription(){ return DESCRIPTION; } } ${sourceinfo.restoreImportedList()}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy