Project

General

Profile

Download (12.1 KB) Statistics
| Branch: | Tag: | Revision:
1
// $Id$
2
/**
3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10

    
11
package eu.etaxonomy.cdm.persistence.dao.hibernate.taxon;
12

    
13
import java.util.ArrayList;
14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.UUID;
18

    
19
import org.apache.log4j.Logger;
20
import org.hibernate.Query;
21
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.beans.factory.annotation.Qualifier;
23
import org.springframework.stereotype.Repository;
24

    
25
import eu.etaxonomy.cdm.model.name.Rank;
26
import eu.etaxonomy.cdm.model.taxon.Classification;
27
import eu.etaxonomy.cdm.model.taxon.Taxon;
28
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
29
import eu.etaxonomy.cdm.persistence.dao.hibernate.common.IdentifiableDaoBase;
30
import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
31
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
32
import eu.etaxonomy.cdm.persistence.dto.ClassificationLookupDTO;
33

    
34
/**
35
 * @author a.mueller
36
 * @created 16.06.2009
37
 */
38
@Repository
39
@Qualifier("classificationDaoHibernateImpl")
40
public class ClassificationDaoHibernateImpl extends IdentifiableDaoBase<Classification>
41
        implements IClassificationDao {
42
    @SuppressWarnings("unused")
43
    private static final Logger logger = Logger.getLogger(ClassificationDaoHibernateImpl.class);
44

    
45
    @Autowired
46
    private ITaxonNodeDao taxonNodeDao;
47

    
48
    public ClassificationDaoHibernateImpl() {
49
        super(Classification.class);
50
        indexedClasses = new Class[1];
51
        indexedClasses[0] = Classification.class;
52
    }
53

    
54
    @Override
55
    @SuppressWarnings("unchecked")
56
    public List<TaxonNode> listRankSpecificRootNodes(Classification classification, Rank rank,
57
            Integer limit, Integer start, List<String> propertyPaths, int queryIndex){
58

    
59
        List<TaxonNode> results = new ArrayList<TaxonNode>();
60
        Query[] queries = prepareRankSpecificRootNodes(classification, rank, false);
61

    
62
        // since this method is using two queries sequentially the handling of limit and start
63
        // is a bit more complex
64
        // the prepareRankSpecificRootNodes returns 1 or 2 queries
65

    
66
        Query q = queries[queryIndex];
67
        if(limit != null) {
68
            q.setMaxResults(limit);
69
            if(start != null) {
70
                q.setFirstResult(start);
71
            }
72
        }
73
//        long start_t = System.currentTimeMillis();
74
        results = q.list();
75
//        System.err.println("dao.listRankSpecificRootNodes() - query[" + queryIndex + "].list() " + (System.currentTimeMillis() - start_t));
76
//        start_t = System.currentTimeMillis();
77
        defaultBeanInitializer.initializeAll(results, propertyPaths);
78
//        System.err.println("dao.listRankSpecificRootNodes() - defaultBeanInitializer.initializeAll() " + (System.currentTimeMillis() - start_t));
79

    
80
        return results;
81

    
82
    }
83

    
84
    @Override
85
    public long[] countRankSpecificRootNodes(Classification classification, Rank rank) {
86

    
87
        long[] result = new long[(rank == null ? 1 : 2)];
88
        Query[] queries = prepareRankSpecificRootNodes(classification, rank, true);
89
        int i = 0;
90
        for(Query q : queries) {
91
            result[i++] = (Long)q.uniqueResult();
92
        }
93
        return result;
94
    }
95

    
96
    /**
97
     * See <a href="http://dev.e-taxonomy.eu/trac/wiki/CdmClassificationRankSpecificRootnodes">
98
     * http://dev.e-taxonomy.eu/trac/wiki/CdmClassificationRankSpecificRootnodes</a>
99
     *
100
     * @param classification
101
     * @param rank
102
     * @return
103
     *      one or two Queries as array, depending on the <code>rank</code> parameter:
104
     *      <code>rank == null</code>: array with one item, <code>rank != null</code>: array with two items.
105
     */
106
    private Query[] prepareRankSpecificRootNodes(Classification classification, Rank rank, boolean doCount) {
107
        Query query1;
108
        Query query2 = null;
109

    
110
        String whereClassification = "";
111
        if (classification != null){
112
            whereClassification = " AND tn.classification = :classification ";
113
        }
114

    
115
        String selectWhat = doCount ? "count(distinct tn)" : "distinct tn";
116

    
117
        String joinFetch = doCount ? "" : " JOIN FETCH tn.taxon t JOIN FETCH t.name n LEFT JOIN FETCH n.rank LEFT JOIN FETCH t.sec ";
118

    
119
        if(rank == null){
120
            String hql = "SELECT " + selectWhat + " FROM TaxonNode tn" +
121
                    joinFetch +
122
                    " WHERE tn.parent.parent = null " +
123
                    whereClassification;
124
            query1 = getSession().createQuery(hql);
125
        } else {
126
            // this is for the cases
127
            //   - exact match of the ranks
128
            //   - rank of root node is lower but is has no parents
129
            String hql1 = "SELECT " + selectWhat + " FROM TaxonNode tn " +
130
                    joinFetch +
131
                    " WHERE " +
132
                    " (tn.taxon.name.rank = :rank" +
133
                    "   OR (tn.taxon.name.rank.orderIndex > :rankOrderIndex AND tn.parent.parent = null)" +
134
                    " )"
135
                    + whereClassification ;
136

    
137
            // this is for the case
138
            //   - rank of root node is lower and it has a parent with higher rank
139
            String hql2 = "SELECT " + selectWhat + " FROM TaxonNode tn JOIN tn.parent as parent" +
140
                    joinFetch +
141
                    " WHERE " +
142
                    " (tn.taxon.name.rank.orderIndex > :rankOrderIndex AND parent.taxon.name.rank.orderIndex < :rankOrderIndex )"
143
                    + whereClassification ;
144
            query1 = getSession().createQuery(hql1);
145
            query2 = getSession().createQuery(hql2);
146
            query1.setParameter("rank", rank);
147
            query1.setParameter("rankOrderIndex", rank.getOrderIndex());
148
            query2.setParameter("rankOrderIndex", rank.getOrderIndex());
149
        }
150

    
151
        if (classification != null){
152
            query1.setParameter("classification", classification);
153
            if(query2 != null) {
154
                query2.setParameter("classification", classification);
155
            }
156
        }
157
        if(query2 != null) {
158
            return new Query[]{query1, query2};
159
        } else {
160
            return new Query[]{query1};
161
        }
162
    }
163

    
164
    @Override
165
    public List<TaxonNode> listChildrenOf(Taxon taxon, Classification classification, Integer pageSize, Integer pageIndex, List<String> propertyPaths){
166
    	 Query query = prepareListChildrenOf(taxon, classification, false);
167

    
168
         setPagingParameter(query, pageSize, pageIndex);
169

    
170
         @SuppressWarnings("unchecked")
171
         List<TaxonNode> result = query.list();
172
         //check if array is "empty" (not containing null objects)
173
         if(!result.isEmpty() && result.iterator().next()==null){
174
         	return java.util.Collections.emptyList();
175
         }
176
         defaultBeanInitializer.initializeAll(result, propertyPaths);
177
         return result;
178
    }
179

    
180
    @Override
181
    public List<TaxonNode> listSiblingsOf(Taxon taxon, Classification classification, Integer pageSize, Integer pageIndex, List<String> propertyPaths){
182
         Query query = prepareListSiblingsOf(taxon, classification, false);
183

    
184
         setPagingParameter(query, pageSize, pageIndex);
185

    
186
         @SuppressWarnings("unchecked")
187
         List<TaxonNode> result = query.list();
188
         //check if array is "empty" (not containing null objects)
189
         if(!result.isEmpty() && result.iterator().next()==null){
190
            return java.util.Collections.emptyList();
191
         }
192
         defaultBeanInitializer.initializeAll(result, propertyPaths);
193
         return result;
194
    }
195

    
196

    
197

    
198
    @Override
199
    public Long countChildrenOf(Taxon taxon, Classification classification){
200
        Query query = prepareListChildrenOf(taxon, classification, true);
201
        Long count = (Long) query.uniqueResult();
202
        return count;
203
    }
204

    
205
    @Override
206
    public Long countSiblingsOf(Taxon taxon, Classification classification){
207
        Query query = prepareListSiblingsOf(taxon, classification, true);
208
        Long count = (Long) query.uniqueResult();
209
        return count;
210
    }
211

    
212
    private Query prepareListChildrenOf(Taxon taxon, Classification classification, boolean doCount){
213

    
214
    	String selectWhat = doCount ? "count(cn)" : "cn";
215

    
216
         String hql = "select " + selectWhat + " from TaxonNode as tn JOIN tn.classification as c JOIN tn.taxon as t JOIN tn.childNodes as cn "
217
                 + "where t = :taxon and c = :classification";
218
         Query query = getSession().createQuery(hql);
219
         query.setParameter("taxon", taxon);
220
         query.setParameter("classification", classification);
221
         return query;
222
    }
223

    
224
    private Query prepareListSiblingsOf(Taxon taxon, Classification classification, boolean doCount){
225

    
226
        String selectWhat = doCount ? "count(tn)" : "tn";
227

    
228
         String subSelect = "SELECT tn.parent FROM TaxonNode as tn JOIN tn.classification as c JOIN tn.taxon as t "
229
                 + "WHERE t = :taxon AND c = :classification";
230
         String hql = "SELECT " + selectWhat + " FROM TaxonNode as tn WHERE tn.parent IN ( " + subSelect + ")";
231
         Query query = getSession().createQuery(hql);
232
         query.setParameter("taxon", taxon);
233
         query.setParameter("classification", classification);
234
         return query;
235
    }
236

    
237

    
238
    @Override
239
    public UUID delete(Classification persistentObject){
240
        //delete all childnodes, then delete the tree
241

    
242
        List<TaxonNode> nodes = persistentObject.getChildNodes();
243
        List<TaxonNode> nodesTmp = new ArrayList<TaxonNode>(nodes);
244

    
245
//        Iterator<TaxonNode> nodesIterator = nodes.iterator();
246
        for(TaxonNode node : nodesTmp){
247
            persistentObject.deleteChildNode(node, true);
248
            taxonNodeDao.delete(node, true);
249
        }
250

    
251
        TaxonNode rootNode = persistentObject.getRootNode();
252
        persistentObject.removeRootNode();
253
        taxonNodeDao.delete(rootNode);
254
        super.delete(persistentObject);
255

    
256
        return persistentObject.getUuid();
257
    }
258

    
259
    @Override
260
    public ClassificationLookupDTO classificationLookup(Classification classification) {
261

    
262
        ClassificationLookupDTO classificationLookupDTO = new ClassificationLookupDTO(classification);
263

    
264
        // only for debugging:
265
//        logger.setLevel(Level.TRACE);
266
//        Logger.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
267

    
268
        String hql = "select t.id, n.rank, tp.id from TaxonNode as tn join tn.classification as c join tn.taxon as t join t.name as n "
269
                + " left join tn.parent as tnp left join tnp.taxon as tp "
270
                + " where c = :classification";
271
        Query query = getSession().createQuery(hql);
272
        query.setParameter("classification", classification);
273
        @SuppressWarnings("unchecked")
274
        List<Object[]> result = query.list();
275
        for(Object[] row : result) {
276
            Integer parentId = null;
277
            parentId = (Integer) row[2];
278
            classificationLookupDTO.add((Integer)row[0], (Rank)row[1], parentId);
279
        }
280

    
281
        return classificationLookupDTO ;
282
    }
283

    
284
    @Override
285
    public Map<UUID, String> treeIndexForTaxonUuids(UUID classificationUuid,
286
            List<UUID> taxonUuids) {
287
        String hql = " SELECT t.uuid, tn.treeIndex "
288
                + " FROM Taxon t JOIN t.taxonNodes tn "
289
                + " WHERE (1=1)"
290
                + "     AND tn.classification.uuid = :classificationUuid "
291
                + "     AND t.uuid IN (:taxonUuids) "
292
                ;
293
        Query query =  getSession().createQuery(hql);
294
        query.setParameter("classificationUuid", classificationUuid);
295
        query.setParameterList("taxonUuids", taxonUuids);
296

    
297
        Map<UUID, String> result = new HashMap<>();
298
        @SuppressWarnings("unchecked")
299
        List<Object[]> list = query.list();
300
        for (Object[] o : list){
301
            result.put((UUID)o[0], (String)o[1]);
302
        }
303
        return result;
304
    }
305

    
306

    
307
}
(1-1/4)