package org.opentrafficsim.base.parameters.constraint; import java.util.HashSet; import java.util.Set; /** * Constraint containing multiple constraints. *

* Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
* BSD-style license. See OpenTrafficSim License. *

* @version $Revision$, $LastChangedDate$, by $Author$, initial version 11 sep. 2017
* @author Alexander Verbraeck * @author Peter Knoppers * @author Wouter Schakel * @param value type */ public class MultiConstraint implements Constraint { /** Set of constraints. */ private final Set> constraints; /** Message of the latest failed constrained. */ private String failedConstraintMessage = null; /** String representation. */ private final String stringRepresentation; /** * Creates a {@code MultiConstraint} from given constraints. * @param constraints Constraint<T>...; constraints * @param value type * @return {@code MultiConstraint} */ @SafeVarargs public static final MultiConstraint create(final Constraint... constraints) { Set> set = new HashSet<>(); for (Constraint constraint : constraints) { set.add(constraint); } return new MultiConstraint<>(set); } /** * Constructor. * @param constraints Set<Constraint<T>>; constraints */ public MultiConstraint(final Set> constraints) { this.constraints = constraints; this.stringRepresentation = String.format("MultiConstraint [contains %d constraints]", this.constraints.size()); } /** {@inheritDoc} */ @Override public boolean accept(final T value) { for (Constraint constraint : this.constraints) { if (!constraint.accept(value)) { this.failedConstraintMessage = constraint.failMessage(); return false; } } return true; } /** {@inheritDoc} */ @Override public String failMessage() { if (this.failedConstraintMessage == null) { return "A constraint failed for parameter '%s'."; } // note that we do not synchronize, nor can't we be assured that after accept()=false, this method is (directly) invoked return "A constraint failed, most likely: " + this.failedConstraintMessage; } /** {@inheritDoc} */ @Override public String toString() { return this.stringRepresentation; } }