Project

General

Profile

Download (15.5 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
package eu.etaxonomy.cdm.persistence.dao.hibernate.reference;
10

    
11
import java.util.ArrayList;
12
import java.util.HashSet;
13
import java.util.List;
14
import java.util.Set;
15
import java.util.UUID;
16

    
17
import org.apache.log4j.Logger;
18
import org.hibernate.Criteria;
19
import org.hibernate.Hibernate;
20
import org.hibernate.Query;
21
import org.hibernate.Session;
22
import org.hibernate.criterion.Criterion;
23
import org.hibernate.criterion.Restrictions;
24
import org.hibernate.search.FullTextSession;
25
import org.hibernate.search.Search;
26
import org.springframework.beans.factory.annotation.Qualifier;
27
import org.springframework.stereotype.Repository;
28

    
29
import eu.etaxonomy.cdm.model.reference.IArticle;
30
import eu.etaxonomy.cdm.model.reference.IBookSection;
31
import eu.etaxonomy.cdm.model.reference.IInProceedings;
32
import eu.etaxonomy.cdm.model.reference.IPrintedUnitBase;
33
import eu.etaxonomy.cdm.model.reference.IReport;
34
import eu.etaxonomy.cdm.model.reference.IThesis;
35
import eu.etaxonomy.cdm.model.reference.Reference;
36
import eu.etaxonomy.cdm.model.reference.ReferenceType;
37
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
38
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
39
import eu.etaxonomy.cdm.persistence.dao.hibernate.common.IdentifiableDaoBase;
40
import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
41
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
42
import eu.etaxonomy.cdm.persistence.query.MatchMode;
43
import eu.etaxonomy.cdm.persistence.query.OrderHint;
44
import eu.etaxonomy.cdm.strategy.cache.reference.DefaultReferenceCacheStrategy;
45

    
46
/**
47
 * @author a.mueller
48
 *
49
 */
50
@Repository
51
@Qualifier("referenceDaoHibernateImpl")
52
public class ReferenceDaoHibernateImpl extends IdentifiableDaoBase<Reference> implements IReferenceDao {
53
	private static final Logger logger = Logger.getLogger(ReferenceDaoHibernateImpl.class);
54

    
55
	public ReferenceDaoHibernateImpl() {
56
		super(Reference.class);
57
	}
58

    
59
	@Override
60
	public void rebuildIndex() {
61
		FullTextSession fullTextSession = Search.getFullTextSession(getSession());
62

    
63
		for(Reference reference : list(null,null)) { // re-index all agents
64
			Hibernate.initialize(reference.getAuthorship());
65

    
66
			if(reference.getType().equals(ReferenceType.Article)) {
67
				Hibernate.initialize(((IArticle)reference).getInJournal());
68
			} else if(reference.getType().equals(ReferenceType.BookSection)) {
69
				   Hibernate.initialize(((IBookSection)reference).getInBook());
70
			} else if(reference.getType().equals(ReferenceType.InProceedings)) {
71
					Hibernate.initialize(((IInProceedings)reference).getInProceedings());
72
			}else if(reference.getType().equals(ReferenceType.Thesis)) {
73
				Hibernate.initialize(((IThesis)reference).getSchool());
74
			} else if(reference.getType().equals(ReferenceType.Report)) {
75
				Hibernate.initialize(((IReport)reference).getInstitution());
76
			} else if(reference.getType().isPrintedUnit()) {
77
				Hibernate.initialize(((IPrintedUnitBase)reference).getInSeries());
78
			}
79
			fullTextSession.index(reference);
80
		}
81
		fullTextSession.flushToIndexes();
82
	}
83

    
84
	@Override
85
    public List<UuidAndTitleCache<Reference>> getUuidAndTitle(){
86
		List<UuidAndTitleCache<Reference>> list = new ArrayList<UuidAndTitleCache<Reference>>();
87
		Session session = getSession();
88

    
89
		Query query = session.createQuery("select uuid, id, titleCache from " + type.getSimpleName());
90

    
91
		@SuppressWarnings("unchecked")
92
        List<Object[]> result = query.list();
93

    
94
		for(Object[] object : result){
95
			list.add(new UuidAndTitleCache<Reference>(type, (UUID) object[0], (Integer)object[1], (String) object[2]));
96
		}
97

    
98
		return list;
99
	}
100

    
101
	@Override
102
    public List<UuidAndTitleCache<Reference>> getUuidAndTitle(Set<UUID> uuids){
103
	    return getUuidAndTitle(uuids, null);
104
    }
105

    
106

    
107
    @Override
108
    public List<UuidAndTitleCache<Reference>> getUuidAndTitle(Set<UUID> uuids, ReferenceType refType) {
109
        List<Reference> result = getReferenceListForUuids(uuids, refType);
110
        List<UuidAndTitleCache<Reference>> list = new ArrayList<>();
111

    
112
        for(Reference object : result){
113
                list.add(new UuidAndTitleCache<Reference>(type, object.getUuid(), object.getId(), object.getTitleCache()));
114
        }
115

    
116
        return list;
117
    }
118

    
119
	private List<Reference> getReferenceListForUuids(Set<UUID> uuids, ReferenceType refType){
120
	    if (uuids.isEmpty()){
121
            return new ArrayList<>();
122
        }
123
        Criteria criteria = null;
124

    
125
        criteria = getSession().createCriteria(Reference.class);
126

    
127
        if (refType != null){
128
            criteria.add(Restrictions.and(Restrictions.in("uuid", uuids ),Restrictions.eq("type", refType)));
129
        }else{
130
            criteria.add(Restrictions.in("uuid", uuids ) );
131
        }
132

    
133
        @SuppressWarnings("unchecked")
134
        List<Reference> result = criteria.list();
135
        return result;
136
	}
137

    
138
	@Override
139
	public List<UuidAndTitleCache<Reference>> getUuidAndTitleCache(Integer limit, String pattern, ReferenceType refType) {
140
		List<UuidAndTitleCache<Reference>> list = new ArrayList<>();
141
		Session session = getSession();
142

    
143
		String queryString = "SELECT " +"r.uuid, r.id, r.titleCache, ab.titleCache "
144
		        + " FROM " + type.getSimpleName() + " AS r LEFT OUTER JOIN r.authorship AS ab ";
145

    
146
		if (refType != null || pattern != null){
147
		    queryString += " WHERE (1=1) ";
148
		    if (refType != null ){
149
		        queryString += " AND (r.type = :type) ";// OR r.type = :genericType) " ;
150
		    }
151
		    if (pattern != null){
152
		        queryString += " AND (r.titleCache LIKE :pattern) ";
153
		    }
154
		}
155

    
156
		Query query;
157
		//if (pattern != null){
158
		    query = session.createQuery(queryString);
159
//		}else{
160
//		    query = session.createQuery("SELECT " +"r.uuid, r.id, r.titleCache, ab.titleCache FROM " + type.getSimpleName() + " AS r LEFT OUTER JOIN r.authorship AS ab ");//"select uuid, titleCache from " + type.getSimpleName());
161
//		}
162

    
163
		if (limit != null){
164
		    query.setMaxResults(limit);
165
		}
166
		if (pattern != null){
167
		      pattern = pattern.replace("*", "%");
168
		      pattern = pattern.replace("?", "_");
169
		      pattern = pattern + "%";
170
	          query.setParameter("pattern", pattern);
171
	    }
172
		if (refType != null){
173
		    query.setParameter("type", refType);
174
		   // query.setParameter("genericType", ReferenceType.Generic);
175
		}
176
		@SuppressWarnings("unchecked")
177
        List<Object[]> result = query.list();
178

    
179
		for(Object[] object : result){
180
			String referenceTitle = (String) object[2];
181

    
182
			if(referenceTitle != null){
183
				String teamTitle = (String) object[3];
184
				referenceTitle = DefaultReferenceCacheStrategy.putAuthorToEndOfString(referenceTitle, teamTitle);
185

    
186
				list.add(new UuidAndTitleCache<Reference>(Reference.class, (UUID) object[0],(Integer)object[1], referenceTitle));
187
			}else{
188
				logger.warn("Title cache of reference is null. This should not happen. Please fix data. UUID: " + object[0]);
189
			}
190
		}
191

    
192
		return list;
193
	}
194

    
195
	@Override
196
	public List<Object[]> findByIdentifierAbbrev(String identifier, DefinedTermBase identifierType,
197
            MatchMode matchmode,Integer limit){
198
	    checkNotInPriorView("IdentifiableDaoBase.findByIdentifier(T clazz, String identifier, DefinedTerm identifierType, MatchMode matchmode, Integer pageSize, Integer pageNumber, List<OrderHint> orderHints, List<String> propertyPaths)");
199

    
200

    
201
        String queryString = "SELECT ids.type, ids.identifier, %s FROM %s as c " +
202
                " INNER JOIN c.identifiers as ids " +
203
                " WHERE (1=1) ";
204
        queryString = String.format(queryString, "c.uuid, c.titleCache, c.abbrevTitleCache" , "Reference");
205

    
206
        //Matchmode and identifier
207
        if (identifier != null){
208
            if (matchmode == null || matchmode == MatchMode.EXACT){
209
                queryString += " AND ids.identifier = '"  + identifier + "'";
210
            }else {
211
                queryString += " AND ids.identifier LIKE '" + matchmode.queryStringFrom(identifier)  + "'";
212
            }
213
        }
214
        if (identifierType != null){
215
            queryString += " AND ids.type = :type";
216
        }
217
        //order
218
        queryString +=" ORDER BY ids.type.uuid, ids.identifier, c.uuid ";
219

    
220
        Query query = getSession().createQuery(queryString);
221

    
222
        //parameters
223
        if (identifierType != null){
224
            query.setEntity("type", identifierType);
225
        }
226

    
227

    
228

    
229
        List<Object[]> results = query.list();
230
        //initialize
231

    
232
        return results;
233
	}
234

    
235
	@Override
236
    public List<Reference> getAllReferencesForPublishing(){
237
		@SuppressWarnings("unchecked")
238
        List<Reference> references = getSession().createQuery("SELECT r FROM Reference r "+
239
				"WHERE r.id IN "+
240
					"(SELECT m.markedObj.id FROM Marker m WHERE "+
241
						"m.markerType.id = "+
242
							"(SELECT dtb.id FROM DefinedTermBase dtb, Representation r WHERE r MEMBER OF dtb.representations AND r.text='publish'))").list();
243
		return references;
244
	}
245

    
246
	@Override
247
    public List<Reference> getAllNotNomenclaturalReferencesForPublishing(){
248

    
249
		@SuppressWarnings("unchecked")
250
        List<Reference> references = getSession().createQuery("select t.nomenclaturalReference from TaxonName t").list();
251
		String queryString = "from Reference b where b not in (:referenceList) and b in (:publish)" ;
252
		Query referenceQuery = getSession().createQuery(queryString).setParameterList("referenceList", references);
253
		referenceQuery.setParameterList("publish", getAllReferencesForPublishing());
254
		@SuppressWarnings("unchecked")
255
        List<Reference> resultRefernces =referenceQuery.list();
256

    
257
		return resultRefernces;
258
	}
259

    
260
	// the result list held doubles therefore I put a "distinct" in the query string
261
	@Override
262
    public List<Reference> getAllNomenclaturalReferences() {
263
		@SuppressWarnings("unchecked")
264
        List<Reference> references = getSession().createQuery(
265
				"SELECT DISTINCT t.nomenclaturalReference FROM TaxonName t").list();
266
		return references;
267
	}
268

    
269

    
270
    @Override
271
	public List<Reference> getSubordinateReferences(Reference reference) {
272

    
273
		List<Reference> references = new ArrayList<>();
274
		List<Reference> subordinateReferences = new ArrayList<>();
275

    
276
		Query query = getSession().createQuery("select r from Reference r where r.inReference = (:reference)");
277
		query.setParameter("reference", reference);
278

    
279
		@SuppressWarnings("unchecked")
280
	    List<Reference> list = query.list();
281
	    references.addAll(list);
282
		for(Reference ref : references){
283
			subordinateReferences.addAll(getSubordinateReferences(ref));
284
		}
285
		references.addAll(subordinateReferences);
286
		return references;
287
	}
288

    
289
    @Override
290
	public List<TaxonBase> listCoveredTaxa(Reference reference, boolean includeSubordinateReferences,
291
	        List<OrderHint> orderHints, List<String> propertyPaths) {
292

    
293
		/*
294
		 * <li>taxon.name.nomenclaturalreference</li>
295
		 * <li>taxon.descriptions.descriptionElement.sources.citation</li>
296
		 * <li>taxon.descriptions.descriptionSources</li>
297
		 * <li>taxon.name.descriptions.descriptionElement.sources</li>
298
		 * <li>taxon.name.descriptions.descriptionSources</li>
299
		 */
300

    
301
		//TODO implement search in nameDescriptions
302
		Set<Reference> referenceSet = new HashSet<>();
303
		referenceSet.add(reference);
304
		if(includeSubordinateReferences){
305
			referenceSet.addAll(getSubordinateReferences(reference));
306
		}
307

    
308
		StringBuilder taxonDescriptionSql = new StringBuilder();
309
		taxonDescriptionSql.append(
310
			"SELECT DISTINCT t from Taxon t " +
311
			// TaxonDescription
312
			"LEFT JOIN t.descriptions td " +
313
			"LEFT JOIN td.descriptionSources td_s " +
314
			"LEFT JOIN td.descriptionElements td_e " +
315
			"LEFT JOIN td_e.sources td_e_s " +
316
			// TaxonNameDescription
317
			"LEFT JOIN t.name n " +
318
			"LEFT JOIN n.descriptions nd " +
319
			"LEFT JOIN nd.descriptionSources nd_s " +
320
			"LEFT JOIN nd.descriptionElements nd_e " +
321
			"LEFT JOIN nd_e.sources nd_e_s " +
322
			//nomenclatural citation
323
			"LEFT JOIN n.nomenclaturalSource ns " +
324

    
325
			"WHERE td_e_s.citation IN (:referenceBase_1) " +
326
			  " OR td_s IN (:referenceBase_2) " +
327
			  " OR nd_e_s.citation IN (:referenceBase_3) " +
328
			  " OR nd_s IN (:referenceBase_4) " +
329
			  " OR ns.citation IN (:referenceBase_5) " +
330
			  " OR t.sec IN (:referenceBase_6)"
331
			);
332

    
333
		if (orderHints != null && orderHints.size() > 0){
334
		    taxonDescriptionSql.append(" order by ");
335
		    int i = 0;
336
		    for (OrderHint hint : orderHints) {
337
		        if(i > 0) {
338
		            taxonDescriptionSql.append(", ");
339
		        }
340
		        taxonDescriptionSql.append("t.").append(hint.toHql());
341
            }
342
		}
343

    
344
		// TODO include:
345
		// name relations
346
		// taxon relations
347

    
348
		Query query = getSession().createQuery(taxonDescriptionSql.toString());
349
		query.setParameterList("referenceBase_1", referenceSet);
350
		query.setParameterList("referenceBase_2", referenceSet);
351
		query.setParameterList("referenceBase_3", referenceSet);
352
		query.setParameterList("referenceBase_4", referenceSet);
353
		query.setParameterList("referenceBase_5", referenceSet);
354
		query.setParameterList("referenceBase_6", referenceSet);
355

    
356
		@SuppressWarnings("unchecked")
357
        List<TaxonBase> taxonBaseList = query.list();
358

    
359
		defaultBeanInitializer.initializeAll(taxonBaseList, propertyPaths);
360

    
361
		return taxonBaseList;
362
	}
363

    
364
    @Override
365
    public List<UuidAndTitleCache<Reference>> getUuidAndAbbrevTitleCache(Integer limit, String pattern, ReferenceType refType) {
366
        Session session = getSession();
367

    
368
        Query query = null;
369
        if (pattern != null){
370
            if (pattern.startsWith("*")){
371
                query = session.createQuery("select uuid, id, abbrevTitleCache, titleCache from " + type.getSimpleName() +" where abbrevTitleCache like :pattern OR titleCache like :pattern ");
372
            }else{
373
                query = session.createQuery("select uuid, id, abbrevTitleCache, titleCache from " + type.getSimpleName() +" where abbrevTitleCache like :pattern  ");
374
            }
375
            pattern = pattern + "%";
376
            pattern = pattern.replace("*", "%");
377
            pattern = pattern.replace("?", "_");
378
            query.setParameter("pattern", pattern);
379
        } else {
380
            query = session.createQuery("select uuid, id, abbrevTitleCache, titleCache from " + type.getSimpleName() );
381
        }
382
        if (limit != null){
383
           query.setMaxResults(limit);
384
        }
385

    
386
        return getUuidAndAbbrevTitleCache(query);
387

    
388
    }
389

    
390
    @Override
391
    public List<UuidAndTitleCache<Reference>> getUuidAndAbbrevTitleCacheForAuthor(Integer limit, String pattern, ReferenceType refType) {
392
        Session session = getSession();
393

    
394
        Query query = null;
395
        if (pattern != null){
396
            query = session.createQuery("SELECT uuid, id, abbrevTitleCache, titleCache from " + type.getSimpleName()
397
            +" as r where r.authorship.nomenclaturalTitle like :pattern  ");
398

    
399
            query.setParameter("pattern", pattern);
400
        } else {
401
            query = session.createQuery("select uuid, id, abbrevTitleCache, titleCache from " + type.getSimpleName() );
402
        }
403
        if (limit != null){
404
           query.setMaxResults(limit);
405
        }
406
        if(pattern != null){
407
            pattern = pattern.replace("*", "%");
408
            pattern = pattern.replace("?", "_");
409
            query.setParameter("pattern", pattern);
410
        }
411
        return getUuidAndAbbrevTitleCache(query);
412

    
413
    }
414

    
415
    @Override
416
    public List<Reference> findByTitleAndAbbrevTitle(Class clazz, String queryString, MatchMode matchmode, List<Criterion> criterion, Integer pageSize, Integer pageNumber, List<OrderHint> orderHints, List<String> propertyPaths) {
417
        Set<String> params = new HashSet<>();
418
        params.add("titleCache");
419
        params.add("abbrevTitleCache");
420

    
421
        return findByParam(clazz, params, queryString, matchmode, criterion, pageSize, pageNumber, orderHints, propertyPaths);
422
    }
423

    
424
}
(2-2/2)