View Javadoc
1   package org.opentrafficsim.base.parameters.constraint;
2   
3   import java.util.Collection;
4   
5   /**
6    * Constraint containing multiple constraints.
7    * <p>
8    * Copyright (c) 2013-2026 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
9    * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
10   * </p>
11   * @author Alexander Verbraeck
12   * @author Peter Knoppers
13   * @author Wouter Schakel
14   * @param <T> value type
15   */
16  public class MultiConstraint<T> implements Constraint<T>
17  {
18  
19      /** Set of constraints. */
20      private final Collection<Constraint<? super T>> constraints;
21  
22      /** Message of the latest failed constrained. */
23      private String failedConstraintMessage = null;
24  
25      /** String representation. */
26      private final String stringRepresentation;
27  
28      /**
29       * Constructor.
30       * @param constraints constraints
31       */
32      public MultiConstraint(final Collection<Constraint<? super T>> constraints)
33      {
34          this.constraints = constraints;
35          this.stringRepresentation = String.format("MultiConstraint [contains %d constraints]", this.constraints.size());
36      }
37  
38      @Override
39      public boolean accept(final T value)
40      {
41          for (Constraint<? super T> constraint : this.constraints)
42          {
43              if (!constraint.accept(value))
44              {
45                  this.failedConstraintMessage = constraint.failMessage();
46                  return false;
47              }
48          }
49          return true;
50      }
51  
52      @Override
53      public String failMessage()
54      {
55          if (this.failedConstraintMessage == null)
56          {
57              return "A constraint failed for parameter '%s'.";
58          }
59          // note that we do not synchronize, nor can't we be assured that after accept()=false, this method is (directly) invoked
60          return "A constraint failed, most likely: " + this.failedConstraintMessage;
61      }
62  
63      @Override
64      public String toString()
65      {
66          return this.stringRepresentation;
67      }
68  
69  }