2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.data.impl.codec;
10 import java.util.Optional;
11 import java.util.regex.Pattern;
12 import org.opendaylight.yangtools.yang.model.api.type.ModifierKind;
13 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
15 class CompiledPatternContext {
17 private final Pattern pattern;
18 private final String errorMessage;
19 private final String regEx;
20 private final boolean invert;
22 CompiledPatternContext(final PatternConstraint yangConstraint) {
23 pattern = Pattern.compile(yangConstraint.getJavaPatternString());
24 errorMessage = yangConstraint.getErrorMessage().orElse(null);
25 regEx = errorMessage == null ? yangConstraint.getRegularExpressionString() : null;
27 final Optional<ModifierKind> optModifier = yangConstraint.getModifier();
28 if (optModifier.isPresent()) {
29 final ModifierKind modifier = optModifier.get();
35 throw new IllegalStateException("Unhandled modifier " + modifier);
42 void validate(final String str) {
43 if (pattern.matcher(str).matches() == invert) {
44 if (errorMessage != null) {
45 throw new IllegalArgumentException(errorMessage);
48 throw new IllegalArgumentException("Value '" + str + "' " + (invert ? "matches" : "does not match")
49 + " regular expression '" + regEx + "'");