1   /* Copyright 2002-2024 CS GROUP
2    * Licensed to CS GROUP (CS) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * CS licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *   http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.orekit.gnss.metric.ntrip;
18  
19  import org.orekit.gnss.metric.messages.ParsedMessage;
20  
21  import java.util.concurrent.Phaser;
22  import java.util.concurrent.TimeUnit;
23  import java.util.concurrent.TimeoutException;
24  import java.util.concurrent.atomic.AtomicInteger;
25  import java.util.function.Function;
26  
27  
28  
29  public class CountingObserver implements MessageObserver {
30  
31      private Function<ParsedMessage, Boolean> filter;
32      private AtomicInteger received = new AtomicInteger(0);
33      private Phaser phaser = new Phaser(1);
34  
35      public CountingObserver(final Function<ParsedMessage, Boolean> filter) {
36          this.filter = filter;
37      }
38  
39      public void messageAvailable(String mountPoint, ParsedMessage message) {
40          if (filter.apply(message)) {
41              received.incrementAndGet();
42              phaser.arrive();
43          }
44      }
45  
46      /**
47       * Wait for a certain number of messages to be received.
48       *
49       * @param count   number of messages to wait for.
50       * @param timeout when waiting in ms.
51       * @throws InterruptedException if interrupted while waiting.
52       * @throws TimeoutException     if timeout is reached while waiting.
53       */
54      public void awaitCount(int count, long timeout) throws InterruptedException, TimeoutException {
55          final long start = System.currentTimeMillis();
56          final long end = start + timeout;
57          int phase = phaser.getPhase();
58          while (received.get() < count && (timeout = end - System.currentTimeMillis()) > 0) {
59              phase = phaser.awaitAdvanceInterruptibly(phase, timeout, TimeUnit.MILLISECONDS);
60          }
61      }
62  
63  }
64