Project

General

Profile

Download (7.56 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.Collections;
15
import java.util.Comparator;
16
import java.util.HashMap;
17
import java.util.HashSet;
18
import java.util.Iterator;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.Optional;
22
import java.util.Set;
23

    
24
import org.apache.log4j.Logger;
25
import org.apache.lucene.search.Sort;
26
import org.apache.lucene.search.SortField;
27
import org.hibernate.Criteria;
28
import org.hibernate.HibernateException;
29
import org.hibernate.Session;
30
import org.hibernate.SessionFactory;
31
import org.hibernate.criterion.Criterion;
32
import org.hibernate.search.FullTextQuery;
33
import org.springframework.beans.factory.annotation.Autowired;
34

    
35
import eu.etaxonomy.cdm.persistence.query.OrderHint;
36

    
37
public abstract class DaoBase {
38

    
39
    final static Logger logger = Logger.getLogger(DaoBase.class);
40

    
41
    public final static boolean NO_UNPUBLISHED = false;  //constant for unpublished
42
    public final static boolean INCLUDE_UNPUBLISHED = true;  //constant for unpublished
43

    
44
    @Autowired
45
    private SessionFactory factory;
46

    
47
    public void setSessionFactory(SessionFactory sessionFactory) {
48
        this.factory = sessionFactory;
49
    }
50
    public SessionFactory getSessionFactory() {
51
        return factory;
52
    }
53
    protected Session getSession(){
54
        Session session ;
55
        try {
56

    
57
            session = factory.getCurrentSession();
58
        } catch (HibernateException e) {
59
            logger.error("Opening new session in turn of a HibernateException", e);
60
            session = factory.openSession();
61
        }
62
        return session;
63
    }
64

    
65
    public void flush(){
66
        getSession().flush();
67
    }
68

    
69
    private class OrderHintComparator implements Comparator<OrderHint> {
70

    
71
        @Override
72
        public int compare(OrderHint o1, OrderHint o2) {
73
            if (o1.equals(o2)){
74
                return 0;
75
            }
76
            int result = o1.getPropertyName().compareTo(o2.getPropertyName());
77
            if (result == 0){
78
                result = o1.toString().compareTo(o2.toString());
79
            }
80
            return result;
81
        }
82

    
83
    }
84

    
85
    /**
86
     * Splits a set of e.g. query parameters into a list of sets with size <code>splitSize</code>.
87
     * Only the last set may be smaller if the collection's size is not an exact multiple of split size.
88
     * @param collection the collection to split
89
     * @param splitSize the split size
90
     * @return a list of collections
91
     */
92
    protected <T extends Object> List<Collection<T>> splitCollection(Set<T> collection, int splitSize) {
93
        if (splitSize < 1){
94
            throw new IllegalArgumentException("Split size must not be positive integer");
95
        }
96
        List<Collection<T>> result = new ArrayList<>();
97
        Iterator<T> it = collection.iterator();
98
        int i = 0;
99
        Set<T> nextCollection = new HashSet<>();
100
        while (it.hasNext()){
101
            nextCollection.add(it.next());
102
            i++;
103
            if (i == splitSize){
104
                result.add(nextCollection);
105
                nextCollection = new HashSet<>();
106
                i = 0;
107
            }
108
        }
109
        if (!nextCollection.isEmpty()){
110
            result.add(nextCollection);
111
        }
112
        return result;
113
    }
114

    
115
    // -------------- hql, query and criteria helper methods -------------- //
116

    
117
    protected void addFieldPredicate(StringBuilder hql, String field, Optional<String> value) {
118
        if(value != null){
119
            hql.append("and " + field);
120
            if(value.isPresent()){
121
                if(value.get().contains("*")){
122
                    hql.append(" like '" + value.get().replace('*', '%') + "' ");
123
                } else {
124
                    hql.append(" = '" + value.get() + "' ");
125
                }
126
            } else {
127
                hql.append(" is null ");
128
            }
129
        }
130
    }
131
    /**
132
     * @param limit
133
     * @param start
134
     * @param criteria
135
     */
136
    protected void addLimitAndStart(Integer limit, Integer start, Criteria criteria) {
137
        if(limit != null) {
138
            if(start != null) {
139
                criteria.setFirstResult(start);
140
            } else {
141
                criteria.setFirstResult(0);
142
            }
143
            criteria.setMaxResults(limit);
144
        }
145
    }
146

    
147
    protected void addCriteria(Criteria criteria, List<Criterion> criterion) {
148
        if(criterion != null) {
149
            for(Criterion c : criterion) {
150
                criteria.add(c);
151
            }
152
        }
153
    }
154

    
155
    /**
156
     * Null save method which compiles an order by clause from the given list of OrderHints
157
     *
158
     * @param orderHints can be NULL
159
     * @return a StringBuffer holding the hql orderby clause
160
     */
161
    protected StringBuffer orderByClause(List<OrderHint> orderHints, String aliasName) {
162

    
163
        StringBuffer orderString = new StringBuffer();
164

    
165
        StringBuffer aliasPrefix = new StringBuffer(" ");
166
        if(aliasName != null && !aliasName.isEmpty()){
167
            aliasPrefix.append(aliasName).append(".");
168
        }
169

    
170
        if(orderHints != null && !orderHints.isEmpty()) {
171
            orderString.append(" ORDER BY ");
172
            for(OrderHint orderHint : orderHints) {
173
                orderString.append(aliasPrefix).append(orderHint.toHql());
174
            }
175
        }
176
        return orderString;
177
    }
178
    protected void addOrder(Criteria criteria, List<OrderHint> orderHints) {
179

    
180
        if(orderHints != null){
181
            Collections.sort(orderHints, new OrderHintComparator());
182

    
183
            Map<String,Criteria> criteriaMap = new HashMap<>();
184
            for(OrderHint orderHint : orderHints){
185
                orderHint.add(criteria, criteriaMap);
186
            }
187
        }
188
    }
189
    protected void addOrder(FullTextQuery fullTextQuery, List<OrderHint> orderHints) {
190
        //FIXME preliminary hardcoded type:
191
        SortField.Type type = SortField.Type.STRING;
192

    
193
        if(orderHints != null && !orderHints.isEmpty()) {
194
            org.apache.lucene.search.Sort sort = new Sort();
195
            SortField[] sortFields = new SortField[orderHints.size()];
196
            for(int i = 0; i < orderHints.size(); i++) {
197
                OrderHint orderHint = orderHints.get(i);
198
                switch(orderHint.getSortOrder()) {
199
                case ASCENDING:
200
                    sortFields[i] = new SortField(orderHint.getPropertyName(), type, true);
201
                    break;
202
                case DESCENDING:
203
                default:
204
                    sortFields[i] = new SortField(orderHint.getPropertyName(), type, false);
205
                }
206
            }
207
            sort.setSort(sortFields);
208
            fullTextQuery.setSort(sort);
209
        }
210
    }
211

    
212
    /**
213
     * @param hql
214
     * @param orderHints
215
     */
216
    protected void addOrder(StringBuilder hql, String alias, List<OrderHint> orderHints) {
217
        boolean orderByAdded = false;
218
        String fieldPrefix = "";
219
        if(alias != null){
220
            fieldPrefix = alias + ".";
221
        }
222
        if(orderHints != null && !orderHints.isEmpty()){
223
            for(OrderHint oh : orderHints){
224
                if(oh != null){
225
                    if(!orderByAdded){
226
                        hql.append(" order by ");
227
                    }
228
                    hql.append(fieldPrefix + oh.toHql() + (orderByAdded ? ", ": " "));
229
                    orderByAdded = true;
230
                }
231
            }
232

    
233
        }
234
    }
235

    
236
   // ---------------------------- //
237

    
238
}
(5-5/24)