allow saving FullDataGenerator data through API (preliminary)
[cdmlib.git] / cdmlib-persistence / src / main / java / eu / etaxonomy / cdm / persistence / dao / hibernate / common / CdmGenericDaoImpl.java
index c3c2d3227fb1aaf759ca608399b11a179590a0fc..a4dcdf05a52b9f79bc4ccbfed393982c6eaaef6b 100644 (file)
@@ -32,10 +32,14 @@ import org.hibernate.MappingException;
 import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
+import org.hibernate.collection.internal.AbstractPersistentCollection;
+import org.hibernate.collection.spi.PersistentCollection;
 import org.hibernate.criterion.CriteriaSpecification;
 import org.hibernate.criterion.Criterion;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.engine.spi.CollectionEntry;
 import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.engine.spi.SessionImplementor;
 import org.hibernate.internal.SessionFactoryImpl;
 import org.hibernate.internal.SessionImpl;
 import org.hibernate.metadata.ClassMetadata;
@@ -65,6 +69,7 @@ import org.springframework.stereotype.Repository;
 
 import eu.etaxonomy.cdm.common.CdmUtils;
 import eu.etaxonomy.cdm.common.DoubleResult;
+import eu.etaxonomy.cdm.datagenerator.FullCoverageDataGenerator;
 import eu.etaxonomy.cdm.hibernate.DOIUserType;
 import eu.etaxonomy.cdm.hibernate.EnumUserType;
 import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
@@ -121,6 +126,7 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
        @Override
        public List<CdmBase> getCdmBasesByFieldAndClass(Class clazz, String propertyName, CdmBase referencedCdmBase){
                Session session = super.getSession();
+       
                Criteria criteria = session.createCriteria(clazz);
                criteria.add(Restrictions.eq(propertyName, referencedCdmBase));
                return criteria.list();
@@ -187,6 +193,28 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                        throw new RuntimeException(e);
                }
                
+       }
+       @Override
+       public Set<CdmBase> getReferencingObjectsForDeletion(CdmBase referencedCdmBase){
+               Set<CdmBase> result = getReferencingObjects(referencedCdmBase);
+               Set<ReferenceHolder> holderSet = referenceMap.get(IdentifiableEntity.class);
+               try {
+                       if (holderSet == null){
+                               holderSet = makeHolderSet(IdentifiableEntity.class);
+                               referenceMap.put(IdentifiableEntity.class, holderSet);
+                       }
+                       Set<CdmBase> resultIdentifiableEntity = new HashSet<CdmBase>();
+                       for (ReferenceHolder refHolder: holderSet){
+                               handleReferenceHolder(referencedCdmBase, resultIdentifiableEntity, refHolder);
+                       }
+                       result.removeAll(resultIdentifiableEntity);
+                       
+                       return result;
+               } catch (Exception e) {
+                       e.printStackTrace();
+                       throw new RuntimeException(e);
+               }
+               
        }
 
        /**
@@ -378,6 +406,7 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                return query;
        }
        
+       @Override
        public <T extends CdmBase> void   merge(T cdmBase1, T cdmBase2, IMergeStrategy mergeStrategy) throws MergeException {
                Class<T> clazz = (Class<T>)cdmBase1.getClass();
                SessionImpl session = (SessionImpl) getSession();
@@ -453,7 +482,7 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                
                SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
                
-               Map allClassMetadata = sessionFactory.getAllClassMetadata();
+               Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
                
                //TODO cast
                getCollectionRoles(clazz, sessionFactory);
@@ -841,10 +870,8 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                }
        }
        
-       /* (non-Javadoc)
-        * @see eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao#test()
-        */
-       public void test() {
+       //TODO Move to test classes if still needed
+       private void test() {
                SessionFactoryImpl factory = (SessionFactoryImpl)getSession().getSessionFactory();
                Type propType = factory.getReferencedPropertyType(BotanicalName.class.getCanonicalName(), "titleCache");
                Map collMetadata = factory.getAllCollectionMetadata();
@@ -862,16 +889,16 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                
        }
 
+       @Override
        public <T extends CdmBase> T find(Class<T> clazz, int id){
                Session session;
                session =  getSession();
                //session = getSession().getSessionFactory().getCurrentSession();
-               return (T)session.get(clazz, id);
+               Object o = session.get(clazz, id);
+               return (T)o;
        }
 
-       /* (non-Javadoc)
-        * @see eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao#findMatching(eu.etaxonomy.cdm.strategy.match.IMatchable, eu.etaxonomy.cdm.strategy.match.IMatchStrategy)
-        */
+       @Override
        public <T extends IMatchable> List<T> findMatching(T objectToMatch,
                        IMatchStrategy matchStrategy) throws MatchException {
                try {
@@ -891,10 +918,10 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                }
        }
        
-       public <T extends IMatchable> List<T> findMatchingNullSafe(T objectToMatch,     IMatchStrategy matchStrategy) throws IllegalArgumentException, IllegalAccessException, MatchException {
+       private <T extends IMatchable> List<T> findMatchingNullSafe(T objectToMatch,    IMatchStrategy matchStrategy) throws IllegalArgumentException, IllegalAccessException, MatchException {
                List<T> result = new ArrayList<T>();
                Session session = getSession();
-               Class matchClass = objectToMatch.getClass();
+               Class<?> matchClass = objectToMatch.getClass();
                ClassMetadata classMetaData = session.getSessionFactory().getClassMetadata(matchClass.getCanonicalName());
                Criteria criteria = session.createCriteria(matchClass);
                boolean noMatch = makeCriteria(objectToMatch, matchStrategy, classMetaData, criteria);
@@ -1164,6 +1191,102 @@ public class CdmGenericDaoImpl extends CdmEntityDaoBase<CdmBase> implements ICdm
                List<CdmMetaData> results = crit.list();
                return results;
        }
+       
+    @Override
+    public PersistentCollection initializeCollection(PersistentCollection col) {
+            Session session = getSession();
+            col.setCurrentSession((SessionImplementor) session);
+            
+            if(!((SessionImplementor)session).getPersistenceContext().getCollectionEntries().containsKey(col)) {
+                    ((SessionImplementor)session).getPersistenceContext().addUninitializedDetachedCollection(
+                                    ((SessionImplementor)session).getFactory().getCollectionPersister( col.getRole() ),col);
+            }
+            col.forceInitialization();    
+            logger.debug("initialising persistent collection with with role : " + col.getRole() + " and key : " + col.getKey());
+            return col;
+    }
+    
+    @Override
+    public boolean isEmpty(PersistentCollection col) {
+       return initializeCollection(col).empty();
+    }
+    
+    @Override
+    public int size(PersistentCollection col) {
+       logger.debug("remote size() - for role : " + col.getRole() + " and key : " + col.getKey());
+       initializeCollection(col);   
+       SessionImplementor session = (SessionImplementor)getSession();
+       CollectionEntry entry = session.getPersistenceContext().getCollectionEntry(col);
+
+       if ( entry != null ) {
+               
+               CollectionPersister persister = entry.getLoadedPersister();                     
+               return persister.getSize( entry.getLoadedKey(), session );
+       }
+       return -1;
+    }
+    
+    @Override
+    public Object get(PersistentCollection col, int index) {
+       logger.debug("remote get() - for role : " + col.getRole() + " and key : " + col.getKey());
+       initializeCollection(col);    
+       SessionImplementor session = (SessionImplementor)getSession();
+       CollectionEntry entry = session.getPersistenceContext().getCollectionEntry(col);
+       
+       if ( entry != null ) {
+               
+               CollectionPersister persister = entry.getLoadedPersister();                             
+               return persister.getElementByIndex(entry.getLoadedKey(), index, session, col);
+               
+       }
+       //FIXME:Remoting Should we not be throwing an exception here ?
+       return null;
+    }
+    
+    @Override
+    public boolean contains(PersistentCollection col, Object element) {
+       logger.debug("remote contains() - for role : " + col.getRole() + " and key : " + col.getKey());
+       initializeCollection(col);    
+       SessionImplementor session = (SessionImplementor)getSession();
+       CollectionEntry entry = session.getPersistenceContext().getCollectionEntry(col);
+       
+       if ( entry != null ) {
+               
+               CollectionPersister persister = entry.getLoadedPersister();             
+               return persister.elementExists(entry.getLoadedKey(), element, session);                                 
+       }
+       //FIXME:Remoting Should we not be throwing an exception here ?
+       return false;
+    }
+
+    @Override
+    public boolean containsKey(PersistentCollection col, Object key) {
+       logger.debug("remote containsKey() - for role : " + col.getRole() + " and key : " + col.getKey());
+       initializeCollection(col);    
+       SessionImplementor session = (SessionImplementor)getSession();
+       CollectionEntry entry = session.getPersistenceContext().getCollectionEntry(col);
+       
+       if ( entry != null ) {
+               
+               CollectionPersister persister = entry.getLoadedPersister();             
+               return persister.indexExists(entry.getLoadedKey(), key, session);                               
+       }
+       //FIXME:Remoting Should we not be throwing an exception here ?
+       return false;
+       
+    }
+    
+    @Override
+    public boolean containsValue(PersistentCollection col, Object element) {           
+       return contains(col, element);
+    }
+
+       @Override
+       public void createFullSampleData() {
+               FullCoverageDataGenerator dataGenerator = new FullCoverageDataGenerator();
+               dataGenerator.fillWithData(getSession());
+       }
+
 }