001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.component.mock;
018
019import java.io.File;
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Collection;
023import java.util.Date;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.Set;
028import java.util.concurrent.CopyOnWriteArrayList;
029import java.util.concurrent.CopyOnWriteArraySet;
030import java.util.concurrent.CountDownLatch;
031import java.util.concurrent.TimeUnit;
032
033import org.apache.camel.AsyncCallback;
034import org.apache.camel.CamelContext;
035import org.apache.camel.Component;
036import org.apache.camel.Consumer;
037import org.apache.camel.Endpoint;
038import org.apache.camel.Exchange;
039import org.apache.camel.ExchangePattern;
040import org.apache.camel.Expression;
041import org.apache.camel.Handler;
042import org.apache.camel.Message;
043import org.apache.camel.Predicate;
044import org.apache.camel.Processor;
045import org.apache.camel.Producer;
046import org.apache.camel.builder.ProcessorBuilder;
047import org.apache.camel.impl.DefaultAsyncProducer;
048import org.apache.camel.impl.DefaultEndpoint;
049import org.apache.camel.impl.InterceptSendToEndpoint;
050import org.apache.camel.spi.BrowsableEndpoint;
051import org.apache.camel.spi.Metadata;
052import org.apache.camel.spi.UriEndpoint;
053import org.apache.camel.spi.UriParam;
054import org.apache.camel.spi.UriPath;
055import org.apache.camel.util.CamelContextHelper;
056import org.apache.camel.util.ExchangeHelper;
057import org.apache.camel.util.ExpressionComparator;
058import org.apache.camel.util.FileUtil;
059import org.apache.camel.util.ObjectHelper;
060import org.apache.camel.util.StopWatch;
061import org.slf4j.Logger;
062import org.slf4j.LoggerFactory;
063
064/**
065 * The mock component is used for testing routes and mediation rules using mocks.
066 * <p/>
067 * A Mock endpoint which provides a literate, fluent API for testing routes
068 * using a <a href="http://jmock.org/">JMock style</a> API.
069 * <p/>
070 * The mock endpoint have two set of methods
071 * <ul>
072 *   <li>expectedXXX or expectsXXX - To set pre conditions, before the test is executed</li>
073 *   <li>assertXXX - To assert assertions, after the test has been executed</li>
074 * </ul>
075 * Its <b>important</b> to know the difference between the two set. The former is used to
076 * set expectations before the test is being started (eg before the mock receives messages).
077 * The latter is used after the test has been executed, to verify the expectations; or
078 * other assertions which you can perform after the test has been completed.
079 * <p/>
080 * <b>Beware:</b> If you want to expect a mock does not receive any messages, by calling
081 * {@link #setExpectedMessageCount(int)} with <tt>0</tt>, then take extra care,
082 * as <tt>0</tt> matches when the tests starts, so you need to set a assert period time
083 * to let the test run for a while to make sure there are still no messages arrived; for
084 * that use {@link #setAssertPeriod(long)}.
085 * An alternative is to use <a href="http://camel.apache.org/notifybuilder.html">NotifyBuilder</a>, and use the notifier
086 * to know when Camel is done routing some messages, before you call the {@link #assertIsSatisfied()} method on the mocks.
087 * This allows you to not use a fixed assert period, to speedup testing times.
088 * <p/>
089 * <b>Important:</b> If using {@link #expectedMessageCount(int)} and also {@link #expectedBodiesReceived(java.util.List)} or
090 * {@link #expectedHeaderReceived(String, Object)} then the latter overrides the number of expected message based on the
091 * number of values provided in the bodies/headers.
092 *
093 * @version 
094 */
095@UriEndpoint(firstVersion = "1.0.0", scheme = "mock", title = "Mock", syntax = "mock:name", producerOnly = true, label = "core,testing", lenientProperties = true)
096public class MockEndpoint extends DefaultEndpoint implements BrowsableEndpoint {
097    private static final Logger LOG = LoggerFactory.getLogger(MockEndpoint.class);
098    // must be volatile so changes is visible between the thread which performs the assertions
099    // and the threads which process the exchanges when routing messages in Camel
100    protected volatile Processor reporter;
101    
102    private volatile Processor defaultProcessor;
103    private volatile Map<Integer, Processor> processors;
104    private volatile List<Exchange> receivedExchanges;
105    private volatile List<Throwable> failures;
106    private volatile List<Runnable> tests;
107    private volatile CountDownLatch latch;
108    private volatile int expectedMinimumCount;
109    private volatile List<?> expectedBodyValues;
110    private volatile List<Object> actualBodyValues;
111    private volatile Map<String, Object> expectedHeaderValues;
112    private volatile Map<String, Object> actualHeaderValues;
113    private volatile Map<String, Object> expectedPropertyValues;
114    private volatile Map<String, Object> actualPropertyValues;
115
116    private volatile int counter;
117
118    @UriPath(description = "Name of mock endpoint") @Metadata(required = "true")
119    private String name;
120    @UriParam(label = "producer", defaultValue = "-1")
121    private int expectedCount;
122    @UriParam(label = "producer", defaultValue = "0")
123    private long sleepForEmptyTest;
124    @UriParam(label = "producer", defaultValue = "0")
125    private long resultWaitTime;
126    @UriParam(label = "producer", defaultValue = "0")
127    private long resultMinimumWaitTime;
128    @UriParam(label = "producer", defaultValue = "0")
129    private long assertPeriod;
130    @UriParam(label = "producer", defaultValue = "-1")
131    private int retainFirst;
132    @UriParam(label = "producer", defaultValue = "-1")
133    private int retainLast;
134    @UriParam(label = "producer")
135    private int reportGroup;
136    @UriParam(label = "producer,advanced", defaultValue = "true")
137    private boolean copyOnExchange = true;
138
139    public MockEndpoint(String endpointUri, Component component) {
140        super(endpointUri, component);
141        init();
142    }
143
144    @Deprecated
145    public MockEndpoint(String endpointUri) {
146        super(endpointUri);
147        init();
148    }
149
150    public MockEndpoint() {
151        this(null);
152    }
153
154    /**
155     * A helper method to resolve the mock endpoint of the given URI on the given context
156     *
157     * @param context the camel context to try resolve the mock endpoint from
158     * @param uri the uri of the endpoint to resolve
159     * @return the endpoint
160     */
161    public static MockEndpoint resolve(CamelContext context, String uri) {
162        return CamelContextHelper.getMandatoryEndpoint(context, uri, MockEndpoint.class);
163    }
164
165    public static void assertWait(long timeout, TimeUnit unit, MockEndpoint... endpoints) throws InterruptedException {
166        long start = System.currentTimeMillis();
167        long left = unit.toMillis(timeout);
168        long end = start + left;
169        for (MockEndpoint endpoint : endpoints) {
170            if (!endpoint.await(left, TimeUnit.MILLISECONDS)) {
171                throw new AssertionError("Timeout waiting for endpoints to receive enough messages. " + endpoint.getEndpointUri() + " timed out.");
172            }
173            left = end - System.currentTimeMillis();
174            if (left <= 0) {
175                left = 0;
176            }
177        }
178    }
179
180    public static void assertIsSatisfied(long timeout, TimeUnit unit, MockEndpoint... endpoints) throws InterruptedException {
181        assertWait(timeout, unit, endpoints);
182        for (MockEndpoint endpoint : endpoints) {
183            endpoint.assertIsSatisfied();
184        }
185    }
186
187    public static void assertIsSatisfied(MockEndpoint... endpoints) throws InterruptedException {
188        for (MockEndpoint endpoint : endpoints) {
189            endpoint.assertIsSatisfied();
190        }
191    }
192
193
194    /**
195     * Asserts that all the expectations on any {@link MockEndpoint} instances registered
196     * in the given context are valid
197     *
198     * @param context the camel context used to find all the available endpoints to be asserted
199     */
200    public static void assertIsSatisfied(CamelContext context) throws InterruptedException {
201        ObjectHelper.notNull(context, "camelContext");
202        Collection<Endpoint> endpoints = context.getEndpoints();
203        for (Endpoint endpoint : endpoints) {
204            // if the endpoint was intercepted we should get the delegate
205            if (endpoint instanceof InterceptSendToEndpoint) {
206                endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
207            }
208            if (endpoint instanceof MockEndpoint) {
209                MockEndpoint mockEndpoint = (MockEndpoint) endpoint;
210                mockEndpoint.assertIsSatisfied();
211            }
212        }
213    }
214
215    /**
216     * Asserts that all the expectations on any {@link MockEndpoint} instances registered
217     * in the given context are valid
218     *
219     * @param context the camel context used to find all the available endpoints to be asserted
220     * @param timeout timeout
221     * @param unit    time unit
222     */
223    public static void assertIsSatisfied(CamelContext context, long timeout, TimeUnit unit) throws InterruptedException {
224        ObjectHelper.notNull(context, "camelContext");
225        ObjectHelper.notNull(unit, "unit");
226        Collection<Endpoint> endpoints = context.getEndpoints();
227        long millis = unit.toMillis(timeout);
228        for (Endpoint endpoint : endpoints) {
229            // if the endpoint was intercepted we should get the delegate
230            if (endpoint instanceof InterceptSendToEndpoint) {
231                endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
232            }
233            if (endpoint instanceof MockEndpoint) {
234                MockEndpoint mockEndpoint = (MockEndpoint) endpoint;
235                mockEndpoint.setResultWaitTime(millis);
236                mockEndpoint.assertIsSatisfied();
237            }
238        }
239    }
240
241    /**
242     * Sets the assert period on all the expectations on any {@link MockEndpoint} instances registered
243     * in the given context.
244     *
245     * @param context the camel context used to find all the available endpoints
246     * @param period the period in millis
247     */
248    public static void setAssertPeriod(CamelContext context, long period) {
249        ObjectHelper.notNull(context, "camelContext");
250        Collection<Endpoint> endpoints = context.getEndpoints();
251        for (Endpoint endpoint : endpoints) {
252            // if the endpoint was intercepted we should get the delegate
253            if (endpoint instanceof InterceptSendToEndpoint) {
254                endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
255            }
256            if (endpoint instanceof MockEndpoint) {
257                MockEndpoint mockEndpoint = (MockEndpoint) endpoint;
258                mockEndpoint.setAssertPeriod(period);
259            }
260        }
261    }
262
263    /**
264     * Reset all mock endpoints
265     *
266     * @param context the camel context used to find all the available endpoints to reset
267     */
268    public static void resetMocks(CamelContext context) {
269        ObjectHelper.notNull(context, "camelContext");
270        Collection<Endpoint> endpoints = context.getEndpoints();
271        for (Endpoint endpoint : endpoints) {
272            // if the endpoint was intercepted we should get the delegate
273            if (endpoint instanceof InterceptSendToEndpoint) {
274                endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
275            }
276            if (endpoint instanceof MockEndpoint) {
277                MockEndpoint mockEndpoint = (MockEndpoint) endpoint;
278                mockEndpoint.reset();
279            }
280        }
281    }
282
283    public static void expectsMessageCount(int count, MockEndpoint... endpoints) throws InterruptedException {
284        for (MockEndpoint endpoint : endpoints) {
285            endpoint.setExpectedMessageCount(count);
286        }
287    }
288
289    public List<Exchange> getExchanges() {
290        return getReceivedExchanges();
291    }
292
293    public Consumer createConsumer(Processor processor) throws Exception {
294        throw new UnsupportedOperationException("You cannot consume from this endpoint");
295    }
296
297    public Producer createProducer() throws Exception {
298        return new DefaultAsyncProducer(this) {
299            public boolean process(Exchange exchange, AsyncCallback callback) {
300                onExchange(exchange);
301                callback.done(true);
302                return true;
303            }
304        };
305    }
306
307    public void reset() {
308        init();
309    }
310
311
312    // Testing API
313    // -------------------------------------------------------------------------
314
315    /**
316     * Handles the incoming exchange.
317     * <p/>
318     * This method turns this mock endpoint into a bean which you can use
319     * in the Camel routes, which allows you to inject MockEndpoint as beans
320     * in your routes and use the features of the mock to control the bean.
321     *
322     * @param exchange  the exchange
323     * @throws Exception can be thrown
324     */
325    @Handler
326    public void handle(Exchange exchange) throws Exception {
327        onExchange(exchange);
328    }
329
330    /**
331     * Set the processor that will be invoked when the index
332     * message is received.
333     */
334    public void whenExchangeReceived(int index, Processor processor) {
335        this.processors.put(index, processor);
336    }
337
338    /**
339     * Set the processor that will be invoked when the some message
340     * is received.
341     *
342     * This processor could be overwritten by
343     * {@link #whenExchangeReceived(int, Processor)} method.
344     */
345    public void whenAnyExchangeReceived(Processor processor) {
346        this.defaultProcessor = processor;
347    }
348    
349    /**
350     * Set the expression which value will be set to the message body
351     * @param expression which is use to set the message body 
352     */
353    public void returnReplyBody(Expression expression) {
354        this.defaultProcessor = ProcessorBuilder.setBody(expression);
355    }
356    
357    /**
358     * Set the expression which value will be set to the message header
359     * @param headerName that will be set value
360     * @param expression which is use to set the message header 
361     */
362    public void returnReplyHeader(String headerName, Expression expression) {
363        this.defaultProcessor = ProcessorBuilder.setHeader(headerName, expression);
364    }
365    
366
367    /**
368     * Validates that all the available expectations on this endpoint are
369     * satisfied; or throw an exception
370     */
371    public void assertIsSatisfied() throws InterruptedException {
372        assertIsSatisfied(sleepForEmptyTest);
373    }
374
375    /**
376     * Validates that all the available expectations on this endpoint are
377     * satisfied; or throw an exception
378     *
379     * @param timeoutForEmptyEndpoints the timeout in milliseconds that we
380     *                should wait for the test to be true
381     */
382    public void assertIsSatisfied(long timeoutForEmptyEndpoints) throws InterruptedException {
383        LOG.info("Asserting: {} is satisfied", this);
384        doAssertIsSatisfied(timeoutForEmptyEndpoints);
385        if (assertPeriod > 0) {
386            // if an assert period was set then re-assert again to ensure the assertion is still valid
387            Thread.sleep(assertPeriod);
388            LOG.info("Re-asserting: {} is satisfied after {} millis", this, assertPeriod);
389            // do not use timeout when we re-assert
390            doAssertIsSatisfied(0);
391        }
392    }
393
394    protected void doAssertIsSatisfied(long timeoutForEmptyEndpoints) throws InterruptedException {
395        if (expectedCount == 0) {
396            if (timeoutForEmptyEndpoints > 0) {
397                LOG.debug("Sleeping for: {} millis to check there really are no messages received", timeoutForEmptyEndpoints);
398                Thread.sleep(timeoutForEmptyEndpoints);
399            }
400            assertEquals("Received message count", expectedCount, getReceivedCounter());
401        } else if (expectedCount > 0) {
402            if (expectedCount != getReceivedCounter()) {
403                waitForCompleteLatch();
404            }
405            assertEquals("Received message count", expectedCount, getReceivedCounter());
406        } else if (expectedMinimumCount > 0 && getReceivedCounter() < expectedMinimumCount) {
407            waitForCompleteLatch();
408        }
409
410        if (expectedMinimumCount >= 0) {
411            int receivedCounter = getReceivedCounter();
412            assertTrue("Received message count " + receivedCounter + ", expected at least " + expectedMinimumCount, expectedMinimumCount <= receivedCounter);
413        }
414
415        for (Runnable test : tests) {
416            test.run();
417        }
418
419        for (Throwable failure : failures) {
420            if (failure != null) {
421                LOG.error("Caught on " + getEndpointUri() + " Exception: " + failure, failure);
422                fail("Failed due to caught exception: " + failure);
423            }
424        }
425    }
426
427    /**
428     * Validates that the assertions fail on this endpoint
429     */
430    public void assertIsNotSatisfied() throws InterruptedException {
431        boolean failed = false;
432        try {
433            assertIsSatisfied();
434            // did not throw expected error... fail!
435            failed = true;
436        } catch (AssertionError e) {
437            if (LOG.isDebugEnabled()) {
438                // log incl stacktrace
439                LOG.debug("Caught expected failure: " + e.getMessage(), e);
440            } else {
441                LOG.info("Caught expected failure: " + e.getMessage());
442            }
443        }
444        if (failed) {
445            // fail() throws the AssertionError to indicate the test failed. 
446            fail("Expected assertion failure but test succeeded!");
447        }
448    }
449
450    /**
451     * Validates that the assertions fail on this endpoint
452
453     * @param timeoutForEmptyEndpoints the timeout in milliseconds that we
454     *        should wait for the test to be true
455     */
456    public void assertIsNotSatisfied(long timeoutForEmptyEndpoints) throws InterruptedException {
457        boolean failed = false;
458        try {
459            assertIsSatisfied(timeoutForEmptyEndpoints);
460            // did not throw expected error... fail!
461            failed = true;
462        } catch (AssertionError e) {
463            if (LOG.isDebugEnabled()) {
464                // log incl stacktrace
465                LOG.debug("Caught expected failure: " + e.getMessage(), e);
466            } else {
467                LOG.info("Caught expected failure: " + e.getMessage());
468            }
469        }
470        if (failed) { 
471            // fail() throws the AssertionError to indicate the test failed. 
472            fail("Expected assertion failure but test succeeded!");
473        }
474    }    
475    
476    /**
477     * Specifies the expected number of message exchanges that should be
478     * received by this endpoint
479     *
480     * If you want to assert that <b>exactly</b> n messages arrives to this mock
481     * endpoint, then see also the {@link #setAssertPeriod(long)} method for further details.
482     *
483     * @param expectedCount the number of message exchanges that should be
484     *                expected by this endpoint
485     * @see #setAssertPeriod(long)
486     */
487    public void expectedMessageCount(int expectedCount) {
488        setExpectedMessageCount(expectedCount);
489    }
490
491    /**
492     * Sets a grace period after which the mock endpoint will re-assert
493     * to ensure the preliminary assertion is still valid.
494     * <p/>
495     * This is used for example to assert that <b>exactly</b> a number of messages 
496     * arrives. For example if {@link #expectedMessageCount(int)} was set to 5, then
497     * the assertion is satisfied when 5 or more message arrives. To ensure that
498     * exactly 5 messages arrives, then you would need to wait a little period
499     * to ensure no further message arrives. This is what you can use this
500     * {@link #setAssertPeriod(long)} method for.
501     * <p/>
502     * By default this period is disabled.
503     *
504     * @param period grace period in millis
505     */
506    public void setAssertPeriod(long period) {
507        this.assertPeriod = period;
508    }
509
510    /**
511     * Specifies the minimum number of expected message exchanges that should be
512     * received by this endpoint
513     *
514     * @param expectedCount the number of message exchanges that should be
515     *                expected by this endpoint
516     */
517    public void expectedMinimumMessageCount(int expectedCount) {
518        setMinimumExpectedMessageCount(expectedCount);
519    }
520
521    /**
522     * Sets an expectation that the given header name & value are received by this endpoint
523     * <p/>
524     * You can set multiple expectations for different header names.
525     * If you set a value of <tt>null</tt> that means we accept either the header is absent, or its value is <tt>null</tt>
526     */
527    public void expectedHeaderReceived(final String name, final Object value) {
528        // default to 1 expected message if unset message count
529        if (expectedCount == -1 && expectedMinimumCount == -1) {
530            expectedMessageCount(1);
531        }
532        if (expectedHeaderValues == null) {
533            expectedHeaderValues = getCamelContext().getHeadersMapFactory().newMap();
534            // we just wants to expects to be called once
535            expects(new Runnable() {
536                public void run() {
537                    for (int i = 0; i < getReceivedExchanges().size(); i++) {
538                        Exchange exchange = getReceivedExchange(i);
539                        for (Map.Entry<String, Object> entry : expectedHeaderValues.entrySet()) {
540                            String key = entry.getKey();
541                            Object expectedValue = entry.getValue();
542
543                            // we accept that an expectedValue of null also means that the header may be absent
544                            if (expectedValue != null) {
545                                assertTrue("Exchange " + i + " has no headers", exchange.getIn().hasHeaders());
546                                boolean hasKey = exchange.getIn().getHeaders().containsKey(key);
547                                assertTrue("No header with name " + key + " found for message: " + i, hasKey);
548                            }
549
550                            Object actualValue = exchange.getIn().getHeader(key);
551                            actualValue = extractActualValue(exchange, actualValue, expectedValue);
552
553                            assertEquals("Header with name " + key + " for message: " + i, expectedValue, actualValue);
554                        }
555                    }
556                }
557            });
558        }
559        expectedHeaderValues.put(name, value);
560    }
561
562    /**
563     * Adds an expectation that the given header values are received by this
564     * endpoint in any order.
565     * <p/>
566     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
567     * there must be 3 values.
568     * <p/>
569     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
570     */
571    public void expectedHeaderValuesReceivedInAnyOrder(final String name, final List<?> values) {
572        expectedMessageCount(values.size());
573
574        expects(new Runnable() {
575            public void run() {
576                // these are the expected values to find
577                final Set<Object> actualHeaderValues = new CopyOnWriteArraySet<>(values);
578
579                for (int i = 0; i < getReceivedExchanges().size(); i++) {
580                    Exchange exchange = getReceivedExchange(i);
581
582                    Object actualValue = exchange.getIn().getHeader(name);
583                    for (Object expectedValue : actualHeaderValues) {
584                        actualValue = extractActualValue(exchange, actualValue, expectedValue);
585                        // remove any found values
586                        actualHeaderValues.remove(actualValue);
587                    }
588                }
589
590                // should be empty, as we should find all the values
591                assertTrue("Expected " + values.size() + " headers with key[" + name + "], received " + (values.size() - actualHeaderValues.size())
592                        + " headers. Expected header values: " + actualHeaderValues, actualHeaderValues.isEmpty());
593            }
594        });
595    }
596
597    /**
598     * Adds an expectation that the given header values are received by this
599     * endpoint in any order
600     * <p/>
601     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
602     * there must be 3 values.
603     * <p/>
604     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
605     */
606    public void expectedHeaderValuesReceivedInAnyOrder(String name, Object... values) {
607        List<Object> valueList = new ArrayList<>();
608        valueList.addAll(Arrays.asList(values));
609        expectedHeaderValuesReceivedInAnyOrder(name, valueList);
610    }
611
612    /**
613     * Sets an expectation that the given property name & value are received by this endpoint
614     * <p/>
615     * You can set multiple expectations for different property names.
616     * If you set a value of <tt>null</tt> that means we accept either the property is absent, or its value is <tt>null</tt>
617     */
618    public void expectedPropertyReceived(final String name, final Object value) {
619        if (expectedPropertyValues == null) {
620            expectedPropertyValues = new HashMap<>();
621        }
622        expectedPropertyValues.put(name, value);
623
624        expects(new Runnable() {
625            public void run() {
626                for (int i = 0; i < getReceivedExchanges().size(); i++) {
627                    Exchange exchange = getReceivedExchange(i);
628                    for (Map.Entry<String, Object> entry : expectedPropertyValues.entrySet()) {
629                        String key = entry.getKey();
630                        Object expectedValue = entry.getValue();
631
632                        // we accept that an expectedValue of null also means that the property may be absent
633                        if (expectedValue != null) {
634                            assertTrue("Exchange " + i + " has no properties", !exchange.getProperties().isEmpty());
635                            boolean hasKey = exchange.getProperties().containsKey(key);
636                            assertTrue("No property with name " + key + " found for message: " + i, hasKey);
637                        }
638
639                        Object actualValue = exchange.getProperty(key);
640                        actualValue = extractActualValue(exchange, actualValue, expectedValue);
641
642                        assertEquals("Property with name " + key + " for message: " + i, expectedValue, actualValue);
643                    }
644                }
645            }
646        });
647    }
648
649    /**
650     * Adds an expectation that the given property values are received by this
651     * endpoint in any order.
652     * <p/>
653     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
654     * there must be 3 values.
655     * <p/>
656     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
657     */
658    public void expectedPropertyValuesReceivedInAnyOrder(final String name, final List<?> values) {
659        expectedMessageCount(values.size());
660
661        expects(new Runnable() {
662            public void run() {
663                // these are the expected values to find
664                final Set<Object> actualPropertyValues = new CopyOnWriteArraySet<>(values);
665
666                for (int i = 0; i < getReceivedExchanges().size(); i++) {
667                    Exchange exchange = getReceivedExchange(i);
668
669                    Object actualValue = exchange.getProperty(name);
670                    for (Object expectedValue : actualPropertyValues) {
671                        actualValue = extractActualValue(exchange, actualValue, expectedValue);
672                        // remove any found values
673                        actualPropertyValues.remove(actualValue);
674                    }
675                }
676
677                // should be empty, as we should find all the values
678                assertTrue("Expected " + values.size() + " properties with key[" + name + "], received " + (values.size() - actualPropertyValues.size())
679                        + " properties. Expected property values: " + actualPropertyValues, actualPropertyValues.isEmpty());
680            }
681        });
682    }
683
684    /**
685     * Adds an expectation that the given property values are received by this
686     * endpoint in any order
687     * <p/>
688     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
689     * there must be 3 values.
690     * <p/>
691     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
692     */
693    public void expectedPropertyValuesReceivedInAnyOrder(String name, Object... values) {
694        List<Object> valueList = new ArrayList<>();
695        valueList.addAll(Arrays.asList(values));
696        expectedPropertyValuesReceivedInAnyOrder(name, valueList);
697    }    
698
699    /**
700     * Adds an expectation that the given body values are received by this
701     * endpoint in the specified order
702     * <p/>
703     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
704     * there must be 3 values.
705     * <p/>
706     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
707     */
708    public void expectedBodiesReceived(final List<?> bodies) {
709        expectedMessageCount(bodies.size());
710        this.expectedBodyValues = bodies;
711        this.actualBodyValues = new ArrayList<>();
712
713        expects(new Runnable() {
714            public void run() {
715                for (int i = 0; i < expectedBodyValues.size(); i++) {
716                    Exchange exchange = getReceivedExchange(i);
717                    assertTrue("No exchange received for counter: " + i, exchange != null);
718
719                    Object expectedBody = expectedBodyValues.get(i);
720                    Object actualBody = null;
721                    if (i < actualBodyValues.size()) {
722                        actualBody = actualBodyValues.get(i);
723                    }
724                    actualBody = extractActualValue(exchange, actualBody, expectedBody);
725
726                    assertEquals("Body of message: " + i, expectedBody, actualBody);
727                }
728            }
729        });
730    }
731
732    private Object extractActualValue(Exchange exchange, Object actualValue, Object expectedValue) {
733        if (actualValue == null) {
734            return null;
735        }
736
737        if (actualValue instanceof Expression) {
738            Class clazz = Object.class;
739            if (expectedValue != null) {
740                clazz = expectedValue.getClass();
741            }
742            actualValue = ((Expression)actualValue).evaluate(exchange, clazz);
743        } else if (actualValue instanceof Predicate) {
744            actualValue = ((Predicate)actualValue).matches(exchange);
745        } else if (expectedValue != null) {
746            String from = actualValue.getClass().getName();
747            String to = expectedValue.getClass().getName();
748            actualValue = getCamelContext().getTypeConverter().convertTo(expectedValue.getClass(), exchange, actualValue);
749            assertTrue("There is no type conversion possible from " + from + " to " + to, actualValue != null);
750        }
751        return actualValue;
752    }
753
754    /**
755     * Sets an expectation that the given predicates matches the received messages by this endpoint
756     */
757    public void expectedMessagesMatches(Predicate... predicates) {
758        for (int i = 0; i < predicates.length; i++) {
759            final int messageIndex = i;
760            final Predicate predicate = predicates[i];
761            final AssertionClause clause = new AssertionClause(this) {
762                public void run() {
763                    addPredicate(predicate);
764                    applyAssertionOn(MockEndpoint.this, messageIndex, assertExchangeReceived(messageIndex));
765                }
766            };
767            expects(clause);
768        }
769    }
770
771    /**
772     * Sets an expectation that the given body values are received by this endpoint
773     * <p/>
774     * <b>Important:</b> The number of bodies must match the expected number of messages, so if you expect 3 messages, then
775     * there must be 3 bodies.
776     * <p/>
777     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
778     */
779    public void expectedBodiesReceived(Object... bodies) {
780        List<Object> bodyList = new ArrayList<>();
781        bodyList.addAll(Arrays.asList(bodies));
782        expectedBodiesReceived(bodyList);
783    }
784
785    /**
786     * Adds an expectation that the given body value are received by this endpoint
787     */
788    public AssertionClause expectedBodyReceived() {
789        expectedMessageCount(1);
790        final AssertionClause clause = new AssertionClause(this) {
791            public void run() {
792                Exchange exchange = getReceivedExchange(0);
793                assertTrue("No exchange received for counter: " + 0, exchange != null);
794
795                Object actualBody = exchange.getIn().getBody();
796                Expression exp = createExpression(getCamelContext());
797                Object expectedBody = exp.evaluate(exchange, Object.class);
798
799                assertEquals("Body of message: " + 0, expectedBody, actualBody);
800            }
801        };
802        expects(clause);
803        return clause;
804    }
805
806    /**
807     * Adds an expectation that the given body values are received by this
808     * endpoint in any order
809     * <p/>
810     * <b>Important:</b> The number of bodies must match the expected number of messages, so if you expect 3 messages, then
811     * there must be 3 bodies.
812     * <p/>
813     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
814     */
815    public void expectedBodiesReceivedInAnyOrder(final List<?> bodies) {
816        expectedMessageCount(bodies.size());
817        this.expectedBodyValues = bodies;
818        this.actualBodyValues = new ArrayList<>();
819
820        expects(new Runnable() {
821            public void run() {
822                List<Object> actualBodyValuesSet = new ArrayList<>(actualBodyValues);
823                for (int i = 0; i < expectedBodyValues.size(); i++) {
824                    Exchange exchange = getReceivedExchange(i);
825                    assertTrue("No exchange received for counter: " + i, exchange != null);
826
827                    Object expectedBody = expectedBodyValues.get(i);
828                    assertTrue("Message with body " + expectedBody + " was expected but not found in " + actualBodyValuesSet, actualBodyValuesSet.remove(expectedBody));
829                }
830            }
831        });
832    }
833
834    /**
835     * Adds an expectation that the given body values are received by this
836     * endpoint in any order
837     * <p/>
838     * <b>Important:</b> The number of bodies must match the expected number of messages, so if you expect 3 messages, then
839     * there must be 3 bodies.
840     * <p/>
841     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
842     */
843    public void expectedBodiesReceivedInAnyOrder(Object... bodies) {
844        List<Object> bodyList = new ArrayList<>();
845        bodyList.addAll(Arrays.asList(bodies));
846        expectedBodiesReceivedInAnyOrder(bodyList);
847    }
848
849    /**
850     * Adds an expectation that a file exists with the given name
851     *
852     * @param name name of file, will cater for / and \ on different OS platforms
853     */
854    public void expectedFileExists(final String name) {
855        expectedFileExists(name, null);
856    }
857
858    /**
859     * Adds an expectation that a file exists with the given name
860     * <p/>
861     * Will wait at most 5 seconds while checking for the existence of the file.
862     *
863     * @param name name of file, will cater for / and \ on different OS platforms
864     * @param content content of file to compare, can be <tt>null</tt> to not compare content
865     */
866    public void expectedFileExists(final String name, final String content) {
867        final File file = new File(FileUtil.normalizePath(name));
868
869        expects(new Runnable() {
870            public void run() {
871                // wait at most 5 seconds for the file to exists
872                final long timeout = System.currentTimeMillis() + 5000;
873
874                boolean stop = false;
875                while (!stop && !file.exists()) {
876                    try {
877                        Thread.sleep(50);
878                    } catch (InterruptedException e) {
879                        // ignore
880                    }
881                    stop = System.currentTimeMillis() > timeout;
882                }
883
884                assertTrue("The file should exists: " + name, file.exists());
885
886                if (content != null) {
887                    String body = getCamelContext().getTypeConverter().convertTo(String.class, file);
888                    assertEquals("Content of file: " + name, content, body);
889                }
890            }
891        });
892    }
893
894    /**
895     * Adds an expectation that messages received should have the given exchange pattern
896     */
897    public void expectedExchangePattern(final ExchangePattern exchangePattern) {
898        expectedMessagesMatches(new Predicate() {
899            public boolean matches(Exchange exchange) {
900                return exchange.getPattern().equals(exchangePattern);
901            }
902        });
903    }
904
905    /**
906     * Adds an expectation that messages received should have ascending values
907     * of the given expression such as a user generated counter value
908     */
909    public void expectsAscending(final Expression expression) {
910        expects(new Runnable() {
911            public void run() {
912                assertMessagesAscending(expression);
913            }
914        });
915    }
916
917    /**
918     * Adds an expectation that messages received should have ascending values
919     * of the given expression such as a user generated counter value
920     */
921    public AssertionClause expectsAscending() {
922        final AssertionClause clause = new AssertionClause(this) {
923            public void run() {
924                assertMessagesAscending(createExpression(getCamelContext()));
925            }
926        };
927        expects(clause);
928        return clause;
929    }
930
931    /**
932     * Adds an expectation that messages received should have descending values
933     * of the given expression such as a user generated counter value
934     */
935    public void expectsDescending(final Expression expression) {
936        expects(new Runnable() {
937            public void run() {
938                assertMessagesDescending(expression);
939            }
940        });
941    }
942
943    /**
944     * Adds an expectation that messages received should have descending values
945     * of the given expression such as a user generated counter value
946     */
947    public AssertionClause expectsDescending() {
948        final AssertionClause clause = new AssertionClause(this) {
949            public void run() {
950                assertMessagesDescending(createExpression(getCamelContext()));
951            }
952        };
953        expects(clause);
954        return clause;
955    }
956
957    /**
958     * Adds an expectation that no duplicate messages should be received using
959     * the expression to determine the message ID
960     *
961     * @param expression the expression used to create a unique message ID for
962     *                message comparison (which could just be the message
963     *                payload if the payload can be tested for uniqueness using
964     *                {@link Object#equals(Object)} and
965     *                {@link Object#hashCode()}
966     */
967    public void expectsNoDuplicates(final Expression expression) {
968        expects(new Runnable() {
969            public void run() {
970                assertNoDuplicates(expression);
971            }
972        });
973    }
974
975    /**
976     * Adds an expectation that no duplicate messages should be received using
977     * the expression to determine the message ID
978     */
979    public AssertionClause expectsNoDuplicates() {
980        final AssertionClause clause = new AssertionClause(this) {
981            public void run() {
982                assertNoDuplicates(createExpression(getCamelContext()));
983            }
984        };
985        expects(clause);
986        return clause;
987    }
988
989    /**
990     * Asserts that the messages have ascending values of the given expression
991     */
992    public void assertMessagesAscending(Expression expression) {
993        assertMessagesSorted(expression, true);
994    }
995
996    /**
997     * Asserts that the messages have descending values of the given expression
998     */
999    public void assertMessagesDescending(Expression expression) {
1000        assertMessagesSorted(expression, false);
1001    }
1002
1003    protected void assertMessagesSorted(Expression expression, boolean ascending) {
1004        String type = ascending ? "ascending" : "descending";
1005        ExpressionComparator comparator = new ExpressionComparator(expression);
1006        List<Exchange> list = getReceivedExchanges();
1007        for (int i = 1; i < list.size(); i++) {
1008            int j = i - 1;
1009            Exchange e1 = list.get(j);
1010            Exchange e2 = list.get(i);
1011            int result = comparator.compare(e1, e2);
1012            if (result == 0) {
1013                fail("Messages not " + type + ". Messages" + j + " and " + i + " are equal with value: "
1014                    + expression.evaluate(e1, Object.class) + " for expression: " + expression + ". Exchanges: " + e1 + " and " + e2);
1015            } else {
1016                if (!ascending) {
1017                    result = result * -1;
1018                }
1019                if (result > 0) {
1020                    fail("Messages not " + type + ". Message " + j + " has value: " + expression.evaluate(e1, Object.class)
1021                        + " and message " + i + " has value: " + expression.evaluate(e2, Object.class) + " for expression: "
1022                        + expression + ". Exchanges: " + e1 + " and " + e2);
1023                }
1024            }
1025        }
1026    }
1027
1028    public void assertNoDuplicates(Expression expression) {
1029        Map<Object, Exchange> map = new HashMap<>();
1030        List<Exchange> list = getReceivedExchanges();
1031        for (int i = 0; i < list.size(); i++) {
1032            Exchange e2 = list.get(i);
1033            Object key = expression.evaluate(e2, Object.class);
1034            Exchange e1 = map.get(key);
1035            if (e1 != null) {
1036                fail("Duplicate message found on message " + i + " has value: " + key + " for expression: " + expression + ". Exchanges: " + e1 + " and " + e2);
1037            } else {
1038                map.put(key, e2);
1039            }
1040        }
1041    }
1042
1043    /**
1044     * Adds the expectation which will be invoked when enough messages are received
1045     */
1046    public void expects(Runnable runnable) {
1047        tests.add(runnable);
1048    }
1049
1050    /**
1051     * Adds an assertion to the given message index
1052     *
1053     * @param messageIndex the number of the message
1054     * @return the assertion clause
1055     */
1056    public AssertionClause message(final int messageIndex) {
1057        final AssertionClause clause = new AssertionClause(this) {
1058            public void run() {
1059                applyAssertionOn(MockEndpoint.this, messageIndex, assertExchangeReceived(messageIndex));
1060            }
1061        };
1062        expects(clause);
1063        return clause;
1064    }
1065
1066    /**
1067     * Adds an assertion to all the received messages
1068     *
1069     * @return the assertion clause
1070     */
1071    public AssertionClause allMessages() {
1072        final AssertionClause clause = new AssertionClause(this) {
1073            public void run() {
1074                List<Exchange> list = getReceivedExchanges();
1075                int index = 0;
1076                for (Exchange exchange : list) {
1077                    applyAssertionOn(MockEndpoint.this, index++, exchange);
1078                }
1079            }
1080        };
1081        expects(clause);
1082        return clause;
1083    }
1084
1085    /**
1086     * Asserts that the given index of message is received (starting at zero)
1087     */
1088    public Exchange assertExchangeReceived(int index) {
1089        int count = getReceivedCounter();
1090        assertTrue("Not enough messages received. Was: " + count, count > index);
1091        return getReceivedExchange(index);
1092    }
1093
1094    // Properties
1095    // -------------------------------------------------------------------------
1096
1097    public String getName() {
1098        return name;
1099    }
1100
1101    public void setName(String name) {
1102        this.name = name;
1103    }
1104
1105    public List<Throwable> getFailures() {
1106        return failures;
1107    }
1108
1109    public int getReceivedCounter() {
1110        return counter;
1111    }
1112
1113    public List<Exchange> getReceivedExchanges() {
1114        return receivedExchanges;
1115    }
1116
1117    public int getExpectedCount() {
1118        return expectedCount;
1119    }
1120
1121    public long getSleepForEmptyTest() {
1122        return sleepForEmptyTest;
1123    }
1124
1125    /**
1126     * Allows a sleep to be specified to wait to check that this endpoint really
1127     * is empty when {@link #expectedMessageCount(int)} is called with zero
1128     *
1129     * @param sleepForEmptyTest the milliseconds to sleep for to determine that
1130     *                this endpoint really is empty
1131     */
1132    public void setSleepForEmptyTest(long sleepForEmptyTest) {
1133        this.sleepForEmptyTest = sleepForEmptyTest;
1134    }
1135
1136    public long getResultWaitTime() {
1137        return resultWaitTime;
1138    }
1139
1140    /**
1141     * Sets the maximum amount of time (in millis) the {@link #assertIsSatisfied()} will
1142     * wait on a latch until it is satisfied
1143     */
1144    public void setResultWaitTime(long resultWaitTime) {
1145        this.resultWaitTime = resultWaitTime;
1146    }
1147
1148    /**
1149     * Sets the minimum expected amount of time (in millis) the {@link #assertIsSatisfied()} will
1150     * wait on a latch until it is satisfied
1151     */
1152    public void setResultMinimumWaitTime(long resultMinimumWaitTime) {
1153        this.resultMinimumWaitTime = resultMinimumWaitTime;
1154    }
1155
1156    /**
1157     * @deprecated use {@link #setResultMinimumWaitTime(long)}
1158     */
1159    @Deprecated
1160    public void setMinimumResultWaitTime(long resultMinimumWaitTime) {
1161        setResultMinimumWaitTime(resultMinimumWaitTime);
1162    }
1163
1164    /**
1165     * Specifies the expected number of message exchanges that should be
1166     * received by this endpoint.
1167     * <p/>
1168     * <b>Beware:</b> If you want to expect that <tt>0</tt> messages, then take extra care,
1169     * as <tt>0</tt> matches when the tests starts, so you need to set a assert period time
1170     * to let the test run for a while to make sure there are still no messages arrived; for
1171     * that use {@link #setAssertPeriod(long)}.
1172     * An alternative is to use <a href="http://camel.apache.org/notifybuilder.html">NotifyBuilder</a>, and use the notifier
1173     * to know when Camel is done routing some messages, before you call the {@link #assertIsSatisfied()} method on the mocks.
1174     * This allows you to not use a fixed assert period, to speedup testing times.
1175     * <p/>
1176     * If you want to assert that <b>exactly</b> n'th message arrives to this mock
1177     * endpoint, then see also the {@link #setAssertPeriod(long)} method for further details.
1178     *
1179     * @param expectedCount the number of message exchanges that should be
1180     *                expected by this endpoint
1181     * @see #setAssertPeriod(long)                      
1182     */
1183    public void setExpectedCount(int expectedCount) {
1184        setExpectedMessageCount(expectedCount);
1185    }
1186
1187    /**
1188     * @see #setExpectedCount(int)
1189     */
1190    public void setExpectedMessageCount(int expectedCount) {
1191        this.expectedCount = expectedCount;
1192        if (expectedCount <= 0) {
1193            latch = null;
1194        } else {
1195            latch = new CountDownLatch(expectedCount);
1196        }
1197    }
1198
1199    /**
1200     * Specifies the minimum number of expected message exchanges that should be
1201     * received by this endpoint
1202     *
1203     * @param expectedCount the number of message exchanges that should be
1204     *                expected by this endpoint
1205     */
1206    public void setMinimumExpectedMessageCount(int expectedCount) {
1207        this.expectedMinimumCount = expectedCount;
1208        if (expectedCount <= 0) {
1209            latch = null;
1210        } else {
1211            latch = new CountDownLatch(expectedMinimumCount);
1212        }
1213    }
1214
1215    public Processor getReporter() {
1216        return reporter;
1217    }
1218
1219    /**
1220     * Allows a processor to added to the endpoint to report on progress of the test
1221     */
1222    public void setReporter(Processor reporter) {
1223        this.reporter = reporter;
1224    }
1225
1226    /**
1227     * Specifies to only retain the first n'th number of received {@link Exchange}s.
1228     * <p/>
1229     * This is used when testing with big data, to reduce memory consumption by not storing
1230     * copies of every {@link Exchange} this mock endpoint receives.
1231     * <p/>
1232     * <b>Important:</b> When using this limitation, then the {@link #getReceivedCounter()}
1233     * will still return the actual number of received {@link Exchange}s. For example
1234     * if we have received 5000 {@link Exchange}s, and have configured to only retain the first
1235     * 10 {@link Exchange}s, then the {@link #getReceivedCounter()} will still return <tt>5000</tt>
1236     * but there is only the first 10 {@link Exchange}s in the {@link #getExchanges()} and
1237     * {@link #getReceivedExchanges()} methods.
1238     * <p/>
1239     * When using this method, then some of the other expectation methods is not supported,
1240     * for example the {@link #expectedBodiesReceived(Object...)} sets a expectation on the first
1241     * number of bodies received.
1242     * <p/>
1243     * You can configure both {@link #setRetainFirst(int)} and {@link #setRetainLast(int)} methods,
1244     * to limit both the first and last received.
1245     * 
1246     * @param retainFirst  to limit and only keep the first n'th received {@link Exchange}s, use
1247     *                     <tt>0</tt> to not retain any messages, or <tt>-1</tt> to retain all.
1248     * @see #setRetainLast(int)
1249     */
1250    public void setRetainFirst(int retainFirst) {
1251        this.retainFirst = retainFirst;
1252    }
1253
1254    /**
1255     * Specifies to only retain the last n'th number of received {@link Exchange}s.
1256     * <p/>
1257     * This is used when testing with big data, to reduce memory consumption by not storing
1258     * copies of every {@link Exchange} this mock endpoint receives.
1259     * <p/>
1260     * <b>Important:</b> When using this limitation, then the {@link #getReceivedCounter()}
1261     * will still return the actual number of received {@link Exchange}s. For example
1262     * if we have received 5000 {@link Exchange}s, and have configured to only retain the last
1263     * 20 {@link Exchange}s, then the {@link #getReceivedCounter()} will still return <tt>5000</tt>
1264     * but there is only the last 20 {@link Exchange}s in the {@link #getExchanges()} and
1265     * {@link #getReceivedExchanges()} methods.
1266     * <p/>
1267     * When using this method, then some of the other expectation methods is not supported,
1268     * for example the {@link #expectedBodiesReceived(Object...)} sets a expectation on the first
1269     * number of bodies received.
1270     * <p/>
1271     * You can configure both {@link #setRetainFirst(int)} and {@link #setRetainLast(int)} methods,
1272     * to limit both the first and last received.
1273     *
1274     * @param retainLast  to limit and only keep the last n'th received {@link Exchange}s, use
1275     *                     <tt>0</tt> to not retain any messages, or <tt>-1</tt> to retain all.
1276     * @see #setRetainFirst(int)
1277     */
1278    public void setRetainLast(int retainLast) {
1279        this.retainLast = retainLast;
1280    }
1281
1282    public int isReportGroup() {
1283        return reportGroup;
1284    }
1285
1286    /**
1287     * A number that is used to turn on throughput logging based on groups of the size.
1288     */
1289    public void setReportGroup(int reportGroup) {
1290        this.reportGroup = reportGroup;
1291    }
1292
1293    public boolean isCopyOnExchange() {
1294        return copyOnExchange;
1295    }
1296
1297    /**
1298     * Sets whether to make a deep copy of the incoming {@link Exchange} when received at this mock endpoint.
1299     * <p/>
1300     * Is by default <tt>true</tt>.
1301     */
1302    public void setCopyOnExchange(boolean copyOnExchange) {
1303        this.copyOnExchange = copyOnExchange;
1304    }
1305
1306    // Implementation methods
1307    // -------------------------------------------------------------------------
1308    private void init() {
1309        expectedCount = -1;
1310        counter = 0;
1311        defaultProcessor = null;
1312        processors = new HashMap<>();
1313        receivedExchanges = new CopyOnWriteArrayList<>();
1314        failures = new CopyOnWriteArrayList<>();
1315        tests = new CopyOnWriteArrayList<>();
1316        latch = null;
1317        sleepForEmptyTest = 0;
1318        resultWaitTime = 0;
1319        resultMinimumWaitTime = 0L;
1320        assertPeriod = 0L;
1321        expectedMinimumCount = -1;
1322        expectedBodyValues = null;
1323        actualBodyValues = new ArrayList<>();
1324        expectedHeaderValues = null;
1325        actualHeaderValues = null;
1326        expectedPropertyValues = null;
1327        actualPropertyValues = null;
1328        retainFirst = -1;
1329        retainLast = -1;
1330    }
1331
1332    protected synchronized void onExchange(Exchange exchange) {
1333        try {
1334            if (reporter != null) {
1335                reporter.process(exchange);
1336            }
1337            Exchange copy = exchange;
1338            if (copyOnExchange) {
1339                // copy the exchange so the mock stores the copy and not the actual exchange
1340                copy = ExchangeHelper.createCopy(exchange, true);
1341            }
1342            performAssertions(exchange, copy);
1343        } catch (Throwable e) {
1344            // must catch java.lang.Throwable as AssertionError extends java.lang.Error
1345            failures.add(e);
1346        } finally {
1347            // make sure latch is counted down to avoid test hanging forever
1348            if (latch != null) {
1349                latch.countDown();
1350            }
1351        }
1352    }
1353
1354    /**
1355     * Performs the assertions on the incoming exchange.
1356     *
1357     * @param exchange   the actual exchange
1358     * @param copy       a copy of the exchange (only store this)
1359     * @throws Exception can be thrown if something went wrong
1360     */
1361    protected void performAssertions(Exchange exchange, Exchange copy) throws Exception {
1362        Message in = copy.getIn();
1363        Object actualBody = in.getBody();
1364
1365        if (expectedHeaderValues != null) {
1366            if (actualHeaderValues == null) {
1367                actualHeaderValues = getCamelContext().getHeadersMapFactory().newMap();
1368            }
1369            if (in.hasHeaders()) {
1370                actualHeaderValues.putAll(in.getHeaders());
1371            }
1372        }
1373
1374        if (expectedPropertyValues != null) {
1375            if (actualPropertyValues == null) {
1376                actualPropertyValues = getCamelContext().getHeadersMapFactory().newMap();
1377            }
1378            actualPropertyValues.putAll(copy.getProperties());
1379        }
1380
1381        if (expectedBodyValues != null) {
1382            int index = actualBodyValues.size();
1383            if (expectedBodyValues.size() > index) {
1384                Object expectedBody = expectedBodyValues.get(index);
1385                if (expectedBody != null) {
1386                    // prefer to convert body early, for example when using files
1387                    // we need to read the content at this time
1388                    Object body = in.getBody(expectedBody.getClass());
1389                    if (body != null) {
1390                        actualBody = body;
1391                    }
1392                }
1393                actualBodyValues.add(actualBody);
1394            }
1395        }
1396
1397        // let counter be 0 index-based in the logs
1398        if (LOG.isDebugEnabled()) {
1399            String msg = getEndpointUri() + " >>>> " + counter + " : " + copy + " with body: " + actualBody;
1400            if (copy.getIn().hasHeaders()) {
1401                msg += " and headers:" + copy.getIn().getHeaders();
1402            }
1403            LOG.debug(msg);
1404        }
1405
1406        // record timestamp when exchange was received
1407        copy.setProperty(Exchange.RECEIVED_TIMESTAMP, new Date());
1408
1409        // add a copy of the received exchange
1410        addReceivedExchange(copy);
1411        // and then increment counter after adding received exchange
1412        ++counter;
1413
1414        Processor processor = processors.get(getReceivedCounter()) != null
1415                ? processors.get(getReceivedCounter()) : defaultProcessor;
1416
1417        if (processor != null) {
1418            try {
1419                // must process the incoming exchange and NOT the copy as the idea
1420                // is the end user can manipulate the exchange
1421                processor.process(exchange);
1422            } catch (Exception e) {
1423                // set exceptions on exchange so we can throw exceptions to simulate errors
1424                exchange.setException(e);
1425            }
1426        }
1427    }
1428
1429    /**
1430     * Adds the received exchange.
1431     * 
1432     * @param copy  a copy of the received exchange
1433     */
1434    protected void addReceivedExchange(Exchange copy) {
1435        if (retainFirst == 0 && retainLast == 0) {
1436            // do not retain any messages at all
1437        } else if (retainFirst < 0 && retainLast < 0) {
1438            // no limitation so keep them all
1439            receivedExchanges.add(copy);
1440        } else {
1441            // okay there is some sort of limitations, so figure out what to retain
1442            if (retainFirst > 0 && counter < retainFirst) {
1443                // store a copy as its within the retain first limitation
1444                receivedExchanges.add(copy);
1445            } else if (retainLast > 0) {
1446                // remove the oldest from the last retained boundary,
1447                int index = receivedExchanges.size() - retainLast;
1448                if (index >= 0) {
1449                    // but must be outside the first range as well
1450                    // otherwise we should not remove the oldest
1451                    if (retainFirst <= 0 || retainFirst <= index) {
1452                        receivedExchanges.remove(index);
1453                    }
1454                }
1455                // store a copy of the last n'th received
1456                receivedExchanges.add(copy);
1457            }
1458        }
1459    }
1460
1461    protected void waitForCompleteLatch() throws InterruptedException {
1462        if (latch == null) {
1463            fail("Should have a latch!");
1464        }
1465
1466        StopWatch watch = new StopWatch();
1467        waitForCompleteLatch(resultWaitTime);
1468        long delta = watch.taken();
1469        LOG.debug("Took {} millis to complete latch", delta);
1470
1471        if (resultMinimumWaitTime > 0 && delta < resultMinimumWaitTime) {
1472            fail("Expected minimum " + resultMinimumWaitTime
1473                + " millis waiting on the result, but was faster with " + delta + " millis.");
1474        }
1475    }
1476
1477    protected void waitForCompleteLatch(long timeout) throws InterruptedException {
1478        // Wait for a default 10 seconds if resultWaitTime is not set
1479        long waitTime = timeout == 0 ? 10000L : timeout;
1480
1481        // now let's wait for the results
1482        LOG.debug("Waiting on the latch for: {} millis", timeout);
1483        latch.await(waitTime, TimeUnit.MILLISECONDS);
1484    }
1485
1486    protected void assertEquals(String message, Object expectedValue, Object actualValue) {
1487        if (!ObjectHelper.equal(expectedValue, actualValue)) {
1488            fail(message + ". Expected: <" + expectedValue + "> but was: <" + actualValue + ">");
1489        }
1490    }
1491
1492    protected void assertTrue(String message, boolean predicate) {
1493        if (!predicate) {
1494            fail(message);
1495        }
1496    }
1497
1498    protected void fail(Object message) {
1499        if (LOG.isDebugEnabled()) {
1500            List<Exchange> list = getReceivedExchanges();
1501            int index = 0;
1502            for (Exchange exchange : list) {
1503                LOG.debug("{} failed and received[{}]: {}", getEndpointUri(), ++index, exchange);
1504            }
1505        }
1506        throw new AssertionError(getEndpointUri() + " " + message);
1507    }
1508
1509    public int getExpectedMinimumCount() {
1510        return expectedMinimumCount;
1511    }
1512
1513    public void await() throws InterruptedException {
1514        if (latch != null) {
1515            latch.await();
1516        }
1517    }
1518
1519    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
1520        if (latch != null) {
1521            return latch.await(timeout, unit);
1522        }
1523        return true;
1524    }
1525
1526    public boolean isSingleton() {
1527        return true;
1528    }
1529
1530    public boolean isLenientProperties() {
1531        return true;
1532    }
1533
1534    private Exchange getReceivedExchange(int index) {
1535        if (index <= receivedExchanges.size() - 1) {
1536            return receivedExchanges.get(index);
1537        } else {
1538            return null;
1539        }
1540    }
1541
1542}