1 package org.sapia.regis.hibernate; 2 3 import java.io.File ; 4 import java.io.FileInputStream ; 5 import java.io.InputStream ; 6 import java.util.Iterator ; 7 8 import org.hibernate.Session; 9 import org.hibernate.SessionFactory; 10 import org.hibernate.Transaction; 11 import org.hibernate.criterion.Restrictions; 12 import org.sapia.regis.DuplicateNodeException; 13 import org.sapia.regis.Node; 14 import org.sapia.regis.Path; 15 import org.sapia.regis.RWNode; 16 import org.sapia.regis.RegisSession; 17 import org.sapia.regis.Registry; 18 import org.sapia.regis.impl.NodeImpl; 19 import org.sapia.regis.loader.RegistryConfigLoader; 20 21 public class HibernateRegistry implements Registry{ 22 23 private SessionFactory _fac; 24 private Long _rootId; 25 26 public HibernateRegistry(SessionFactory fac){ 27 _fac = fac; 28 _rootId = acquireRoot().getId(); 29 } 30 31 public RegisSession open() { 32 Session s = _fac.openSession(); 33 Sessions.join(s); 34 return new HibernateRegisSession(s); 35 } 36 37 public Node getRoot(){ 38 Session s = Sessions.get(); 39 Node n = (Node)s.load(NodeImpl.class, _rootId); 40 return n; 41 } 42 43 public void close(){ 44 _fac.close(); 45 } 46 47 public void load(File config) throws Exception { 48 load(new FileInputStream (config)); 49 } 50 51 public void load(InputStream is) throws Exception { 52 RegistryConfigLoader loader = new RegistryConfigLoader((RWNode)getRoot()); 53 loader.load(is); 54 } 55 56 public SessionFactory getSessionFactory(){ 57 return _fac; 58 } 59 60 public Node createNode(Path path) throws DuplicateNodeException{ 61 RWNode node; 62 RWNode root; 63 64 if(path.isRoot()){ 65 return acquireRoot(); 66 } 67 else{ 68 root = acquireRoot(); 69 } 70 node = root; 71 RWNode child; 72 Iterator tokens = path.tokens(); 73 while(tokens.hasNext()){ 74 String token = (String )tokens.next(); 75 child = (RWNode)node.getChild(token); 76 if(child == null){ 77 child = (RWNode)node.createChild(token); 78 } 79 node = child; 80 } 81 return node; 82 } 83 84 private NodeImpl acquireRoot(){ 85 Session session = null; 86 if(Sessions.isRegistered()){ 87 session = Sessions.get(); 88 } 89 else{ 90 session = _fac.openSession(); 91 } 92 try{ 93 NodeImpl root = doAcquireRoot(session); 94 return root; 95 }finally{ 96 if(!Sessions.isRegistered()){ 97 session.close(); 98 } 99 } 100 } 101 102 103 private NodeImpl doAcquireRoot(Session session){ 104 NodeImpl root = (NodeImpl)session.createCriteria(NodeImpl.class) 105 .add(Restrictions.eq("name", Node.ROOT_NAME)).uniqueResult(); 106 107 if(root == null){ 108 Transaction tx = session.beginTransaction(); 109 try{ 110 root = new NodeImpl(null, ""); 111 session.save(root); 112 }finally{ 113 tx.commit(); 114 } 115 } 116 return root; 117 } 118 119 } 120 | Popular Tags |