Project

General

Profile

Download (12.3 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.math.BigInteger;
14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Set;
18
import java.util.UUID;
19

    
20
import org.apache.log4j.Logger;
21
import org.hibernate.Criteria;
22
import org.hibernate.Query;
23
import org.hibernate.criterion.Projections;
24
import org.hibernate.criterion.Restrictions;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.beans.factory.annotation.Qualifier;
27
import org.springframework.stereotype.Repository;
28

    
29
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
30
import eu.etaxonomy.cdm.model.taxon.Classification;
31
import eu.etaxonomy.cdm.model.taxon.Taxon;
32
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
33
import eu.etaxonomy.cdm.model.taxon.TaxonNodeAgentRelation;
34
import eu.etaxonomy.cdm.persistence.dao.hibernate.common.AnnotatableDaoImpl;
35
import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
36
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
37
import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
38
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
39

    
40
/**
41
 * @author a.mueller
42
 * @created 16.06.2009
43
 */
44
@Repository
45
@Qualifier("taxonNodeDaoHibernateImpl")
46
public class TaxonNodeDaoHibernateImpl extends AnnotatableDaoImpl<TaxonNode>
47
		implements ITaxonNodeDao {
48
	@SuppressWarnings("unused")
49
	private static final Logger logger = Logger.getLogger(TaxonNodeDaoHibernateImpl.class);
50

    
51
	@Autowired
52
	private ITaxonDao taxonDao;
53
	@Autowired
54
	private IClassificationDao classificationDao;
55

    
56
	public TaxonNodeDaoHibernateImpl() {
57
		super(TaxonNode.class);
58
	}
59
	@Override
60
	public UUID delete(TaxonNode persistentObject, boolean deleteChildren){
61
		Taxon taxon = persistentObject.getTaxon();
62
		taxon = HibernateProxyHelper.deproxy(taxon, Taxon.class);
63

    
64
		/*Session session = this.getSession();
65
		Query query = session.createQuery("from TaxonNode t where t.taxon = :taxon");
66
		query.setParameter("taxon", taxon);
67
		List result = query.list();*/
68
		if (taxon != null){
69
			Set<TaxonNode> nodes = taxon.getTaxonNodes();
70

    
71
			if (nodes.size()==1){
72

    
73
				TaxonNode node = nodes.iterator().next();
74
				node = HibernateProxyHelper.deproxy(node, TaxonNode.class);
75

    
76
				taxon.removeTaxonNode(node, deleteChildren);
77
				taxonDao.delete(taxon);
78
			}
79
		}
80
		//persistentObject.delete();
81

    
82
		super.delete(persistentObject);
83

    
84

    
85

    
86
		//taxon = (Taxon)taxonDao.findByUuid(taxon.getUuid());
87
		return persistentObject.getUuid();
88
	}
89

    
90
	@Override
91
	public List<TaxonNode> getTaxonOfAcceptedTaxaByClassification(Classification classification, Integer start, Integer end) {
92
		int classificationId = classification.getId();
93
		String limit = "";
94
		if(start !=null && end != null){
95
		    limit = "LIMIT "+start+"," +end;
96
		}
97
		//FIXME write test
98
        String queryString = "SELECT DISTINCT nodes.*,taxa.titleCache FROM TaxonNode AS nodes LEFT JOIN TaxonBase AS taxa ON nodes.taxon_id = taxa.id WHERE taxa.DTYPE = 'Taxon' AND nodes.classification_id = " + classificationId + " ORDER BY taxa.titleCache " + limit;
99
        List<TaxonNode> result  = getSession().createSQLQuery(queryString).addEntity(TaxonNode.class).list();
100

    
101
       return result;
102

    
103

    
104
	}
105

    
106
    @Override
107
    public int countTaxonOfAcceptedTaxaByClassification(Classification classification){
108
        int classificationId = classification.getId();
109
        //FIXME write test
110
        String queryString = "SELECT DISTINCT COUNT('nodes.*') FROM TaxonNode AS nodes LEFT JOIN TaxonBase AS taxa ON nodes.taxon_id = taxa.id WHERE taxa.DTYPE = 'Taxon' AND nodes.classification_id = " + classificationId;
111
         List<BigInteger> result = getSession().createSQLQuery(queryString).list();
112
         return result.get(0).intValue ();
113
    }
114

    
115
    @Override
116
    public List<TaxonNode> listChildrenOf(TaxonNode node, Integer pageSize, Integer pageIndex, List<String> propertyPaths, boolean recursive){
117
    	if (recursive == true){
118
    		Criteria crit = getSession().createCriteria(TaxonNode.class);
119
    		crit.add( Restrictions.like("treeIndex", node.treeIndex()+ "%") );
120
    		if(pageSize != null) {
121
                crit.setMaxResults(pageSize);
122
                if(pageIndex != null) {
123
                    crit.setFirstResult(pageIndex * pageSize);
124
                } else {
125
                    crit.setFirstResult(0);
126
                }
127
            }
128
    		List<TaxonNode> results = crit.list();
129
    		results.remove(node);
130
    		defaultBeanInitializer.initializeAll(results, propertyPaths);
131
    		return results;
132
    	}else{
133
    		return classificationDao.listChildrenOf(node.getTaxon(), node.getClassification(), pageSize, pageIndex, propertyPaths);
134
    	}
135

    
136
    }
137

    
138
    @Override
139
	public Long countChildrenOf(TaxonNode node, Classification classification,
140
			boolean recursive) {
141

    
142
		if (recursive == true){
143
			Criteria crit = getSession().createCriteria(TaxonNode.class);
144
    		crit.add( Restrictions.like("treeIndex", node.treeIndex()+ "%") );
145
    		crit.setProjection(Projections.rowCount());
146
    		return ((Integer)crit.uniqueResult().hashCode()).longValue();
147
		}else{
148
			return classificationDao.countChildrenOf(node.getTaxon(), classification);
149
		}
150
	}
151
    /**
152
     * {@inheritDoc}
153
     */
154
    @Override
155
    public List<TaxonNodeAgentRelation> listTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid,
156
            UUID agentUuid, UUID rankUuid, UUID relTypeUuid, Integer start, Integer limit, List<String> propertyPaths) {
157

    
158

    
159
        StringBuilder hql = prepareListTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid, false);
160

    
161
        Query query =  getSession().createQuery(hql.toString());
162

    
163
        if(limit != null) {
164
            query.setMaxResults(limit);
165
            if(start != null) {
166
                query.setFirstResult(start);
167
            }
168
        }
169

    
170
        setParamsForListTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid, query);
171

    
172
        List<TaxonNodeAgentRelation> records = query.list();
173

    
174
        if(propertyPaths != null) {
175
            defaultBeanInitializer.initializeAll(records, propertyPaths);
176
        }
177
        return records;
178
    }
179

    
180
    /**
181
     * {@inheritDoc}
182
     */
183
    @Override
184
    public long countTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid, UUID agentUuid, UUID rankUuid, UUID relTypeUuid) {
185

    
186
        StringBuilder hql = prepareListTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid, true);
187
        Query query =  getSession().createQuery(hql.toString());
188

    
189
        setParamsForListTaxonNodeAgentRelations(taxonUuid, classificationUuid, agentUuid, rankUuid, relTypeUuid, query);
190

    
191
        Long count = Long.parseLong(query.uniqueResult().toString());
192

    
193
        return count;
194
    }
195
    /**
196
     * @param taxonUuid
197
     * @param classificationUuid
198
     * @param agentUuid
199
     * @param relTypeUuid TODO
200
     * @param doCount TODO
201
     * @param rankId
202
     *     limit to taxa having this rank, only applies if <code>taxonUuid = null</code>
203
     * @return
204
     */
205
    private StringBuilder prepareListTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid, UUID agentUuid, UUID rankUuid, UUID relTypeUuid, boolean doCount) {
206

    
207
        StringBuilder hql = new StringBuilder();
208

    
209
        String join_fetch_mode = doCount ? "join" : "join fetch";
210

    
211
        if(doCount) {
212
            hql.append("select count(tnar)");
213
        } else {
214
            hql.append("select tnar");
215
        }
216

    
217
        hql.append(" from TaxonNodeAgentRelation as tnar ");
218
        if(taxonUuid != null) {
219
            // taxonUuid is search filter, do not fetch it
220
            hql.append(" join tnar.taxonNode as tn join tn.taxon as t ");
221
        } else {
222
            hql.append(join_fetch_mode).append(" tnar.taxonNode as tn ").append(join_fetch_mode).append(" tn.taxon as t ");
223
            if(rankUuid != null) {
224
                hql.append(" join t.name as n ");
225
            }
226
        }
227
        hql.append(" join tn.classification as c ");
228
        if(agentUuid != null) {
229
            // agentUuid is search filter, do not fetch it
230
//            hql.append(" join tnar.agent as a ");
231
            hql.append(join_fetch_mode).append(" tnar.agent as a ");
232
        } else {
233
            hql.append(join_fetch_mode).append(" tnar.agent as a ");
234
        }
235

    
236
        hql.append(" where 1 = 1 ");
237

    
238
        if(relTypeUuid != null) {
239
            hql.append(" and tnar.type.uuid = :relTypeUuid ");
240
        }
241

    
242
        if(taxonUuid != null) {
243
            hql.append(" and t.uuid = :taxonUuid ");
244
        } else {
245
            if(rankUuid != null) {
246
                hql.append(" and n.rank.uuid = :rankUuid ");
247
            }
248
        }
249
        if(classificationUuid != null) {
250
            hql.append(" and c.uuid = :classificationUuid ");
251
        }
252
        if(agentUuid != null) {
253
            hql.append(" and a.uuid = :agentUuid ");
254
        }
255

    
256
        hql.append(" order by a.titleCache");
257
        return hql;
258
    }
259
    /**
260
     * @param taxonUuid
261
     * @param classificationUuid
262
     * @param agentUuid
263
     * @param relTypeUuid TODO
264
     * @param query
265
     * @param rankId TODO
266
     */
267
    private void setParamsForListTaxonNodeAgentRelations(UUID taxonUuid, UUID classificationUuid, UUID agentUuid,
268
            UUID rankUuid, UUID relTypeUuid, Query query) {
269

    
270
        if(taxonUuid != null) {
271
            query.setParameter("taxonUuid", taxonUuid);
272
        } else {
273
            if(rankUuid != null) {
274
                query.setParameter("rankUuid", rankUuid);
275
            }
276
        }
277
        if(classificationUuid != null) {
278
            query.setParameter("classificationUuid", classificationUuid);
279
        }
280
        if(agentUuid != null) {
281
            query.setParameter("agentUuid", agentUuid);
282
        }
283
        if(relTypeUuid != null) {
284
            query.setParameter("relTypeUuid", relTypeUuid);
285
        }
286
    }
287

    
288
    @Override
289
    public Map<String, Integer> rankOrderIndexForTreeIndex(List<String> treeIndexes,
290
            Integer minRankOrderIndex,
291
            Integer maxRankOrderIndex) {
292

    
293
        Map<String, Integer> result = new HashMap<>();
294
        if (treeIndexes == null || treeIndexes.isEmpty()){
295
            return result;
296
        }
297

    
298
        String hql = " SELECT tn.treeIndex, r.orderIndex "
299
                + " FROM TaxonNode tn JOIN tn.taxon t JOIN t.name n JOIN n.rank r "
300
                + " WHERE tn.treeIndex IN (:treeIndexes) ";
301
        if (minRankOrderIndex != null){
302
            hql += " AND r.orderIndex <= :minOrderIndex";
303
        }
304
        if (maxRankOrderIndex != null){
305
            hql += " AND r.orderIndex >= :maxOrderIndex";
306
        }
307

    
308
        Query query =  getSession().createQuery(hql);
309
        query.setParameterList("treeIndexes", treeIndexes);
310
        if (minRankOrderIndex != null){
311
            query.setParameter("minOrderIndex", minRankOrderIndex);
312
        }
313
        if (maxRankOrderIndex != null){
314
            query.setParameter("maxOrderIndex", maxRankOrderIndex);
315
        }
316

    
317
        @SuppressWarnings("unchecked")
318
        List<Object[]> list = query.list();
319
        for (Object[] o : list){
320
            result.put((String)o[0], (Integer)o[1]);
321
        }
322
        return result;
323
    }
324

    
325
    @Override
326
    public Map<String, UuidAndTitleCache<?>> taxonUuidsForTreeIndexes(Set<String> treeIndexes) {
327
        Map<String, UuidAndTitleCache<?>> result = new HashMap<>();
328
        if (treeIndexes == null || treeIndexes.isEmpty()){
329
            return result;
330
        }
331

    
332
        String hql = " SELECT tn.treeIndex, t.uuid, tnb.titleCache "
333
                + " FROM TaxonNode tn JOIN tn.taxon t Join t.name tnb "
334
                + " WHERE tn.treeIndex IN (:treeIndexes) ";
335
        Query query =  getSession().createQuery(hql);
336
        query.setParameterList("treeIndexes", treeIndexes);
337

    
338
        @SuppressWarnings("unchecked")
339
        List<Object[]> list = query.list();
340
        for (Object[] o : list){
341
            result.put((String)o[0], new UuidAndTitleCache<>((UUID)o[1], null, (String)o[2]));
342
        }
343
        return result;
344
    }
345

    
346

    
347

    
348
}
(4-4/4)