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