/*
 * CodeGen.java, Created on 2005-6-18 Title: outcode <br/> Description: <br/> Copyright: Copyright
 * (c) 2005 <br/>
 * @author Yichao.HUANG
 * @version $Revision: 1.0 $ $Date:2005-6-18 23:18:38 $
 */
package cn.com.pubinfo.gen;

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.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @author Yichao.HUANG 2005-5-8
 */
public class CodeGen {
  static private final String CONFIG_FILE = "gen.conf";

  static private final String VARCHAR = "varchar";

  static private final String VARCHAR2 = "varchar2";

  static private final String INT = "int";

  static private final String NUMBER = "number";

  static private final String DATETIME = "datetime";

  static private final String DATE = "date";

  static private final String TIMESTAMP = "timestamp";

  static private final String CHAR = "char";

  static private final String FLOAT = "float";
  static private final String BLOB = "blob";
  static private final String CLOB = "clob";

  private String schema;

  private String template;

  private String outputDirectoryroot;

  private String outputDirectoryconf;

  private String outputDirectorykernel;

  private String outputDirectorycontroller;

  private String outputDirectoryvalidation;

  private String targetPackage;

  private String projectName;

  private String author;

  public List tables;

  public CodeGen() {
    schema = null;
    template = null;
    outputDirectoryroot = null;
    outputDirectoryconf = null;
    outputDirectorykernel = null;
    outputDirectorycontroller = null;
    projectName = null;
    author = null;
    targetPackage = null;

    tables = null;
  }

  public int readConfigFromFile() {
    Properties prop = new Properties();
    try {
      prop.load(new FileInputStream(new File(CONFIG_FILE)));
      schema = prop.getProperty("schema");
      template = prop.getProperty("template");
      outputDirectoryroot = prop.getProperty("outputDirectoryroot");
      outputDirectoryconf = prop.getProperty("outputDirectoryconf");
      outputDirectorykernel = prop.getProperty("outputDirectorykernel");
      outputDirectorycontroller = prop.getProperty("outputDirectorycontroller");
      outputDirectoryvalidation = prop.getProperty("outputDirectoryvalidation");
      projectName = prop.getProperty("projectName");
      author = prop.getProperty("author");
      targetPackage = prop.getProperty("targetPackage");

      if (schema == null || schema.length() == 0 || template == null || template.length() == 0 || outputDirectoryroot == null || outputDirectoryroot.length() == 0 || outputDirectoryconf == null
          || outputDirectoryconf.length() == 0 || outputDirectorykernel == null || outputDirectorykernel.length() == 0 || outputDirectorycontroller == null || outputDirectorycontroller.length() == 0
          || projectName == null || projectName.length() == 0 || author == null || author.length() == 0 || targetPackage == null || targetPackage.length() == 0) {
        System.err.println("----ERROR : Configuration error, pls check ur config file!!");
        return -1;
      }
      return 0;

    } catch (FileNotFoundException e) {
      System.err.println("----Fatal : Config File Not Found!!!");
      e.printStackTrace();
    } catch (IOException ex) {
      System.err.println("----Fatal : Can't read from config file!!!");
      ex.printStackTrace();
    }

    return -1;
  }

  public boolean isTableStart(String line) {
    if (line.indexOf("CREATE") != -1 && line.indexOf("TABLE") != -1 && line.indexOf("(") != -1) {
      return true;
    }
    return false;
  }

  public boolean isTableEnd(String line) {
    if (")".equals(line.trim())) {
      return true;
    }
    return false;
  }

  public boolean isPrimaryKey(String line) {
    if (line.indexOf("PRIMARY KEY") != -1) {
      return true;
    }
    return false;
  }

  public String getTableName(String line) {
    int start = line.toUpperCase().indexOf("TABLE") + 6;
    int end = line.toUpperCase().indexOf("(") - 1;
    String name = line.substring(start, end);
    name = org.apache.commons.lang.StringUtils.deleteWhitespace(name);
    String strtablename = "";
    StringBuffer sb = new StringBuffer();
    name = name.trim();
    name = org.apache.commons.lang.StringUtils.replace(name, "TBL_", "");
    name = org.apache.commons.lang.StringUtils.replace(name, "JNT_", "");
    name = name.toLowerCase();
    String[] strSplit = org.apache.commons.lang.StringUtils.split(name, "_");
    for (int i = 0; i < strSplit.length; i++) {
      strtablename = strSplit[i];
      sb.append(strtablename.substring(0, 1).toUpperCase());
      sb.append(strtablename.substring(1).toLowerCase());
    }
    return sb.toString();

  }

  public String getOldTableName(String line) {
    int start = line.toUpperCase().indexOf("TABLE") + 6;
    int end = line.toUpperCase().indexOf("(") - 1;
    String name = line.substring(start, end);
    name = org.apache.commons.lang.StringUtils.deleteWhitespace(name);
    name = name.trim();
    return name;

  }

  public Field getField(String line) {
    if (line == null || line.trim().length() == 0) {
      return null;
    }
    line = line.trim();
    int pos2 = 0;
    int pos = line.indexOf(' ');
    if (pos != -1) {
      Field field = new Field();
      field.setName(line.substring(0, pos));
      pos2 = line.indexOf('[', pos);
      if (pos2 != -1) {
        pos = line.indexOf(']', pos2);
        if (pos != -1) {
          field.setType(line.substring(pos2 + 1, pos).toLowerCase());
          if (CHAR.equals(field.getType()) || VARCHAR.equals(field.getType())) {
            pos2 = line.indexOf('(', pos + 1);
            if (pos2 != -1) {
              pos = line.indexOf(')', pos2);
              if (pos != -1) {
                String length = line.substring(pos2 + 1, pos);
                field.setLength(Integer.parseInt(length, 10));
                pos2 = line.toUpperCase().indexOf(" NOT NULL", pos);
                if (pos2 != -1) {
                  field.setRequired(true);
                } else {
                  field.setRequired(false);
                }

              }
            }
          }
        }
      }
      return field;
    }
    return null;
  }

  public int readSchemaFromFile() {
    File file = new File(schema);
    if (!file.exists()) {
      return -1;
    }

    BufferedReader br = null;
    try {
      br = new BufferedReader(new FileReader(file));
      String line = null;
      Table table = null;
      boolean tableStart = false;
      boolean tableEnd = false;
      do {
        line = br.readLine();
        if (line != null && line.trim().length() != 0) {
          if (isTableStart(line.toUpperCase())) {
            table = new Table();
            table.setName(getTableName(line));
            table.setOldname(getOldTableName(line));
            if (tables == null) {
              tables = new ArrayList();
            }
            tables.add(table);
            tableStart = true;
            tableEnd = false;
            continue;
          }
          if (isTableEnd(line.toUpperCase())) {
            tableStart = false;
            tableEnd = true;
            continue;
          }
          if (tableStart && !tableEnd) {
            if (isPrimaryKey(line.toUpperCase())) {

              continue;
            }
            table.addField(getField(line));
          }
        }
      } while (line != null);
    } catch (FileNotFoundException e) {
      System.err.println("----Fatal : Schema File Not Found!!!");
      e.printStackTrace();
    } catch (IOException ex) {
      System.err.println("----Fatal : Can't read from config file!!!");
      ex.printStackTrace();
    }
    return -1;
  }

  public String varName(String name) {
    StringBuffer sb = new StringBuffer();
    String strname = "";
    name = org.apache.commons.lang.StringUtils.deleteWhitespace(name);
    name = name.toLowerCase();
    String[] strSplit = org.apache.commons.lang.StringUtils.split(name, "_");
    for (int i = 0; i < strSplit.length; i++) {
      strname = strSplit[i];
      sb.append(strname.substring(0, 1).toUpperCase());
      sb.append(strname.substring(1).toLowerCase());
    }
    name = sb.toString();
    name = org.apache.commons.lang.StringUtils.replace(name, "_", "");
    return name;
  }

  public int genFileConf(String outsrc, String templateName, String output) {
    File file = new File(templateName);
    if (!file.exists()) {
      return -1;
    }
    File outputFile = new File(output);
    File outputPath = new File(outputFile.getParentFile().getPath());
    if (!outputPath.exists()) {
      outputPath.mkdirs();
    }

    BufferedReader br = null;
    BufferedWriter wr = null;
    try {
      br = new BufferedReader(new FileReader(file));
      wr = new BufferedWriter(new FileWriter(new File(output)));
      String line = null;
      boolean foreachStart = false;
      boolean foreachEnd = false;
      List foreachList = new ArrayList();
      do {
        line = br.readLine();
        if (line != null) {
          if (line.indexOf("<foreachfields>") != -1) {
            foreachStart = true;
            foreachEnd = false;
            foreachList.clear();
            continue;
          }

          if (foreachStart && !foreachEnd) {
            foreachList.add(line);
            continue;
          } else {
            line = org.apache.commons.lang.StringUtils.replace(line, "<sqlmapconfig>", outsrc);
            line = org.apache.commons.lang.StringUtils.replace(line, "<beansService>", outsrc);
            line = org.apache.commons.lang.StringUtils.replace(line, "<beansDao>", outsrc);
          }
          wr.write(line);
          wr.newLine();
        }
      } while (line != null);
    } catch (FileNotFoundException e) {
      System.err.println("----Fatal : Schema File Not Found!!!");
      e.printStackTrace();
    } catch (IOException ex) {
      System.err.println("----Fatal : Can't read from config file!!!");
      ex.printStackTrace();
    } finally {
      try {
        wr.flush();
        wr.close();
        br.close();
      } catch (Exception e) {
        System.err.println("------------");
      }
    }
    return -1;
  }

  public int genFile(Table table, String templateName, String output) {
    File file = new File(templateName);
    if (!file.exists()) {
      return -1;
    }
    File outputFile = new File(output);
    File outputPath = new File(outputFile.getParentFile().getPath());
    if (!outputPath.exists()) {
      outputPath.mkdirs();
    }

    BufferedReader br = null;
    BufferedWriter wr = null;
    try {
      br = new BufferedReader(new FileReader(file));
      wr = new BufferedWriter(new FileWriter(new File(output)));
      String line = null;
      boolean foreachStart = false;
      boolean foreachEnd = false;
      List foreachList = new ArrayList();
      do {
        line = br.readLine();
        if (line != null) {
          if (line.indexOf("<foreachfields>") != -1) {
            foreachStart = true;
            foreachEnd = false;
            foreachList.clear();
            continue;
          }
          if (line.indexOf("</foreachfields>") != -1) {
            foreachStart = false;
            foreachEnd = true;
            for (int j = 0; j < table.getFields().size(); j++) {
              Field aField = (Field) table.getFields().get(j);
              String type = null;
              if (CHAR.equalsIgnoreCase(aField.getType())) {
                type = "String";
              }
              if (VARCHAR.equalsIgnoreCase(aField.getType())) {
                type = "String";
              }
              if (VARCHAR2.equalsIgnoreCase(aField.getType())) {
                type = "String";
              }
              if (INT.equalsIgnoreCase(aField.getType())) {
                type = "int";
              }
              //change by tangjun
              if (NUMBER.equalsIgnoreCase(aField.getType())) {
                type = "int";
              }
              if (BLOB.equalsIgnoreCase(aField.getType())) {
                type = "String";
              }
              if (CLOB.equalsIgnoreCase(aField.getType())) {
                type = "String";
              }

              if (DATETIME.equalsIgnoreCase(aField.getType())) {
                type = "Date";
              }
              if (DATE.equalsIgnoreCase(aField.getType())) {
                type = "Date";
              }
              if (TIMESTAMP.equalsIgnoreCase(aField.getType())) {
                type = "Date";
              }
              if (FLOAT.equalsIgnoreCase(aField.getType())) {
                type = "float";
              }
              for (int i = 0; i < foreachList.size(); i++) {
                String newLine = (String) foreachList.get(i);
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<fieldtype>", type);
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<fieldname>", varName(aField.getName()).substring(0, 1).toLowerCase() + varName(aField.getName()).substring(1));
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<capfieldname>", varName(aField.getName()));
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<entitycapfieldname>", aField.getName());
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<tablename>", varName(table.getName()));
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<oldtablename>", varName(table.getOldname()));
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<captablename>", table.getName());
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<lctablename>", table.getName().substring(0, 1).toLowerCase() + table.getName().substring(1));
                newLine = org.apache.commons.lang.StringUtils.replace(newLine, "<alllowertablename>", table.getName().toLowerCase());
                wr.write(newLine);
                wr.newLine();
              }
            }
            continue;
          }
          if (foreachStart && !foreachEnd) {
            foreachList.add(line);
            continue;
          } else {
            line = org.apache.commons.lang.StringUtils.replace(line, "<projectName>", projectName);
            line = org.apache.commons.lang.StringUtils.replace(line, "<author>", author);
            line = org.apache.commons.lang.StringUtils.replace(line, "<package>", targetPackage);
            line = org.apache.commons.lang.StringUtils.replace(line, "<tablename>", varName(table.getName()));
            line = org.apache.commons.lang.StringUtils.replace(line, "<oldtablename>", table.getOldname());
            line = org.apache.commons.lang.StringUtils.replace(line, "<captablename>", table.getName());
            line = org.apache.commons.lang.StringUtils.replace(line, "<lctablename>", table.getName().substring(0, 1).toLowerCase() + table.getName().substring(1));
            line = org.apache.commons.lang.StringUtils.replace(line, "<alllowertablename>", table.getName().toLowerCase());
            Date date = new Date();
            SimpleDateFormat mydate = new SimpleDateFormat(" yyyy-MM-dd");
            SimpleDateFormat mytime = new SimpleDateFormat(" HH:mm:ss");
            SimpleDateFormat mydateyear = new SimpleDateFormat(" yyyy");
            line = org.apache.commons.lang.StringUtils.replace(line, "<date>", mydate.format(date));
            line = org.apache.commons.lang.StringUtils.replace(line, "<year>", mydateyear.format(date));
            line = org.apache.commons.lang.StringUtils.replace(line, "<time>", mytime.format(date));
          }
          wr.write(line);
          wr.newLine();
        }
      } while (line != null);
    } catch (FileNotFoundException e) {
      System.err.println("----Fatal : Schema File Not Found!!!");
      e.printStackTrace();
    } catch (IOException ex) {
      System.err.println("----Fatal : Can't read from config file!!!");
      ex.printStackTrace();
    } finally {
      try {
        wr.flush();
        wr.close();
        br.close();
      } catch (Exception e) {
        System.err.println("------------");
      }
    }
    return -1;
  }

  public int genCodeFromTemplates() {
    StringBuffer sbsqlmapconfig = new StringBuffer();
    StringBuffer sbdao = new StringBuffer();
    StringBuffer sbservice = new StringBuffer();
    Table table = null;
    for (int i = 0; i < tables.size(); i++) {
      table = (Table) tables.get(i);
      /* ---------- 配置文件(sqlmap-config.xml) -------------- */
      sbsqlmapconfig.append("<sqlMap resource=\"conf/sqlmap/${dialect}/" + table.getName() + ".xml\" />");
      sbsqlmapconfig.append('\r');
      sbsqlmapconfig.append('\n');

      /* ---------- 配置文件(beans-dao.xml) -------------- */

      sbdao.append("  <bean id=\"" + table.getName().substring(0, 1).toLowerCase() + table.getName().substring(1) + "Dao\" parent=\"txProxyTemplate\">");
      sbdao.append('\r');
      sbdao.append('\n');
      sbdao.append("    <property name=\"target\">");
      sbdao.append('\r');
      sbdao.append('\n');
      sbdao.append("       <bean class=\"" + targetPackage + ".kernel.dao.impl." + table.getName() + "DaoImpl\" autowire=\"byName\"/>");
      sbdao.append('\r');
      sbdao.append('\n');
      sbdao.append("    </property>");
      sbdao.append('\r');
      sbdao.append('\n');
      sbdao.append("  </bean>");
      sbdao.append('\r');
      sbdao.append('\n');

      /* ---------- 配置文件(beans-service.xml) -------------- */

      sbservice.append("  <bean id=\"" + table.getName().substring(0, 1).toLowerCase() + table.getName().substring(1) + "Service\"");
      sbservice.append("  class=\"" + targetPackage + ".kernel.service.impl." + table.getName() + "ServiceImpl\" singleton=\"true\" autowire=\"byName\"");
      sbservice.append("/>");
      sbservice.append('\r');
      sbservice.append('\n');
      genFile(table, template + "\\entity\\template.java", outputDirectoryroot + "\\" + outputDirectorykernel + "\\entity\\" + table.getName() + ".java");

      genFile(table, template + "\\sqlmap\\oracle\\template.xml", outputDirectoryroot + "\\" + outputDirectoryconf + "\\sqlmap\\oracle\\" + table.getName() + ".xml");
      genFile(table, template + "\\dao\\template.java", outputDirectoryroot + "\\" + outputDirectorykernel + "\\dao\\" + "I" + table.getName() + "Dao.java");
      genFile(table, template + "\\dao\\impl\\template.java", outputDirectoryroot + "\\" + outputDirectorykernel + "\\dao\\impl\\" + table.getName() + "DaoImpl.java");

      genFile(table, template + "\\service\\template.java", outputDirectoryroot + "\\" + outputDirectorykernel + "\\service\\" + "I" + table.getName() + "Service.java");
      genFile(table, template + "\\service\\impl\\template.java", outputDirectoryroot + "\\" + outputDirectorykernel + "\\service\\impl\\" + table.getName() + "ServiceImpl.java");
      genFile(table, template + "\\controller\\template.java", outputDirectoryroot + "\\" + outputDirectorycontroller + "\\" + table.getName() + "Controller.java");
      genFile(table, template + "\\validation\\template.java", outputDirectoryroot + "\\" + outputDirectoryvalidation + "\\" + table.getName() + "Validator.java");
    }

    genFileConf(sbsqlmapconfig.toString(), template + "\\sqlmap\\sqlmap-config.xml", outputDirectoryroot + "\\" + outputDirectoryconf + "\\sqlmap\\sqlmap-config.xml");
    genFileConf(sbdao.toString(), template + "\\spring\\beans-dao.xml", outputDirectoryroot + "\\" + outputDirectoryconf + "\\spring\\beans-dao.xml");
    genFileConf(sbservice.toString(), template + "\\spring\\beans-service.xml", outputDirectoryroot + "\\" + outputDirectoryconf + "\\spring\\beans-service.xml");
    return -1;
  }

  public static void main(String[] args) throws UnsupportedEncodingException {
    CodeGen codegen = new CodeGen();
    codegen.readConfigFromFile();
    codegen.readSchemaFromFile();

    List tables = codegen.tables;
    for (int i = 0; i < tables.size(); i++) {
      Table table = (Table) tables.get(i);
      System.err.println(table.getName());
    }
    codegen.genCodeFromTemplates();
    String ss = "E:\test/CEB0000/Send/FCS_216220216_20171202_20171202_01.zip";
    System.out.println(ss.substring(ss.lastIndexOf("/") + 1));
    //    String t = "14|2017823|20170823|//r//n 7|80510000|5|0|20170823|20170823|7|0|t日对应表1-9支付机构上海银行客户备付金业务未达账项统计表中支付机构业务系统中已增加客户资金账户余额但未增加备付金银行账户余额(J01>)的发生额记为Wt,Wt=表1-1支付机构上海银行客户备付金入金业务明细表0中应收入金业务金额(A07+A08+A09)-表1-1中前期支付机构支付机构业务系统中已贷记客户资金账户但本期实际收>到的款项(A04+A05+A06)|1|||//r//n 7|80510000|5|30083420|20170823|20170823|7|0|t日对应表1-9中已增加备付金银行账户余额但支付机构业务系统中未增加客户资金账户余额(J03)的发生额记为Xt,Xt=表1-1中本期收到的//r//n但未在支付机构业务系统中反映的入金金额A10-表1-1中本期处理的前期未在支付机构业务系统中反映的入金金额(A11+A12+A13+A14)|1|||//r//n 7|80510000|5|30083421|20170823|20170823|7|0|t日对应表1-9中已减少备付金银行账户余额但支付机构业务系统中未减少客户资金账户余额(J04)的发生额记为Zt,Zt=补充表1-2(分银行//r//n账户的1-2表)中支付机构业务系统中未反映,但银行当期已扣款金额(BB06)-补充表1-2中本期处理的前期未在支付机构业务系统中反映的出金金额(BB07+BB08+BB09)|1|||//r//n 7|80510000|5|30083422|2017082";
    //    System.out.println(t.getBytes("gb2312").length);
    //    String tt = "  ";
    //    System.out.println(tt.getBytes("gb2312").length);
  }
}
最近下载更多
42423423  LV1 2020年11月20日
JerryJerry  LV2 2020年5月21日
luoyong12345  LV3 2020年3月5日
universem  LV1 2020年2月7日
0312wangchen  LV26 2019年9月23日
112341321432342  LV1 2019年7月2日
552ffqq  LV1 2019年5月27日
xingai2019  LV7 2019年5月21日
wangyang123  LV9 2019年4月18日
winqble  LV16 2019年3月14日
最近浏览更多
denliv_hui  LV13 4月26日
3334004690  LV3 2023年11月1日
李亮  LV19 2023年3月6日
bai620123  LV16 2022年11月29日
wadadd  LV7 2022年9月4日
wubinbin  LV11 2022年4月12日
fengshengtian  LV8 2022年3月7日
yangliying  LV4 2022年2月15日
qazxsw111  LV11 2021年11月14日
yin出门买了吗了  LV9 2021年10月31日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友