This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
TranslationServiceImpl.java
911 lines (813 loc) · 36.8 KB
/
TranslationServiceImpl.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
/*
* Copyright 2012, 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.service.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.persistence.EntityManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.TransactionPropagationType;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.core.Events;
import org.jboss.seam.security.management.JpaIdentityStore;
import org.jboss.seam.util.Work;
import org.zanata.async.AsyncTaskHandle;
import org.zanata.async.AsyncUtils;
import org.zanata.common.ContentState;
import org.zanata.common.LocaleId;
import org.zanata.common.MergeType;
import org.zanata.common.util.ContentStateUtil;
import org.zanata.dao.DocumentDAO;
import org.zanata.dao.PersonDAO;
import org.zanata.dao.ProjectIterationDAO;
import org.zanata.dao.TextFlowDAO;
import org.zanata.dao.TextFlowTargetDAO;
import org.zanata.events.DocumentUploadedEvent;
import org.zanata.events.TextFlowTargetStateEvent;
import org.zanata.exception.ZanataServiceException;
import org.zanata.lock.Lock;
import org.zanata.model.HAccount;
import org.zanata.model.HDocument;
import org.zanata.model.HLocale;
import org.zanata.model.HPerson;
import org.zanata.model.HProjectIteration;
import org.zanata.model.HSimpleComment;
import org.zanata.model.HTextFlow;
import org.zanata.model.HTextFlowTarget;
import org.zanata.model.HTextFlowTargetHistory;
import org.zanata.rest.dto.resource.TextFlowTarget;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.rest.service.ResourceUtils;
import org.zanata.security.ZanataIdentity;
import org.zanata.service.LocaleService;
import org.zanata.service.LockManagerService;
import org.zanata.service.TranslationMergeService;
import org.zanata.service.TranslationService;
import org.zanata.service.ValidationService;
import org.zanata.util.ShortString;
import org.zanata.util.ZanataMessages;
import org.zanata.webtrans.shared.model.TransUnitId;
import org.zanata.webtrans.shared.model.TransUnitUpdateInfo;
import org.zanata.webtrans.shared.model.TransUnitUpdateRequest;
import org.zanata.webtrans.shared.model.ValidationAction;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
@Name("translationServiceImpl")
@Scope(ScopeType.STATELESS)
@Transactional
@Slf4j
public class TranslationServiceImpl implements TranslationService {
@In
private EntityManager entityManager;
@In
private ProjectIterationDAO projectIterationDAO;
@In
private DocumentDAO documentDAO;
@In
private PersonDAO personDAO;
@In
private TextFlowDAO textFlowDAO;
@In
private TextFlowTargetDAO textFlowTargetDAO;
@In
private ResourceUtils resourceUtils;
@In
private LocaleService localeServiceImpl;
@In
private LockManagerService lockManagerServiceImpl;
@In
private ValidationService validationServiceImpl;
@In(value = JpaIdentityStore.AUTHENTICATED_USER, scope = ScopeType.SESSION,
required = false)
private HAccount authenticatedAccount;
@In
private ZanataIdentity identity;
@In
private TranslationMergeServiceFactory translationMergeServiceFactory;
@In
private ZanataMessages zanataMessages;
@Override
public List<TranslationResult> translate(LocaleId localeId,
List<TransUnitUpdateRequest> translationRequests) {
return translate(localeId, translationRequests, true);
}
/**
* This is used when reverting translation
*
* @param localeId
* @param translationRequests
* @return
*/
private List<TranslationResult>
translateWithoutValidating(LocaleId localeId,
List<TransUnitUpdateRequest> translationRequests) {
return translate(localeId, translationRequests, false);
}
private List<TranslationResult> translate(LocaleId localeId,
List<TransUnitUpdateRequest> translationRequests,
boolean runValidation) {
List<TranslationResult> results = new ArrayList<TranslationResult>();
// avoid locale check if there is nothing to translate
if (translationRequests.isEmpty()) {
return results;
}
// single locale check - assumes update requests are all from the same
// project-iteration
HTextFlow sampleHTextFlow =
entityManager.find(HTextFlow.class, translationRequests.get(0)
.getTransUnitId().getValue());
HProjectIteration projectIteration =
sampleHTextFlow.getDocument().getProjectIteration();
HLocale hLocale = validateLocale(localeId, projectIteration);
// single permission check - assumes update requests are all from same
// project
validateReviewPermissionIfApplicable(translationRequests,
projectIteration, hLocale);
for (TransUnitUpdateRequest request : translationRequests) {
HTextFlow hTextFlow =
entityManager.find(HTextFlow.class, request
.getTransUnitId().getValue());
TranslationResultImpl result = new TranslationResultImpl();
if (runValidation) {
String validationMessage =
validateTranslations(request.getNewContentState(),
projectIteration, request.getTransUnitId()
.toString(), hTextFlow.getContents(),
request.getNewContents());
if (!StringUtils.isEmpty(validationMessage)) {
log.warn(validationMessage);
result.isSuccess = false;
result.errorMessage = validationMessage;
continue;
}
}
HTextFlowTarget hTextFlowTarget =
textFlowTargetDAO.getOrCreateTarget(hTextFlow, hLocale);
// if hTextFlowTarget is created, any further hibernate fetch will
// trigger an implicit flush
// (which will save this target even if it's not fully ready!!!)
if (request.hasTargetComment()) {
hTextFlowTarget.setComment(new HSimpleComment(request
.getTargetComment()));
}
result.baseVersion = hTextFlowTarget.getVersionNum();
result.baseContentState = hTextFlowTarget.getState();
if (request.getBaseTranslationVersion() == hTextFlowTarget
.getVersionNum()) {
try {
int nPlurals = getNumPlurals(hLocale, hTextFlow);
result.targetChanged =
translate(hTextFlowTarget,
request.getNewContents(),
request.getNewContentState(), nPlurals,
projectIteration
.getRequireTranslationReview());
result.isSuccess = true;
} catch (HibernateException e) {
result.isSuccess = false;
log.warn("HibernateException while translating");
}
} else {
// concurrent edits not allowed
String errorMessage =
"translation failed for textflow " + hTextFlow.getId()
+ ": base versionNum + "
+ request.getBaseTranslationVersion()
+ " does not match current versionNum "
+ hTextFlowTarget.getVersionNum();
log.warn(errorMessage);
result.errorMessage = errorMessage;
result.isSuccess = false;
}
result.translatedTextFlowTarget = hTextFlowTarget;
results.add(result);
}
return results;
}
private void validateReviewPermissionIfApplicable(
List<TransUnitUpdateRequest> translationRequests,
HProjectIteration projectIteration, HLocale hLocale) {
Optional<TransUnitUpdateRequest> hasReviewRequest =
Iterables.tryFind(translationRequests,
new Predicate<TransUnitUpdateRequest>() {
@Override
public boolean apply(TransUnitUpdateRequest input) {
return isReviewState(input.getNewContentState());
}
});
if (hasReviewRequest.isPresent()) {
identity.checkPermission("translation-review",
projectIteration.getProject(), hLocale);
}
}
private static boolean isReviewState(ContentState contentState) {
return contentState == ContentState.Approved
|| contentState == ContentState.Rejected;
}
/**
* Generate a {@link HLocale} for the given localeId and check that
* translations for this locale are permitted.
*
* @param localeId
* @param projectIteration
* @return the valid hLocale
* @throws ZanataServiceException
* if the locale is not enabled for the project-iteration or
* server
*/
private HLocale validateLocale(LocaleId localeId,
HProjectIteration projectIteration) throws ZanataServiceException {
String projectSlug = projectIteration.getProject().getSlug();
return localeServiceImpl.validateLocaleByProjectIteration(localeId,
projectSlug, projectIteration.getSlug());
}
/**
* Sends out an event to signal that a Text Flow target has been translated
*/
private void signalPostTranslateEvent(HTextFlowTarget hTextFlowTarget) {
if (Events.exists()) {
HTextFlow textFlow = hTextFlowTarget.getTextFlow();
HDocument document = textFlow.getDocument();
// TODO remove hasError from DocumentStatus, so that we can pass
// everything else directly to cache
// DocumentStatus docStatus = new DocumentStatus(
// new DocumentId(document.getId(), document.getDocId()), hasError,
// hTextFlowTarget.getLastChanged(),
// hTextFlowTarget.getLastModifiedBy().getAccount().getUsername());
Events.instance()
.raiseTransactionSuccessEvent(
TextFlowTargetStateEvent.EVENT_NAME,
new TextFlowTargetStateEvent(document.getId(),
textFlow.getId(), hTextFlowTarget
.getLocale().getLocaleId(),
hTextFlowTarget.getId(), hTextFlowTarget
.getState()));
}
}
private boolean translate(@Nonnull HTextFlowTarget hTextFlowTarget,
@Nonnull List<String> contentsToSave, ContentState requestedState,
int nPlurals, Boolean requireTranslationReview) {
boolean targetChanged = false;
targetChanged |= setContentIfChanged(hTextFlowTarget, contentsToSave);
targetChanged |=
setContentStateIfChanged(requestedState, hTextFlowTarget,
nPlurals, requireTranslationReview);
if (targetChanged || hTextFlowTarget.getVersionNum() == 0) {
HTextFlow textFlow = hTextFlowTarget.getTextFlow();
hTextFlowTarget.setVersionNum(hTextFlowTarget.getVersionNum() + 1);
hTextFlowTarget.setTextFlowRevision(textFlow.getRevision());
hTextFlowTarget.setLastModifiedBy(authenticatedAccount.getPerson());
log.debug("last modified by :{}", authenticatedAccount.getPerson()
.getName());
}
// save the target histories
entityManager.flush();
// fire event after flush
if (targetChanged || hTextFlowTarget.getVersionNum() == 0) {
this.signalPostTranslateEvent(hTextFlowTarget);
}
return targetChanged;
}
/**
* @return true if the content was changed, false otherwise
*/
private boolean setContentIfChanged(
@Nonnull HTextFlowTarget hTextFlowTarget,
@Nonnull List<String> contentsToSave) {
if (!contentsToSave.equals(hTextFlowTarget.getContents())) {
hTextFlowTarget.setContents(contentsToSave);
return true;
} else {
return false;
}
}
/**
* Check that requestedState is valid for the given content, adjust if
* necessary and set the new state if it has changed.
*
* @return true if the content state or contents list were updated, false
* otherwise
* @see #adjustContentsAndState(org.zanata.model.HTextFlowTarget, int,
* java.util.List)
*/
private boolean setContentStateIfChanged(
@Nonnull ContentState requestedState,
@Nonnull HTextFlowTarget target, int nPlurals,
boolean requireTranslationReview) {
boolean changed = false;
ContentState previousState = target.getState();
target.setState(requestedState);
ArrayList<String> warnings = new ArrayList<String>();
changed |= adjustContentsAndState(target, nPlurals, warnings);
for (String warning : warnings) {
log.warn(warning);
}
if (requireTranslationReview) {
if (isReviewState(target.getState())) {
// reviewer saved it
target.setReviewer(authenticatedAccount.getPerson());
} else {
target.setTranslator(authenticatedAccount.getPerson());
}
} else {
if (target.getState() == ContentState.Approved) {
target.setState(ContentState.Translated);
}
target.setTranslator(authenticatedAccount.getPerson());
}
if (target.getState() != previousState) {
changed = true;
}
return changed;
}
/**
* Checks target state against its contents. If necessary, modifies target
* state and generates a warning
*
* @param target
* HTextFlowTarget to check/modify
* @param nPlurals
* number of plurals for this locale for this message: use 1 if
* message does not support plurals
* @param warnings
* a warning string will be added if state is adjusted
* @return true if and only if some state was changed
*/
private static boolean adjustContentsAndState(
@Nonnull HTextFlowTarget target, int nPlurals,
@Nonnull List<String> warnings) {
ContentState oldState = target.getState();
String resId = target.getTextFlow().getResId();
boolean contentsChanged =
ensureContentsSize(target, nPlurals, resId, warnings);
List<String> contents = target.getContents();
target.setState(ContentStateUtil.determineState(oldState, contents,
resId, warnings));
boolean stateChanged = (oldState != target.getState());
return contentsChanged || stateChanged;
}
/**
* Ensures that target.contents has exactly legalSize elements
*
* @param target
* HTextFlowTarget to check/modify
* @param legalSize
* required number of contents
* @param resId
* ID of target
* @param warnings
* if elements were added or removed
* @return
*/
private static boolean ensureContentsSize(HTextFlowTarget target,
int legalSize, String resId, @Nonnull List<String> warnings) {
int contentsSize = target.getContents().size();
if (contentsSize < legalSize) {
String warning =
"Should have "
+ legalSize
+ " contents; adding empty strings: TextFlowTarget "
+ resId + " with contents: " + target.getContents();
warnings.add(warning);
List<String> newContents = new ArrayList<String>(legalSize);
newContents.addAll(target.getContents());
while (newContents.size() < legalSize) {
newContents.add("");
}
target.setContents(newContents);
return true;
} else if (contentsSize > legalSize) {
String warning =
"Should have "
+ legalSize
+ " contents; discarding extra strings: TextFlowTarget "
+ resId + " with contents: " + target.getContents();
warnings.add(warning);
List<String> newContents = new ArrayList<String>(legalSize);
for (int i = 0; i < contentsSize; i++) {
String content = target.getContents().get(i);
newContents.add(content);
}
target.setContents(newContents);
return true;
}
return false;
}
@Override
// This will not run in a transaction. Instead, transactions are controlled
// within the method itself.
@Transactional(TransactionPropagationType.NEVER)
public
List<String> translateAllInDoc(String projectSlug,
String iterationSlug, String docId, LocaleId locale,
TranslationsResource translations, Set<String> extensions,
MergeType mergeType, boolean lock) {
// Lock this document for push
Lock transLock = null;
if (lock) {
transLock =
new Lock(projectSlug, iterationSlug, docId, locale, "push");
lockManagerServiceImpl.attain(transLock);
}
List<String> messages = Lists.newArrayList();
try {
messages =
this.translateAllInDoc(projectSlug, iterationSlug, docId,
locale, translations, extensions, mergeType);
} finally {
if (lock) {
lockManagerServiceImpl.release(transLock);
}
}
return messages;
}
/**
* Run enforced validation check(Error) if target has changed and
* translation saving as 'Translated' or 'Approved'
*
* @param newState
* @param projectVersion
* @param targetId
* @param sources
* @param translations
* @return error messages
*/
private String validateTranslations(ContentState newState,
HProjectIteration projectVersion, String targetId,
List<String> sources, List<String> translations) {
String message = null;
if (newState.isTranslated()) {
List<String> validationMessages =
validationServiceImpl.validateWithServerRules(
projectVersion, sources, translations,
ValidationAction.State.Error);
if (!validationMessages.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String validationMessage : validationMessages) {
sb.append(validationMessage).append("\n");
}
message =
zanataMessages.getMessage(
"jsf.TranslationContainsError",
ShortString.shorten(translations.get(0)),
sb.toString());
}
}
return message;
}
@Override
public List<String> translateAllInDoc(final String projectSlug,
final String iterationSlug, final String docId,
final LocaleId locale, final TranslationsResource translations,
final Set<String> extensions, final MergeType mergeType) {
final HProjectIteration hProjectIteration =
projectIterationDAO.getBySlug(projectSlug, iterationSlug);
if (hProjectIteration == null) {
throw new ZanataServiceException("Version '" + iterationSlug
+ "' for project '" + projectSlug + "' ");
}
if (mergeType == MergeType.IMPORT) {
identity.checkPermission("import-translation", hProjectIteration);
}
ResourceUtils.validateExtensions(extensions);
log.debug("pass evaluate");
final HDocument document =
documentDAO.getByDocIdAndIteration(hProjectIteration, docId);
if (document.isObsolete()) {
throw new ZanataServiceException("A document was not found.", 404);
}
log.debug("start put translations entity:{}", translations);
boolean changed = false;
final HLocale hLocale =
localeServiceImpl.validateLocaleByProjectIteration(locale,
projectSlug, iterationSlug);
final Optional<AsyncTaskHandle> handleOp =
AsyncUtils.getEventAsyncHandle(AsyncTaskHandle.class);
if (handleOp.isPresent()) {
handleOp.get().setMaxProgress(
translations.getTextFlowTargets().size());
}
try {
changed |= new Work<Boolean>() {
@Override
protected Boolean work() throws Exception {
// handle extensions
boolean changed =
resourceUtils
.transferFromTranslationsResourceExtensions(
translations.getExtensions(true),
document, extensions, hLocale,
mergeType);
return changed;
}
}.workInTransaction();
} catch (Exception e) {
throw new ZanataServiceException("Error during translation.", 500,
e);
}
// NB: removedTargets only applies for MergeType.IMPORT
final Collection<HTextFlowTarget> removedTargets =
new HashSet<HTextFlowTarget>();
final List<String> warnings = new ArrayList<String>();
if (mergeType == MergeType.IMPORT) {
for (HTextFlow textFlow : document.getTextFlows()) {
HTextFlowTarget hTarget =
textFlow.getTargets().get(hLocale.getId());
if (hTarget != null) {
removedTargets.add(hTarget);
}
}
}
// Break the target into batches
List<List<TextFlowTarget>> batches =
Lists.partition(translations.getTextFlowTargets(), BATCH_SIZE);
for (final List<TextFlowTarget> batch : batches) {
try {
changed |= new Work<Boolean>() {
@Override
protected Boolean work() throws Exception {
boolean changed = false;
for (TextFlowTarget incomingTarget : batch) {
String resId = incomingTarget.getResId();
HTextFlow textFlow =
textFlowDAO.getById(document, resId);
if (textFlow == null) {
// return warning for unknown resId to caller
String warning =
"Could not find TextFlow for TextFlowTarget "
+ resId + " with contents: "
+ incomingTarget.getContents();
warnings.add(warning);
log.warn(
"skipping TextFlowTarget with unknown resId: {}",
resId);
} else {
String validationMessage =
validateTranslations(
incomingTarget.getState(),
hProjectIteration,
incomingTarget.getResId(),
textFlow.getContents(),
incomingTarget.getContents());
if (!StringUtils.isEmpty(validationMessage)) {
warnings.add(validationMessage);
log.warn(validationMessage);
continue;
}
int nPlurals = getNumPlurals(hLocale, textFlow);
HTextFlowTarget hTarget =
textFlowTargetDAO.getTextFlowTarget(
textFlow, hLocale);
if (mergeType == MergeType.IMPORT) {
removedTargets.remove(hTarget);
}
TranslationMergeServiceFactory.MergeContext mergeContext =
new TranslationMergeServiceFactory.MergeContext(
mergeType, textFlow, hLocale,
hTarget, nPlurals);
TranslationMergeService mergeService =
translationMergeServiceFactory
.getMergeService(mergeContext);
boolean targetChanged =
mergeService.merge(incomingTarget,
hTarget, extensions);
if (hTarget == null) {
// in case hTarget was null, we need to
// retrieve it after merge
hTarget =
textFlow.getTargets().get(
hLocale.getId());
}
targetChanged |=
adjustContentsAndState(hTarget,
nPlurals, warnings);
// update translation information if applicable
if (targetChanged) {
hTarget.setVersionNum(hTarget
.getVersionNum() + 1);
changed = true;
if (incomingTarget.getTranslator() != null) {
String email =
incomingTarget.getTranslator()
.getEmail();
HPerson hPerson =
personDAO.findByEmail(email);
if (hPerson == null) {
hPerson = new HPerson();
hPerson.setEmail(email);
hPerson.setName(incomingTarget
.getTranslator().getName());
personDAO.makePersistent(hPerson);
}
hTarget.setTranslator(hPerson);
hTarget.setLastModifiedBy(hPerson);
} else {
hTarget.setTranslator(null);
hTarget.setLastModifiedBy(null);
}
textFlowTargetDAO.makePersistent(hTarget);
}
signalPostTranslateEvent(hTarget);
}
personDAO.flush();
textFlowTargetDAO.flush();
personDAO.clear();
textFlowTargetDAO.clear();
if (handleOp.isPresent()) {
handleOp.get().increaseProgress(1);
}
}
return changed;
}
}.workInTransaction();
} catch (Exception e) {
throw new ZanataServiceException("Error during translation.",
500, e);
}
}
if (changed || !removedTargets.isEmpty()) {
try {
new Work<Void>() {
@Override
protected Void work() throws Exception {
for (HTextFlowTarget target : removedTargets) {
target =
textFlowTargetDAO.findById(target.getId(),
true); // need to refresh from
// persistence
target.clear();
}
textFlowTargetDAO.flush();
documentDAO.flush();
return null;
}
}.workInTransaction();
if (Events.exists()) {
Events.instance().raiseEvent(
DocumentUploadedEvent.EVENT_NAME,
new DocumentUploadedEvent(document.getId(), false,
hLocale.getLocaleId()));
}
} catch (Exception e) {
throw new ZanataServiceException("Error during translation.",
500, e);
}
}
return warnings;
}
private int getNumPlurals(HLocale hLocale, HTextFlow textFlow) {
int nPlurals;
if (!textFlow.isPlural()) {
nPlurals = 1;
} else {
nPlurals =
resourceUtils
.getNumPlurals(textFlow.getDocument(), hLocale);
}
return nPlurals;
}
public static class TranslationResultImpl implements TranslationResult {
private HTextFlowTarget translatedTextFlowTarget;
private boolean isSuccess;
private boolean targetChanged = false;
private int baseVersion;
private ContentState baseContentState;
private String errorMessage;
@Override
public boolean isTranslationSuccessful() {
return isSuccess;
}
@Override
public boolean isTargetChanged() {
return targetChanged;
}
@Override
public HTextFlowTarget getTranslatedTextFlowTarget() {
return translatedTextFlowTarget;
}
@Override
public int getBaseVersionNum() {
return baseVersion;
}
@Override
public ContentState getBaseContentState() {
return baseContentState;
}
@Override
public String getErrorMessage() {
return errorMessage;
}
}
@Override
public List<TranslationResult> revertTranslations(LocaleId localeId,
List<TransUnitUpdateInfo> translationsToRevert) {
List<TranslationResult> results = new ArrayList<TranslationResult>();
List<TransUnitUpdateRequest> updateRequests =
new ArrayList<TransUnitUpdateRequest>();
if (!translationsToRevert.isEmpty()) {
HTextFlow sampleHTextFlow =
entityManager.find(HTextFlow.class, translationsToRevert
.get(0).getTransUnit().getId().getValue());
HLocale hLocale =
validateLocale(localeId, sampleHTextFlow.getDocument()
.getProjectIteration());
for (TransUnitUpdateInfo info : translationsToRevert) {
if (!info.isSuccess() || !info.isTargetChanged()) {
continue;
}
TransUnitId tuId = info.getTransUnit().getId();
HTextFlow hTextFlow =
entityManager.find(HTextFlow.class, tuId.getValue());
HTextFlowTarget hTextFlowTarget =
textFlowTargetDAO.getOrCreateTarget(hTextFlow, hLocale);
// check that version has not advanced
// TODO probably also want to check that source has not been
// updated
Integer versionNum = hTextFlowTarget.getVersionNum();
log.debug(
"about to revert hTextFlowTarget version {} to TransUnit version {}",
versionNum, info.getTransUnit().getVerNum());
if (versionNum.equals(info.getTransUnit().getVerNum())) {
// look up replaced version
HTextFlowTargetHistory oldTarget =
hTextFlowTarget.getHistory().get(
info.getPreviousVersionNum());
if (oldTarget != null) {
// generate request
List<String> oldContents = oldTarget.getContents();
ContentState oldState = oldTarget.getState();
TransUnitUpdateRequest request =
new TransUnitUpdateRequest(tuId, oldContents,
oldState, versionNum);
// add to list
updateRequests.add(request);
} else {
log.info(
"got null previous target for tu with id {}, version {}. Assuming previous state is untranslated",
hTextFlow.getId(), info.getPreviousVersionNum());
List<String> emptyContents = Lists.newArrayList();
for (int i = 0; i < hTextFlowTarget.getContents()
.size(); i++) {
emptyContents.add("");
}
TransUnitUpdateRequest request =
new TransUnitUpdateRequest(tuId, emptyContents,
ContentState.New, versionNum);
updateRequests.add(request);
}
} else {
log.info(
"attempt to revert target version {} for tu with id {}, but current version is {}. Not reverting.",
new Object[] { info.getTransUnit().getVerNum(),
tuId, versionNum });
results.add(buildFailResult(hTextFlowTarget));
}
}
}
results.addAll(translateWithoutValidating(localeId, updateRequests));
return results;
}
/**
* @param hTextFlowTarget
* @return
*/
private TranslationResultImpl buildFailResult(
HTextFlowTarget hTextFlowTarget) {
TranslationResultImpl result = new TranslationResultImpl();
result.baseVersion = hTextFlowTarget.getVersionNum();
result.baseContentState = hTextFlowTarget.getState();
result.isSuccess = false;
result.translatedTextFlowTarget = hTextFlowTarget;
result.errorMessage = null;
return result;
}
}