This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
TextFlowTargetHistoryDAO.java
278 lines (257 loc) · 12.8 KB
/
TextFlowTargetHistoryDAO.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
* Copyright 2010, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.dao;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.ResultTransformer;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.zanata.model.HPerson;
import org.zanata.model.HTextFlowTarget;
import org.zanata.model.HTextFlowTargetHistory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
@Name("textFlowTargetHistoryDAO")
@AutoCreate
@Scope(ScopeType.STATELESS)
public class TextFlowTargetHistoryDAO extends
AbstractDAOImpl<HTextFlowTargetHistory, Long> {
public TextFlowTargetHistoryDAO() {
super(HTextFlowTargetHistory.class);
}
public TextFlowTargetHistoryDAO(Session session) {
super(HTextFlowTargetHistory.class, session);
}
/**
* Query to get total wordCount of a person(translated_by_id) from
* HTextFlowTarget union HTextFlowTargetHistory tables
* in a project-version, within given date range group by state and locale.
*
* HTextFlowTargetHistory:
* gets latest of all records translated from user in given version,
* locale and dateRange and its target is not translated by same person.
*
* HTextFlowTarget:
* gets all records translated from user in given version, locale and
* dateRange.
*
* @param versionId HProjectIteration identifier
* @param personId HPerson identifier
* @param from start of date range
* @param to end of date range
*
* @return list of Object[wordCount][contentState][localeId]
*/
@NativeQuery
public List<Object[]> getUserContributionStatisticInVersion(
Long versionId, Long personId, Date from, Date to) {
StringBuilder queryString = new StringBuilder();
queryString
.append("select sum(wordCount), state, localeId from ")
.append("(select wordCount, id, state, localeId from ")
.append("(select h.state, tft.id, h.translated_by_id, tf.wordCount, locale.localeId ")
.append("from HTextFlowTargetHistory h ")
.append("JOIN HTextFlowTarget tft ON tft.id = h.target_id ")
.append("JOIN HLocale locale ON locale.id = tft.locale ")
.append("JOIN HTextFlow tf ON tf.id = tft.tf_id ")
.append("JOIN HDocument doc ON doc.id = tf.document_Id ")
.append("where doc.project_iteration_id =:versionId ")
.append("and h.state <> 0 ")
.append("and h.translated_by_id =:personId ")
.append("and h.lastChanged between :from and :to ")
.append("and tft.translated_by_id <> h.translated_by_id ")
.append("and h.lastChanged = ")
.append("(select max(lastChanged) from HTextFlowTargetHistory where h.target_id = target_id) ")
.append("union all ")
.append("select tft.state, tft.id, tft.translated_by_id, tf.wordCount, locale.localeId ")
.append("from HTextFlowTarget tft ")
.append("JOIN HLocale locale ON locale.id = tft.locale ")
.append("JOIN HTextFlow tf ON tf.id = tft.tf_id ")
.append("JOIN HDocument doc ON doc.id = tf.document_Id ")
.append("where doc.project_iteration_id =:versionId ")
.append("and tft.state <> 0 ")
.append("and tft.translated_by_id =:personId ")
.append("and tft.lastChanged between :from and :to ")
.append(") as target_history_union ")
.append("group by state, id, localeId, wordCount) as target_history_group ")
.append("group by state, localeId");
Query query = getSession().createSQLQuery(queryString.toString());
query.setParameter("versionId", versionId);
query.setParameter("personId", personId);
query.setTimestamp("from", from);
query.setTimestamp("to", to);
query.setComment("textFlowTargetHistoryDAO.getUserContributionStatisticInVersion");
return query.list();
}
public boolean findContentInHistory(HTextFlowTarget target,
List<String> contents) {
// Ordinal parameters can't be used in NamedQueries due to the following
// bug:
// https://hibernate.onjira.com/browse/HHH-5653
Query query;
// use named queries for the smaller more common cases
if (contents.size() <= 6) {
query =
getSession().getNamedQuery(
HTextFlowTargetHistory
.getQueryNameMatchingHistory(contents
.size()));
} else {
StringBuilder queryStr =
new StringBuilder(
"select count(*) from HTextFlowTargetHistory t where t.textFlowTarget = :tft and size(t.contents) = :contentCount");
for (int i = 0; i < contents.size(); i++) {
queryStr.append(" and contents[" + i + "] = :content" + i);
}
query = getSession().createQuery(queryStr.toString());
}
query.setParameter("tft", target);
query.setParameter("contentCount", contents.size());
int paramPos = 0;
for (String c : contents) {
query.setParameter("content" + paramPos++, c);
}
query.setComment("TextFlowTargetHistoryDAO.findContentInHistory-"
+ contents.size());
return (Long) query.uniqueResult() != 0;
}
public boolean findConflictInHistory(HTextFlowTarget target,
Integer verNum, String username) {
Query query =
getSession()
.createQuery(
"select count(*) from HTextFlowTargetHistory t where t.textFlowTarget.id =:id and t.textFlowRevision > :ver and t.lastModifiedBy.account.username != :username");
query.setParameter("id", target.getId());
query.setParameter("ver", verNum);
query.setParameter("username", username);
query.setComment("TextFlowTargetHistoryDAO.findConflictInHistory");
Long count = (Long) query.uniqueResult();
return count != 0;
}
/**
* Query to get total wordCount of a person(translated_by_id or
* reviewed_by_id) from HTextFlowTarget union HTextFlowTargetHistory tables
* within given date range group by lastChangeDate (date portion only),
* project version, locale and state.
*
* HTextFlowTargetHistory: gets all records translated from user in any
* version, any locale and dateRange.
*
* HTextFlowTarget: gets all records translated from user in any version,
* any locale and dateRange.
*
* @param user
* a HPerson person
* @param fromDate
* date from
* @param toDate
* date to
*
* @param userZoneOpt
* optional DateTimeZone of the user. Only present if it's
* different from system time zone
* @param systemZone
* current system time zone
* @param resultTransformer
* result transformer to transform query results
* @return a list of transformed object
*/
@NativeQuery(value = "need to use union", specificTo = "mysql due to usage of date() and convert_tz() functions.")
public <T> List<T> getUserTranslationMatrix(
HPerson user, DateTime fromDate, DateTime toDate,
Optional<DateTimeZone> userZoneOpt, DateTimeZone systemZone,
ResultTransformer resultTransformer) {
// @formatter:off
String queryHistory = "select history.id, iter.id as iteration, tft.locale as locale, tf.wordCount as wordCount, history.state as state, history.lastChanged as lastChanged " +
" from HTextFlowTargetHistory history " +
" join HTextFlowTarget tft on tft.id = history.target_id " +
" join HTextFlow tf on tf.id = tft.tf_id " +
" join HDocument doc on doc.id = tf.document_id " +
" join HProjectIteration iter on iter.id = doc.project_iteration_id " +
" where history.lastChanged >= :fromDate and history.lastChanged <= :toDate " +
" and history.last_modified_by_id = :user and (history.translated_by_id is not null or history.reviewed_by_id is not null)" +
" and history.state <> 0";
String queryTarget = "select tft.id, iter.id as iteration, tft.locale as locale, tf.wordCount as wordCount, tft.state as state, tft.lastChanged as lastChanged " +
" from HTextFlowTarget tft " +
" join HTextFlow tf on tf.id = tft.tf_id " +
" join HDocument doc on doc.id = tf.document_id " +
" join HProjectIteration iter on iter.id = doc.project_iteration_id " +
" where tft.lastChanged >= :fromDate and tft.lastChanged <= :toDate " +
" and tft.last_modified_by_id = :user and (tft.translated_by_id is not null or tft.reviewed_by_id is not null)" +
" and tft.state <> 0";
String convertedLastChanged = convertTimeZoneFunction("lastChanged",
userZoneOpt, systemZone);
// @formatter:on
String dateOfLastChanged = stripTimeFromDateTimeFunction(convertedLastChanged);
String queryString =
"select " + dateOfLastChanged + ", iteration, locale, state, sum(wordCount)" +
" from (" +
" (" + queryHistory + ") union (" + queryTarget + ")" +
" ) as all_translation" +
" group by " + dateOfLastChanged + ", iteration, locale, state " +
" order by lastChanged, iteration, locale, state";
Query query = getSession().createSQLQuery(queryString)
.setParameter("user", user.getId())
.setTimestamp("fromDate", fromDate.toDate())
.setTimestamp("toDate", toDate.toDate())
.setResultTransformer(resultTransformer);
return query.list();
}
@VisibleForTesting
protected String convertTimeZoneFunction(String columnName,
Optional<DateTimeZone> userZoneOpt, DateTimeZone systemZone) {
if (userZoneOpt.isPresent()) {
String userOffset = getOffsetAsString(userZoneOpt.get());
String systemOffset = getOffsetAsString(systemZone);
return String.format("CONVERT_TZ(%s, '%s', '%s')", columnName, systemOffset, userOffset);
}
// no need to convert timezone
return columnName;
}
// This is so we can override it in test and be able to test it against h2
@VisibleForTesting
protected String stripTimeFromDateTimeFunction(String columnName) {
return "date(" + columnName + ")";
}
@SuppressWarnings("unchecked")
private <T> T loadById(Object object, Class<T> entityClass) {
return (T) getSession().byId(entityClass).load(
((BigInteger) object).longValue());
}
private static String getOffsetAsString(DateTimeZone zone) {
int standardOffset = zone.getStandardOffset(0);
String prefix = "";
if (standardOffset < 0) {
prefix = "-";
standardOffset = -standardOffset;
}
return String.format("%s%02d:00", prefix,
TimeUnit.MILLISECONDS.toHours(standardOffset));
}
}