-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
PollEnricher.java
539 lines (473 loc) · 20.3 KB
/
PollEnricher.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* 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.apache.camel.processor;
import java.util.Map;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.Expression;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.NoTypeConversionAvailableException;
import org.apache.camel.PollingConsumer;
import org.apache.camel.spi.ConsumerCache;
import org.apache.camel.spi.EndpointUtilizationStatistics;
import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.spi.HeadersMapFactory;
import org.apache.camel.spi.IdAware;
import org.apache.camel.spi.NormalizedEndpointUri;
import org.apache.camel.spi.RouteIdAware;
import org.apache.camel.support.AsyncProcessorSupport;
import org.apache.camel.support.BridgeExceptionHandlerToErrorHandler;
import org.apache.camel.support.DefaultConsumer;
import org.apache.camel.support.EndpointHelper;
import org.apache.camel.support.EventDrivenPollingConsumer;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.cache.DefaultConsumerCache;
import org.apache.camel.support.service.ServiceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.support.ExchangeHelper.copyResultsPreservePattern;
/**
* A content enricher that enriches input data by first obtaining additional data from a <i>resource</i> represented by
* an endpoint <code>producer</code> and second by aggregating input data and additional data. Aggregation of input data
* and additional data is delegated to an {@link AggregationStrategy} object.
* <p/>
* Uses a {@link org.apache.camel.PollingConsumer} to obtain the additional data as opposed to {@link Enricher} that
* uses a {@link org.apache.camel.Producer}.
*
* @see Enricher
*/
public class PollEnricher extends AsyncProcessorSupport implements IdAware, RouteIdAware, CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(PollEnricher.class);
private CamelContext camelContext;
private ConsumerCache consumerCache;
private HeadersMapFactory headersMapFactory;
private volatile String scheme;
private String id;
private String routeId;
private String variableReceive;
private AggregationStrategy aggregationStrategy;
private final Expression expression;
private final String uri;
private long timeout;
private boolean aggregateOnException;
private int cacheSize;
private boolean ignoreInvalidEndpoint;
private boolean autoStartupComponents = true;
/**
* Creates a new {@link PollEnricher}.
*
* @param expression expression to use to compute the endpoint to poll from.
* @param uri the endpoint to poll from.
* @param timeout timeout in millis
*/
public PollEnricher(Expression expression, String uri, long timeout) {
this.expression = expression;
this.uri = uri;
this.timeout = timeout;
}
/**
* Creates a new {@link PollEnricher}.
*
* @param uri the endpoint to poll from.
* @param timeout timeout in millis
*/
public PollEnricher(String uri, long timeout) {
this.expression = null;
this.uri = uri;
this.timeout = timeout;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getRouteId() {
return routeId;
}
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
public Expression getExpression() {
return expression;
}
public EndpointUtilizationStatistics getEndpointUtilizationStatistics() {
return consumerCache.getEndpointUtilizationStatistics();
}
public AggregationStrategy getAggregationStrategy() {
return aggregationStrategy;
}
/**
* Sets the aggregation strategy for this poll enricher.
*
* @param aggregationStrategy the aggregationStrategy to set
*/
public void setAggregationStrategy(AggregationStrategy aggregationStrategy) {
this.aggregationStrategy = aggregationStrategy;
}
public String getVariableReceive() {
return variableReceive;
}
public void setVariableReceive(String variableReceive) {
this.variableReceive = variableReceive;
}
public long getTimeout() {
return timeout;
}
/**
* Sets the timeout to use when polling.
* <p/>
* Use 0 to use receiveNoWait, Use -1 to use receive with no timeout (which will block until data is available).
*
* @param timeout timeout in millis.
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public boolean isAggregateOnException() {
return aggregateOnException;
}
public void setAggregateOnException(boolean aggregateOnException) {
this.aggregateOnException = aggregateOnException;
}
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
public boolean isIgnoreInvalidEndpoint() {
return ignoreInvalidEndpoint;
}
public void setIgnoreInvalidEndpoint(boolean ignoreInvalidEndpoint) {
this.ignoreInvalidEndpoint = ignoreInvalidEndpoint;
}
public boolean isAutoStartupComponents() {
return autoStartupComponents;
}
public void setAutoStartupComponents(boolean autoStartupComponents) {
this.autoStartupComponents = autoStartupComponents;
}
/**
* Enriches the input data (<code>exchange</code>) by first obtaining additional data from an endpoint represented
* by an endpoint <code>producer</code> and second by aggregating input data and additional data. Aggregation of
* input data and additional data is delegated to an {@link AggregationStrategy} object set at construction time. If
* the message exchange with the resource endpoint fails then no aggregation will be done and the failed exchange
* content is copied over to the original message exchange.
*
* @param exchange input data.
*/
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
try {
preCheckPoll(exchange);
} catch (Exception e) {
exchange.setException(new CamelExchangeException("Error during pre poll check", exchange, e));
callback.done(true);
return true;
}
// which consumer to use
PollingConsumer consumer;
Endpoint endpoint;
// use dynamic endpoint so calculate the endpoint to use
Object recipient = null;
boolean prototype = cacheSize < 0;
try {
// favour using expression to compute the recipient endpoint
recipient = expression != null ? expression.evaluate(exchange, Object.class) : uri;
recipient = prepareRecipient(exchange, recipient);
Endpoint existing = getExistingEndpoint(camelContext, recipient);
if (existing == null) {
endpoint = resolveEndpoint(camelContext, recipient, prototype);
} else {
endpoint = existing;
// we have an existing endpoint then its not a prototype scope
prototype = false;
}
// acquire the consumer from the cache
consumer = consumerCache.acquirePollingConsumer(endpoint);
} catch (Exception e) {
if (isIgnoreInvalidEndpoint()) {
LOG.debug("Endpoint uri is invalid: {}. This exception will be ignored.", recipient, e);
} else {
exchange.setException(e);
}
callback.done(true);
return true;
}
// grab the real delegate consumer that performs the actual polling
Consumer delegate = consumer;
if (consumer instanceof EventDrivenPollingConsumer) {
delegate = ((EventDrivenPollingConsumer) consumer).getDelegateConsumer();
}
// is the consumer bridging the error handler?
boolean bridgeErrorHandler = false;
if (delegate instanceof DefaultConsumer) {
ExceptionHandler handler = ((DefaultConsumer) delegate).getExceptionHandler();
if (handler instanceof BridgeExceptionHandlerToErrorHandler) {
bridgeErrorHandler = true;
}
}
Exchange resourceExchange;
try {
if (timeout < 0) {
LOG.debug("Consumer receive: {}", consumer);
resourceExchange = consumer.receive();
} else if (timeout == 0) {
LOG.debug("Consumer receiveNoWait: {}", consumer);
resourceExchange = consumer.receiveNoWait();
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Consumer receive with timeout: {} ms. {}", timeout, consumer);
}
resourceExchange = consumer.receive(timeout);
}
if (resourceExchange == null) {
LOG.debug("Consumer received no exchange");
} else {
LOG.debug("Consumer received: {}", resourceExchange);
}
} catch (Exception e) {
exchange.setException(new CamelExchangeException("Error during poll", exchange, e));
callback.done(true);
return true;
} finally {
// return the consumer back to the cache
consumerCache.releasePollingConsumer(endpoint, consumer);
// and stop prototype endpoints
if (prototype) {
ServiceHelper.stopAndShutdownService(endpoint);
}
}
// remember current redelivery stats
Object redeliveried = exchange.getIn().getHeader(Exchange.REDELIVERED);
Object redeliveryCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER);
Object redeliveryMaxCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_MAX_COUNTER);
// if we are bridging error handler and failed then remember the caused exception
Throwable cause = null;
if (resourceExchange != null && bridgeErrorHandler) {
cause = resourceExchange.getException();
}
// if we should store the received message body in a variable,
// then we need to preserve the original message body
Object originalBody = null;
Map<String, Object> originalHeaders = null;
if (variableReceive != null) {
try {
originalBody = exchange.getMessage().getBody();
// do a defensive copy of the headers
originalHeaders = headersMapFactory.newMap(exchange.getMessage().getHeaders());
} catch (Exception throwable) {
exchange.setException(throwable);
callback.done(true);
return true;
}
}
try {
if (!isAggregateOnException() && resourceExchange != null && resourceExchange.isFailed()) {
// copy resource exchange onto original exchange (preserving pattern)
// and preserve redelivery headers
copyResultsPreservePattern(exchange, resourceExchange);
} else {
prepareResult(exchange);
// prepare the exchanges for aggregation
ExchangeHelper.prepareAggregation(exchange, resourceExchange);
// must catch any exception from aggregation
Exchange aggregatedExchange = aggregationStrategy.aggregate(exchange, resourceExchange);
if (aggregatedExchange != null) {
if (ExchangeHelper.shouldSetVariableResult(aggregatedExchange, variableReceive)) {
// result should be stored in variable instead of message body
ExchangeHelper.setVariableFromMessageBodyAndHeaders(aggregatedExchange, variableReceive,
aggregatedExchange.getMessage());
aggregatedExchange.getMessage().setBody(originalBody);
aggregatedExchange.getMessage().setHeaders(originalHeaders);
}
// copy aggregation result onto original exchange (preserving pattern)
copyResultsPreservePattern(exchange, aggregatedExchange);
// handover any synchronization
if (resourceExchange != null) {
resourceExchange.getExchangeExtension().handoverCompletions(exchange);
}
}
}
// if we failed then restore caused exception
if (cause != null) {
// restore caused exception
exchange.setException(cause);
// remove the exhausted marker as we want to be able to perform redeliveries with the error handler
exchange.getExchangeExtension().setRedeliveryExhausted(false);
// preserve the redelivery stats
if (redeliveried != null) {
exchange.getMessage().setHeader(Exchange.REDELIVERED, redeliveried);
}
if (redeliveryCounter != null) {
exchange.getMessage().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter);
}
if (redeliveryMaxCounter != null) {
exchange.getMessage().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter);
}
}
// set property with the uri of the endpoint enriched so we can use that for tracing etc
exchange.setProperty(ExchangePropertyKey.TO_ENDPOINT, consumer.getEndpoint().getEndpointUri());
} catch (Exception e) {
exchange.setException(new CamelExchangeException("Error occurred during aggregation", exchange, e));
callback.done(true);
return true;
}
callback.done(true);
return true;
}
protected static Object prepareRecipient(Exchange exchange, Object recipient) throws NoTypeConversionAvailableException {
if (recipient instanceof Endpoint || recipient instanceof NormalizedEndpointUri) {
return recipient;
} else if (recipient instanceof String) {
// trim strings as end users might have added spaces between separators
recipient = ((String) recipient).trim();
}
if (recipient != null) {
CamelContext ecc = exchange.getContext();
String uri;
if (recipient instanceof String) {
uri = (String) recipient;
} else {
// convert to a string type we can work with
uri = ecc.getTypeConverter().mandatoryConvertTo(String.class, exchange, recipient);
}
// optimize and normalize endpoint
return ecc.getCamelContextExtension().normalizeUri(uri);
}
return null;
}
protected static Endpoint getExistingEndpoint(CamelContext context, Object recipient) {
if (recipient instanceof Endpoint) {
return (Endpoint) recipient;
}
if (recipient != null) {
if (recipient instanceof NormalizedEndpointUri) {
NormalizedEndpointUri nu = (NormalizedEndpointUri) recipient;
ExtendedCamelContext ecc = context.getCamelContextExtension();
return ecc.hasEndpoint(nu);
} else {
String uri = recipient.toString();
return context.hasEndpoint(uri);
}
}
return null;
}
protected static Endpoint resolveEndpoint(CamelContext camelContext, Object recipient, boolean prototype) {
return prototype
? ExchangeHelper.resolvePrototypeEndpoint(camelContext, recipient)
: ExchangeHelper.resolveEndpoint(camelContext, recipient);
}
/**
* Strategy to pre check polling.
* <p/>
* Is currently used to prevent doing poll enrich from a file based endpoint when the current route also started
* from a file based endpoint as that is not currently supported.
*
* @param exchange the current exchange
*/
protected void preCheckPoll(Exchange exchange) throws Exception {
// noop
}
private static void prepareResult(Exchange exchange) {
if (exchange.getPattern().isOutCapable()) {
exchange.getOut().copyFrom(exchange.getIn());
}
}
@Override
public String toString() {
return id;
}
@Override
protected void doBuild() throws Exception {
if (consumerCache == null) {
// create consumer cache if we use dynamic expressions for computing the endpoints to poll
consumerCache = new DefaultConsumerCache(this, camelContext, cacheSize);
LOG.debug("PollEnrich {} using ConsumerCache with cacheSize={}", this, cacheSize);
}
if (aggregationStrategy == null) {
aggregationStrategy = new CopyAggregationStrategy();
}
CamelContextAware.trySetCamelContext(aggregationStrategy, camelContext);
ServiceHelper.buildService(consumerCache, aggregationStrategy);
}
@Override
protected void doInit() throws Exception {
if (expression != null) {
expression.init(camelContext);
}
if (isAutoStartupComponents() && uri != null) {
// in case path has property placeholders then try to let property component resolve those
String u = EndpointHelper.resolveEndpointUriPropertyPlaceholders(camelContext, uri);
// find out which component it is
scheme = ExchangeHelper.resolveScheme(u);
}
headersMapFactory = camelContext.getCamelContextExtension().getHeadersMapFactory();
ServiceHelper.initService(consumerCache, aggregationStrategy);
}
@Override
protected void doStart() throws Exception {
// ensure the component is started
if (autoStartupComponents && scheme != null) {
camelContext.getComponent(scheme);
}
ServiceHelper.startService(consumerCache, aggregationStrategy);
}
@Override
protected void doStop() throws Exception {
ServiceHelper.stopService(aggregationStrategy, consumerCache);
}
@Override
protected void doShutdown() throws Exception {
ServiceHelper.stopAndShutdownServices(aggregationStrategy, consumerCache);
}
private static class CopyAggregationStrategy implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (newExchange != null) {
copyResultsPreservePattern(oldExchange, newExchange);
} else {
// if no newExchange then there was no message from the external resource
// and therefore we should set an empty body to indicate this fact
// but keep headers/attachments as we want to propagate those
oldExchange.getIn().setBody(null);
oldExchange.setOut(null);
}
return oldExchange;
}
}
}