View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.tck.junit4.rule;
8   
9   import org.apache.commons.logging.Log;
10  import org.apache.commons.logging.LogFactory;
11  import org.junit.runners.model.Statement;
12  
13  /**
14   * Defines a {@link Statement} to execute a test with a given timeout.
15   * Differently from JUnit's {@link org.junit.internal.runners.statements.FailOnTimeout}
16   * this statement just prints a warning in the log, so the test will pass in
17   * case of timeout.
18   */
19  public class WarnOnTimeout extends Statement
20  {
21  
22      private final Log logger = LogFactory.getLog(this.getClass());
23  
24      private Statement next;
25      private final long timeout;
26      private boolean finished = false;
27      private Throwable thrown = null;
28  
29      public WarnOnTimeout(Statement next, long timeout)
30      {
31          this.next = next;
32          this.timeout = timeout;
33      }
34  
35      @Override
36      public void evaluate() throws Throwable
37      {
38          Thread thread = new Thread()
39          {
40              @Override
41              public void run()
42              {
43                  try
44                  {
45                      next.evaluate();
46                      finished = true;
47                  }
48                  catch (Throwable e)
49                  {
50                      thrown = e;
51                  }
52              }
53          };
54          thread.start();
55          thread.join(timeout);
56          if (finished)
57          {
58              return;
59          }
60          if (thrown != null)
61          {
62              throw thrown;
63          }
64  
65          logger.warn("Timeout of " + timeout + "ms exceeded");
66      }
67  }