View Javadoc

1   /*
2    * $Id: CountdownCallback.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  package org.mule.tck.functional;
11  
12  import org.mule.api.MuleEventContext;
13  import org.mule.api.lifecycle.InitialisationException;
14  import org.mule.config.i18n.MessageFactory;
15  
16  import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
17  import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
18  import junit.framework.AssertionFailedError;
19  
20  public class CountdownCallback implements EventCallback
21  {
22      private CountDownLatch countDown;
23  
24      public CountdownCallback(int messagesExpected)
25      {
26          this.countDown = new CountDownLatch(messagesExpected);
27      }
28  
29      public void eventReceived(MuleEventContext context, Object Component) throws Exception
30      {
31          synchronized (this)
32          {            
33              if (countDown.getCount() > 0)
34              {
35                  countDown.countDown();
36              }
37              else
38              {
39                  throw new AssertionFailedError("Too many messages received");
40              }
41          }
42      }
43  
44      public long getCount() throws InitialisationException
45      {
46          if (countDown != null)
47          {
48              return countDown.getCount();
49          }
50          else 
51          {
52              throw new InitialisationException(MessageFactory.createStaticMessage("CountDownLatch has not been initialized."), null);
53          }
54      }
55  
56      public boolean await(long timeout) throws InterruptedException
57      {
58          return countDown.await(timeout, TimeUnit.MILLISECONDS);
59      }
60      
61  }