Clean up PatternConstraint's String confusion
[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     private final String regEx;
18
19     CompiledPatternContext(final PatternConstraint yangConstraint) {
20         pattern = Pattern.compile(yangConstraint.getJavaPatternString());
21         errorMessage = yangConstraint.getErrorMessage().orElse(null);
22         regEx = errorMessage == null ? yangConstraint.getRegularExpressionString() : null;
23     }
24
25     void validate(final String str) {
26         if (!pattern.matcher(str).matches()) {
27             if (errorMessage != null) {
28                 throw new IllegalArgumentException(errorMessage);
29             }
30
31             throw new IllegalArgumentException("Value " + str + "does not match regular expression '" + regEx + "'");
32         }
33     }
34 }