svn hooks 增加数据库数据校验

业务需求:

  小乌龟提交java文件时如果该java文件中存在StrUtil.getText("");则拿到里面的数据,使用该数据查数据库如果数据库不存在该数据则不让用户提交svn

windows系统下

  1:在svn服务端中找到对应项目的hooks

       

 

 

 

 

  2:写pre-commit.bat

@echo off
set export LANG=zh_CN.UTF-8
setlocal
set Repos=%1
set TXN=%2
set SCM=admin
set CUR=%~dp0
rem 输出路径 预先存放数据库驱动包、conf.properties文件
set outdir=D:\hdcn\multlang_svn\out
set tmpfile=
for /f %%k in ('java -classpath ".;C:/Repositories/springboot/hooks" CheckString "uuid"') do set tmpfile=%%k
for /f "tokens=1-2 delims= " %%i in ('svnlook changed -t "%TXN%" "%Repos%"') do (
    svnlook cat -t "%TXN%" "%Repos%" "%%j" >%outdir%\%tmpfile%
    for /f %%y in ('java -cp ".;C:/Repositories/springboot/hooks;D:/hdcn/multlang_svn/out/ojdbc8.jar" CheckString "%%i" "%outdir%\%tmpfile%" "%%j" "%outdir%"') do (
        echo file:"%%j" "no found [%%y] in t_sys_language" 1>&2
        goto err
    )
)
del %outdir%\%tmpfile%
goto right

:err
del %outdir%\%tmpfile%
exit 1

:right
exit 0

  3:写java类CheckString 供bat调用

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckString {
    private final static String varregex = "\"(.*?)\"";
    private final static String javaregex = "StrUtil\\s*.\\s*getText\\s*\\(\\s*\"(.*?)\"\\s*\\)";
    Properties properties = null;
    Connection connection = null;

    private String dbdriver;
    private String dburl;
    private String dbuser;
    private String dbpasswd;
    private String logfile;
    private String curdir;
    public static void main(String[] args) {
        CheckString svnLang = new CheckString();
        if (args[0].equalsIgnoreCase("uuid")) {
            System.out.println(svnLang.getRandFileName());
            return;
        }
        svnLang.setCurdir(args[3]);
        try { 
            svnLang.loadConf();
            svnLang.vaildLang(args[0], args[1], args[2]);
            svnLang.writeLog("success");
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            svnLang.writeLog(sw.toString());
            pw.close();
        }
   }

   public boolean vaildLang(String ope, String textfile, String svnfile) throws Exception {
       //只有新增和修改的数据才需要校验 U修改  A新增
       if (!("U".equalsIgnoreCase(ope) || "A".equalsIgnoreCase(ope))) {
           return true;
       }
       List<String> langKey = new ArrayList<>();
       String extname = getFileExt(svnfile);
       if ("java".equalsIgnoreCase(extname)) {
           String textcontext = txt2String(textfile);
           langKey.addAll(regularJava(textcontext));
       } else {
           return true;
       }
       if (langKey.size() <= 0) { 
           return true;
       }
       try {
           for (String key: langKey) {
               if (!hasLang(key)) {
                   System.out.println(key);
                   return false;
               }
           }
       } finally {
           closeDb();
       }
       return true;
   }
    
   private void connDb() throws Exception {
       Class.forName(dbdriver);
       connection = DriverManager.getConnection(dburl, dbuser, dbpasswd);
   }

   private void closeDb() throws Exception {
       if (connection != null) {
           connection.close();
       }
   }

   private boolean hasLang(String msgname) throws Exception {
       if (connection == null) {
           connDb();
       }
       String sql = "select count(1) as cou from t_language where msgname=? ";
       PreparedStatement pstmt = connection.prepareStatement(sql);
       pstmt.setString(1, msgname);
       ResultSet rst = pstmt.executeQuery();
       rst.next();
       Long cou = rst.getLong("cou");
       if (cou > 0) {
           return true;
       }
       return false;
   }

   private static String txt2String(String filename) throws Exception {
       File file = new File(filename);
       StringBuilder result = new StringBuilder();
       InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");  
       BufferedReader br = new BufferedReader(read);
       try {
           String s;
           while ((s = br.readLine()) != null) {
               result.append(System.lineSeparator() + s);
           }
       } finally {
           br.close();
       }
       return result.toString();
   }

   private List<String> regularJava(String text) {
       return regular(text, javaregex);
   }

   private List<String> regular(String text, String regex) {
       List<String> rt = new ArrayList<>();
       Pattern p=Pattern.compile(regex);
       Matcher m=p.matcher(text);
       while(m.find()){
           String gs = m.group();
           String v = getVarLang(gs);
           if (v != null) {
               rt.add(v);
           }
       }
       return rt;
   }

   private String getVarLang(String text) {
       Pattern p=Pattern.compile(varregex);
       Matcher m=p.matcher(text);
       while(m.find()){
           String gs = m.group();
           gs = gs.substring(1, gs.length()-1);
           return gs;
       }
       return null;
   }

   private String getFileExt(String filename) {
       String extname = filename.substring(filename.lastIndexOf(".") + 1);
       return extname;
   }

   public String getRandFileName() {
       UUID uuid = UUID.randomUUID();
       return uuid.toString().replace("-", "")+".txt";
   }

   private void loadConf() throws Exception {
       if (properties == null) {
           properties = new Properties();
           properties.load(new FileInputStream(this.curdir+ System.getProperty("file.separator")+ "conf.properties"));
           Enumeration<?> enum1 = properties.propertyNames();
           while(enum1.hasMoreElements()) {
               String strKey = (String) enum1.nextElement();
               String strValue = properties.getProperty(strKey);
               if ("db_driver".equalsIgnoreCase(strKey)) {
                   this.dbdriver = strValue;
               } else if ("db_url".equalsIgnoreCase(strKey)) {
                   this.dburl = strValue;
               } else if ("db_username".equalsIgnoreCase(strKey)) {
                   this.dbuser = strValue;
               } else if ("db_password".equalsIgnoreCase(strKey)) {
                   this.dbpasswd = strValue;
               }
           }
       }
   }
   public void writeLog(String txt) {
       FileWriter fw = null;
       PrintWriter pw = null;
       try {
           File file = new File(this.logfile);
           fw = new FileWriter(file, true);
           pw = new PrintWriter(fw);
           pw.write(txt);
           pw.write("\r\n");
           pw.flush();
           pw.close();
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (fw != null) {
               try {
                   fw.close();
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
           if (pw != null) {
               try {
                   pw.close();
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }

   }
   public void setCurdir(String dir) {
       this.curdir = dir;
       this.logfile = this.curdir + System.getProperty("file.separator") + "log.log";
   }
}

  4:将checkString编译的.class文件、pre-commit.bat 放到hooks路径底下

  5:小乌龟测试提交

 

 

FAQ

 

 

 bat 容易出现乱码问题

 

java 回写到bat中乱码问题(这边是读取文件指定编码格式)

 

posted @ 2020-05-20 17:11  再也不见  阅读(217)  评论(0编辑  收藏  举报