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