View Javadoc
1   package org.opentrafficsim.road.gtu.lane;
2   
3   import org.djutils.event.Event;
4   import org.djutils.event.EventListener;
5   import org.opentrafficsim.base.OtsRuntimeException;
6   import org.opentrafficsim.core.network.Network;
7   
8   /**
9    * Abstract class that listens to move events of GTUs so checks can be performed.
10   * <p>
11   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
13   * </p>
14   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
15   * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
16   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
17   */
18  public abstract class AbstractLaneBasedMoveChecker implements EventListener
19  {
20      /** Network. */
21      private final Network network;
22  
23      /**
24       * Constructor.
25       * @param network network
26       */
27      public AbstractLaneBasedMoveChecker(final Network network)
28      {
29          network.addListener(this, Network.GTU_ADD_EVENT);
30          network.addListener(this, Network.GTU_REMOVE_EVENT);
31          this.network = network;
32      }
33  
34      @Override
35      public void notify(final Event event)
36      {
37          if (event.getType().equals(LaneBasedGtu.LANEBASED_MOVE_EVENT))
38          {
39              try
40              {
41                  Object[] payload = (Object[]) event.getContent();
42                  checkMove((LaneBasedGtu) this.network.getGTU((String) payload[0])
43                          .orElseThrow(() -> new OtsRuntimeException("Check move event on GTU not in the network.")));
44              }
45              catch (OtsRuntimeException ex)
46              {
47                  throw ex;
48              }
49              catch (Exception ex)
50              {
51                  throw new OtsRuntimeException(ex);
52              }
53          }
54          else if (event.getType().equals(Network.GTU_ADD_EVENT))
55          {
56              this.network.getGTU((String) event.getContent()).get().addListener(this, LaneBasedGtu.LANEBASED_MOVE_EVENT);
57          }
58          else if (event.getType().equals(Network.GTU_REMOVE_EVENT))
59          {
60              this.network.getGTU((String) event.getContent()).get().removeListener(this, LaneBasedGtu.LANEBASED_MOVE_EVENT);
61          }
62          else
63          {
64              throw new OtsRuntimeException("AbstractMoveChecker is a listener to an unknown event type.");
65          }
66      }
67  
68      /**
69       * Check the move of the given GTU.
70       * @param gtu GTU.
71       * @throws Exception thrown when something is not all right
72       */
73      public abstract void checkMove(LaneBasedGtu gtu) throws Exception;
74  
75  }