View Javadoc

1   /*
2    * $Id: CountdownCallback.java 21939 2011-05-18 13:32:09Z aperepel $
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 java.util.concurrent.CountDownLatch;
17  import java.util.concurrent.TimeUnit;
18  
19  import junit.framework.AssertionFailedError;
20  
21  public class CountdownCallback implements EventCallback
22  {
23      private CountDownLatch countDown;
24  
25      public CountdownCallback(int messagesExpected)
26      {
27          this.countDown = new CountDownLatch(messagesExpected);
28      }
29  
30      public void eventReceived(MuleEventContext context, Object Component) throws Exception
31      {
32          synchronized (this)
33          {            
34              if (countDown.getCount() > 0)
35              {
36                  countDown.countDown();
37              }
38              else
39              {
40                  throw new AssertionFailedError("Too many messages received");
41              }
42          }
43      }
44  
45      public long getCount() throws InitialisationException
46      {
47          if (countDown != null)
48          {
49              return countDown.getCount();
50          }
51          else 
52          {
53              throw new InitialisationException(MessageFactory.createStaticMessage("CountDownLatch has not been initialized."), null);
54          }
55      }
56  
57      public boolean await(long timeout) throws InterruptedException
58      {
59          return countDown.await(timeout, TimeUnit.MILLISECONDS);
60      }
61      
62  }