惯例先放一下JAVAPOET的简介 源码在此
前几日其他项目突然出现了60多个表单的开发任务,开发任务之大令人发指,虽然手头项目暂时没有如此巨额的表单开发需求,但是为了防患于未然,加上最近确实没有了梳理业务的兴趣,就想弄一个代码生成器
翻遍了无数资料甚至还为此花了大洋去看所谓的名师教程(被骗,心痛),基本上能用的寥寥无几,而且生成的代码和项目架构不符,也没法应用。
找到一篇写的好详细的源码分析 简书链接
一咬牙 一跺脚,自己来!
放代码。
ublic class CodeCreate {
private String fileSrc;
public CodeCreate(){
this.fileSrc = "D:/TEMP/";
}
public CodeCreate(String fileSrc){
this.fileSrc = fileSrc;
}
/*
* 生成所有层代码并输出到对应的文件位置中
*
*/
public void createAll(String tablename,String classname){
try {
List<TableInfo> tableInfoList =
ConnectDatabase.sysoutStrTablePdmCloumns(tablename);
//生成实体测试
createModel(tableInfoList,classname);
//生成Dao层测试
createDao(tablename,classname);
//生成Service层测试
createService(classname);
//生成ServiceImpl层测试
createServiceImpl(tableInfoList,classname);
//生成Controller层测试
createController(classname);
} catch (SQLException e) {
e.printStackTrace();
}
}
//生成model层代码
private void createModel(List<TableInfo> list,String className){
Builder builder = TypeSpec.classBuilder(className);
for (int i = 0; i < list.size(); i++) {
TableInfo infotemp = list.get(i);
String column = PoetUtils.getFieldName(infotemp.getColumnname());
Class datatype = PoetUtils.getClassType(infotemp.getColumntype());
builder = PoetUtils.addGetAndSet(builder,datatype,column);
}
builder.addModifiers(Modifier.PUBLIC);
TypeSpec relust = builder.build();
JavaFile javaFile = JavaFile.builder("persistence.entity", relust).build();
File outputFile = new File(fileSrc+className+"/"); //输出文件
try {
javaFile.writeTo(outputFile);
javaFile.writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 生成dao层代码
*/
private void createDao(String tablename,String className){
Builder builder = TypeSpec.classBuilder(className+"Dao");
//定义动态类型
ClassName baseJdbcDao = ClassName.get("cn.jasgroup.jasframework.dataaccess.base", "BaseJdbcDao");
ClassName bo = ClassName.get("business.bo", className+"Bo");
ClassName entity = ClassName.get("persistence.entity", className);
ClassName pageRequest = ClassName.get("com.jasgroup.platform.common.utils.page", "PageRequest");
ClassName page = ClassName.get("com.jasgroup.platform.common.utils.page", "Page");
ClassName abstractExcutiveDaoImpl = ClassName.get("com.jasgroup.platform.common.persistence.dao.impl", "AbstractExcutiveDaoImpl");
ClassName string = ClassName.get("java.lang", "String");
//添加baseJdbcDao的get和set方法
builder = PoetUtils.addGetAndSet(builder,baseJdbcDao,"baseJdbcDao");
builder.addModifiers(Modifier.PUBLIC);
//添加getAll方法
MethodSpec getAll = MethodSpec.methodBuilder("getAll")
.addModifiers(Modifier.PUBLIC)
.returns(ParameterizedTypeName.get(page, entity))
.addParameter(bo,"bo")
.addParameter(pageRequest,"pageRequest")
.addStatement("$T hql = new $T($S)",StringBuffer.class,StringBuffer.class,"from "+className+" x where x.active = 1")
.addStatement("return this.findPage(pageRequest, hql.toString(), new $T<Object>().toArray())",ArrayList.class)
.build();
builder.addMethod(getAll);
//添加delete方法代码
MethodSpec delete = MethodSpec.methodBuilder("delete")
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class,"eventid")
.addStatement("String sql = $S"+"+eventid+"+"$S","update "+tablename+" t set t.active = 0 where eventid = '","' ")
.addStatement("this.baseJdbcDao.execute(sql)")
.build();
builder.addMethod(delete);
builder.superclass(ParameterizedTypeName.get(abstractExcutiveDaoImpl,entity,string));
TypeSpec relust = builder.build();
JavaFile javaFile = JavaFile.builder("persistence.dao", relust).build();
File outputFile = new File(this.fileSrc+className+"/"); //输出文件
try {
javaFile.writeTo(outputFile);
javaFile.writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 生成service层代码service接口
*/
private void createService(String className){
Builder builder = TypeSpec.interfaceBuilder(className+"Service");
//定义动态类型
ClassName baseService = ClassName.get("cn.jasgroup.jasframework.main.business.service", "BaseService");
ClassName bo = ClassName.get("business.bo", className+"Bo");
ClassName pageRequest = ClassName.get("com.jasgroup.platform.common.utils.page", "PageRequest");
ClassName page = ClassName.get("com.jasgroup.platform.common.utils.page", "Page");
ClassName file = ClassName.get("org.springframework.web.multipart", "MultipartFile");
//定义getAll接口
MethodSpec getAll = MethodSpec.methodBuilder("getAll")
.addModifiers(Modifier.PUBLIC,Modifier.ABSTRACT)
.returns(ParameterizedTypeName.get(page, bo))
.addParameter(bo,"bo")
.addParameter(pageRequest,"pageRequest")
.build();
builder.addMethod(getAll);
//定义findByID接口
MethodSpec findByID = MethodSpec.methodBuilder("findByID")
.addModifiers(Modifier.PUBLIC,Modifier.ABSTRACT)
.returns(bo)
.addParameter(String.class,"eventid")
.build();
builder.addMethod(findByID);
//定义addorUpdatebo接口
MethodSpec addorUpdatebo = MethodSpec.methodBuilder("addorUpdatebo")
.addModifiers(Modifier.PUBLIC,Modifier.ABSTRACT)
.returns(String.class)
.addParameter(bo,"bo")
.build();
builder.addMethod(addorUpdatebo);
//定义delete接口
MethodSpec delete = MethodSpec.methodBuilder("delete")
.addModifiers(Modifier.PUBLIC,Modifier.ABSTRACT)
.returns(int.class)
.addParameter(String.class,"ids")
.build();
builder.addMethod(delete);
//定义excelVerify接口
MethodSpec excelVerify = MethodSpec.methodBuilder("excelVerify")
.addModifiers(Modifier.PUBLIC,Modifier.ABSTRACT)
.returns(ParameterizedTypeName.get(Map.class,String.class,Object.class))
.addParameter(file,"file")
.addParameter(String.class,"coverRepeat")
.addException(Exception.class)
.build();
builder.addMethod(excelVerify);
builder.addSuperinterface(baseService);
builder.addModifiers(Modifier.PUBLIC);
TypeSpec relust = builder.build();
JavaFile javaFile = JavaFile.builder("business.service", relust).build();
File outputFile = new File(this.fileSrc+className+"/"); //输出文件
try {
javaFile.writeTo(outputFile);
javaFile.writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 生成serviceImpl层代码serviceImpl
*/
private void createServiceImpl(List<TableInfo> list,String className){
Builder builder = TypeSpec.classBuilder(className+"ServiceImpl");
//定义动态类型
ClassName abstractExcutiveServiceImpl = ClassName.get("com.jasgroup.platform.common.business.service.impl", "AbstractBusinessServiceImpl");
ClassName interf = ClassName.get("persistence.service",className+"Service");
ClassName impl = ClassName.get("persistence.service.impl",className+"ServiceImpl");
ClassName bo = ClassName.get("business.bo", className+"Bo");
ClassName entity = ClassName.get("persistence.entity", className);
ClassName pageRequest = ClassName.get("com.jasgroup.platform.common.utils.page", "PageRequest");
ClassName page = ClassName.get("com.jasgroup.platform.common.utils.page", "Page");
ClassName file = ClassName.get("org.springframework.web.multipart", "MultipartFile");
ClassName entityDao = ClassName.get("persistence.dao", className+"Dao");
ClassName logService = ClassName.get("cn.jasgroup.jasframework.log.business.service","LogService");
ClassName log = ClassName.get("org.slf4j","Logger");
ClassName logFactory = ClassName.get("org.slf4j","LoggerFactory");
//定义基本方法
String dao = PoetUtils.toLowerCaseFirstOne(className)+"Dao";
String logInfo = "logService";
builder = PoetUtils.addGetAndSet(builder,entityDao,dao);
builder = PoetUtils.addGetAndSet(builder,logService,logInfo);
//定义modeltitle属性 以及初始值
FieldSpec modeltitle = FieldSpec.builder(String.class,
"modeltitle")
.addModifiers(Modifier.PRIVATE,Modifier.FINAL)
.initializer("$S","xxxxxx数据表")
.build();
builder.addField(modeltitle);
//定义log属性 以及初始值
FieldSpec logSpec = FieldSpec.builder(log,
"log")
.addModifiers(Modifier.PROTECTED,Modifier.FINAL,Modifier.STATIC)
.initializer("$T.getLogger($T.class)",logFactory,impl)
.build();
builder.addField(logSpec);
//定义coverToBo方法
com.squareup.javapoet.MethodSpec.Builder builderMethod = MethodSpec.methodBuilder("coverToBo");
builderMethod
.addModifiers(Modifier.PRIVATE)
.returns(bo)
.addParameter(entity,"sg")
.addStatement("if(sg == null)return null")
.addStatement("$T bo = new $T()",bo,bo);
for (int i = 0; i < list.size(); i++) {
String columnTemp = PoetUtils.getFieldName(list.get(i).getColumnname());
String column = PoetUtils.toUpperCaseFirstOne(columnTemp);
builderMethod.addStatement("bo.set"+column+"(sg.get"+column+"())");
}
builderMethod.addStatement("return bo");
MethodSpec coverToBo = builderMethod.build();
builder.addMethod(coverToBo);
//定义coverToEntity方法
com.squareup.javapoet.MethodSpec.Builder builderMethodEntity = MethodSpec.methodBuilder("coverToEntity");
builderMethodEntity
.addModifiers(Modifier.PRIVATE)
.returns(entity)
.addParameter(bo,"bo")
.addException(ParseException.class)
.addStatement("$T sg = null",entity)
.addStatement("String eventid = bo.getEventid()")
.beginControlFlow("if(eventid != null && !$S.equals(eventid))","")
.addStatement("sg = this."+dao+".get(eventid)")
.addStatement("sg.setModifiedby(this.getUser().getName())")
//.endControlFlow("")
.beginControlFlow("} else")
.addStatement("sg = new $T()",entity)
.addStatement("sg.setEventid($T.randomUUID().toString())",UUID.class)
.addStatement("sg.setActive(1)")
.addStatement("sg.setCreatedby(this.getUser().getName())")
.addStatement("sg.setCreateddate(new $T())",Date.class)
.endControlFlow();
for (int i = 0; i < list.size(); i++) {
if("EVENTID".equals(list.get(i).getColumnname())||
"EVENTID".equals(list.get(i).getColumnname())||
"ACTIVE".equals(list.get(i).getColumnname())||
"MODIFIEDBY".equals(list.get(i).getColumnname())||
"CREATEDBY".equals(list.get(i).getColumnname())||
"CREATEDDATE".equals(list.get(i).getColumnname())){
continue;
}
String columnTemp = PoetUtils.getFieldName(list.get(i).getColumnname());
String column = PoetUtils.toUpperCaseFirstOne(columnTemp);
builderMethodEntity.addStatement("sg.set"+column+"(bo.get"+column+"())");
}
builderMethodEntity.addStatement("return sg");
MethodSpec coverToEntity = builderMethodEntity.build();
builder.addMethod(coverToEntity);
//定义getAll方法
MethodSpec getAll = MethodSpec.methodBuilder("getAll")
.addModifiers(Modifier.PUBLIC)
.returns(ParameterizedTypeName.get(page, bo))
.addParameter(bo,"bo")
.addParameter(pageRequest,"pageRequest")
.addStatement("$T<$T> pagebo = new $T<$T>()",page,bo,page,bo)
.addStatement("$T<$T> page = this."+dao+".getAll(bo,pageRequest)",page,entity)
.addStatement("$T<$T> sglist = page.getResult()",List.class,entity)
.addStatement("$T<$T> bolist = new $T<$T>()",List.class,bo,ArrayList.class,bo)
.beginControlFlow("for($T sg : sglist)", entity)
.addStatement("$T boTemp = this.coverToBo(sg)",bo)
.addStatement("bolist.add(boTemp)")
.endControlFlow()
.addStatement("pagebo.setResult(bolist)")
.addStatement("pagebo.setTotalItems(page.getTotalItems())")
.addStatement("return pagebo")
.addAnnotation(Override.class)
.build();
builder.addMethod(getAll);
//定义findByID方法
MethodSpec findByID = MethodSpec.methodBuilder("findByID")
.addModifiers(Modifier.PUBLIC)
.returns(bo)
.addParameter(String.class,"eventid")
.addStatement("$T sg = null",entity)
.beginControlFlow("if(eventid != null && !$S.equals(eventid))","")
.addStatement("sg = this."+dao+".get(eventid)")
.endControlFlow()
.addStatement("return this.coverToBo(sg)")
.addAnnotation(Override.class)
.build();
builder.addMethod(findByID);
//定义addorUpdatebo方法
MethodSpec addorUpdatebo = MethodSpec.methodBuilder("addorUpdatebo")
.addModifiers(Modifier.PUBLIC)
.returns(String.class)
.addParameter(bo,"bo")
.addStatement("if(bo == null)return null")
.addStatement("$T sg = null",entity)
.beginControlFlow("try")
.addStatement("String eventid = $S","")
.addStatement("sg = this.coverToEntity(bo)")
.beginControlFlow("if(null!=sg)")
.addStatement("eventid = this."+dao+".saveOrUpdate(sg)")
.addStatement("if(null!=sg.getEventid())"+logInfo+".withLogUpdate(sg,getUser())")
.addStatement("else logService.withLogSave(sg,getUser())")
.endControlFlow()
.addStatement("return eventid")
.beginControlFlow("} catch (Exception e)")
.addStatement("e.printStackTrace()")
.endControlFlow()
.addStatement("return null")
.addAnnotation(Override.class)
.build();
builder.addMethod(addorUpdatebo);
//定义delete方法
MethodSpec delete = MethodSpec.methodBuilder("delete")
.addModifiers(Modifier.PUBLIC)
.returns(int.class)
.addParameter(String.class,"ids")
.addStatement("int i = 0")
.beginControlFlow("if(ids !=null && !$S.equals(ids))","")
.addStatement("String idss = ids.substring(0, ids.length() - 1)")
.addStatement("String[] idsss = idss.split($S)",",")
.addStatement("$T sg = null",entity)
.beginControlFlow("for (String id : idsss)")
.beginControlFlow("try")
.addStatement("sg = this."+dao+".get(id);")
.beginControlFlow("if(sg != null)")
.addStatement("sg.setActive(0)")
.addStatement("this."+dao+".update(sg)")
.addStatement(logInfo+".withLogDelete(sg.getEventid(), $T.class)",entity)
.addStatement("i++")
.endControlFlow()
.beginControlFlow("} catch (Exception e)")
.addStatement("e.printStackTrace()")
.endControlFlow()
.endControlFlow()
.endControlFlow()
.addStatement("return i")
.addAnnotation(Override.class)
.build();
builder.addMethod(delete);
//定义导入功能
MethodSpec excelVerify = MethodSpec.methodBuilder("excelVerify")
.addModifiers(Modifier.PUBLIC)
.returns(ParameterizedTypeName.get(Map.class,String.class,Object.class))
.addParameter(file,"file")
.addParameter(String.class,"coverRepeat")
.addException(Exception.class)
.addJavadoc("此模块待开发")
.addStatement("return null")
.addAnnotation(Override.class)
.build();
builder.addMethod(excelVerify);
builder.addSuperinterface(interf);
builder.superclass(ParameterizedTypeName.get(abstractExcutiveServiceImpl,entity));
builder.addModifiers(Modifier.PUBLIC);
TypeSpec relust = builder.build();
JavaFile javaFile = JavaFile.builder("business.service.impl", relust).build();
File outputFile = new File(this.fileSrc+className+"/"); //输出文件
try {
javaFile.writeTo(outputFile);
javaFile.writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 生成Controller层代码serviceImpl
*/
private void createController(String className){
Builder builder = TypeSpec.classBuilder(className+"Controller");
//注解的动态类型
ClassName controller = ClassName.get("org.springframework.stereotype", "Controller");
ClassName requestMapping = ClassName.get("org.springframework.web.bind.annotation", "RequestMapping");
ClassName requestMethod = ClassName.get("org.springframework.web.bind.annotation", "RequestMethod");
ClassName requestParam = ClassName.get("org.springframework.web.bind.annotation", "RequestParam");
ClassName responseBody = ClassName.get("org.springframework.web.bind.annotation", "ResponseBody");
//定义动态类型
ClassName bo = ClassName.get("business.bo", className+"Bo");
ClassName baseController = ClassName.get("com.jasgroup.platform.common.web.controller", "BaseController");
ClassName pageRequest = ClassName.get("com.jasgroup.platform.common.utils.page", "PageRequest");
ClassName page = ClassName.get("com.jasgroup.platform.common.utils.page", "Page");
ClassName file = ClassName.get("org.springframework.web.multipart", "MultipartFile");
ClassName entityService = ClassName.get("business.service", className+"Service"); //http相关
ClassName request = ClassName.get("javax.servlet.http","HttpServletRequest");
ClassName response = ClassName.get("javax.servlet.http","HttpServletResponse");
//工具相关
ClassName excelUtil = ClassName.get("com.jasgroup.platform.common.utils","ExcelUtil");
ClassName constants = ClassName.get("com.jasgroup.platform.common.utils","Constants");
ClassName encodeUtil = ClassName.get("cn.jasgroup.jasframework.utils","EncodeUtil");
ClassName readConfigUtil = ClassName.get("cn.jasgroup.jasframework.utils","ReadConfigUtil");
ClassName enterdataMultipartFile = ClassName.get("com.jasgroup.platform.common.inputexcel","EnterdataMultipartFile");
ClassName diskFileItemFactory = ClassName.get("org.apache.commons.fileupload.disk","DiskFileItemFactory");
ClassName fileItem = ClassName.get("org.apache.commons.fileupload","FileItem");
ClassName servletFileUpload = ClassName.get("org.apache.commons.fileupload.servlet","ServletFileUpload");
//定义属性
String service = PoetUtils.toLowerCaseFirstOne(className)+"Service";
builder = PoetUtils.addGetAndSet(builder,entityService,service);
//定义getAll方法
MethodSpec getAll = MethodSpec.methodBuilder("getAll")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(requestMapping).addMember("value", "$S","getAll").build())
.addAnnotation(responseBody)
.returns(Object.class)
.addParameter(request,"request")
.addParameter(response,"response")
.addParameter(bo,"bo")
.addStatement("$T<Object, Object> map = new $T<Object, Object>()",Map.class,HashMap.class)
.addStatement("$T pageRequest = getPage(request)",pageRequest)
.addStatement("$T<$T> page = null",page,bo)
.beginControlFlow("try")
.addStatement("page = this."+service+".getAll(bo, pageRequest)")
.addStatement("$T exportExcel = request.getParameter($S)",String.class,"exportExcel")
.beginControlFlow("if ($S.equals(exportExcel))", "exportExcel")
.addStatement("pageRequest.setPageSize($T.PAGE_SIZE)",constants)
.addStatement("page = this."+service+".getAll(bo, pageRequest)")
.addStatement("$T propertyName = $T.urlDecode(request.getParameter($S))",String.class,encodeUtil,"propertyName")
.addStatement("$T<String> listname = new $T<String>()",List.class,ArrayList.class)
.beginControlFlow("if(propertyName != null)")
.addStatement("listname = $T.asList(propertyName.split($S))",Arrays.class,",")
.endControlFlow()
.addStatement("String propertyDes = $T.urlDecode(request.getParameter($S))",encodeUtil,"propertyDes")
.addStatement("$T<String> listdesc = new $T<String>()",List.class,ArrayList.class)
.beginControlFlow("if (propertyDes != null)")
.addStatement("listdesc = $T.asList(propertyDes.split($S))",Arrays.class,",")
.endControlFlow()
.addStatement("new $T().exportDataListToExcel($S, page.getResult(), listname, listdesc, request,response)",excelUtil,"xxxxxxx数据.xls")
.addStatement("return null")
.endControlFlow()
.addStatement("map.put($S, $S)","1","success")
.addStatement("map.put($S, page.getTotalItems())","total")
.addStatement("map.put($S, page.getResult())","rows")
.addStatement("return map")
.beginControlFlow("} catch (Exception e) ")
.addStatement("log.error(e.getMessage())")
.addStatement("e.printStackTrace()")
.endControlFlow()
.addStatement("return null")
.build();
builder.addMethod(getAll);
//定义save方法
MethodSpec save = MethodSpec.methodBuilder("save")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(requestMapping).addMember("value", "$S","save").build())
.addAnnotation(responseBody)
.returns(Object.class)
.addParameter(request,"request")
.addParameter(bo,"bo")
.addStatement("$T<Object, Object> map = new $T<Object, Object>()",Map.class,HashMap.class)
.beginControlFlow("try")
.addStatement("this.setLoginUser(request, "+service+")")
.addStatement("String eventid = this."+service+".addorUpdatebo(bo)")
.addStatement("map.put($S, 1)","success")
.addStatement("map.put($S, $S)","msg","保存成功")
.addStatement("map.put($S, eventid)","eventid")
.beginControlFlow("} catch (Exception e) ")
.addStatement("map.put($S, -1)","error")
.addStatement("map.put($S, $S)","msg","保存失败")
.addStatement("e.printStackTrace()")
.endControlFlow()
.addStatement("return map")
.build();
builder.addMethod(save);
//定义findByID方法
MethodSpec findByID = MethodSpec.methodBuilder("findByID")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(requestMapping).addMember("value", "$S","findByID").build())
.addAnnotation(responseBody)
.returns(bo)
.addParameter(String.class,"eventid")
.addStatement("return this."+service+".findByID(eventid)")
.build();
builder.addMethod(findByID);
//定义delete方法
MethodSpec delete = MethodSpec.methodBuilder("delete")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(requestMapping).addMember("value", "$S","delete").build())
.addAnnotation(responseBody)
.returns(Object.class)
.addParameter(String.class,"ids")
.addStatement("$T<Object, Object> map = new $T<Object, Object>()",Map.class,HashMap.class)
.beginControlFlow("try")
.addStatement("int i = this."+service+".delete(ids)")
.addStatement("log.info($S + i)","删除数目:")
.addStatement("map.put($S, $S)","success","1")
.addStatement("map.put($S, $S)","msg","删除成功")
.beginControlFlow("} catch (Exception e) ")
.addStatement("map.put($S, $S)","error","-1")
.addStatement("map.put($S, $S)","msg","删除失败")
.addStatement("e.printStackTrace()")
.endControlFlow()
.addStatement("return map")
.build();
builder.addMethod(delete);
//定义outTankPlateExcel方法 下载导入模板
MethodSpec outTankPlateExcel = MethodSpec.methodBuilder("outPilefoundationExcel")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(requestMapping).addMember("value", "$S","outTankPlateExcel").build())
.addAnnotation(responseBody)
.returns(Object.class)
.addParameter(request,"request")
.addParameter(response,"response")
.addStatement("$T bis = null",BufferedInputStream.class)
.addStatement("$T bos = null",BufferedOutputStream.class)
.addStatement("String str = $S","XXXXX数据表导入模板.xls")
.beginControlFlow("try")
.addStatement("response.setContentType($S)","application/x-msdownload;")
.addStatement("response.setHeader($S, $S + $T.encode(str, $S))","Content-disposition","attachment; filename=",URLEncoder.class,"utf-8")
.addStatement("String rootpath = request.getSession().getServletContext().getRealPath($S) + $S + str","/","\\help\\")
.addStatement("$T f = new $T(rootpath)",File.class,File.class)
.beginControlFlow("if (f.exists())")
.addStatement("$T is = new $T(f)",FileInputStream.class,FileInputStream.class)
.addStatement("bis = new $T(is)",BufferedInputStream.class)
.addStatement("bos = new $T(response.getOutputStream())",BufferedOutputStream.class)
.addStatement("byte[] buff = new byte[2048]")
.addStatement("int bytesRead")
.beginControlFlow("while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))")
.addStatement("bos.write(buff, 0, bytesRead)")
.endControlFlow()
.endControlFlow()
.beginControlFlow("} catch ($T e) ",Exception.class)
.addStatement("log.error($S + e.getMessage())","下载导入模板失败:")
.addStatement("e.printStackTrace()")
.beginControlFlow("} finally ")
.beginControlFlow("try")
.addStatement("if (bis != null)bis.close()")
.addStatement("if (bos != null)bos.close()")
.beginControlFlow("} catch ($T e) ",Exception.class)
.addStatement("log.error($S + e.getMessage())","下载导入模板失败:")
.addStatement("e.printStackTrace()")
.endControlFlow()
.endControlFlow()
.addStatement("return null")
.build();
builder.addMethod(outTankPlateExcel);
//定义uploadForm方法 上传文件
MethodSpec uploadForm = MethodSpec.methodBuilder("handleFormUpload")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(requestMapping).addMember("value", "$S","/uploadForm").addMember("method", "$T.POST",requestMethod).build())
.addAnnotation(responseBody)
.addException(Exception.class)
.returns(Object.class)
.addParameter(request,"request")
.addParameter(ParameterSpec.builder(String.class, "coverRepeat")
.addAnnotation(AnnotationSpec.builder(requestParam).addMember("value", "$S","coverRepeat").build())
.build())
.addStatement("$T<String, Object> result = new $T<String, Object>()",Map.class,HashMap.class)
.addStatement("$T file = this.uploadAttachement(request)",file)
.beginControlFlow("if (!file.isEmpty())")
.beginControlFlow("try")
.addStatement("setLoginUser(request, "+service+")")
.addStatement("result = this."+service+".excelVerify(file, coverRepeat)")
.beginControlFlow("} catch ($T e) ",Exception.class)
.addStatement("result.put($S, -1)","error")
.addStatement("result.put($S, $S)","msg","文件校验失败!")
.addStatement("log.error($S + e.getMessage())","上传文件失败:")
.addStatement("e.printStackTrace()")
.endControlFlow()
.beginControlFlow("} else ")
.addStatement("result.put($S, -1)","error")
.addStatement("result.put($S, $S)","msg","文件上传失败!")
.endControlFlow()
.addStatement("return result")
.build();
builder.addMethod(uploadForm);
//定义uploadAttachement方法
MethodSpec uploadAttachement = MethodSpec.methodBuilder("uploadAttachement")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S","rawtypes").build())
.returns(file)
.addParameter(request,"request")
.addStatement("$T file = new $T()",enterdataMultipartFile,enterdataMultipartFile)
.addStatement("$T factory = new $T()",diskFileItemFactory,diskFileItemFactory)
.addStatement("factory.setSizeThreshold($T.parseInt($T.getPlatformConfig($S)))",Integer.class,readConfigUtil,"Tmaxsize")
.addStatement("$T upload = new $T(factory)",servletFileUpload,servletFileUpload)
.addStatement("upload.setSizeMax($T.parseInt($T.getPlatformConfig($S)))",Integer.class,readConfigUtil,"uploadMaxsize")
.addStatement("upload.setHeaderEncoding($S)","UTF-8")
.addStatement("if (!$T.isMultipartContent(request))return null",servletFileUpload)
.beginControlFlow("try")
.addStatement("$T items = upload.parseRequest(request)",List.class)
.addStatement("$T item = null",fileItem)
.beginControlFlow("for (int i = 0; i < items.size(); i++)")
.addStatement("item = ($T) items.get(i)",fileItem)
.addStatement("file.setOriginalFilename(item.getName())")
.addStatement("file.setInputStream(item.getInputStream())")
.addStatement("item.delete()")
.endControlFlow()
.beginControlFlow("} catch ($T e) ",Exception.class)
.addStatement("e.printStackTrace()")
.endControlFlow()
.addStatement("return file")
.build();
builder.addMethod(uploadAttachement);
builder.addModifiers(Modifier.PUBLIC);
builder.addAnnotation(controller);
AnnotationSpec annotationSpec = AnnotationSpec.builder(requestMapping)
.addMember("value", "$S", PoetUtils.toLowerCaseFirstOne(className))
.build();
builder.addAnnotation(annotationSpec);
builder.superclass(baseController);
TypeSpec relust = builder.build();
JavaFile javaFile = JavaFile.builder("web.controller", relust).build();
File outputFile = new File(this.fileSrc+className+"/"); //输出文件
try {
javaFile.writeTo(outputFile);
javaFile.writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}