Project

General

Profile

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

    
10
package eu.etaxonomy.cdm.persistence.dao.hibernate.common;
11

    
12
import java.util.ArrayList;
13
import java.util.Collection;
14
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Set;
19
import java.util.UUID;
20

    
21
import org.hibernate.Criteria;
22
import org.hibernate.Query;
23
import org.hibernate.Session;
24
import org.hibernate.criterion.Restrictions;
25
import org.hibernate.envers.query.AuditEntity;
26
import org.hibernate.envers.query.AuditQuery;
27
import org.springframework.stereotype.Repository;
28

    
29
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
30
import eu.etaxonomy.cdm.model.common.OrderedTermVocabulary;
31
import eu.etaxonomy.cdm.model.common.Representation;
32
import eu.etaxonomy.cdm.model.common.TermType;
33
import eu.etaxonomy.cdm.model.common.TermVocabulary;
34
import eu.etaxonomy.cdm.model.view.AuditEvent;
35
import eu.etaxonomy.cdm.persistence.dao.common.ITermVocabularyDao;
36
import eu.etaxonomy.cdm.persistence.dto.TermDto;
37
import eu.etaxonomy.cdm.persistence.dto.TermVocabularyDto;
38
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
39
import eu.etaxonomy.cdm.persistence.query.OrderHint;
40

    
41
/**
42
 * @author a.mueller
43
 *
44
 */
45
@Repository
46
public class TermVocabularyDaoImpl extends IdentifiableDaoBase<TermVocabulary> implements
47
		ITermVocabularyDao {
48

    
49
	/**
50
	 * @param type
51
	 */
52
	public TermVocabularyDaoImpl() {
53
		super(TermVocabulary.class);
54
		indexedClasses = new Class[2];
55
		indexedClasses[0] = TermVocabulary.class;
56
		indexedClasses[1] = OrderedTermVocabulary.class;
57
	}
58

    
59
	@Override
60
    public long countTerms(TermVocabulary termVocabulary) {
61
		AuditEvent auditEvent = getAuditEventFromContext();
62
		if(auditEvent.equals(AuditEvent.CURRENT_VIEW)) {
63
		    Query query = getSession().createQuery("select count(term) from DefinedTermBase term where term.vocabulary = :vocabulary");
64
		    query.setParameter("vocabulary", termVocabulary);
65

    
66
		    return (Long)query.uniqueResult();
67
		} else {
68
			AuditQuery query = makeAuditQuery(null, auditEvent);
69
			query.addProjection(AuditEntity.id().count());
70
			query.add(AuditEntity.relatedId("vocabulary").eq(termVocabulary.getId()));
71
			return (Long)query.getSingleResult();
72
		}
73
	}
74

    
75
	@Override
76
    public <T extends DefinedTermBase> List<T> getTerms(TermVocabulary<T> vocabulary,Integer pageSize, Integer pageNumber, List<OrderHint> orderHints,List<String> propertyPaths) {
77
		AuditEvent auditEvent = getAuditEventFromContext();
78
		if(auditEvent.equals(AuditEvent.CURRENT_VIEW)) {
79
			Criteria criteria = getCriteria(DefinedTermBase.class);
80
			criteria.createCriteria("vocabulary").add(Restrictions.idEq(vocabulary.getId()));
81

    
82
			addPageSizeAndNumber(criteria, pageSize, pageNumber);
83
		    this.addOrder(criteria, orderHints);
84

    
85
		    @SuppressWarnings("unchecked")
86
            List<T> result = criteria.list();
87
		    defaultBeanInitializer.initializeAll(result, propertyPaths);
88
		    return result;
89
		} else {
90
			AuditQuery query = makeAuditQuery(null, auditEvent);
91
			query.add(AuditEntity.relatedId("vocabulary").eq(vocabulary.getId()));
92

    
93
			addPageSizeAndNumber(query, pageSize, pageNumber);
94

    
95
			@SuppressWarnings("unchecked")
96
            List<T> result = query.getResultList();
97
		    defaultBeanInitializer.initializeAll(result, propertyPaths);
98
			return result;
99
		}
100
	}
101

    
102
    @Override
103
    public <T extends DefinedTermBase> TermVocabulary<T> findByUri(String termSourceUri, Class<T> clazz) {
104
		AuditEvent auditEvent = getAuditEventFromContext();
105
		if(auditEvent.equals(AuditEvent.CURRENT_VIEW)) {
106
		    //TODO use clazz
107
    		Query query = getSession().createQuery("select vocabulary from TermVocabulary vocabulary where vocabulary.termSourceUri= :termSourceUri");
108
	    	query.setParameter("termSourceUri", termSourceUri);
109

    
110
	    	@SuppressWarnings("unchecked")
111
	    	TermVocabulary<T> result = (TermVocabulary<T>)query.uniqueResult();
112
	    	return result;
113
		} else {
114
			@SuppressWarnings("unchecked")
115
            AuditQuery query = makeAuditQuery(clazz, auditEvent);
116
			query.add(AuditEntity.property("termSourceUri").eq(termSourceUri));
117

    
118
			@SuppressWarnings("unchecked")
119
            TermVocabulary<T> result = (TermVocabulary<T>)query.getSingleResult();
120
			return result;
121
		}
122
	}
123

    
124

    
125
	@Override
126
    public <T extends DefinedTermBase> List<T> getTerms(TermVocabulary<T> termVocabulary, Integer pageSize,	Integer pageNumber) {
127
		return getTerms(termVocabulary, pageSize, pageNumber, null, null);
128
	}
129

    
130

    
131
    @Override
132
    public <T extends DefinedTermBase> List<TermVocabulary<T>> findByTermType(TermType termType, List<String> propertyPaths) {
133

    
134
        Criteria criteria = getSession().createCriteria(type);
135
        criteria.add(Restrictions.eq("termType", termType));
136
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
137
        //this.addOrder(criteria, orderHints);
138

    
139
        @SuppressWarnings("unchecked")
140
        List<TermVocabulary<T>> result = criteria.list();
141
        defaultBeanInitializer.initializeAll(result, propertyPaths);
142
        return result;
143
    }
144

    
145
	@Override
146
    public List<TermVocabulary> listByTermType(TermType termType, boolean includeSubTypes, Integer limit, Integer start,List<OrderHint> orderHints, List<String> propertyPaths) {
147
        checkNotInPriorView("TermVocabularyDao.listByTermType(TermType termType, Integer limit, Integer start, List<OrderHint> orderHints, List<String> propertyPaths)");
148

    
149
        Set<TermType> allTermTypes = new HashSet<TermType>();
150
        allTermTypes.add(termType);
151
        if (includeSubTypes){
152
            allTermTypes.addAll(termType.getGeneralizationOf(true));
153
        }
154

    
155
        Criteria criteria = getSession().createCriteria(type);
156
        criteria.add(Restrictions.in("termType", allTermTypes));
157

    
158
        if(limit != null) {
159
            criteria.setMaxResults(limit);
160
            if(start != null) {
161
                criteria.setFirstResult(start);
162
            }
163
        }
164

    
165
        this.addOrder(criteria, orderHints);
166

    
167
        @SuppressWarnings("unchecked")
168
        List<TermVocabulary> result = criteria.list();
169
        defaultBeanInitializer.initializeAll(result, propertyPaths);
170
        return result;
171
    }
172

    
173
	@Override
174
	public void missingTermUuids(
175
			Map<UUID, Set<UUID>> uuidsRequested,
176
			Map<UUID, Set<UUID>> uuidMissingTermsRepsonse,
177
			Map<UUID, TermVocabulary<?>> vocabularyResponse){
178

    
179
		Set<UUID> missingTermCandidateUuids = new HashSet<>();
180

    
181
		for (Set<UUID> uuidsPerVocSet : uuidsRequested.values()){
182
			missingTermCandidateUuids.addAll(uuidsPerVocSet);
183
		}
184

    
185
 		//search persisted subset of required (usually all)
186
		String hql = " SELECT terms.uuid " +
187
				" FROM TermVocabulary voc join voc.terms terms  " +
188
				" WHERE terms.uuid IN (:uuids) " +
189
				" ORDER BY voc.uuid ";
190
		Query query = getSession().createQuery(hql);
191

    
192
		int splitSize = 2000;
193
		List<Collection<UUID>> missingTermCandidates = splitCollection(missingTermCandidateUuids, splitSize);
194
		List<UUID> persistedUuids = new ArrayList<>();
195

    
196
		for (Collection<UUID> uuids : missingTermCandidates){
197
		    query.setParameterList("uuids", uuids);
198
		    @SuppressWarnings("unchecked")
199
            List<UUID> list = query.list();
200
		    persistedUuids.addAll(list);
201
		}
202

    
203

    
204
 		//fully load and initialize vocabularies if required
205
		if (vocabularyResponse != null){
206
			String hql2 = " SELECT DISTINCT voc " +
207
					" FROM TermVocabulary voc " +
208
						" LEFT JOIN FETCH voc.terms terms " +
209
						" LEFT JOIN FETCH terms.representations representations " +
210
						" LEFT JOIN FETCH voc.representations vocReps " +
211
					" WHERE terms.uuid IN (:termUuids) OR  (  voc.uuid IN (:vocUuids)  ) " +  //was: AND voc.terms is empty, but did not load originally empty vocabularies with user defined terms added
212
//					" WHERE  voc.uuid IN (:vocUuids) AND voc.terms is empty  " +
213
					" ORDER BY voc.uuid ";
214
			query = getSession().createQuery(hql2);
215
			query.setParameterList("termUuids", missingTermCandidateUuids);
216
			query.setParameterList("vocUuids", uuidsRequested.keySet());
217

    
218
			for (Collection<UUID> uuids : missingTermCandidates){
219
			    query.setParameterList("termUuids", uuids);
220
			    @SuppressWarnings("unchecked")
221
	            List<TermVocabulary<?>> o = query.list();
222
	            for (TermVocabulary<?> voc : o){
223
	                vocabularyResponse.put(voc.getUuid(), voc);
224
	            }
225
	        }
226
		}
227

    
228
		//compute missing terms
229
		if (missingTermCandidateUuids.size() == persistedUuids.size()){
230
			missingTermCandidateUuids.clear();
231
		}else{
232
			missingTermCandidateUuids.removeAll(persistedUuids);
233
			//add missing terms to response
234
			for (UUID vocUUID : uuidsRequested.keySet()){
235
				for (UUID termUuid : uuidsRequested.get(vocUUID)){
236
					if (missingTermCandidateUuids.contains(termUuid)){
237
						Set<UUID> r = uuidMissingTermsRepsonse.get(vocUUID);
238
						if (r == null){
239
							r = new HashSet<>();
240
							uuidMissingTermsRepsonse.put(vocUUID, r);
241
						}
242
						r.add(termUuid);
243
					}
244
				}
245
			}
246
		}
247

    
248
		return;
249
	}
250

    
251
    @Override
252
    public Collection<TermDto> getTopLevelTerms(UUID vocabularyUuid) {
253
        String queryString = TermDto.getTermDtoSelect()
254
                + "where v.uuid = :vocabularyUuid "
255
                + "and a.partOf is null "
256
                + "and a.kindOf is null";
257
        Query query =  getSession().createQuery(queryString);
258
        query.setParameter("vocabularyUuid", vocabularyUuid);
259

    
260
        @SuppressWarnings("unchecked")
261
        List<Object[]> result = query.list();
262

    
263
        List<TermDto> list = TermDto.termDtoListFrom(result);
264
        return list;
265
    }
266

    
267
    @Override
268
    public List<TermVocabularyDto> findVocabularyDtoByTermType(TermType termType) {
269
        String queryString = ""
270
                + "select v.uuid, r "
271
                + "from TermVocabulary as v LEFT JOIN v.representations AS r "
272
                + "where v.termType = :termType "
273
                ;
274
        Query query =  getSession().createQuery(queryString);
275
        query.setParameter("termType", termType);
276

    
277
        @SuppressWarnings("unchecked")
278
        List<Object[]> result = query.list();
279

    
280
        Map<UUID, TermVocabularyDto> dtoMap = new HashMap<>(result.size());
281
        for (Object[] elements : result) {
282
            UUID uuid = (UUID)elements[0];
283
            if(dtoMap.containsKey(uuid)){
284
                dtoMap.get(uuid).addRepresentation((Representation)elements[1]);
285
            } else {
286
                Set<Representation> representations = new HashSet<>();
287
                if(elements[1] instanceof Representation) {
288
                    representations = new HashSet<Representation>(1);
289
                    representations.add((Representation)elements[1]);
290
                } else {
291
                    representations = (Set<Representation>)elements[1];
292
                }
293
                dtoMap.put(uuid, new TermVocabularyDto(uuid, representations));
294
            }
295
        }
296
        return new ArrayList<>(dtoMap.values());
297
    }
298

    
299
    @Override
300
    public <S extends TermVocabulary> List<UuidAndTitleCache<S>> getUuidAndTitleCache(Class<S> clazz, TermType termType,
301
            Integer limit, String pattern) {
302
        if(termType==null){
303
            return getUuidAndTitleCache(clazz, limit, pattern);
304
        }
305
        Session session = getSession();
306
        Query query = null;
307
        if (pattern != null){
308
            query = session.createQuery(
309
                      " SELECT uuid, id, titleCache "
310
                    + " FROM " + clazz.getSimpleName()
311
                    + " WHERE titleCache LIKE :pattern "
312
                    + " AND termType = :termType");
313
            pattern = pattern.replace("*", "%");
314
            pattern = pattern.replace("?", "_");
315
            pattern = pattern + "%";
316
            query.setParameter("pattern", pattern);
317
        } else {
318
            query = session.createQuery(
319
                      " SELECT uuid, id, titleCache "
320
                    + " FROM  " + clazz.getSimpleName()
321
                    + " WHERE termType = :termType");
322
        }
323
        query.setParameter("termType", termType);
324
        if (limit != null){
325
           query.setMaxResults(limit);
326
        }
327
        return getUuidAndTitleCache(query);
328
    }
329

    
330
}
(23-23/25)