1 package org.opentrafficsim.base.parameters.constraint;
2
3 import java.util.LinkedHashSet;
4 import java.util.Set;
5
6
7
8
9
10
11
12
13
14
15
16
17 public class MultiConstraint<T> implements Constraint<T>
18 {
19
20
21 private final Set<Constraint<? super T>> constraints;
22
23
24 private String failedConstraintMessage = null;
25
26
27 private final String stringRepresentation;
28
29
30
31
32
33
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
48
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
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
72 @Override
73 public String failMessage()
74 {
75 if (this.failedConstraintMessage == null)
76 {
77 return "A constraint failed for parameter '%s'.";
78 }
79
80 return "A constraint failed, most likely: " + this.failedConstraintMessage;
81 }
82
83
84 @Override
85 public String toString()
86 {
87 return this.stringRepresentation;
88 }
89
90 }