JAVAPOET小试牛刀

惯例先放一下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();

        }

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,752评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,100评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,244评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,099评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,210评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,307评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,346评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,133评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,546评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,849评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,019评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,702评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,331评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,030评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,260评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,871评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,898评论 2 351

推荐阅读更多精彩内容