/
ProcessRequestBean.java
433 lines (387 loc) · 19.1 KB
/
ProcessRequestBean.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
/*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.remote.services.cdi;
import static org.kie.remote.services.cdi.DeploymentInfoBean.emptyDeploymentId;
import static org.kie.services.client.serialization.jaxb.impl.JaxbRequestStatus.FAILURE;
import static org.kie.services.client.serialization.jaxb.impl.JaxbRequestStatus.PERMISSIONS_CONFLICT;
import static org.kie.services.shared.ServicesVersion.VERSION;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import org.drools.core.command.runtime.SetGlobalCommand;
import org.drools.core.command.runtime.process.CompleteWorkItemCommand;
import org.drools.core.command.runtime.process.SignalEventCommand;
import org.drools.core.command.runtime.process.StartCorrelatedProcessCommand;
import org.drools.core.command.runtime.process.StartProcessCommand;
import org.drools.core.command.runtime.process.StartProcessInstanceCommand;
import org.drools.core.command.runtime.rule.InsertObjectCommand;
import org.drools.core.command.runtime.rule.UpdateCommand;
import org.jbpm.process.audit.AuditLogService;
import org.jbpm.process.audit.JPAAuditLogService;
import org.jbpm.process.audit.command.AuditCommand;
import org.jbpm.services.api.ProcessInstanceNotFoundException;
import org.jbpm.services.api.ProcessService;
import org.jbpm.services.api.TaskNotFoundException;
import org.jbpm.services.api.UserTaskService;
import org.jbpm.services.task.commands.AddTaskCommand;
import org.jbpm.services.task.commands.CancelDeadlineCommand;
import org.jbpm.services.task.commands.CompleteTaskCommand;
import org.jbpm.services.task.commands.CompositeCommand;
import org.jbpm.services.task.commands.FailTaskCommand;
import org.jbpm.services.task.commands.GetContentCommand;
import org.jbpm.services.task.commands.GetTaskCommand;
import org.jbpm.services.task.commands.GetTaskContentCommand;
import org.jbpm.services.task.commands.ProcessSubTaskCommand;
import org.jbpm.services.task.commands.SkipTaskCommand;
import org.jbpm.services.task.commands.TaskCommand;
import org.jbpm.services.task.exception.PermissionDeniedException;
import org.kie.api.command.Command;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.Context;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.task.TaskService;
import org.kie.api.task.model.Task;
import org.kie.internal.KieInternalServices;
import org.kie.internal.command.CorrelationKeyCommand;
import org.kie.internal.command.ProcessInstanceIdCommand;
import org.kie.internal.process.CorrelationKey;
import org.kie.internal.process.CorrelationKeyFactory;
import org.kie.internal.runtime.manager.context.CorrelationKeyContext;
import org.kie.internal.runtime.manager.context.EmptyContext;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.kie.remote.services.AcceptedServerCommands;
import org.kie.remote.services.exception.DeploymentNotFoundException;
import org.kie.remote.services.jaxb.JaxbCommandsRequest;
import org.kie.remote.services.jaxb.JaxbCommandsResponse;
import org.kie.remote.services.rest.RuntimeResourceImpl;
import org.kie.remote.services.rest.TaskResourceImpl;
import org.kie.remote.services.rest.exception.KieRemoteRestOperationException;
import org.kie.remote.services.util.ExecuteAndSerializeCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
/**
* This class is used by both the {@link RuntimeResourceImpl} and {@link TaskResourceImpl} to do the core operations on
* the Deployment/Runtime's {@link KieSession} and {@link TaskService}.
* </p>
* It contains the necessary logic to do the following:
* <ul>
* <li>Retrieve the KieSession or TaskService</li>
* <li>Execute the submitted command</li>
* </ul>
*/
@ApplicationScoped
public class ProcessRequestBean {
private static final Logger logger = LoggerFactory.getLogger(ProcessRequestBean.class);
/* KIE processing */
@Inject
private ProcessService processService;
@Inject
private UserTaskService userTaskService;
/** AuditLogService **/
private static final String PERSISTENCE_UNIT_NAME = "org.jbpm.domain";
@PersistenceUnit(unitName = PERSISTENCE_UNIT_NAME)
private EntityManagerFactory emf;
private AuditLogService auditLogService;
// Injection methods for tests
public void setProcessService(ProcessService processService) {
this.processService = processService;
}
public void setUserTaskService(UserTaskService userTaskService) {
this.userTaskService = userTaskService;
}
public void setAuditLogService(AuditLogService auditLogService) {
this.auditLogService = auditLogService;
}
// Audit Log Service logic
@PostConstruct
public void initAuditLogService() {
auditLogService = new JPAAuditLogService(emf);
if( emf == null ) {
((JPAAuditLogService) auditLogService).setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
}
}
public AuditLogService getAuditLogService() {
return auditLogService;
}
// Methods used
public <T> void processCommand(Command<T> cmd, JaxbCommandsRequest request, int i, JaxbCommandsResponse jaxbResponse) {
String version = request.getVersion();
if( version == null ) {
version = "pre-6.0.3";
}
if( ! version.equals(VERSION) ) {
logger.warn( "Request received from client version [{}] while server is version [{}]! THIS MAY CAUSE PROBLEMS!", version, VERSION);
}
jaxbResponse.setVersion(VERSION);
String cmdName = cmd.getClass().getSimpleName();
logger.debug("Processing command " + cmdName);
String errMsg = "Unable to execute " + cmdName + "/" + i;
Object cmdResult = null;
try {
// check that all parameters have been correctly deserialized/unmarshalled
preprocessCommand(cmd);
String corrKeyString = request.getCorrelationKeyString();
List<String> correlationKeyProps = null;
if( corrKeyString != null ) {
String [] correlationKeyPropsArr = corrKeyString.split(":");
if( correlationKeyPropsArr.length > 0 ) {
correlationKeyProps = Arrays.asList(correlationKeyPropsArr);
}
}
if( cmd instanceof TaskCommand<?> ) {
TaskCommand<?> taskCmd = (TaskCommand<?>) cmd;
// TODO: correlation key sessions and task completion! BZ-1245616-related
cmdResult = doTaskOperation(
taskCmd.getTaskId(),
request.getDeploymentId(),
request.getProcessInstanceId(),
null,
taskCmd);
} else if( cmd instanceof AuditCommand<?>) {
AuditCommand<?> auditCmd = ((AuditCommand<?>) cmd);
auditCmd.setAuditLogService(getAuditLogService());
cmdResult = auditCmd.execute(null);
} else {
cmdResult = doKieSessionOperation(
cmd,
request.getDeploymentId(),
correlationKeyProps,
request.getProcessInstanceId());
}
} catch (PermissionDeniedException pde) {
logger.warn(errMsg, pde);
jaxbResponse.addException(pde, i, cmd, PERMISSIONS_CONFLICT);
} catch (Exception e) {
logger.warn(errMsg, e);
jaxbResponse.addException(e, i, cmd, FAILURE);
}
if (cmdResult != null) {
try {
// addResult could possibly throw an exception, which is why it's here and not above
jaxbResponse.addResult(cmdResult, i, cmd);
} catch (Exception e) {
errMsg = "Unable to add result from " + cmdName + "/" + i;
logger.error(errMsg, e);
jaxbResponse.addException(e, i, cmd, FAILURE);
}
}
};
void preprocessCommand(Command cmd) {
if( AcceptedServerCommands.SEND_OBJECT_PARAMETER_COMMANDS.contains(cmd.getClass()) ) {
if( cmd instanceof CompleteWorkItemCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((CompleteWorkItemCommand) cmd).getResults());
} else if( cmd instanceof SignalEventCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((SignalEventCommand) cmd).getEvent());
} else if( cmd instanceof StartCorrelatedProcessCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((StartCorrelatedProcessCommand) cmd).getData());
checkThatUserDefinedClassesWereUnmarshalled(((StartCorrelatedProcessCommand) cmd).getParameters());
} else if( cmd instanceof StartProcessCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((StartProcessCommand) cmd).getData());
checkThatUserDefinedClassesWereUnmarshalled(((StartProcessCommand) cmd).getParameters());
} else if( cmd instanceof SetGlobalCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((SetGlobalCommand) cmd).getObject());
} else if( cmd instanceof InsertObjectCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((InsertObjectCommand) cmd).getObject());
} else if( cmd instanceof UpdateCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((UpdateCommand) cmd).getObject());
} else if( cmd instanceof AddTaskCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((AddTaskCommand) cmd).getParams());
} else if( cmd instanceof CompleteTaskCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((CompleteTaskCommand) cmd).getData());
} else if( cmd instanceof FailTaskCommand ) {
checkThatUserDefinedClassesWereUnmarshalled(((FailTaskCommand) cmd).getData());
}
}
}
void checkThatUserDefinedClassesWereUnmarshalled(Object obj) {
if( obj != null ) {
if( obj instanceof List ) {
for( Object listElem : (List) obj ) {
verifyObjectHasBeenUnmarshalled(listElem);
}
} else if( obj instanceof Map ) {
for( Object mapVal : ((Map) obj).values() ) {
verifyObjectHasBeenUnmarshalled(mapVal);
}
} else {
verifyObjectHasBeenUnmarshalled(obj);
}
}
}
private void verifyObjectHasBeenUnmarshalled(Object obj) {
if( Element.class.isAssignableFrom(obj.getClass()) ) {
String typeName = ((Element) obj).getAttribute("xsi:type");
throw new IllegalStateException("Could not unmarshall user-defined class instance parameter of type '" + typeName + "'");
}
}
/**
* Executes a command on the {@link KieSession} from the proper {@link RuntimeManager}. This method
* ends up synchronizing around the retrieved {@link KieSession} in order to avoid race-conditions.
*
* @param cmd The command to be executed.
* @param deploymentId The id of the runtim
* @param correlationKeyProps The defining properties for a correlation key
* @param processInstanceId The process instance id, if available (otherwise null).
* @return The result of the {@link Command}.
*/
public <T> T doKieSessionOperation(Command<T> cmd, String deploymentId, List<String> correlationKeyProps, Long processInstanceId) {
if( emptyDeploymentId(deploymentId) ) {
throw new DeploymentNotFoundException("No deployment id supplied! Could not retrieve runtime to execute " + cmd.getClass().getSimpleName());
}
try {
Context cmdContext = getDeploymentCommandContext(correlationKeyProps, processInstanceId, cmd);
T result = processService.execute(deploymentId, cmdContext, cmd);
return result;
} catch (ProcessInstanceNotFoundException e) {
throw KieRemoteRestOperationException.notFound("Process instance " + processInstanceId + " could not be found!");
} catch (org.jbpm.services.api.DeploymentNotFoundException e) {
throw KieRemoteRestOperationException.notFound(e.getMessage());
} catch (RuntimeException re) {
throw KieRemoteRestOperationException.internalServerError(re.getMessage(), re);
}
}
private Context getDeploymentCommandContext(List<String> correlationKeyProps, Long processInstanceId, Command cmd) {
if( cmd instanceof StartCorrelatedProcessCommand || cmd instanceof StartProcessInstanceCommand ) {
return EmptyContext.get();
}
// correlation key
CorrelationKey correlationKey = null;
if( correlationKeyProps != null && ! correlationKeyProps.isEmpty() ) {
CorrelationKeyFactory factory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
correlationKey = factory.newCorrelationKey(correlationKeyProps);
} else if (cmd instanceof CorrelationKeyCommand ) {
correlationKey = ((CorrelationKeyCommand) cmd).getCorrelationKey();
}
if( correlationKey != null ) {
return CorrelationKeyContext.get(correlationKey);
}
// process instance
if( processInstanceId == null && cmd instanceof ProcessInstanceIdCommand ) {
processInstanceId = ((ProcessInstanceIdCommand) cmd).getProcessInstanceId();
if( processInstanceId != null ) {
return ProcessInstanceIdContext.get(processInstanceId);
}
}
if( processInstanceId != null ) {
return ProcessInstanceIdContext.get(processInstanceId);
}
// empty
return EmptyContext.get();
}
/**
* Returns the actual variable instance from the runtime (as opposed to retrieving the string value of the
* variable via the history/audit operations.
*
* @param deploymentId The id of the runtime
* @param processInstanceId The process instance id (required)
* @param varName The name of the variable
* @return The variable object instance.
*/
public Object getVariableObjectInstanceFromRuntime(String deploymentId, long processInstanceId, String varName) {
try {
Object procVar = processService.getProcessInstanceVariable(processInstanceId, varName);
return procVar;
} catch (ProcessInstanceNotFoundException e) {
throw KieRemoteRestOperationException.notFound("Process instance " + processInstanceId + " could not be found!");
} catch (org.jbpm.services.api.DeploymentNotFoundException e) {
throw KieRemoteRestOperationException.notFound(e.getMessage());
} catch (RuntimeException re) {
throw KieRemoteRestOperationException.internalServerError(re.getMessage(), re);
}
}
// task operations ------------------------------------------------------------------------------------------------------------
private static Set<Class<? extends TaskCommand>> taskDeploymentIdCommands = new HashSet<Class<? extends TaskCommand>>();
static {
taskDeploymentIdCommands.add(CompleteTaskCommand.class);
taskDeploymentIdCommands.add(FailTaskCommand.class);
taskDeploymentIdCommands.add(SkipTaskCommand.class);
}
/**
* There are 3 possibilities here: <ol>
* <li>This is an operation that should be done on a deployment if possible, but it's an independent task.</li>
* <li>This is an operation that should be done on a deployment, and a deployment/runtime is available.</li>
* <li>This is an operation that does <b>not</b> modify the {@link KieSession} and should be done via the injected {@link TaskService}.</li>
* </ol>
*
* @param taskId
* @param deploymentId
* @param processInstanceId
* @param cmd
* @param onDeployment
* @param errorMsg
* @return
*/
private <T> T doTaskOperation(Long taskId, String deploymentId, Long processInstanceId, Task task, TaskCommand<T> cmd) {
// take care of serialization
if( cmd instanceof GetTaskCommand
|| cmd instanceof GetContentCommand
|| cmd instanceof GetTaskContentCommand ) {
cmd = new ExecuteAndSerializeCommand(cmd);
}
if( emptyDeploymentId(deploymentId) && taskDeploymentIdCommands.contains(cmd.getClass()) ) {
deploymentId = getDeploymentId(task,taskId, cmd);
}
if( cmd instanceof CompleteTaskCommand ) {
CompleteTaskCommand completeCmd = (CompleteTaskCommand) cmd;
String userId = completeCmd.getUserId();
Map<String, Object> data = completeCmd.getData();
cmd = new CompositeCommand(
new CompleteTaskCommand(taskId, userId, data),
new ProcessSubTaskCommand(taskId, userId, data),
new CancelDeadlineCommand(taskId, true, true));
}
try {
return userTaskService.execute(deploymentId, cmd);
} catch (TaskNotFoundException e) {
throw KieRemoteRestOperationException.notFound("Task " + taskId + " could not be found!");
} catch (ProcessInstanceNotFoundException e) {
throw KieRemoteRestOperationException.notFound("Process instance " + processInstanceId + " could not be found!");
} catch (org.jbpm.services.api.DeploymentNotFoundException e) {
throw KieRemoteRestOperationException.notFound(e.getMessage());
} catch (RuntimeException re) {
throw KieRemoteRestOperationException.internalServerError(re.getMessage(), re);
}
}
public <T> T doRestTaskOperation(Long taskId, String deploymentId, Long processInstanceId, Task task, TaskCommand<T> cmd) {
try {
return doTaskOperation(taskId, deploymentId, processInstanceId, task, cmd);
} catch (PermissionDeniedException pde) {
throw KieRemoteRestOperationException.conflict(pde.getMessage(), pde);
} catch (RuntimeException re) {
throw re;
}
}
private String getDeploymentId(Task task, Long taskId, TaskCommand cmd) {
if( task == null ) {
if( taskId == null ) {
taskId = cmd.getTaskId();
}
task = userTaskService.getTask(taskId);
}
String deploymentId = null;
if( task != null && task.getTaskData() != null ) {
deploymentId = task.getTaskData().getDeploymentId();
}
return deploymentId;
}
}