根据excel中的列表值,导入注解单元写入到指定包下所有java类方法中

根据excel中的列表值,导入注解单元写入到指定包下所有java类方法中
总体思路:
1.读入excel,遍历excel清单内容,保存到数据结构中。
2.遍历包下所有java文件,将文件内容按行存储到集合中。
3.两次对比遍历插入内容到文件对象中。
4.写文件。

代码:

ReadApiExcelForShiro

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.shiro.authz.annotation.RequiresRoles;

import com.dimeng.framework.utils.ExcelUtil;
import com.dimeng.framework.utils.StringUtil;

/**
 * 
 * 读取api excel 导入权限配置到文件中
 * <功能详细描述>
 * 
 * @author  liubeihua
 * @version  [版本号, 2016年1月15日]
 */
public class ReadApiExcelForShiro
{
    /**
     * 换行符
     */
    String newLineCode =System.getProperty("line.separator");
    /**
     * 导入文件的位置
     */
    private String apiExlfilePath = "F:/api/api.xls";
    
    private String applyDirectory = "F:/api/platform/controller";
    
    /**
     * 根据类名称存放API文档
     */
    private HashMap<String,ArrayList<ApiEntity>> fileApi = new HashMap<String,ArrayList<ApiEntity>>();
    

    enum Cols
    {
        /**
         * 包名
         */
        bm(0,"包名"),
        /**
         * 类说明
         */
        lsm(1,"类说明"),
        /**
         * 类名称
         */
        lmc(2,"类名称"),
        /**
         * 方法说明
         */
        ffsm(3,"方法说明"),
        /**
         * 方法名称
         */
        ffmc(4,"方法名称"),
        /**
         * restful类型
         */
        qqlx(5,"restful类型"),
        /**
         * 请求路径
         */
        qqlj(6,"请求路径"),
        /**
         * 包名
         */
        jsqx(7,"角色权限")
        ;
        
        /**
         * 类型值
         */
        private final int index;
        
        /**
         * 类型名称
         */
        private final String name;
        
        Cols(int index,String name)
        {
            this.index = index;
            this.name = name;
        }
    }
    
    
    /**
     * 文件列表(含有所有文件内容)
     */
    private ArrayList<JavaFileEntity> javaFiles = new ArrayList<JavaFileEntity>();
    
    
    public void read()
        throws FileNotFoundException, IOException
    {
        File file = new File(apiExlfilePath);
        File directory = new File(applyDirectory);
        //excel 中的数据
        String[][] datas = ExcelUtil.readData(file, 1);
        
        //根据类名称存放api到hash fileApi
        ArrayList<ApiEntity> javaFile = null;
        for(String[] api : datas)
        {
            String key = api[Cols.lmc.index]+".java";
            ApiEntity apiEntity = new ApiEntity();
            apiEntity.setPackageStr(api[Cols.bm.index]);
            apiEntity.setApiExplain(api[Cols.ffsm.index]);
            apiEntity.setClassExplain(api[Cols.lsm.index]);
            apiEntity.setClassStr(key);
            apiEntity.setMethodStr(api[Cols.ffmc.index]);
            apiEntity.setMethodType(api[Cols.qqlj.index]);
            apiEntity.setRoleCodes(api[Cols.jsqx.index]);
            apiEntity.setUrlStr(api[Cols.qqlj.index]);
            //如果集合中有则直接取
            if(fileApi.containsKey(key))
            {
                javaFile = fileApi.get(key);
            }else//没有就创建一个
            {
                javaFile=new ArrayList<ApiEntity>();
                fileApi.put(key, javaFile);
            }
            //单个api接口清单,添加到文件
            javaFile.add(apiEntity);
        }
        //遍历目录文件
        File[] dirs = directory.listFiles();
        for (File d : dirs)
        {
            String[] filelist = d.list();
            for (String f : filelist)
            {
                File readfile = new File(d.getPath() + "\\" + f);
                //构建java文件对象
                JavaFileEntity jfe = new JavaFileEntity();
                jfe.setFileName(f);
                jfe.setPath(readfile.getPath());
                jfe.setContent(readToStringArray(readfile));
                javaFiles.add(jfe);
                
            }
        }
        for (JavaFileEntity jf : javaFiles)
        {
            //更新文件内容
            jf.setContent(getNewContentByRoleApi(jf));  
            this.writeFile(new File(jf.getPath()) , jf); 
        }
        
    }
    
    /**
     * 按行读取文件内容
     * <功能详细描述>
     * @param file
     * @return 文件内容数组
     * @throws IOException
     */
    public  ArrayList<String> readToStringArray(File file)
        throws IOException
    {
        
        ArrayList<String> contents = new ArrayList<String>();
        FileReader reader = new FileReader(file);
        BufferedReader br = new BufferedReader(reader);
        String str = null;
        while ((str = br.readLine()) != null)
        {
            contents.add(str);
        }
        br.close();
        reader.close();
        return contents;
    }
    
    /**
     * 根据 JavaFileEntity写文件
     * <功能详细描述>
     * @param file 待覆盖的文件
     * @param javaFile 要写入的内容
     * @throws IOException 
     */
    public void writeFile(File file,JavaFileEntity javaFile) throws IOException
    {
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for(String line : javaFile.getContent())
        {
            bw.write(line);
            bw.newLine();//换行
        }
        bw.flush();
        bw.close();
        fw.close();
    }
    
    /**
     * 根据权限api获得新的文件内容(导入权限)
     * 加入权限注解
     * @param content
     * @return
     */
    public ArrayList<String> getNewContentByRoleApi(JavaFileEntity fileEntity)
    {
        //除去权限注解的内容
        ArrayList<String> newContent = new ArrayList<String>();
        //最终返回的结果内容
        ArrayList<String> newContentResult = new ArrayList<String>();
        //对应java文件中的所有接口
        ArrayList<ApiEntity> javaFileApis = fileApi.get(fileEntity.getFileName());
        if(javaFileApis == null)
            return newContent;
        ArrayList<String> oldContent = fileEntity.getContent();
        //除去所有权限注解  @RequiresRoles
        for(String c : oldContent)
        {
            if(c.contains("@RequiresRoles"))
            {
                continue;
            }
            newContent.add(c);
        }
        
        int newIndex = 0;
        //扫描文件每一行 判断
        for(int i=0;i<newContent.size();i++)
        {
            String line = newContent.get(i);
            //添加到结果内容
            newContentResult.add(line);
            //编译文件对应的接口清单api
            for(ApiEntity api : javaFileApis)
            {
                //该行必须 包含方法名 和 pulibc 关键字 (保证该行为方法)
                if(line.contains(" "+api.getMethodStr()+"(") && line.contains("public")   && line.contains(")"))
                {
                  //如果找到对应的方法 则在方法上一行插入 权限注解@RequiresRoles
                    if(!StringUtil.isEmpty(api.getRoleCodes()))
                    {
                        StringBuffer requiresRoles = new StringBuffer();
                        requiresRoles.append("    @RequiresRoles(\"");
                        requiresRoles.append(api.getRoleCodes());
                        requiresRoles.append("\")");
                        //插入注解内容
                        newContentResult.add(newIndex, requiresRoles.toString());   
                        //添加一条注解后当前索引加1 
                        newIndex += 1;
                    }
                }
                
            }
            newIndex ++;
        }
        
        return newContentResult;
    }
    
    public  String readToString(File file)
    {
        Long filelength = file.length(); //获取文件长度
        byte[] filecontent = new byte[filelength.intValue()];
        try
        {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return new String(filecontent);//返回文件内容,默认编码
    }
    
    public static void main(String[] arr)
    {
        ReadApiExcelForShiro s = new ReadApiExcelForShiro();
        try
        {
            s.read();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
JavaFileEntity

import java.util.ArrayList;

/**
 * 
 * java 文件
 * <功能详细描述>
 * 
 * @author  liubeihua
 * @version  [版本号, 2016年1月15日]
 */
public class JavaFileEntity
{
    /**
     * 文件名
     */
    private String fileName;
    /**
     * 文件内容
     */
    private ArrayList<String> content;
    
    /**
     * 文件路径
     */
    private String path;
    
    public String getFileName()
    {
        return fileName;
    }
    public void setFileName(String fileName)
    {
        this.fileName = fileName;
    }
    public ArrayList<String> getContent()
    {
        return content;
    }
    public void setContent(ArrayList<String> content)
    {
        this.content = content;
    }
    public String getPath()
    {
        return path;
    }
    public void setPath(String path)
    {
        this.path = path;
    }
    
    
    
    
    
    
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值