取得eclipse 的src路径 和webroot路径包括 相对路径

来源:互联网 发布:淘宝超级店长在哪里 编辑:程序博客网 时间:2024/04/30 13:16
package com.generate;import java.util.HashMap;import java.util.List;import java.util.Map;import org.w3c.dom.*;  import javax.xml.parsers.*; import com.sunwayworld.Constants;import com.sunwayworld.common.util.StringUtil;import com.sunwayworld.srm30.common.util.SafeString;import org.apache.log4j.Logger;import org.apache.velocity.Template;import org.apache.velocity.context.Context;import org.apache.velocity.app.Velocity;import org.apache.velocity.app.VelocityEngine;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import java.io.Writer;import org.apache.velocity.VelocityContext;import java.util.Properties;import java.io.*;import java.net.URL;enum CreateType{//简单无关联的表,比如系统单表SimpleSingleTable}public class GenerateMaster{   //jsp文件绝对路径 public staticLogger llog=Logger.getLogger(GenerateMaster.class);//生成类型  String  jsprealpath =null;  String  javarealpath=null;  String  javatemplatesPath="Templates\\SimpleSingleTable\\java\\";  String  jsptemplatesPath ="Templates\\jsp\\";  String  javaoutpath="com\\sunwayworld\\suppsyb\\";  String  jspoutpath="suppsyb";  private Map m=null;  private CreateType createtype=null;  private String tablename=null;  private String titlename=null;  private GetTableCols tableinformation;//  String javatemplatesPath = "D:\\crccworkspace\\coal_code\\template\\MasterDetail\\java\\";//  String jsptemplatesPath="D:\\crccworkspace\\coal_code\\template\\MasterDetail\\jsp\\";//  String javaoutpath="D:\\crccworkspace\\coal_code\\src\\com\\sunwayworld\\ccsup\\";//  String jspoutpath="D:\\Oracle\\Middleware\\user_projects\\domains\\crcctedit_domain\\autodeploy\\DefaultWebApp\\ccsup\\";private   GenerateMaster(){ }public  GenerateMaster(String tablename,String titlename,CreateType c)throws Exception{ System.out.println(  getSourceRealPath()); createtype=c; this.tablename  =tablename; this.titlename  =titlename; this.tableinformation=new GetTableCols();}public static void main(String[] args){// 获取工程路径try {GenerateMaster m=  new GenerateMaster("bwbmbm", "评分记录",CreateType.SimpleSingleTable);m.createNewFile();llog.debug("文件生成完毕");} catch (Exception e) {llog.debug("文件生成失败");e.printStackTrace();}}public void createNewFile()throws Exception{ this.createNewFile(tablename, titlename);}//检查"表格"是否符合要求  public boolean checkUerTable(){List l=tableinformation.getAllColumnList(tablename);switch(createtype){case  SimpleSingleTable://简单的TableColumnInfo  columninfo=new TableColumnInfo();columninfo.setLowercolumnname("xgrmc");l.contains(columninfo);            break;     default: break;}return true;}  /**   * 系统自动生成模块文件   * @param templatesPath   * @param outpath   * @param tablename   * @param filetype   * @param  charset   * @return   */  private  boolean createNewFile(String tablename,String titlename){    boolean b = true;    try{      String fileoutpath="";      String filename ="";      //---初始化生成器      VelocityEngine ve = new VelocityEngine();      VelocityEngine jspve = new VelocityEngine();      VelocityEngine jspcommonve = new VelocityEngine();      Properties propertie = new Properties();      propertie.put("input.encoding",  "UTF-8");//--设置输入编码      propertie.put("output.encoding", "UTF-8");//--设置输出编码      File f=new File(".");      //包路径      String  PACKAGENAME=javaoutpath;  //获取工程路径  String projectpath=f.getCanonicalPath();  javatemplatesPath =projectpath+"\\"+javatemplatesPath;  jsptemplatesPath  =projectpath+"\\"+jsptemplatesPath;  javaoutpath       =javarealpath+"\\"+javaoutpath;  jspoutpath        =jsprealpath+"\\"+jspoutpath;      //--初始化替换文件及属性    //  HashMap map = this.getReplacePropertys(tablename,titlename,PACKAGENAME);           try{        VelocityContext context = this.generate(tablename,titlename,PACKAGENAME);                //---生成类文件-------------------------------------------        propertie.put("file.resource.loader.path", javatemplatesPath);//--模板所在文件夹        ve.init(propertie);        Template template = null;        tablename = tablename.substring(0,1).toLowerCase()+tablename.substring(1,tablename.length());        tablename = tablename.replace("_", "");        String firstuppertablename = tablename.substring(0,1).toUpperCase()+tablename.substring(1,tablename.length());        //生成action        template = ve.getTemplate("Action.vm");        fileoutpath=javaoutpath+"\\"+tablename.toLowerCase()+"\\action\\";         filename= firstuppertablename+"Action.java";        writeFile(context,template,fileoutpath,filename);                //生成bean        template = ve.getTemplate("Bean.vm");        fileoutpath=javaoutpath+"\\"+tablename.toLowerCase()+"\\bean\\";        filename= firstuppertablename+"Bean.java";        writeFile(context,template,fileoutpath,filename);                        //生成beansql        template = ve.getTemplate("BeanSql.vm");        fileoutpath=javaoutpath+"\\"+tablename.toLowerCase()+"\\beansql\\";        filename= firstuppertablename+"BeanSql.java";        writeFile(context,template,fileoutpath,filename);                //生成info        template = ve.getTemplate("Info.vm");        fileoutpath=javaoutpath+"\\"+tablename.toLowerCase()+"\\valueobject\\";        filename= firstuppertablename+"Info.java";        writeFile(context,template,fileoutpath,filename);        /*           //---生成共通的JSP文件-------------------------------------------        propertie.put("file.resource.loader.path", jsptemplatesPath+"\\MasterDetail\\jsp");//--模板所在文件夹        jspcommonve.init(propertie);        //--编辑文件列表        template = jspcommonve.getTemplate("createlist.vm");        fileoutpath=jspoutpath+"\\"+tablename.toLowerCase()+"\\";        filename= "createlist.jsp";        writeFile(context,template,fileoutpath,filename);        //--审核页面        template = jspcommonve.getTemplate("approvelist.vm");        fileoutpath=jspoutpath+"\\"+tablename.toLowerCase()+"\\";        filename= "approvelist.jsp";        writeFile(context,template,fileoutpath,filename);                //--回退页面        template = jspcommonve.getTemplate("retrievelist.vm");        fileoutpath=jspoutpath+"\\"+tablename.toLowerCase()+"\\";        filename= "retrievelist.jsp";        writeFile(context,template,fileoutpath,filename);                //--查询页面        template = jspcommonve.getTemplate("querylist.vm");        fileoutpath=jspoutpath+"\\"+tablename.toLowerCase()+"\\";        filename= "querylist.jsp";        writeFile(context,template,fileoutpath,filename);                //---生成独立的JSP文件-------------------------------------------        propertie.put("file.resource.loader.path", jsptemplatesPath+"\\Master\\jsp");//--模板所在文件夹        jspve.init(propertie);                //--详细信息页面        template = jspve.getTemplate("detail.vm");        fileoutpath=jspoutpath+"\\"+tablename.toLowerCase()+"\\";        filename= "detail.jsp";        writeFile(context,template,fileoutpath,filename);                //--生成struts-config文件        template = jspve.getTemplate("struts.vm");        fileoutpath=jspoutpath+"\\"+tablename.toLowerCase()+"\\";        filename= "struts-config.xml";        writeFile(context,template,fileoutpath,filename);*/      }catch (Exception e){        e.printStackTrace();      }    }catch(Exception e){    e.printStackTrace();        b=false;    }    return b;  }  public HashMap getReplacePropertys(String tablename,String titlename,String PACKAGEPATH)throws Exception{    HashMap map = new HashMap();    //--初始化主表信息    String UPPERTABLENAME = tablename.toUpperCase();//--大写的表名    String LOWERTABLENAME = tablename.toLowerCase();//--小写的表名    String FIRSTUPPERTABLENAME = tablename.substring(0,1).toUpperCase()+tablename.substring(1,tablename.length());//--首字母大写的表名    String CHECKTABLENAME = tablename.replace("_", "");    String CHECKUPPERTABLENAME = CHECKTABLENAME.toUpperCase();//--去下划线后大写的表名    String CHECKLOWERTABLENAME = CHECKTABLENAME.toLowerCase();//--去下划线后小写的表名    String CHECKFIRSTUPPERTABLENAME = CHECKTABLENAME.substring(0,1).toUpperCase()+CHECKTABLENAME.substring(1,CHECKTABLENAME.length());//--去下划线后首字母大写的表名    //--初始化明细表信息    //--获取主表主键    String  TBALEPK = new GetTableCols().getTablePrimaryKey(UPPERTABLENAME);    if(TBALEPK.equals("")){    throw new Exception("此表格没有标明主键");    }    TBALEPK = TBALEPK.toLowerCase();    TBALEPK = TBALEPK.substring(0,1).toUpperCase()+TBALEPK.substring(1,TBALEPK.length()).toLowerCase();//--首字母大写        //--创建主表主键序列 及明细表主键序列   // new GetTableCols().createTablePKisBm(UPPERTABLENAME);      new GetTableCols().createTablePKisSeq(UPPERTABLENAME);    //---初始化替换参数           // String packagename = javaoutpath.substring(javaoutpath.indexOf("\\supp")+5).replace("\\", "");    //llog.debug("packagename="+packagename);    map.put("actionPath", CHECKLOWERTABLENAME);// 类的包名       // if(!"".equals(SafeString.safeString(packagename))){    //CHECKLOWERTABLENAME=packagename+"."+CHECKLOWERTABLENAME;    CHECKLOWERTABLENAME=PACKAGEPATH.replaceAll("\\\\", ".").replaceAll("/",".")+CHECKLOWERTABLENAME;  //  }        map.put("packageName", CHECKLOWERTABLENAME);// 类的包名    map.put("className", CHECKFIRSTUPPERTABLENAME);// java类名    map.put("lowerTableName", LOWERTABLENAME);// 主表名-小写    map.put("upperTableName", UPPERTABLENAME);// 主表名-大写    map.put("lowerPk", TBALEPK.toLowerCase());// 主键字段-小写    map.put("firstUpperPk", TBALEPK);// 主键字段-首字母大写    map.put("upperPk", TBALEPK.toUpperCase());// 主键字段-大写    map.put("title", titlename);// 标题    return map;  }    /**   * 统一参数替换   * @param map   * @return   */  public VelocityContext generate(String tablename,String titlename,String PACKAGEPATH) throws Exception  {    if(m==null){   m= this.getReplacePropertys(tablename,titlename,PACKAGEPATH)  ;  }    Map map=m;      String templatesPath = (String)map.get("templatesPath");// 模板路径    VelocityContext context =null;    try{      context = new VelocityContext();      //获取基础字段      String packageName = (String)map.get("packageName");// 类的包名      String actionPath = (String)map.get("actionPath");// action路径      String className = (String)map.get("className");// java类名      String upperTableName = (String)map.get("upperTableName");// 主表名-大写      String lowerTableName = (String)map.get("lowerTableName");// 主表名-小写      String firstUpperPk = (String)map.get("firstUpperPk");// 主键字段-首字母大写      String upperPk = (String)map.get("upperPk");// 主键字段-大写        String lowerPk = (String)map.get("lowerPk");// 主键字段-小写        String title = (String) map.get("title") ;//标题名称                  //获取表结构      GetTableCols cols = new GetTableCols();      List alltablelist = cols.getAllColumnList(upperTableName);//--主表所有字段      List tablelistnocommnopk = cols.getColumnListNoCommNoPK(upperTableName);//--主表的字段(除基础字段外和主键)      List tablelistnocomm = cols.getColumnListNoComm(upperTableName);//--主表的字段(除基础字段外)      List tablelistnopk = cols.getColumnListNoPK(upperTableName);//--主表字段(除PK)      List tablelistnopkfk= cols.getColumnListNoPkFk(upperTableName);//--主表字段(除PK和FK)      //---------------基础的参数替换----------------      context.put("PACKAGENAME", packageName); // 类的包名      context.put("ACTIONPATH", actionPath); // action path=      context.put("CLASSNAME", className); // java类名      context.put("UPPERTABLENAME", upperTableName);// 主表名-大写      context.put("LOWERTABLENAME", lowerTableName);//主表全小写            context.put("FIRSTUPPERPK", firstUpperPk);// 主键字段-首字母大写      context.put("UPPERPK", upperPk);// 主键字段-大写        context.put("LOWERPK", lowerPk);// 主键字段-小写       context.put("TITLE",  title);//标题名称            //---------------数据库表信息替换---------------------      context.put("ALLTABLELIST", alltablelist);      context.put("TABLELISTNOCOMM", tablelistnocomm);      context.put("TABLELISTNOCOMMNOPK", tablelistnocommnopk);      context.put("TABLELISTNOPKFK", tablelistnopkfk);      context.put("TABLELISTNOPK", tablelistnopk);      }catch(Exception e){          e.printStackTrace();      }      return context;  }      /**   * 写文件   * @param context   * @param template   * @param filepath   * @param filename   */  public void writeFile(VelocityContext context,Template template,String filepath,String filename){    try{      //输出路径      String fileRealPath =filepath;      System.out.println("filePath=" + fileRealPath);            java.io.File fileTemp = new java.io.File(fileRealPath);      //目录不存在,则创建      if (!fileTemp.exists())      {        System.out.println("make dir ");        fileTemp.mkdirs();      }      String newFileName = fileRealPath + filename;      System.out.println("newFileName: "+newFileName);      java.io.File fileDst = new java.io.File(newFileName);      //输出//      if(fileDst.exists()){//        System.out.println("文件:"+filename+"创建失败,当前文件已经存在!");//      }else{        Writer writer = new PrintWriter(new FileOutputStream(fileDst));                 template.merge(context, writer);        writer.flush();//      }    }catch(Exception e){      e.printStackTrace();    }  }  /**   * 得到类的路径,例如E:/workspace/JavaGUI/bin/com/util   * @return   * @throws java.lang.Exception   */  public String getClassPath() throws Exception {      try {          String strClassName = getClass().getName();          String strPackageName = "";          if (getClass().getPackage() != null) {              strPackageName = getClass().getPackage().getName();          }          String strClassFileName = "";          if (!"".equals(strPackageName)) {              strClassFileName = strClassName.substring(strPackageName.length() + 1,                      strClassName.length());          } else {              strClassFileName = strClassName;          }          URL url = null;          url = getClass().getResource(strClassFileName + ".class");          String strURL = url.toString();          strURL = strURL.substring(strURL.indexOf('/') + 1, strURL                  .lastIndexOf('/'));          //返回当前类的路径,并且处理路径中的空格,因为在路径中出现的空格如果不处理的话,          //在访问时就会从空格处断开,那么也就取不到完整的信息了,这个问题在web开发中尤其要注意          return strURL.replaceAll("%20", " ");      } catch (Exception ex) {          ex.printStackTrace();          throw ex;      }  } /***/  public String getSourceRealPath()throws Exception{        String srcprefix="";     String Webrootprefix="";     File fclasspath=new File(".classpath");     File fproject=new File(".project");     //很明显该类是一个单例,先获取产生DocumentBuilder工厂       //的工厂,在通过这个工厂产生一个DocumentBuilder,       //DocumentBuilder就是用来产生Document的       Document docclasspath=null;     Document docproject  =null;     DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();       DocumentBuilder db=dbf.newDocumentBuilder();         //这个Document就是一个XML文件在内存中的镜像       docclasspath=db.parse(fclasspath);             NodeList nodeListclasspath= docclasspath.getElementsByTagName("classpathentry");      for(int i=0;i<nodeListclasspath.getLength();i++){     NamedNodeMap attributes=  nodeListclasspath.item(i).getAttributes();     Map m=new HashMap();     for(int j=0;j<attributes.getLength();j++){         Node attribute=attributes.item(j);         System.out.println("dbstore的属性名为:"+attribute.getNodeName()+" 相对应的属性值为:"+attribute.getNodeValue());                  m.put(attribute.getNodeName(), attribute.getNodeValue());    }     System.out.println(m.containsKey("kind")&&m.get("kind").equals("src"));     if(m.containsKey("kind")&&m.get("kind").equals("src")){     srcprefix=m.get("path")+"";     }     if(m.containsKey("kind")&&m.get("kind").equals("output")){     Webrootprefix=m.get("path")+"";     Webrootprefix=Webrootprefix.substring(0,Webrootprefix.indexOf("/WEB-INF/classes"));    // System.out.println(Webrootprefix);     }     m.clear();     }     if(!srcprefix.equals("")&&!Webrootprefix.equals("")){      docproject  =db.parse(fproject);          NodeList nodeListproject= docproject.getElementsByTagName("linkedResources");           if(nodeListproject.getLength()==0){        //    System.getProperty("user.dir");            javarealpath=System.getProperty("user.dir")+                         System.getProperty("file.separator")+srcprefix;            jsprealpath=System.getProperty("user.dir")+                 System.getProperty("file.separator")+Webrootprefix;        //  System.out.println("文件就在workspace下面");          }else{        //  System.out.println("存在外链"+nodeListproject.getLength());         Node n            =nodeListproject.item(0);        // System.out.println(n.getNodeName());         NodeList childnodelist=n.getChildNodes();        // System.out.println(childnodelist.getLength());         for(int i=0;i<childnodelist.getLength();i++){           Node childn=  childnodelist.item(i);           if(!childn.getNodeName().equals("link"))continue;        //   System.out.println(childn.getNodeName());             Map m =new HashMap();                for(int j=0;j<childn.getChildNodes().getLength();j++){                if(childn.getChildNodes().item(j).getNodeName().equals("#text")){                continue;                }        //           System.out.println(childn.getChildNodes().item(j).getNodeName()        //           +childn.getChildNodes().item(j).getTextContent());                   m.put(childn.getChildNodes().item(j).getNodeName(),                 childn.getChildNodes().item(j).getTextContent()                                           );                                };              if(  m.containsKey("name")&&m.get("name").equals(srcprefix)                ){              javarealpath=  m.get("location")+"";                  }                if(  m.containsKey("name")&&m.get("name").equals(Webrootprefix)                ){              jsprealpath=  m.get("location")+"";                  }              m.clear();              }                    }     }         return " jsprealpath ="+jsprealpath +"---"+           " javarealpath="+javarealpath;  }  }


0 0
原创粉丝点击