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            LOG.info("Caught expected failure: " + e);
438        }
439        if (failed) {
440            // fail() throws the AssertionError to indicate the test failed. 
441            fail("Expected assertion failure but test succeeded!");
442        }
443    }
444
445    /**
446     * Validates that the assertions fail on this endpoint
447
448     * @param timeoutForEmptyEndpoints the timeout in milliseconds that we
449     *        should wait for the test to be true
450     */
451    public void assertIsNotSatisfied(long timeoutForEmptyEndpoints) throws InterruptedException {
452        boolean failed = false;
453        try {
454            assertIsSatisfied(timeoutForEmptyEndpoints);
455            // did not throw expected error... fail!
456            failed = true;
457        } catch (AssertionError e) {
458            LOG.info("Caught expected failure: " + e);
459        }
460        if (failed) { 
461            // fail() throws the AssertionError to indicate the test failed. 
462            fail("Expected assertion failure but test succeeded!");
463        }
464    }    
465    
466    /**
467     * Specifies the expected number of message exchanges that should be
468     * received by this endpoint
469     *
470     * If you want to assert that <b>exactly</b> n messages arrives to this mock
471     * endpoint, then see also the {@link #setAssertPeriod(long)} method for further details.
472     *
473     * @param expectedCount the number of message exchanges that should be
474     *                expected by this endpoint
475     * @see #setAssertPeriod(long)
476     */
477    public void expectedMessageCount(int expectedCount) {
478        setExpectedMessageCount(expectedCount);
479    }
480
481    /**
482     * Sets a grace period after which the mock endpoint will re-assert
483     * to ensure the preliminary assertion is still valid.
484     * <p/>
485     * This is used for example to assert that <b>exactly</b> a number of messages 
486     * arrives. For example if {@link #expectedMessageCount(int)} was set to 5, then
487     * the assertion is satisfied when 5 or more message arrives. To ensure that
488     * exactly 5 messages arrives, then you would need to wait a little period
489     * to ensure no further message arrives. This is what you can use this
490     * {@link #setAssertPeriod(long)} method for.
491     * <p/>
492     * By default this period is disabled.
493     *
494     * @param period grace period in millis
495     */
496    public void setAssertPeriod(long period) {
497        this.assertPeriod = period;
498    }
499
500    /**
501     * Specifies the minimum number of expected message exchanges that should be
502     * received by this endpoint
503     *
504     * @param expectedCount the number of message exchanges that should be
505     *                expected by this endpoint
506     */
507    public void expectedMinimumMessageCount(int expectedCount) {
508        setMinimumExpectedMessageCount(expectedCount);
509    }
510
511    /**
512     * Sets an expectation that the given header name & value are received by this endpoint
513     * <p/>
514     * You can set multiple expectations for different header names.
515     * 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>
516     * <p/>
517     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
518     */
519    public void expectedHeaderReceived(final String name, final Object value) {
520        if (expectedHeaderValues == null) {
521            expectedHeaderValues = getCamelContext().getHeadersMapFactory().newMap();
522            // we just wants to expects to be called once
523            expects(new Runnable() {
524                public void run() {
525                    for (int i = 0; i < getReceivedExchanges().size(); i++) {
526                        Exchange exchange = getReceivedExchange(i);
527                        for (Map.Entry<String, Object> entry : expectedHeaderValues.entrySet()) {
528                            String key = entry.getKey();
529                            Object expectedValue = entry.getValue();
530
531                            // we accept that an expectedValue of null also means that the header may be absent
532                            if (expectedValue != null) {
533                                assertTrue("Exchange " + i + " has no headers", exchange.getIn().hasHeaders());
534                                boolean hasKey = exchange.getIn().getHeaders().containsKey(key);
535                                assertTrue("No header with name " + key + " found for message: " + i, hasKey);
536                            }
537
538                            Object actualValue = exchange.getIn().getHeader(key);
539                            actualValue = extractActualValue(exchange, actualValue, expectedValue);
540
541                            assertEquals("Header with name " + key + " for message: " + i, expectedValue, actualValue);
542                        }
543                    }
544                }
545            });
546        }
547        expectedHeaderValues.put(name, value);
548    }
549
550    /**
551     * Adds an expectation that the given header values are received by this
552     * endpoint in any order.
553     * <p/>
554     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
555     * there must be 3 values.
556     * <p/>
557     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
558     */
559    public void expectedHeaderValuesReceivedInAnyOrder(final String name, final List<?> values) {
560        expectedMessageCount(values.size());
561
562        expects(new Runnable() {
563            public void run() {
564                // these are the expected values to find
565                final Set<Object> actualHeaderValues = new CopyOnWriteArraySet<Object>(values);
566
567                for (int i = 0; i < getReceivedExchanges().size(); i++) {
568                    Exchange exchange = getReceivedExchange(i);
569
570                    Object actualValue = exchange.getIn().getHeader(name);
571                    for (Object expectedValue : actualHeaderValues) {
572                        actualValue = extractActualValue(exchange, actualValue, expectedValue);
573                        // remove any found values
574                        actualHeaderValues.remove(actualValue);
575                    }
576                }
577
578                // should be empty, as we should find all the values
579                assertTrue("Expected " + values.size() + " headers with key[" + name + "], received " + (values.size() - actualHeaderValues.size())
580                        + " headers. Expected header values: " + actualHeaderValues, actualHeaderValues.isEmpty());
581            }
582        });
583    }
584
585    /**
586     * Adds an expectation that the given header values are received by this
587     * endpoint in any order
588     * <p/>
589     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
590     * there must be 3 values.
591     * <p/>
592     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
593     */
594    public void expectedHeaderValuesReceivedInAnyOrder(String name, Object... values) {
595        List<Object> valueList = new ArrayList<Object>();
596        valueList.addAll(Arrays.asList(values));
597        expectedHeaderValuesReceivedInAnyOrder(name, valueList);
598    }
599
600    /**
601     * Sets an expectation that the given property name & value are received by this endpoint
602     * <p/>
603     * You can set multiple expectations for different property names.
604     * 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>
605     */
606    public void expectedPropertyReceived(final String name, final Object value) {
607        if (expectedPropertyValues == null) {
608            expectedPropertyValues = new HashMap<String, Object>();
609        }
610        expectedPropertyValues.put(name, value);
611
612        expects(new Runnable() {
613            public void run() {
614                for (int i = 0; i < getReceivedExchanges().size(); i++) {
615                    Exchange exchange = getReceivedExchange(i);
616                    for (Map.Entry<String, Object> entry : expectedPropertyValues.entrySet()) {
617                        String key = entry.getKey();
618                        Object expectedValue = entry.getValue();
619
620                        // we accept that an expectedValue of null also means that the property may be absent
621                        if (expectedValue != null) {
622                            assertTrue("Exchange " + i + " has no properties", !exchange.getProperties().isEmpty());
623                            boolean hasKey = exchange.getProperties().containsKey(key);
624                            assertTrue("No property with name " + key + " found for message: " + i, hasKey);
625                        }
626
627                        Object actualValue = exchange.getProperty(key);
628                        actualValue = extractActualValue(exchange, actualValue, expectedValue);
629
630                        assertEquals("Property with name " + key + " for message: " + i, expectedValue, actualValue);
631                    }
632                }
633            }
634        });
635    }
636
637    /**
638     * Adds an expectation that the given property values are received by this
639     * endpoint in any order.
640     * <p/>
641     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
642     * there must be 3 values.
643     * <p/>
644     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
645     */
646    public void expectedPropertyValuesReceivedInAnyOrder(final String name, final List<?> values) {
647        expectedMessageCount(values.size());
648
649        expects(new Runnable() {
650            public void run() {
651                // these are the expected values to find
652                final Set<Object> actualPropertyValues = new CopyOnWriteArraySet<Object>(values);
653
654                for (int i = 0; i < getReceivedExchanges().size(); i++) {
655                    Exchange exchange = getReceivedExchange(i);
656
657                    Object actualValue = exchange.getProperty(name);
658                    for (Object expectedValue : actualPropertyValues) {
659                        actualValue = extractActualValue(exchange, actualValue, expectedValue);
660                        // remove any found values
661                        actualPropertyValues.remove(actualValue);
662                    }
663                }
664
665                // should be empty, as we should find all the values
666                assertTrue("Expected " + values.size() + " properties with key[" + name + "], received " + (values.size() - actualPropertyValues.size())
667                        + " properties. Expected property values: " + actualPropertyValues, actualPropertyValues.isEmpty());
668            }
669        });
670    }
671
672    /**
673     * Adds an expectation that the given property values are received by this
674     * endpoint in any order
675     * <p/>
676     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
677     * there must be 3 values.
678     * <p/>
679     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
680     */
681    public void expectedPropertyValuesReceivedInAnyOrder(String name, Object... values) {
682        List<Object> valueList = new ArrayList<Object>();
683        valueList.addAll(Arrays.asList(values));
684        expectedPropertyValuesReceivedInAnyOrder(name, valueList);
685    }    
686
687    /**
688     * Adds an expectation that the given body values are received by this
689     * endpoint in the specified order
690     * <p/>
691     * <b>Important:</b> The number of values must match the expected number of messages, so if you expect 3 messages, then
692     * there must be 3 values.
693     * <p/>
694     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
695     */
696    public void expectedBodiesReceived(final List<?> bodies) {
697        expectedMessageCount(bodies.size());
698        this.expectedBodyValues = bodies;
699        this.actualBodyValues = new ArrayList<Object>();
700
701        expects(new Runnable() {
702            public void run() {
703                for (int i = 0; i < expectedBodyValues.size(); i++) {
704                    Exchange exchange = getReceivedExchange(i);
705                    assertTrue("No exchange received for counter: " + i, exchange != null);
706
707                    Object expectedBody = expectedBodyValues.get(i);
708                    Object actualBody = null;
709                    if (i < actualBodyValues.size()) {
710                        actualBody = actualBodyValues.get(i);
711                    }
712                    actualBody = extractActualValue(exchange, actualBody, expectedBody);
713
714                    assertEquals("Body of message: " + i, expectedBody, actualBody);
715                }
716            }
717        });
718    }
719
720    private Object extractActualValue(Exchange exchange, Object actualValue, Object expectedValue) {
721        if (actualValue == null) {
722            return null;
723        }
724
725        if (actualValue instanceof Expression) {
726            Class clazz = Object.class;
727            if (expectedValue != null) {
728                clazz = expectedValue.getClass();
729            }
730            actualValue = ((Expression)actualValue).evaluate(exchange, clazz);
731        } else if (actualValue instanceof Predicate) {
732            actualValue = ((Predicate)actualValue).matches(exchange);
733        } else if (expectedValue != null) {
734            String from = actualValue.getClass().getName();
735            String to = expectedValue.getClass().getName();
736            actualValue = getCamelContext().getTypeConverter().convertTo(expectedValue.getClass(), exchange, actualValue);
737            assertTrue("There is no type conversion possible from " + from + " to " + to, actualValue != null);
738        }
739        return actualValue;
740    }
741
742    /**
743     * Sets an expectation that the given predicates matches the received messages by this endpoint
744     */
745    public void expectedMessagesMatches(Predicate... predicates) {
746        for (int i = 0; i < predicates.length; i++) {
747            final int messageIndex = i;
748            final Predicate predicate = predicates[i];
749            final AssertionClause clause = new AssertionClause(this) {
750                public void run() {
751                    addPredicate(predicate);
752                    applyAssertionOn(MockEndpoint.this, messageIndex, assertExchangeReceived(messageIndex));
753                }
754            };
755            expects(clause);
756        }
757    }
758
759    /**
760     * Sets an expectation that the given body values are received by this endpoint
761     * <p/>
762     * <b>Important:</b> The number of bodies must match the expected number of messages, so if you expect 3 messages, then
763     * there must be 3 bodies.
764     * <p/>
765     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
766     */
767    public void expectedBodiesReceived(Object... bodies) {
768        List<Object> bodyList = new ArrayList<Object>();
769        bodyList.addAll(Arrays.asList(bodies));
770        expectedBodiesReceived(bodyList);
771    }
772
773    /**
774     * Adds an expectation that the given body value are received by this endpoint
775     */
776    public AssertionClause expectedBodyReceived() {
777        expectedMessageCount(1);
778        final AssertionClause clause = new AssertionClause(this) {
779            public void run() {
780                Exchange exchange = getReceivedExchange(0);
781                assertTrue("No exchange received for counter: " + 0, exchange != null);
782
783                Object actualBody = exchange.getIn().getBody();
784                Expression exp = createExpression(getCamelContext());
785                Object expectedBody = exp.evaluate(exchange, Object.class);
786
787                assertEquals("Body of message: " + 0, expectedBody, actualBody);
788            }
789        };
790        expects(clause);
791        return clause;
792    }
793
794    /**
795     * Adds an expectation that the given body values are received by this
796     * endpoint in any order
797     * <p/>
798     * <b>Important:</b> The number of bodies must match the expected number of messages, so if you expect 3 messages, then
799     * there must be 3 bodies.
800     * <p/>
801     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
802     */
803    public void expectedBodiesReceivedInAnyOrder(final List<?> bodies) {
804        expectedMessageCount(bodies.size());
805        this.expectedBodyValues = bodies;
806        this.actualBodyValues = new ArrayList<Object>();
807
808        expects(new Runnable() {
809            public void run() {
810                List<Object> actualBodyValuesSet = new ArrayList<Object>(actualBodyValues);
811                for (int i = 0; i < expectedBodyValues.size(); i++) {
812                    Exchange exchange = getReceivedExchange(i);
813                    assertTrue("No exchange received for counter: " + i, exchange != null);
814
815                    Object expectedBody = expectedBodyValues.get(i);
816                    assertTrue("Message with body " + expectedBody + " was expected but not found in " + actualBodyValuesSet, actualBodyValuesSet.remove(expectedBody));
817                }
818            }
819        });
820    }
821
822    /**
823     * Adds an expectation that the given body values are received by this
824     * endpoint in any order
825     * <p/>
826     * <b>Important:</b> The number of bodies must match the expected number of messages, so if you expect 3 messages, then
827     * there must be 3 bodies.
828     * <p/>
829     * <b>Important:</b> This overrides any previous set value using {@link #expectedMessageCount(int)}
830     */
831    public void expectedBodiesReceivedInAnyOrder(Object... bodies) {
832        List<Object> bodyList = new ArrayList<Object>();
833        bodyList.addAll(Arrays.asList(bodies));
834        expectedBodiesReceivedInAnyOrder(bodyList);
835    }
836
837    /**
838     * Adds an expectation that a file exists with the given name
839     *
840     * @param name name of file, will cater for / and \ on different OS platforms
841     */
842    public void expectedFileExists(final String name) {
843        expectedFileExists(name, null);
844    }
845
846    /**
847     * Adds an expectation that a file exists with the given name
848     * <p/>
849     * Will wait at most 5 seconds while checking for the existence of the file.
850     *
851     * @param name name of file, will cater for / and \ on different OS platforms
852     * @param content content of file to compare, can be <tt>null</tt> to not compare content
853     */
854    public void expectedFileExists(final String name, final String content) {
855        final File file = new File(FileUtil.normalizePath(name));
856
857        expects(new Runnable() {
858            public void run() {
859                // wait at most 5 seconds for the file to exists
860                final long timeout = System.currentTimeMillis() + 5000;
861
862                boolean stop = false;
863                while (!stop && !file.exists()) {
864                    try {
865                        Thread.sleep(50);
866                    } catch (InterruptedException e) {
867                        // ignore
868                    }
869                    stop = System.currentTimeMillis() > timeout;
870                }
871
872                assertTrue("The file should exists: " + name, file.exists());
873
874                if (content != null) {
875                    String body = getCamelContext().getTypeConverter().convertTo(String.class, file);
876                    assertEquals("Content of file: " + name, content, body);
877                }
878            }
879        });
880    }
881
882    /**
883     * Adds an expectation that messages received should have the given exchange pattern
884     */
885    public void expectedExchangePattern(final ExchangePattern exchangePattern) {
886        expectedMessagesMatches(new Predicate() {
887            public boolean matches(Exchange exchange) {
888                return exchange.getPattern().equals(exchangePattern);
889            }
890        });
891    }
892
893    /**
894     * Adds an expectation that messages received should have ascending values
895     * of the given expression such as a user generated counter value
896     */
897    public void expectsAscending(final Expression expression) {
898        expects(new Runnable() {
899            public void run() {
900                assertMessagesAscending(expression);
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 AssertionClause expectsAscending() {
910        final AssertionClause clause = new AssertionClause(this) {
911            public void run() {
912                assertMessagesAscending(createExpression(getCamelContext()));
913            }
914        };
915        expects(clause);
916        return clause;
917    }
918
919    /**
920     * Adds an expectation that messages received should have descending values
921     * of the given expression such as a user generated counter value
922     */
923    public void expectsDescending(final Expression expression) {
924        expects(new Runnable() {
925            public void run() {
926                assertMessagesDescending(expression);
927            }
928        });
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 AssertionClause expectsDescending() {
936        final AssertionClause clause = new AssertionClause(this) {
937            public void run() {
938                assertMessagesDescending(createExpression(getCamelContext()));
939            }
940        };
941        expects(clause);
942        return clause;
943    }
944
945    /**
946     * Adds an expectation that no duplicate messages should be received using
947     * the expression to determine the message ID
948     *
949     * @param expression the expression used to create a unique message ID for
950     *                message comparison (which could just be the message
951     *                payload if the payload can be tested for uniqueness using
952     *                {@link Object#equals(Object)} and
953     *                {@link Object#hashCode()}
954     */
955    public void expectsNoDuplicates(final Expression expression) {
956        expects(new Runnable() {
957            public void run() {
958                assertNoDuplicates(expression);
959            }
960        });
961    }
962
963    /**
964     * Adds an expectation that no duplicate messages should be received using
965     * the expression to determine the message ID
966     */
967    public AssertionClause expectsNoDuplicates() {
968        final AssertionClause clause = new AssertionClause(this) {
969            public void run() {
970                assertNoDuplicates(createExpression(getCamelContext()));
971            }
972        };
973        expects(clause);
974        return clause;
975    }
976
977    /**
978     * Asserts that the messages have ascending values of the given expression
979     */
980    public void assertMessagesAscending(Expression expression) {
981        assertMessagesSorted(expression, true);
982    }
983
984    /**
985     * Asserts that the messages have descending values of the given expression
986     */
987    public void assertMessagesDescending(Expression expression) {
988        assertMessagesSorted(expression, false);
989    }
990
991    protected void assertMessagesSorted(Expression expression, boolean ascending) {
992        String type = ascending ? "ascending" : "descending";
993        ExpressionComparator comparator = new ExpressionComparator(expression);
994        List<Exchange> list = getReceivedExchanges();
995        for (int i = 1; i < list.size(); i++) {
996            int j = i - 1;
997            Exchange e1 = list.get(j);
998            Exchange e2 = list.get(i);
999            int result = comparator.compare(e1, e2);
1000            if (result == 0) {
1001                fail("Messages not " + type + ". Messages" + j + " and " + i + " are equal with value: "
1002                    + expression.evaluate(e1, Object.class) + " for expression: " + expression + ". Exchanges: " + e1 + " and " + e2);
1003            } else {
1004                if (!ascending) {
1005                    result = result * -1;
1006                }
1007                if (result > 0) {
1008                    fail("Messages not " + type + ". Message " + j + " has value: " + expression.evaluate(e1, Object.class)
1009                        + " and message " + i + " has value: " + expression.evaluate(e2, Object.class) + " for expression: "
1010                        + expression + ". Exchanges: " + e1 + " and " + e2);
1011                }
1012            }
1013        }
1014    }
1015
1016    public void assertNoDuplicates(Expression expression) {
1017        Map<Object, Exchange> map = new HashMap<Object, Exchange>();
1018        List<Exchange> list = getReceivedExchanges();
1019        for (int i = 0; i < list.size(); i++) {
1020            Exchange e2 = list.get(i);
1021            Object key = expression.evaluate(e2, Object.class);
1022            Exchange e1 = map.get(key);
1023            if (e1 != null) {
1024                fail("Duplicate message found on message " + i + " has value: " + key + " for expression: " + expression + ". Exchanges: " + e1 + " and " + e2);
1025            } else {
1026                map.put(key, e2);
1027            }
1028        }
1029    }
1030
1031    /**
1032     * Adds the expectation which will be invoked when enough messages are received
1033     */
1034    public void expects(Runnable runnable) {
1035        tests.add(runnable);
1036    }
1037
1038    /**
1039     * Adds an assertion to the given message index
1040     *
1041     * @param messageIndex the number of the message
1042     * @return the assertion clause
1043     */
1044    public AssertionClause message(final int messageIndex) {
1045        final AssertionClause clause = new AssertionClause(this) {
1046            public void run() {
1047                applyAssertionOn(MockEndpoint.this, messageIndex, assertExchangeReceived(messageIndex));
1048            }
1049        };
1050        expects(clause);
1051        return clause;
1052    }
1053
1054    /**
1055     * Adds an assertion to all the received messages
1056     *
1057     * @return the assertion clause
1058     */
1059    public AssertionClause allMessages() {
1060        final AssertionClause clause = new AssertionClause(this) {
1061            public void run() {
1062                List<Exchange> list = getReceivedExchanges();
1063                int index = 0;
1064                for (Exchange exchange : list) {
1065                    applyAssertionOn(MockEndpoint.this, index++, exchange);
1066                }
1067            }
1068        };
1069        expects(clause);
1070        return clause;
1071    }
1072
1073    /**
1074     * Asserts that the given index of message is received (starting at zero)
1075     */
1076    public Exchange assertExchangeReceived(int index) {
1077        int count = getReceivedCounter();
1078        assertTrue("Not enough messages received. Was: " + count, count > index);
1079        return getReceivedExchange(index);
1080    }
1081
1082    // Properties
1083    // -------------------------------------------------------------------------
1084
1085    public String getName() {
1086        return name;
1087    }
1088
1089    public void setName(String name) {
1090        this.name = name;
1091    }
1092
1093    public List<Throwable> getFailures() {
1094        return failures;
1095    }
1096
1097    public int getReceivedCounter() {
1098        return counter;
1099    }
1100
1101    public List<Exchange> getReceivedExchanges() {
1102        return receivedExchanges;
1103    }
1104
1105    public int getExpectedCount() {
1106        return expectedCount;
1107    }
1108
1109    public long getSleepForEmptyTest() {
1110        return sleepForEmptyTest;
1111    }
1112
1113    /**
1114     * Allows a sleep to be specified to wait to check that this endpoint really
1115     * is empty when {@link #expectedMessageCount(int)} is called with zero
1116     *
1117     * @param sleepForEmptyTest the milliseconds to sleep for to determine that
1118     *                this endpoint really is empty
1119     */
1120    public void setSleepForEmptyTest(long sleepForEmptyTest) {
1121        this.sleepForEmptyTest = sleepForEmptyTest;
1122    }
1123
1124    public long getResultWaitTime() {
1125        return resultWaitTime;
1126    }
1127
1128    /**
1129     * Sets the maximum amount of time (in millis) the {@link #assertIsSatisfied()} will
1130     * wait on a latch until it is satisfied
1131     */
1132    public void setResultWaitTime(long resultWaitTime) {
1133        this.resultWaitTime = resultWaitTime;
1134    }
1135
1136    /**
1137     * Sets the minimum expected amount of time (in millis) the {@link #assertIsSatisfied()} will
1138     * wait on a latch until it is satisfied
1139     */
1140    public void setResultMinimumWaitTime(long resultMinimumWaitTime) {
1141        this.resultMinimumWaitTime = resultMinimumWaitTime;
1142    }
1143
1144    /**
1145     * @deprecated use {@link #setResultMinimumWaitTime(long)}
1146     */
1147    @Deprecated
1148    public void setMinimumResultWaitTime(long resultMinimumWaitTime) {
1149        setResultMinimumWaitTime(resultMinimumWaitTime);
1150    }
1151
1152    /**
1153     * Specifies the expected number of message exchanges that should be
1154     * received by this endpoint.
1155     * <p/>
1156     * <b>Beware:</b> If you want to expect that <tt>0</tt> messages, then take extra care,
1157     * as <tt>0</tt> matches when the tests starts, so you need to set a assert period time
1158     * to let the test run for a while to make sure there are still no messages arrived; for
1159     * that use {@link #setAssertPeriod(long)}.
1160     * An alternative is to use <a href="http://camel.apache.org/notifybuilder.html">NotifyBuilder</a>, and use the notifier
1161     * to know when Camel is done routing some messages, before you call the {@link #assertIsSatisfied()} method on the mocks.
1162     * This allows you to not use a fixed assert period, to speedup testing times.
1163     * <p/>
1164     * If you want to assert that <b>exactly</b> n'th message arrives to this mock
1165     * endpoint, then see also the {@link #setAssertPeriod(long)} method for further details.
1166     *
1167     * @param expectedCount the number of message exchanges that should be
1168     *                expected by this endpoint
1169     * @see #setAssertPeriod(long)                      
1170     */
1171    public void setExpectedCount(int expectedCount) {
1172        setExpectedMessageCount(expectedCount);
1173    }
1174
1175    /**
1176     * @see #setExpectedCount(int)
1177     */
1178    public void setExpectedMessageCount(int expectedCount) {
1179        this.expectedCount = expectedCount;
1180        if (expectedCount <= 0) {
1181            latch = null;
1182        } else {
1183            latch = new CountDownLatch(expectedCount);
1184        }
1185    }
1186
1187    /**
1188     * Specifies the minimum number of expected message exchanges that should be
1189     * received by this endpoint
1190     *
1191     * @param expectedCount the number of message exchanges that should be
1192     *                expected by this endpoint
1193     */
1194    public void setMinimumExpectedMessageCount(int expectedCount) {
1195        this.expectedMinimumCount = expectedCount;
1196        if (expectedCount <= 0) {
1197            latch = null;
1198        } else {
1199            latch = new CountDownLatch(expectedMinimumCount);
1200        }
1201    }
1202
1203    public Processor getReporter() {
1204        return reporter;
1205    }
1206
1207    /**
1208     * Allows a processor to added to the endpoint to report on progress of the test
1209     */
1210    public void setReporter(Processor reporter) {
1211        this.reporter = reporter;
1212    }
1213
1214    /**
1215     * Specifies to only retain the first n'th number of received {@link Exchange}s.
1216     * <p/>
1217     * This is used when testing with big data, to reduce memory consumption by not storing
1218     * copies of every {@link Exchange} this mock endpoint receives.
1219     * <p/>
1220     * <b>Important:</b> When using this limitation, then the {@link #getReceivedCounter()}
1221     * will still return the actual number of received {@link Exchange}s. For example
1222     * if we have received 5000 {@link Exchange}s, and have configured to only retain the first
1223     * 10 {@link Exchange}s, then the {@link #getReceivedCounter()} will still return <tt>5000</tt>
1224     * but there is only the first 10 {@link Exchange}s in the {@link #getExchanges()} and
1225     * {@link #getReceivedExchanges()} methods.
1226     * <p/>
1227     * When using this method, then some of the other expectation methods is not supported,
1228     * for example the {@link #expectedBodiesReceived(Object...)} sets a expectation on the first
1229     * number of bodies received.
1230     * <p/>
1231     * You can configure both {@link #setRetainFirst(int)} and {@link #setRetainLast(int)} methods,
1232     * to limit both the first and last received.
1233     * 
1234     * @param retainFirst  to limit and only keep the first n'th received {@link Exchange}s, use
1235     *                     <tt>0</tt> to not retain any messages, or <tt>-1</tt> to retain all.
1236     * @see #setRetainLast(int)
1237     */
1238    public void setRetainFirst(int retainFirst) {
1239        this.retainFirst = retainFirst;
1240    }
1241
1242    /**
1243     * Specifies to only retain the last n'th number of received {@link Exchange}s.
1244     * <p/>
1245     * This is used when testing with big data, to reduce memory consumption by not storing
1246     * copies of every {@link Exchange} this mock endpoint receives.
1247     * <p/>
1248     * <b>Important:</b> When using this limitation, then the {@link #getReceivedCounter()}
1249     * will still return the actual number of received {@link Exchange}s. For example
1250     * if we have received 5000 {@link Exchange}s, and have configured to only retain the last
1251     * 20 {@link Exchange}s, then the {@link #getReceivedCounter()} will still return <tt>5000</tt>
1252     * but there is only the last 20 {@link Exchange}s in the {@link #getExchanges()} and
1253     * {@link #getReceivedExchanges()} methods.
1254     * <p/>
1255     * When using this method, then some of the other expectation methods is not supported,
1256     * for example the {@link #expectedBodiesReceived(Object...)} sets a expectation on the first
1257     * number of bodies received.
1258     * <p/>
1259     * You can configure both {@link #setRetainFirst(int)} and {@link #setRetainLast(int)} methods,
1260     * to limit both the first and last received.
1261     *
1262     * @param retainLast  to limit and only keep the last n'th received {@link Exchange}s, use
1263     *                     <tt>0</tt> to not retain any messages, or <tt>-1</tt> to retain all.
1264     * @see #setRetainFirst(int)
1265     */
1266    public void setRetainLast(int retainLast) {
1267        this.retainLast = retainLast;
1268    }
1269
1270    public int isReportGroup() {
1271        return reportGroup;
1272    }
1273
1274    /**
1275     * A number that is used to turn on throughput logging based on groups of the size.
1276     */
1277    public void setReportGroup(int reportGroup) {
1278        this.reportGroup = reportGroup;
1279    }
1280
1281    public boolean isCopyOnExchange() {
1282        return copyOnExchange;
1283    }
1284
1285    /**
1286     * Sets whether to make a deep copy of the incoming {@link Exchange} when received at this mock endpoint.
1287     * <p/>
1288     * Is by default <tt>true</tt>.
1289     */
1290    public void setCopyOnExchange(boolean copyOnExchange) {
1291        this.copyOnExchange = copyOnExchange;
1292    }
1293
1294    // Implementation methods
1295    // -------------------------------------------------------------------------
1296    private void init() {
1297        expectedCount = -1;
1298        counter = 0;
1299        defaultProcessor = null;
1300        processors = new HashMap<Integer, Processor>();
1301        receivedExchanges = new CopyOnWriteArrayList<Exchange>();
1302        failures = new CopyOnWriteArrayList<Throwable>();
1303        tests = new CopyOnWriteArrayList<Runnable>();
1304        latch = null;
1305        sleepForEmptyTest = 0;
1306        resultWaitTime = 0;
1307        resultMinimumWaitTime = 0L;
1308        assertPeriod = 0L;
1309        expectedMinimumCount = -1;
1310        expectedBodyValues = null;
1311        actualBodyValues = new ArrayList<Object>();
1312        expectedHeaderValues = null;
1313        actualHeaderValues = null;
1314        expectedPropertyValues = null;
1315        actualPropertyValues = null;
1316        retainFirst = -1;
1317        retainLast = -1;
1318    }
1319
1320    protected synchronized void onExchange(Exchange exchange) {
1321        try {
1322            if (reporter != null) {
1323                reporter.process(exchange);
1324            }
1325            Exchange copy = exchange;
1326            if (copyOnExchange) {
1327                // copy the exchange so the mock stores the copy and not the actual exchange
1328                copy = ExchangeHelper.createCopy(exchange, true);
1329            }
1330            performAssertions(exchange, copy);
1331        } catch (Throwable e) {
1332            // must catch java.lang.Throwable as AssertionError extends java.lang.Error
1333            failures.add(e);
1334        } finally {
1335            // make sure latch is counted down to avoid test hanging forever
1336            if (latch != null) {
1337                latch.countDown();
1338            }
1339        }
1340    }
1341
1342    /**
1343     * Performs the assertions on the incoming exchange.
1344     *
1345     * @param exchange   the actual exchange
1346     * @param copy       a copy of the exchange (only store this)
1347     * @throws Exception can be thrown if something went wrong
1348     */
1349    protected void performAssertions(Exchange exchange, Exchange copy) throws Exception {
1350        Message in = copy.getIn();
1351        Object actualBody = in.getBody();
1352
1353        if (expectedHeaderValues != null) {
1354            if (actualHeaderValues == null) {
1355                actualHeaderValues = getCamelContext().getHeadersMapFactory().newMap();
1356            }
1357            if (in.hasHeaders()) {
1358                actualHeaderValues.putAll(in.getHeaders());
1359            }
1360        }
1361
1362        if (expectedPropertyValues != null) {
1363            if (actualPropertyValues == null) {
1364                actualPropertyValues = getCamelContext().getHeadersMapFactory().newMap();
1365            }
1366            actualPropertyValues.putAll(copy.getProperties());
1367        }
1368
1369        if (expectedBodyValues != null) {
1370            int index = actualBodyValues.size();
1371            if (expectedBodyValues.size() > index) {
1372                Object expectedBody = expectedBodyValues.get(index);
1373                if (expectedBody != null) {
1374                    // prefer to convert body early, for example when using files
1375                    // we need to read the content at this time
1376                    Object body = in.getBody(expectedBody.getClass());
1377                    if (body != null) {
1378                        actualBody = body;
1379                    }
1380                }
1381                actualBodyValues.add(actualBody);
1382            }
1383        }
1384
1385        // let counter be 0 index-based in the logs
1386        if (LOG.isDebugEnabled()) {
1387            String msg = getEndpointUri() + " >>>> " + counter + " : " + copy + " with body: " + actualBody;
1388            if (copy.getIn().hasHeaders()) {
1389                msg += " and headers:" + copy.getIn().getHeaders();
1390            }
1391            LOG.debug(msg);
1392        }
1393
1394        // record timestamp when exchange was received
1395        copy.setProperty(Exchange.RECEIVED_TIMESTAMP, new Date());
1396
1397        // add a copy of the received exchange
1398        addReceivedExchange(copy);
1399        // and then increment counter after adding received exchange
1400        ++counter;
1401
1402        Processor processor = processors.get(getReceivedCounter()) != null
1403                ? processors.get(getReceivedCounter()) : defaultProcessor;
1404
1405        if (processor != null) {
1406            try {
1407                // must process the incoming exchange and NOT the copy as the idea
1408                // is the end user can manipulate the exchange
1409                processor.process(exchange);
1410            } catch (Exception e) {
1411                // set exceptions on exchange so we can throw exceptions to simulate errors
1412                exchange.setException(e);
1413            }
1414        }
1415    }
1416
1417    /**
1418     * Adds the received exchange.
1419     * 
1420     * @param copy  a copy of the received exchange
1421     */
1422    protected void addReceivedExchange(Exchange copy) {
1423        if (retainFirst == 0 && retainLast == 0) {
1424            // do not retain any messages at all
1425        } else if (retainFirst < 0 && retainLast < 0) {
1426            // no limitation so keep them all
1427            receivedExchanges.add(copy);
1428        } else {
1429            // okay there is some sort of limitations, so figure out what to retain
1430            if (retainFirst > 0 && counter < retainFirst) {
1431                // store a copy as its within the retain first limitation
1432                receivedExchanges.add(copy);
1433            } else if (retainLast > 0) {
1434                // remove the oldest from the last retained boundary,
1435                int index = receivedExchanges.size() - retainLast;
1436                if (index >= 0) {
1437                    // but must be outside the first range as well
1438                    // otherwise we should not remove the oldest
1439                    if (retainFirst <= 0 || retainFirst <= index) {
1440                        receivedExchanges.remove(index);
1441                    }
1442                }
1443                // store a copy of the last n'th received
1444                receivedExchanges.add(copy);
1445            }
1446        }
1447    }
1448
1449    protected void waitForCompleteLatch() throws InterruptedException {
1450        if (latch == null) {
1451            fail("Should have a latch!");
1452        }
1453
1454        StopWatch watch = new StopWatch();
1455        waitForCompleteLatch(resultWaitTime);
1456        long delta = watch.taken();
1457        LOG.debug("Took {} millis to complete latch", delta);
1458
1459        if (resultMinimumWaitTime > 0 && delta < resultMinimumWaitTime) {
1460            fail("Expected minimum " + resultMinimumWaitTime
1461                + " millis waiting on the result, but was faster with " + delta + " millis.");
1462        }
1463    }
1464
1465    protected void waitForCompleteLatch(long timeout) throws InterruptedException {
1466        // Wait for a default 10 seconds if resultWaitTime is not set
1467        long waitTime = timeout == 0 ? 10000L : timeout;
1468
1469        // now let's wait for the results
1470        LOG.debug("Waiting on the latch for: {} millis", timeout);
1471        latch.await(waitTime, TimeUnit.MILLISECONDS);
1472    }
1473
1474    protected void assertEquals(String message, Object expectedValue, Object actualValue) {
1475        if (!ObjectHelper.equal(expectedValue, actualValue)) {
1476            fail(message + ". Expected: <" + expectedValue + "> but was: <" + actualValue + ">");
1477        }
1478    }
1479
1480    protected void assertTrue(String message, boolean predicate) {
1481        if (!predicate) {
1482            fail(message);
1483        }
1484    }
1485
1486    protected void fail(Object message) {
1487        if (LOG.isDebugEnabled()) {
1488            List<Exchange> list = getReceivedExchanges();
1489            int index = 0;
1490            for (Exchange exchange : list) {
1491                LOG.debug("{} failed and received[{}]: {}", new Object[]{getEndpointUri(), ++index, exchange});
1492            }
1493        }
1494        throw new AssertionError(getEndpointUri() + " " + message);
1495    }
1496
1497    public int getExpectedMinimumCount() {
1498        return expectedMinimumCount;
1499    }
1500
1501    public void await() throws InterruptedException {
1502        if (latch != null) {
1503            latch.await();
1504        }
1505    }
1506
1507    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
1508        if (latch != null) {
1509            return latch.await(timeout, unit);
1510        }
1511        return true;
1512    }
1513
1514    public boolean isSingleton() {
1515        return true;
1516    }
1517
1518    public boolean isLenientProperties() {
1519        return true;
1520    }
1521
1522    private Exchange getReceivedExchange(int index) {
1523        if (index <= receivedExchanges.size() - 1) {
1524            return receivedExchanges.get(index);
1525        } else {
1526            return null;
1527        }
1528    }
1529
1530}