View Javadoc
1   /*
2    * Copyright 2018 SPF4J.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.spf4j.test.log;
17  
18  import java.util.concurrent.TimeUnit;
19  import org.spf4j.base.TimeSource;
20  import org.spf4j.log.Level;
21  
22  /**
23   *
24   * @author Zoltan Farkas
25   */
26  abstract class LogMatchingHandlerAsync extends LogMatchingHandler {
27  
28    private final long timeout;
29    private final TimeUnit tu;
30    private final Object sync;
31  
32    LogMatchingHandlerAsync(
33            final Level minLevel, final long timeout, final TimeUnit tu, final LogStreamMatcher streamMatcher) {
34      super(minLevel, streamMatcher);
35      this.timeout = timeout;
36      this.tu = tu;
37      this.sync = new Object();
38    }
39  
40    public abstract void close();
41  
42  
43    @Override
44    public TestLogRecord handle(final TestLogRecord record) {
45      TestLogRecord result = super.handle(record);
46      synchronized (sync) {
47        sync.notifyAll();
48      }
49      return result;
50    }
51  
52  
53  
54    @Override
55    public void assertObservation() {
56      long deadline = TimeSource.nanoTime() + tu.toNanos(timeout);
57      try {
58        synchronized (sync) {
59          while (!streamMatcher.isMatched()) {
60            long nanosToDeadline = deadline - TimeSource.nanoTime();
61            if (nanosToDeadline <= 0) {
62                throw new AssertionError(this);
63            }
64            TimeUnit.NANOSECONDS.timedWait(sync, nanosToDeadline);
65          }
66        }
67      } catch (InterruptedException ex) {
68        Thread.currentThread().isInterrupted();
69      }
70    }
71  
72    @Override
73    public String toString() {
74      return "LogMatchingHandlerAsync{" + "timeout=" + timeout + ", tu=" + tu + ", super = " + super.toString() + '}';
75    }
76  
77  }