View Javadoc

1   /*
2    * $Id: WarnOnTimeout.java 22017 2011-05-27 20:28:27Z pablo.kraan $
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  
11  package org.mule.tck.junit4.rule;
12  
13  import org.apache.commons.logging.Log;
14  import org.apache.commons.logging.LogFactory;
15  import org.junit.runners.model.Statement;
16  
17  /**
18   * Defines a {@link Statement} to execute a test with a given timeout.
19   * Differently from JUnit's {@link org.junit.internal.runners.statements.FailOnTimeout}
20   * this statement just prints a warning in the log, so the test will pass in
21   * case of timeout.
22   */
23  public class WarnOnTimeout extends Statement
24  {
25  
26      private final Log logger = LogFactory.getLog(this.getClass());
27  
28      private Statement next;
29      private final long timeout;
30      private boolean finished = false;
31      private Throwable thrown = null;
32  
33      public WarnOnTimeout(Statement next, long timeout)
34      {
35          this.next = next;
36          this.timeout = timeout;
37      }
38  
39      @Override
40      public void evaluate() throws Throwable
41      {
42          Thread thread = new Thread()
43          {
44              @Override
45              public void run()
46              {
47                  try
48                  {
49                      next.evaluate();
50                      finished = true;
51                  }
52                  catch (Throwable e)
53                  {
54                      thrown = e;
55                  }
56              }
57          };
58          thread.start();
59          thread.join(timeout);
60          if (finished)
61          {
62              return;
63          }
64          if (thrown != null)
65          {
66              throw thrown;
67          }
68  
69          logger.warn("Timeout of " + timeout + "ms exceeded");
70      }
71  }