1 16 package web.layout; 17 18 import java.io.File ; 19 import java.io.IOException ; 20 import java.io.InputStream ; 21 import java.util.ArrayList ; 22 import java.util.List ; 23 24 import javax.servlet.ServletContext ; 25 26 import org.apache.commons.digester.Digester; 27 import org.apache.commons.digester.ExtendedBaseRules; 28 import org.xml.sax.SAXException ; 29 30 34 public class LayoutConfig { 35 36 private List pages; 37 private boolean freezed = false; 38 private static LayoutConfig config; 39 private static File configFile; 40 private static long lastModified; 41 42 private LayoutConfig(){ 43 pages = new ArrayList (); 44 } 45 46 52 public static LayoutConfig getConfig(ServletContext context) throws IOException , SAXException { 53 if(config!=null && configFile.lastModified()==lastModified){ 54 return config; 55 } 56 config = new LayoutConfig(); 57 Digester dig = new Digester(); 58 dig.push(config); 59 dig.setValidating(false); 60 dig.setRules(new ExtendedBaseRules()); 61 dig.addSetProperties("layout"); 62 63 dig.addObjectCreate("layout/pages/page", Page.class); 64 dig.addSetProperties("layout/pages/page"); 65 dig.addBeanPropertySetter("layout/pages/page" + "/?"); 66 dig.addSetNext("layout/pages/page", "addPage"); 67 68 InputStream in = null; 69 if(context != null){ 70 in = context.getResourceAsStream("/WEB-INF/layout.xml"); 71 configFile = new File (context.getRealPath("/WEB-INF/layout.xml")); 72 } 73 if(in == null){ 74 in = LayoutConfig.class.getResourceAsStream("layout.xml"); 75 configFile = new File (LayoutConfig.class.getResource("layout.xml").getPath()); 76 } 77 try{ 78 lastModified = configFile.lastModified(); 79 dig.parse(in); 80 config.freezed = true; 81 }finally{ 82 if(in!=null) 83 in.close(); 84 } 85 return config; 86 } 87 88 public Page getPage(int index) { 89 return (Page)pages.get(index); 90 } 91 public int pageSize() { 92 return pages.size(); 93 } 94 95 public void addPage(Page page) throws IllegalAccessException { 96 if(!freezed) 97 pages.add(page); 98 else 99 throw new IllegalAccessException ("LayoutConfig is fozened."); 100 } 101 102 public static void main(String [] args) throws Exception { 103 LayoutConfig config = LayoutConfig.getConfig(null); 104 int pc = config.pageSize(); 105 for(int i=0;i<pc;i++){ 106 Page p = config.getPage(i); 107 System.out.println("Name:"+p.getName()+",uri:"+p.getUri()+",param:"+p.getParam()); 108 } 109 config = LayoutConfig.getConfig(null); 110 pc = config.pageSize(); 111 for(int i=0;i<pc;i++){ 112 Page p = config.getPage(i); 113 System.out.println("Name:"+p.getName()+",uri:"+p.getUri()+",param:"+p.getParam()); 114 } 115 } 116 117 } 118 | Popular Tags |