Make ConstraintMetaDefition attributes Optional
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / CompiledPatternContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec;
9
10 import java.util.regex.Pattern;
11 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
12
13 class CompiledPatternContext {
14
15     private final Pattern pattern;
16     private final String errorMessage;
17
18     CompiledPatternContext(final PatternConstraint yangConstraint) {
19         pattern = Pattern.compile("^" + yangConstraint.getRegularExpression() + "$");
20         errorMessage = yangConstraint.getErrorMessage().orElse(null);
21     }
22
23     void validate(final String str) {
24         if (!pattern.matcher(str).matches()) {
25             if (errorMessage != null) {
26                 throw new IllegalArgumentException(errorMessage);
27             }
28
29             throw new IllegalArgumentException("Value " + str + "does not match regular expression '"
30                     + pattern.pattern() + "'");
31         }
32     }
33 }