/
AbstractPollingEndpoint.java
568 lines (493 loc) · 18.4 KB
/
AbstractPollingEndpoint.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
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.integration.endpoint;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import org.aopalliance.aop.Advice;
import org.reactivestreams.Subscription;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.integration.aop.ReceiveMessageAdvice;
import org.springframework.integration.channel.ChannelUtils;
import org.springframework.integration.channel.MessagePublishingErrorHandler;
import org.springframework.integration.support.MessagingExceptionWrapper;
import org.springframework.integration.transaction.IntegrationResourceHolder;
import org.springframework.integration.transaction.IntegrationResourceHolderSynchronization;
import org.springframework.integration.transaction.PassThroughTransactionSynchronizationFactory;
import org.springframework.integration.transaction.TransactionSynchronizationFactory;
import org.springframework.integration.util.ErrorHandlingTaskExecutor;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ErrorHandler;
import org.springframework.util.ReflectionUtils;
/**
* An {@link AbstractEndpoint} extension for Polling Consumer pattern basics.
* The standard polling logic is based on a periodic task scheduling according the provided
* {@link Trigger}.
* When this endpoint is treated as {@link #isReactive()}, a polling logic is turned into a
* {@link Flux#generate(java.util.function.Consumer)} and {@link Mono#delay(Duration)} combination based on the
* {@link SimpleTriggerContext} state.
*
* @author Mark Fisher
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
* @author Andreas Baer
* @author Christian Tzolov
*/
public abstract class AbstractPollingEndpoint extends AbstractEndpoint implements BeanClassLoaderAware {
/**
* A default polling period for {@link PeriodicTrigger}.
*/
public static final long DEFAULT_POLLING_PERIOD = 1000;
private final Collection<Advice> appliedAdvices = new HashSet<>();
private final Lock initializationMonitor = new ReentrantLock();
private Executor taskExecutor = new SyncTaskExecutor();
private boolean syncExecutor = true;
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private Trigger trigger = new PeriodicTrigger(Duration.ofMillis(DEFAULT_POLLING_PERIOD));
private ErrorHandler errorHandler;
private boolean errorHandlerIsDefault;
private List<Advice> adviceChain;
private TransactionSynchronizationFactory transactionSynchronizationFactory;
private volatile long maxMessagesPerPoll = -1;
private volatile Callable<Message<?>> pollingTask;
private volatile Flux<Message<?>> pollingFlux;
private volatile Subscription subscription;
private volatile ScheduledFuture<?> runningTask;
private volatile boolean initialized;
public AbstractPollingEndpoint() {
this.setPhase(Integer.MAX_VALUE / 2);
}
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = (taskExecutor != null ? taskExecutor : new SyncTaskExecutor());
this.syncExecutor = this.taskExecutor instanceof SyncTaskExecutor
|| (this.taskExecutor instanceof ErrorHandlingTaskExecutor
&& ((ErrorHandlingTaskExecutor) this.taskExecutor).isSyncExecutor());
}
protected Executor getTaskExecutor() {
return this.taskExecutor;
}
protected boolean isSyncExecutor() {
return this.syncExecutor;
}
public void setTrigger(Trigger trigger) {
this.trigger = (trigger != null ? trigger : new PeriodicTrigger(Duration.ofMillis(DEFAULT_POLLING_PERIOD)));
}
public void setAdviceChain(List<Advice> adviceChain) {
this.adviceChain = adviceChain;
}
/**
* Configure a cap for messages to poll from the source per scheduling cycle.
* A negative number means retrieve unlimited messages until the {@code MessageSource} returns {@code null}.
* Zero means do not poll for any records - it
* can be considered as pausing if 'maxMessagesPerPoll' is later changed to a non-zero value.
* The polling cycle may exit earlier if the source returns null for the current receive call.
* @param maxMessagesPerPoll the number of message to poll per schedule.
*/
@ManagedAttribute
public void setMaxMessagesPerPoll(long maxMessagesPerPoll) {
this.maxMessagesPerPoll = maxMessagesPerPoll;
}
public long getMaxMessagesPerPoll() {
return this.maxMessagesPerPoll;
}
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
public void setTransactionSynchronizationFactory(TransactionSynchronizationFactory
transactionSynchronizationFactory) {
this.transactionSynchronizationFactory = transactionSynchronizationFactory;
}
/**
* Return the default error channel if the error handler is explicitly provided and
* it is a {@link MessagePublishingErrorHandler}.
* @return the channel or null.
* @since 4.3
*/
public MessageChannel getDefaultErrorChannel() {
if (!this.errorHandlerIsDefault && this.errorHandler instanceof MessagePublishingErrorHandler) {
return ((MessagePublishingErrorHandler) this.errorHandler).getDefaultErrorChannel();
}
else {
return null;
}
}
protected ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
/**
* Return true if this advice should be applied only to the {@link #receiveMessage()} operation
* rather than the whole poll.
* @param advice The advice.
* @return true to only advise the {@code receive} operation.
*/
protected boolean isReceiveOnlyAdvice(Advice advice) {
return advice instanceof ReceiveMessageAdvice;
}
/**
* Add the advice chain to the component that responds to {@link #receiveMessage()} calls.
* @param chain the advice chain {@code Collection}.
*/
protected void applyReceiveOnlyAdviceChain(Collection<Advice> chain) {
if (!CollectionUtils.isEmpty(chain)) {
Object source = getReceiveMessageSource();
if (source != null) {
if (AopUtils.isAopProxy(source)) {
Advised advised = (Advised) source;
this.appliedAdvices.forEach(advised::removeAdvice);
chain.forEach(advice -> advised.addAdvisor(adviceToReceiveAdvisor(advice)));
}
else {
ProxyFactory proxyFactory = new ProxyFactory(source);
chain.forEach(advice -> proxyFactory.addAdvisor(adviceToReceiveAdvisor(advice)));
source = proxyFactory.getProxy(getBeanClassLoader());
}
this.appliedAdvices.clear();
this.appliedAdvices.addAll(chain);
if (!isSyncExecutor()) {
logger.warn(() -> getComponentName() + ": A task executor is supplied and " + chain.size()
+ "ReceiveMessageAdvice(s) is/are provided. If an advice mutates the source, such "
+ "mutations are not thread safe and could cause unexpected results, especially with "
+ "high frequency pollers. Consider using a downstream ExecutorChannel instead of "
+ "adding an executor to the poller");
}
setReceiveMessageSource(source);
}
}
}
private NameMatchMethodPointcutAdvisor adviceToReceiveAdvisor(Advice advice) {
NameMatchMethodPointcutAdvisor sourceAdvisor = new NameMatchMethodPointcutAdvisor(advice);
sourceAdvisor.addMethodName("receive");
return sourceAdvisor;
}
protected boolean isReactive() {
return false;
}
protected Flux<Message<?>> getPollingFlux() {
return this.pollingFlux;
}
protected Object getReceiveMessageSource() {
return null;
}
protected void setReceiveMessageSource(Object source) {
}
@Override
protected void onInit() {
this.initializationMonitor.lock();
try {
if (this.initialized) {
return;
}
Assert.notNull(this.trigger, "Trigger is required");
if (this.taskExecutor != null && !(this.taskExecutor instanceof ErrorHandlingTaskExecutor)) {
if (this.errorHandler == null) {
this.errorHandler = ChannelUtils.getErrorHandler(getBeanFactory());
this.errorHandlerIsDefault = true;
}
this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, this.errorHandler);
}
if (this.transactionSynchronizationFactory == null && this.adviceChain != null &&
this.adviceChain.stream().anyMatch(TransactionInterceptor.class::isInstance)) {
this.transactionSynchronizationFactory = new PassThroughTransactionSynchronizationFactory();
}
this.initialized = true;
}
finally {
this.initializationMonitor.unlock();
}
try {
super.onInit();
}
catch (Exception ex) {
throw new BeanInitializationException("Cannot initialize: " + this, ex);
}
}
// LifecycleSupport implementation
@Override // guarded by super#lifecycleLock
protected void doStart() {
if (!this.initialized) {
onInit();
}
this.pollingTask = createPollingTask();
if (isReactive()) {
this.pollingFlux = createFluxGenerator();
}
else {
TaskScheduler taskScheduler = getTaskScheduler();
Assert.state(taskScheduler != null, "unable to start polling, no taskScheduler available");
this.runningTask = taskScheduler.schedule(createPoller(), this.trigger);
}
}
@SuppressWarnings("unchecked")
private Callable<Message<?>> createPollingTask() {
List<Advice> receiveOnlyAdviceChain = null;
if (!CollectionUtils.isEmpty(this.adviceChain)) {
receiveOnlyAdviceChain = this.adviceChain.stream()
.filter(this::isReceiveOnlyAdvice)
.collect(Collectors.toList());
}
Callable<Message<?>> task = this::doPoll;
List<Advice> advices = this.adviceChain;
if (!CollectionUtils.isEmpty(advices)) {
ProxyFactory proxyFactory = new ProxyFactory(task);
if (!CollectionUtils.isEmpty(advices)) {
advices.stream()
.filter(advice -> !isReceiveOnlyAdvice(advice))
.forEach(proxyFactory::addAdvice);
}
task = (Callable<Message<?>>) proxyFactory.getProxy(this.beanClassLoader);
}
if (!CollectionUtils.isEmpty(receiveOnlyAdviceChain)) {
applyReceiveOnlyAdviceChain(receiveOnlyAdviceChain);
}
return task;
}
private Runnable createPoller() {
return () ->
this.taskExecutor.execute(() -> {
int count = 0;
while (this.initialized && (this.maxMessagesPerPoll <= 0 || count < this.maxMessagesPerPoll)) {
if (this.maxMessagesPerPoll == 0) {
logger.info("Polling disabled while 'maxMessagesPerPoll == 0'");
break;
}
if (pollForMessage() == null) {
break;
}
count++;
}
});
}
private Flux<Message<?>> createFluxGenerator() {
SimpleTriggerContext triggerContext = new SimpleTriggerContext();
return Flux
.<Duration>generate(sink -> {
Instant date = this.trigger.nextExecution(triggerContext);
if (date != null) {
triggerContext.update(date, null, null);
sink.next(Duration.ofMillis(date.toEpochMilli() - System.currentTimeMillis()));
}
else {
sink.complete();
}
})
.concatMap(duration ->
Mono.delay(duration)
.doOnNext(l ->
triggerContext.update(
triggerContext.lastScheduledExecution(), Instant.now(), null))
.flatMapMany(l ->
Flux
.defer(() -> {
if (this.maxMessagesPerPoll == 0) {
logger.info("Polling disabled while 'maxMessagesPerPoll == 0'");
return Mono.empty();
}
else {
return Flux
.<Message<?>>generate(fluxSink -> {
Message<?> message = pollForMessage();
if (message != null) {
fluxSink.next(message);
}
else {
fluxSink.complete();
}
})
.take(this.maxMessagesPerPoll < 0
? Long.MAX_VALUE
: this.maxMessagesPerPoll,
true);
}
})
.subscribeOn(Schedulers.fromExecutor(this.taskExecutor))
.doOnComplete(() ->
triggerContext
.update(triggerContext.lastScheduledExecution(),
triggerContext.lastActualExecution(),
Instant.now())
)), 0)
.repeat(this::isActive)
.doOnSubscribe(subs -> this.subscription = subs);
}
private Message<?> pollForMessage() {
try {
return this.pollingTask.call();
}
catch (Exception ex) {
if (ex instanceof MessagingException) { // NOSONAR
throw (MessagingException) ex;
}
else {
Message<?> failedMessage = null;
if (this.transactionSynchronizationFactory != null) {
Object resource = TransactionSynchronizationManager.getResource(getResourceToBind());
if (resource instanceof IntegrationResourceHolder) {
failedMessage = ((IntegrationResourceHolder) resource).getMessage();
}
}
throw new MessagingException(failedMessage, ex); // NOSONAR (null failedMessage)
}
}
finally {
if (this.transactionSynchronizationFactory != null) {
Object resource = getResourceToBind();
if (TransactionSynchronizationManager.hasResource(resource)) {
TransactionSynchronizationManager.unbindResource(resource);
}
}
}
}
private Message<?> doPoll() {
IntegrationResourceHolder holder = bindResourceHolderIfNecessary(getResourceKey(), getResourceToBind());
Message<?> message = null;
try {
message = receiveMessage();
}
catch (Exception ex) {
if (Thread.interrupted()) {
logger.debug(() -> "Poll interrupted - during stop()? : " + ex.getMessage());
return null;
}
else {
ReflectionUtils.rethrowRuntimeException(ex);
}
}
if (message == null) {
this.logger.debug("Received no Message during the poll, returning 'false'");
return null;
}
else {
messageReceived(holder, message);
}
return message;
}
private void messageReceived(IntegrationResourceHolder holder, Message<?> message) {
this.logger.debug(() -> "Poll resulted in Message: " + message);
if (holder != null) {
holder.setMessage(message);
}
if (!isReactive()) {
try {
handleMessage(message);
}
catch (MessagingException ex) {
throw new MessagingExceptionWrapper(message, ex);
}
catch (Exception ex) {
throw new MessagingException(message, ex);
}
}
}
@Override // guarded by super#lifecycleLock
protected void doStop() {
if (this.runningTask != null) {
this.runningTask.cancel(true);
}
this.runningTask = null;
if (this.subscription != null) {
this.subscription.cancel();
}
}
/**
* Obtain the next message (if one is available). MAY return null
* if no message is immediately available.
* @return The message or null.
*/
protected abstract Message<?> receiveMessage();
/**
* Handle a message.
* @param message The message.
*/
protected abstract void handleMessage(Message<?> message);
/**
* Return a resource (MessageSource etc.) to bind when using transaction
* synchronization.
* @return The resource, or null if transaction synchronization is not required.
*/
protected Object getResourceToBind() {
return null;
}
/**
* Return the key under which the resource will be made available as an
* attribute on the {@link IntegrationResourceHolder}. The default
* {@link org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor}
* makes this attribute available as a variable in SpEL expressions.
* @return The key, or null (default) if the resource shouldn't be
* made available as a attribute.
*/
protected String getResourceKey() {
return null;
}
private IntegrationResourceHolder bindResourceHolderIfNecessary(String key, Object resource) {
if (this.transactionSynchronizationFactory != null && resource != null &&
TransactionSynchronizationManager.isActualTransactionActive()) {
TransactionSynchronization synchronization = this.transactionSynchronizationFactory.create(resource);
if (synchronization != null) {
TransactionSynchronizationManager.registerSynchronization(synchronization);
if (synchronization instanceof IntegrationResourceHolderSynchronization integrationSynchronization) {
integrationSynchronization.setShouldUnbindAtCompletion(false);
if (!TransactionSynchronizationManager.hasResource(resource)) {
TransactionSynchronizationManager.bindResource(resource,
integrationSynchronization.getResourceHolder());
}
}
}
Object resourceHolder = TransactionSynchronizationManager.getResource(resource);
if (resourceHolder instanceof IntegrationResourceHolder integrationResourceHolder) {
if (key != null) {
integrationResourceHolder.addAttribute(key, resource);
}
return integrationResourceHolder;
}
}
return null;
}
}