Project

General

Profile

Download (7.63 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.persistence.dao.hibernate.description;
2

    
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.HashSet;
6
import java.util.List;
7
import java.util.Map;
8
import java.util.Set;
9
import java.util.UUID;
10

    
11
import org.apache.log4j.Logger;
12
import org.hibernate.Criteria;
13
import org.hibernate.Query;
14
import org.hibernate.Session;
15
import org.hibernate.criterion.Restrictions;
16
import org.springframework.beans.factory.annotation.Qualifier;
17
import org.springframework.stereotype.Repository;
18

    
19
import eu.etaxonomy.cdm.model.description.CategoricalData;
20
import eu.etaxonomy.cdm.model.description.DescriptionBase;
21
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
22
import eu.etaxonomy.cdm.model.description.DescriptiveSystemRole;
23
import eu.etaxonomy.cdm.model.description.Feature;
24
import eu.etaxonomy.cdm.model.description.QuantitativeData;
25
import eu.etaxonomy.cdm.model.description.WorkingSet;
26
import eu.etaxonomy.cdm.persistence.dao.description.IWorkingSetDao;
27
import eu.etaxonomy.cdm.persistence.dao.hibernate.common.IdentifiableDaoBase;
28
import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
29

    
30
@Repository
31
@Qualifier("workingSetDaoImpl")
32
public class WorkingSetDao
33
        extends IdentifiableDaoBase<WorkingSet>
34
        implements IWorkingSetDao {
35
	private static final Logger logger = Logger.getLogger(WorkingSetDao.class);
36

    
37
	public WorkingSetDao() {
38
		super(WorkingSet.class);
39
	}
40

    
41
	@Override
42
    public Map<DescriptionBase, Set<DescriptionElementBase>> getDescriptionElements(WorkingSet workingSet, Set<Feature> features, Integer pageSize,	Integer pageNumber,	List<String> propertyPaths) {
43
		checkNotInPriorView("WorkingSetDao.getDescriptionElements(WorkingSet workingSet, Set<Feature> features, Integer pageSize,Integer pageNumber, List<String> propertyPaths)");
44
		Query query = getSession().createQuery("SELECT description FROM WorkingSet workingSet JOIN workingSet.descriptions description ORDER BY description.titleCache ASC");
45

    
46
		if(pageSize != null) {
47
			query.setMaxResults(pageSize);
48
	        if(pageNumber != null) {
49
	        	query.setFirstResult(pageNumber * pageSize);
50
	        } else {
51
	        	query.setFirstResult(0);
52
	        }
53
	    }
54
		List<DescriptionBase> descriptions = query.list();
55
		Map<DescriptionBase, Set<DescriptionElementBase>> result = new HashMap<>();
56
		for(DescriptionBase description : descriptions) {
57
			Criteria criteria = getSession().createCriteria(DescriptionElementBase.class);
58
			criteria.add(Restrictions.eq("inDescription", description));
59
			if(features != null && !features.isEmpty()) {
60
				criteria.add(Restrictions.in("feature", features));
61
			}
62

    
63
			List<DescriptionElementBase> r = criteria.list();
64
			defaultBeanInitializer.initializeAll(r, propertyPaths);
65
			result.put(description, new HashSet<>(r));
66
		}
67
		return result;
68
	}
69

    
70
	@Override
71
	public <T extends DescriptionElementBase> Map<UuidAndTitleCache, Map<UUID, Set<T>>> getTaxonFeatureDescriptionElementMap(Class<T> clazz, UUID workingSetUuid, DescriptiveSystemRole role) {
72
		checkNotInPriorView("WorkingSetDao.getTaxonFeatureDescriptionElementMap(WorkingSet workingSet, Set<Feature> features, Integer pageSize,Integer pageNumber, List<OrderHint> orderHints,	List<String> propertyPaths)");
73
		Map<UuidAndTitleCache, Map<UUID, Set<T>>> result = new HashMap<UuidAndTitleCache, Map<UUID, Set<T>>>();
74
		try {
75

    
76
			//for maps see
77
//			http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html
78
//			Elements of indexed collections (arrays, lists, and maps) can be referred to by index in a where clause only:
79
//
80
//			Example: from Order order where order.items[0].id = 1234
81

    
82

    
83
			//feature
84
			String strQueryTreeId = "SELECT ws.descriptiveSystem.id FROM WorkingSet ws join ws.descriptiveSystem tree WHERE ws.uuid = :workingSetUuid ";
85
			Query queryTree = getSession().createQuery(strQueryTreeId);
86
			queryTree.setParameter("workingSetUuid", workingSetUuid);
87
			List<?> trees = queryTree.list();
88

    
89

    
90
			String ftSelect = "SELECT feature.id FROM FeatureNode node join node.feature as feature " +
91
					" WHERE node.featureTree.id in (:trees) ";
92
			Query ftQuery = getSession().createQuery(ftSelect);
93
			ftQuery.setParameterList("trees", trees);
94
			List<?> features = ftQuery.list();
95

    
96
			String strClass = (clazz == null )? "DescriptionElementBase" : clazz.getSimpleName();
97

    
98
			String fetch = "";
99
			if (clazz.equals(CategoricalData.class)){
100
				fetch = " left join fetch el.states stateList join fetch stateList.state ";
101
			}else if (clazz.equals(QuantitativeData.class)){
102
				fetch = " left join fetch el.statisticalValues valueList join fetch valueList.type ";
103
			}
104

    
105
			String strQuery = " select taxon.uuid, taxon.id, taxon.titleCache, feature.uuid, el "
106
				+ " from " + strClass + " el "
107
				+ " join el.feature feature "
108
				+ " join el.inDescription d "
109
				+ " join d.taxon taxon "
110
				+ " join d.workingSets ws "
111
				+ " join ws.descriptiveSystem ftree "
112
				+ fetch
113
				+ " where ws.uuid = :workingSetUuid "
114
					+ " and el.class = :clazz "
115
					+ " and feature.id in (:features)  "
116
				+ " order by taxon.uuid asc, feature.uuid asc"
117
				;
118
			Query query = getSession().createQuery(strQuery);
119

    
120
			query.setParameter("workingSetUuid", workingSetUuid);
121
			query.setParameter("clazz", clazz.getSimpleName());
122
			query.setParameterList("features", features);
123

    
124
			//NOTE: Paging does not work with fetch
125

    
126
			// fill result
127
			@SuppressWarnings("unchecked")
128
            List<Object[]> list = query.list();
129
			for (Object[] listEntry : list){
130
				UUID taxonUuid = (UUID)listEntry[0];
131
				Integer id = (Integer)listEntry[1];
132
				String titleCache = (String)listEntry[2];
133
				UuidAndTitleCache taxon = new UuidAndTitleCache(taxonUuid, id, titleCache);
134
				UUID featureUuid = (UUID)listEntry[3];
135
                T data = (T)listEntry[4];
136
				Map<UUID, Set<T>> taxonMap = result.get(taxon);
137
				if (taxonMap == null){
138
					taxonMap = new HashMap<UUID, Set<T>>();
139
					result.put(taxon, taxonMap);
140
				}
141
				Set<T> featureSet = taxonMap.get(featureUuid);
142
				if (featureSet == null){
143
					featureSet = new HashSet<T>();
144
					taxonMap.put(featureUuid, featureSet);
145
				}else{
146
					if (logger.isDebugEnabled()){logger.debug("feature set already exists");}
147
				}
148
				featureSet.add(data);
149

    
150
			}
151

    
152
//			defaultBeanInitializer.initialize(
153

    
154
			return result;
155
		} catch (Exception e) {
156
			e.printStackTrace();
157
			throw new RuntimeException(e);
158
		}
159
	}
160

    
161
    /**
162
     * {@inheritDoc}
163
     */
164
    @Override
165
    public List<UuidAndTitleCache<WorkingSet>> getWorkingSetUuidAndTitleCache(Integer limitOfInitialElements,
166
            String pattern) {
167
        Session session = getSession();
168

    
169
        String queryString = "SELECT uuid, id, label FROM WorkingSet ";
170

    
171
        if ( pattern != null){
172
            queryString += " WHERE ";
173
            queryString += " label LIKE :pattern";
174

    
175
        }
176

    
177
        Query query;
178
        query = session.createQuery(queryString);
179

    
180

    
181
        if (limitOfInitialElements != null){
182
            query.setMaxResults(limitOfInitialElements);
183
        }
184
        if (pattern != null){
185
              pattern = pattern.replace("*", "%");
186
              pattern = pattern.replace("?", "_");
187
              pattern = pattern + "%";
188
              query.setParameter("pattern", pattern);
189
        }
190

    
191
        @SuppressWarnings("unchecked")
192
        List<Object[]> result = query.list();
193
        List<UuidAndTitleCache<WorkingSet>> list = new ArrayList<>();
194
        for(Object[] object : result){
195
            list.add(new UuidAndTitleCache<WorkingSet>(WorkingSet.class, (UUID) object[0],(Integer)object[1], (String)object[2]));
196
        }
197

    
198
        return list;
199
    }
200
}
(10-10/10)