Code Engine 主要用来生成web相关的代码,可以把orm的部分集成进来,形成一条完整的生产线;

利用xpathfreemarker等技术,使得用户通过xml配置文件,模板等简单的方式,快速开发代码和根据需求调整模板;

Dom4j对实现了xpath 1.0 非常的好用;

所需jar dom4j-1.6.1.jar jaxen-1.1-beta-7.jar

Code

import junit.framework.TestCase;

import org.dom4j.*;

import org.dom4j.io.SAXReader;

import java.util.List;

import java.util.Iterator;

import java.io.File;

/**

 * Created by IntelliJ IDEA.

 * User: duanbin

 * Date: 2007-8-15

 * Time: 9:47:17

 * To change this template use File | Settings | File Templates.

 */

public class XPathTest extends TestCase {

    public void testXPathViaDom4jXpathV1() {

        printSelectedNodeValue("D:""xpath""src""test.xml");

    }

    /**

     * 利用XPath操作XML文件,打印指定节点或者属性的值, using xpath 1.0

     *

     * @param filename String 待操作的XML文件(相对路径或者绝对路径)

     */

    public void printSelectedNodeValue(String filename) {

        try {

            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(new File(filename));

            List list;

            list = document.selectNodes("//qn1:college/@leader[.!='leader1']");

            for (Object aList : list) {

                Attribute attribute = (Attribute) aList;

                System.out.println("//qn1:college/@leader: " + attribute.getValue());

            }

            //打印所有student节点的属性age值,如果有的话

//            list = document.selectNodes("/students/student/@age");

//            for (Object aList : list) {

//                Attribute attribute = (Attribute) aList;

//                System.out.println("/students/student/@age" + attribute.getValue());

//            }

            //打印所有college节点值,如果有的话

//            list = document.selectNodes("/students/student");

//            for (Object aList1 : list) {

//                Element bookElement = (Element) aList1;

//                Iterator iterator = bookElement.elementIterator("college");

//                while (iterator.hasNext()) {

//                    Element titleElement = (Element) iterator.next();

//                    System.out.println("/students/student/college" + titleElement.getText());

//                }

//            }

            //测试节点的一些方法

//            list = document.selectNodes("//city");

//            for (Object aList2 : list) {

//                Element titleElement = (Element) aList2;

//                System.out.print("//telephonegetName:" + titleElement.getName());

//                System.out.print(" ##getNodeType:" + titleElement.getNodeType());

//                System.out.print(" ##getTextTrim:" + titleElement.getTextTrim());

//                System.out.print(" ##getNamespaceURI:" + titleElement.getNamespaceURI());

//                System.out.print(" ##getNodeTypeName:" + titleElement.getNodeTypeName());

//                System.out.print(" ##getQualifiedName:" + titleElement.getQualifiedName());

//                System.out.print(" ##getUniquePath:" + titleElement.getUniquePath());

//                System.out.println(" ##getPath:" + titleElement.getPath());

//            }

            //打印所有name节点值,如果有的话,与上面college的取法不一样

//            list = document.selectNodes("/students/student/name");

//            Iterator iter = list.iterator();

//            for (Object aList3 : list) {

//                Element titleElement = (Element) aList3;

//                System.out.println("/students/student/name" + titleElement.getText());

//            }

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

}

Test.xml:

<?xml version="1.0" encoding="UTF-8"?>

<students xmlns:qn1="http://qn1.com">

    <student age="259911911911"><!--如果没有age属性,默认的为20-->

        <qn1:name>崔卫兵</qn1:name>

        <college>PC学院</college>

        <telephone>62354666</telephone>

        <notes>,1982年生,硕士,现就读于北京邮电大学</notes>

        <addr><city>Beijing</city></addr>

    </student>

    <student>

        <name>cwb</name>

        <qn1:college leader="学院领导">PC学院</qn1:college><!--如果没有leader属性,默认的为leader-->

        <telephone>62358888</telephone>

        <notes>,1987年生,硕士,现就读于中国农业大学</notes>

    </student>

    <student>

        <name>xxxxx</name>

        <college leader="">xxx学院</college>

        <telephone>66666666</telephone>

        <notes>注视中,注释中</notes>

    </student>

    <student age="9911911911">

        <name>yyyyyy</name>

        <qn1:college leader="leader1">yyyy学院</qn1:college>

        <telephone>88888888</telephone>

        <notes>注视中111,注释中222</notes>

    </student>

</students>

Freemarker基本示例:

import freemarker.template.Configuration;

import freemarker.template.DefaultObjectWrapper;

import freemarker.template.Template;

import java.io.File;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.FileOutputStream;

import java.util.Map;

import java.util.HashMap;

import org.apache.log4j.Logger;

/**

 * Created by IntelliJ IDEA.

 * User: duanbin

 * Date: 2007-8-21

 * Time: 22:30:13

 * To change this template use File | Settings | File Templates.

 */

public abstract class BaseGenerator {

    protected Configuration cfg;

    protected final Logger logger = Logger.getLogger(this.getClass());

    public BaseGenerator() {

        try {

            cfg = getConfiguration(CodeEngineConfig.getTemplateDir());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    public abstract void generate();

    protected void generateFile(String template, Map root, String fileName){

           try {

                File dist = new File(fileName);

                FileOutputStream fos = new FileOutputStream(dist);

                Writer out = new OutputStreamWriter(fos);

    //            Writer out2 = new OutputStreamWriter(System.out);

                cfg.getTemplate(template).process(root, out);

                out.flush();

                out.close();

                logger.info("Generated File: " + fileName);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    protected Configuration getConfiguration(String tempDir) throws Exception {

        Configuration cfg = new Configuration();

        // Specify the data source where the template files come from.

        // Here I set a file directory for it:

        cfg.setDirectoryForTemplateLoading(

                new File(tempDir));

        // Specify how templates will see the data model. This is an advanced topic...

        // but just use this:

        cfg.setObjectWrapper(new DefaultObjectWrapper());

        return cfg;

    }

}

模板文件示例:

package ${package}.application.web;

import biz.web.framework.web.BaseController;

<#list managers! as mgr>

import ${package}.application.manager.${mgr};

</#list>

<#list services! as svc>

import ${package}.application.service.${svc};

</#list>

/**

 * Created by IntelliJ IDEA.

 * User: ${author!'admin'} "${r"${build.dir}"} "${'$'}{cfg.startDate}

 * Date: Sep 1, 2006

 * Time: 9:19:17 AM

 * To change this template use File | Settings | File Templates.

 */

public class ${name}Controller extends BaseController {

<#list managers! as mgr>

    protected ${mgr} ${mgr?uncap_first};

</#list>

<#list services! as svc>

    protected ${svc} ${svc?uncap_first};

</#list>

<#list managers! as mgr>

    public void set${mgr}(${mgr} ${mgr?uncap_first}) {

        this.${mgr?uncap_first} = ${mgr?uncap_first};

    }

</#list>

<#list services! as svc>

    public void set${svc}(${svc} ${svc?uncap_first}) {

        this.${svc?uncap_first} = ${svc?uncap_first};

    }

</#list>

     public ModelAndView list${name}(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("update_${name?uncap_first}");

        Long user = getUserId();

        mav.addObject("userId", user);

        return mav;

    }

}