1 package org.sapia.regis.hibernate; 2 3 import java.io.ByteArrayInputStream ; 4 import java.io.ByteArrayOutputStream ; 5 import java.io.IOException ; 6 import java.io.InputStream ; 7 import java.util.Properties ; 8 9 import javax.xml.parsers.DocumentBuilder ; 10 import javax.xml.parsers.DocumentBuilderFactory ; 11 12 import org.hibernate.cfg.Configuration; 13 import org.sapia.regis.Registry; 14 import org.sapia.regis.RegistryFactory; 15 import org.sapia.regis.impl.NodeImpl; 16 import org.sapia.util.text.TemplateContextIF; 17 import org.sapia.util.text.TemplateElementIF; 18 import org.sapia.util.text.TemplateFactory; 19 import org.w3c.dom.Document ; 20 21 27 public class HibernateRegistryFactory implements RegistryFactory{ 28 29 39 public Registry connect(Properties props) throws Exception { 40 Configuration cfg = new Configuration(); 41 cfg.addClass(NodeImpl.class); 42 43 TemplateFactory fac = new TemplateFactory(); 44 TemplateElementIF templ = fac.parse(loadHibernateConfig(props.getProperty("hbm2ddl.auto") != null)); 45 String configStr = templ.render(new HibernateConfigContext(props)); 46 DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance(); 47 DocumentBuilder builder = builderFac.newDocumentBuilder(); 48 Document doc = builder.parse(new ByteArrayInputStream (configStr.getBytes())); 49 50 cfg.configure(doc); 51 return new HibernateRegistry(cfg.buildSessionFactory()); 52 } 53 54 private String loadHibernateConfig(boolean ddl) throws IOException { 55 56 InputStream is = null; 57 if(ddl){ 58 is = getClass().getResourceAsStream("hibernate.ddl.xml"); 59 } 60 else{ 61 is = getClass().getResourceAsStream("hibernate.xml"); 62 } 63 try{ 64 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 65 byte[] buf = new byte[100]; 66 int i; 67 while((i = is.read(buf)) > 0){ 68 bos.write(buf, 0, i); 69 } 70 return new String (bos.toByteArray()); 71 }finally{ 72 is.close(); 73 } 74 } 75 76 public static class HibernateConfigContext implements TemplateContextIF{ 77 78 private static Properties DEFAULT = new Properties (); 79 private Properties _props; 80 81 HibernateConfigContext(Properties props){ 82 _props = props; 83 } 84 85 static{ 86 InputStream is = HibernateConfigContext.class.getResourceAsStream("hibernate.default.properties"); 87 try{ 88 DEFAULT.load(is); 89 is.close(); 90 }catch(IOException e){ 91 e.printStackTrace(); 92 throw new IllegalStateException ("Could not load default Hibernate configuration properties"); 93 } 94 } 95 96 public Object getValue(String name) { 97 String prop = _props.getProperty(name); 98 if(prop == null) prop = DEFAULT.getProperty(name); 99 return prop; 100 } 101 102 public void put(String arg0, Object arg1) { 103 } 104 105 } 106 107 } 108 | Popular Tags |