1 package org.opentrafficsim.base.parameters.constraint;
2
3 import java.util.HashSet;
4 import java.util.Set;
5
6
7
8
9
10
11
12
13
14
15
16
17
18 public class MultiConstraint<T> implements Constraint<T>
19 {
20
21
22 private final Set<Constraint<T>> constraints;
23
24
25 private String failedConstraintMessage = null;
26
27
28 private final String stringRepresentation;
29
30
31
32
33
34
35
36 @SafeVarargs
37 public static final <T> MultiConstraint<T> create(final Constraint<T>... constraints)
38 {
39 Set<Constraint<T>> set = new HashSet<>();
40 for (Constraint<T> constraint : constraints)
41 {
42 set.add(constraint);
43 }
44 return new MultiConstraint<>(set);
45 }
46
47
48
49
50
51 public MultiConstraint(final Set<Constraint<T>> constraints)
52 {
53 this.constraints = constraints;
54 this.stringRepresentation = String.format("MultiConstraint [contains %d constraints]", this.constraints.size());
55 }
56
57
58 @Override
59 public boolean accept(final T value)
60 {
61 for (Constraint<T> constraint : this.constraints)
62 {
63 if (!constraint.accept(value))
64 {
65 this.failedConstraintMessage = constraint.failMessage();
66 return false;
67 }
68 }
69 return true;
70 }
71
72
73 @Override
74 public String failMessage()
75 {
76 if (this.failedConstraintMessage == null)
77 {
78 return "A constraint failed for parameter '%s'.";
79 }
80
81 return "A constraint failed, most likely: " + this.failedConstraintMessage;
82 }
83
84
85 @Override
86 public String toString()
87 {
88 return this.stringRepresentation;
89 }
90
91 }