vaniglia 源码学习(一)

vaniglia 是一个开源的java工具库,下的版本大概1.7万,学习一下。

一. XML文件操作

封装org.w3c.dom.* 工具类,主要提供下面几个方法:

  • public synchronized final Document getDocument(String fileName) 将xml文件转换为Document对象;
  • public final void storeDocumentToFile(Document document, String fileName) 把Document对象转换成文件;
  • public XMLUtilities() 初始化documentBuilder:
    public XMLUtilities() {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        dbf.setNamespaceAware(true);

        dbf.setValidating(false);

        dbf.setIgnoringComments(true);

        try {

            db = dbf.newDocumentBuilder();

        } catch (ParserConfigurationException e) {

            logger.fatal("Unable to create a DocumentBuilder");

            System.exit(-1);

        }

        db.setErrorHandler(errorHandler);

    }

注:在xml文件中如果出现异常的空格、换行,可能导致#text的错误节点。

二.TextTable 支持在控制台打印一个表

效果如下:

Non Adaptive Text Table



  name   address               zip  

------------------------------------

  pippo  via due               100  

   aa    diecicarat              2  

         via qualtu              8  

  noadr                        188  

   bbb   piudidiecicaratterid   20  

  cccc   this element has not  100  

  pluto  this element has not  130  

  ffff   this element has not   10 

代码实现主要是TextTable,该类的两个主要方法分别是columns和elements,一个存储列信息,一个存储表内的元素

public class TextTable {



    //

    private TableColumn[] columns; //列信息



    private Vector elements; //表内的元素

其中TableColume中包含,它只是列的定义信息,本身并不包含数据。数据在elements中。

public class TableColumn {



    private String name = "";

    private int minWidth;

    private int width;

    private Align alignment; //当前只支持三列,即左、中、右

三.对TextTable的操作如下:

public class App {



    public static void main(String[] args) {

        {

            System.out.println("Non Adaptive Text Table");

            System.out.println();



            TextTable table = new TextTable(new TableColumn[] {

                new TableColumn("name", 5, Align.CENTER),

                new TableColumn("address", 20, Align.LEFT),

                new TableColumn("zip", 3, Align.RIGHT)

            },2, false);



            table.addElement(new String[] {"pippo", "via due", "100"});

            table.addElement(new String[] {"aa", "diecicarat", "2"});

            table.addElement(new String[] {"", "via qualtu", "8"});

            table.addElement(new String[] {"noadr", "", "1888"});

            table.addElement(new String[] {"bbb", "piudidiecicaratteridisicuro", "20"});

            table.print(System.out);

 三.模板引擎,类似于jsp、struts2中的变量标签,如下例:

   public static void main(String[] args) throws IOException {

        String template = "<html><head><title>$title</title></head>\n"+

        "<body style=\"background-color: rgb(202, 227, 255); visibility: visible;\">\n"+

        "<b>Dear $name</b>\n"+

        "<p>\n"+

        "how is going? Is a long time we don't see. Last time was $lasttime\n"+

        "I hope you can join us for my party that is scheduled for $party.\n"+

        "</p>\n"+

        "<p>\n"+

        "Best Regards,<br/>\n"+

        "&nbsp;&nbsp;&nbsp;<i>Michele</i>\n"+

        "</body></html>\n";



        ContextMap context = new ContextMap();

        context.put("title", "Page Title");

        context.put("name", "Luca");

        context.put("lasttime", "10/05/2005");

        context.put("party", "20/07/2005");

        context.put("static", "TemplateEngine.merge static");



        TemplateEngine templateEngine = new TemplateEngine(template);

        templateEngine.merge(context, new PrintWriter(System.out));

上例中$打头的变量将会被新的字符串替换,该特性实现主要分以下几个部分:

1. 定义一个ContextMap,维护一个hash表记录字符串和被替换字符串的映射关系;

2. 实现核心类TemplateEngine,其中重要的是:

  • 成员ReferenceElement[] references,记录每个替换引用的值和在模板中的位置
  • init方法,在构造函数时被调用,遍历模板并记录相应的替换项至references;
  • merge方法,业务方法,遍历模板并将ContextMap中值替换到references中去;
int tokenEnd = findTokenEndIndex(template, tokenBegin+1);



String key = template.substring(tokenBegin+1, tokenEnd);

String value = context.get(key);

if (value != null) {

    writer.write(value);

}

else {

    writer.write(token);

    writer.write(key);

}

start = tokenEnd;
    private static int findTokenEndIndex(String template, int startindex) {

        int currentindex = startindex;

        char current;

        while (currentindex < template.length())

        {

            current = template.charAt(currentindex);

            if ((current >= '0' && current <='9') ||

                    (current >= 'A' && current <= 'Z') ||

                    (current >= 'a' && current <= 'z') ||

                    (current == '_') || (current == '-')) {

                currentindex++;

            }

            else {

                break;

            }

        }

        return currentindex;

    }

 

 

你可能感兴趣的:(学习)