This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
AsynchronousProcessResourceService.java
304 lines (265 loc) · 12.1 KB
/
AsynchronousProcessResourceService.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
/*
* 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.rest.service;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.jboss.resteasy.spi.NotFoundException;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Transactional;
import org.zanata.annotation.RateLimitingResource;
import org.zanata.async.AsyncTaskHandle;
import org.zanata.async.SimpleAsyncTask;
import org.zanata.common.EntityStatus;
import org.zanata.common.LocaleId;
import org.zanata.common.MergeType;
import org.zanata.dao.DocumentDAO;
import org.zanata.dao.ProjectIterationDAO;
import org.zanata.model.HDocument;
import org.zanata.model.HProject;
import org.zanata.model.HProjectIteration;
import org.zanata.rest.NoSuchEntityException;
import org.zanata.rest.ReadOnlyEntityException;
import org.zanata.rest.dto.ProcessStatus;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.security.ZanataIdentity;
import org.zanata.service.AsyncTaskManagerService;
import org.zanata.service.DocumentService;
import org.zanata.service.LocaleService;
import org.zanata.service.TranslationService;
import org.zanata.service.impl.DocumentServiceImpl;
import org.zanata.service.impl.TranslationServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import javax.ws.rs.Path;
import static org.zanata.rest.dto.ProcessStatus.ProcessStatusCode;
/**
* Default server-side implementation of the Asynchronous RunnableProcess
* Resource.
*
* @author Carlos Munoz <a
* href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
*/
@Name("asynchronousProcessResourceService")
@Path(AsynchronousProcessResource.SERVICE_PATH)
@Transactional
@RateLimitingResource
@Slf4j
public class AsynchronousProcessResourceService implements
AsynchronousProcessResource {
@In
private AsyncTaskManagerService asyncTaskManagerServiceImpl;
@In
private LocaleService localeServiceImpl;
@In
private DocumentDAO documentDAO;
@In
private ProjectIterationDAO projectIterationDAO;
@In
private ResourceUtils resourceUtils;
@In
private ZanataIdentity identity;
@Override
public ProcessStatus startSourceDocCreation(final String idNoSlash,
final String projectSlug, final String iterationSlug,
final Resource resource, final Set<String> extensions,
final boolean copytrans) {
HProjectIteration hProjectIteration =
retrieveAndCheckIteration(projectSlug, iterationSlug, true);
resourceUtils.validateExtensions(extensions); // gettext, comment
HDocument document =
documentDAO.getByDocIdAndIteration(hProjectIteration,
resource.getName());
// already existing non-obsolete document.
if (document != null) {
if (!document.isObsolete()) {
// updates must happen through PUT on the actual resource
ProcessStatus status = new ProcessStatus();
status.setStatusCode(ProcessStatusCode.Failed);
status.getMessages().add(
"A document with name " + resource.getName()
+ " already exists.");
return status;
}
}
String name = "SourceDocCreation: "+projectSlug+"-"+iterationSlug+"-"+idNoSlash;
SimpleAsyncTask<Void> task = new SimpleAsyncTask<Void>(name) {
@Override
public Void call() throws Exception {
DocumentService documentServiceImpl =
(DocumentService) Component
.getInstance(DocumentServiceImpl.class);
documentServiceImpl.saveDocument(projectSlug, iterationSlug,
resource, extensions, copytrans, true);
// TODO This should update with real progress
getHandle().setCurrentProgress(getHandle().getMaxProgress());
return null;
}
};
String taskId = asyncTaskManagerServiceImpl.startTask(task);
return getProcessStatus(taskId); // TODO Change to return 202 Accepted,
// with a url to get the progress
}
@Override
public ProcessStatus startSourceDocCreationOrUpdate(final String idNoSlash,
final String projectSlug, final String iterationSlug,
final Resource resource, final Set<String> extensions,
final boolean copytrans) {
HProjectIteration hProjectIteration =
retrieveAndCheckIteration(projectSlug, iterationSlug, true);
resourceUtils.validateExtensions(extensions); // gettext, comment
String name = "SourceDocCreationOrUpdate: "+projectSlug+"-"+iterationSlug+"-"+idNoSlash;
SimpleAsyncTask<Void> task = new SimpleAsyncTask<Void>(name) {
@Override
public Void call() throws Exception {
DocumentService documentServiceImpl =
(DocumentService) Component
.getInstance(DocumentServiceImpl.class);
documentServiceImpl.saveDocument(projectSlug, iterationSlug,
resource, extensions, copytrans, true);
// TODO This should update with real progress
return null;
}
};
String taskId = asyncTaskManagerServiceImpl.startTask(task);
return this.getProcessStatus(taskId); // TODO Change to return 202
// Accepted, with a url to get the
// progress
}
@Override
public ProcessStatus startTranslatedDocCreationOrUpdate(
final String idNoSlash, final String projectSlug,
final String iterationSlug, final LocaleId locale,
final TranslationsResource translatedDoc,
final Set<String> extensions, final String merge) {
// check security (cannot be on @Restrict as it refers to method
// parameters)
identity.checkPermission("modify-translation", this.localeServiceImpl
.getByLocaleId(locale),
this.getSecuredIteration(projectSlug, iterationSlug)
.getProject());
MergeType mergeType;
try {
mergeType = MergeType.valueOf(merge.toUpperCase());
} catch (Exception e) {
ProcessStatus status = new ProcessStatus();
status.setStatusCode(ProcessStatusCode.Failed);
status.getMessages().add("bad merge type " + merge);
return status;
}
final String id = URIHelper.convertFromDocumentURIId(idNoSlash);
final MergeType finalMergeType = mergeType;
String name = "TranslatedDocCreationOrUpdate: "+projectSlug+"-"+iterationSlug+"-"+idNoSlash+"-"+locale;
SimpleAsyncTask<List<String>> task =
new SimpleAsyncTask<List<String>>(name) {
@Override
public List<String> call() throws Exception {
TranslationService translationServiceImpl =
(TranslationService) Component
.getInstance(TranslationServiceImpl.class);
// Translate
List<String> messages =
translationServiceImpl.translateAllInDoc(
projectSlug, iterationSlug, id, locale,
translatedDoc, extensions,
finalMergeType, true);
return messages;
}
};
String taskId = asyncTaskManagerServiceImpl.startTask(task);
return this.getProcessStatus(taskId);
}
@Override
public ProcessStatus getProcessStatus(String processId) {
AsyncTaskHandle handle =
asyncTaskManagerServiceImpl.getHandle(processId);
if (handle == null) {
throw new NotFoundException("A process was not found for id "
+ processId);
}
ProcessStatus status = new ProcessStatus();
status.setStatusCode(handle.isDone() ? ProcessStatusCode.Finished
: ProcessStatusCode.Running);
int perComplete = 100;
if (handle.getMaxProgress() > 0) {
perComplete =
(handle.getCurrentProgress() * 100 / handle
.getMaxProgress());
}
status.setPercentageComplete(perComplete);
status.setUrl("" + processId);
if (handle.isDone()) {
Object result = null;
try {
result = handle.get();
} catch (InterruptedException e) {
// The process was forcefully cancelled
status.setStatusCode(ProcessStatusCode.Failed);
status.setMessages(Lists.newArrayList(e.getMessage()));
} catch (ExecutionException e) {
// Exception thrown while running the task
status.setStatusCode(ProcessStatusCode.Failed);
status.setMessages(Lists
.newArrayList(e.getCause().getMessage()));
}
// TODO Need to find a generic way of returning all object types.
// Since the only current
// scenario involves lists of strings, hardcoding to that
if (result != null && result instanceof List) {
status.getMessages().addAll((List) result);
}
}
return status;
}
private HProjectIteration retrieveAndCheckIteration(String projectSlug,
String iterationSlug, boolean writeOperation) {
HProjectIteration hProjectIteration =
projectIterationDAO.getBySlug(projectSlug, iterationSlug);
HProject hProject =
hProjectIteration == null ? null : hProjectIteration
.getProject();
if (hProjectIteration == null) {
throw new NoSuchEntityException("Project Iteration '" + projectSlug
+ ":" + iterationSlug + "' not found.");
} else if (hProjectIteration.getStatus().equals(EntityStatus.OBSOLETE)
|| hProject.getStatus().equals(EntityStatus.OBSOLETE)) {
throw new NoSuchEntityException("Project Iteration '" + projectSlug
+ ":" + iterationSlug + "' not found.");
} else if (writeOperation) {
if (hProjectIteration.getStatus().equals(EntityStatus.READONLY)
|| hProject.getStatus().equals(EntityStatus.READONLY)) {
throw new ReadOnlyEntityException("Project Iteration '"
+ projectSlug + ":" + iterationSlug + "' is read-only.");
} else {
return hProjectIteration;
}
} else {
return hProjectIteration;
}
}
public HProjectIteration getSecuredIteration(String projectSlug,
String iterationSlug) {
return retrieveAndCheckIteration(projectSlug, iterationSlug, false);
}
}