Merge branch 'master' of ../controller
[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.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;
14
15 class CompiledPatternContext {
16
17     private final Pattern pattern;
18     private final String errorMessage;
19     private final String regEx;
20     private final boolean invert;
21
22     CompiledPatternContext(final PatternConstraint yangConstraint) {
23         pattern = Pattern.compile(yangConstraint.getJavaPatternString());
24         errorMessage = yangConstraint.getErrorMessage().orElse(null);
25         regEx = errorMessage == null ? yangConstraint.getRegularExpressionString() : null;
26
27         final Optional<ModifierKind> optModifier = yangConstraint.getModifier();
28         if (optModifier.isPresent()) {
29             final ModifierKind modifier = optModifier.get();
30             switch (modifier) {
31                 case INVERT_MATCH:
32                     invert = true;
33                     break;
34                 default:
35                     throw new IllegalStateException("Unhandled modifier " + modifier);
36             }
37         } else {
38             invert = false;
39         }
40     }
41
42     void validate(final String str) {
43         if (pattern.matcher(str).matches() == invert) {
44             if (errorMessage != null) {
45                 throw new IllegalArgumentException(errorMessage);
46             }
47
48             throw new IllegalArgumentException("Value '" + str + "' " + (invert ? "matches" : "does not match")
49                     + " regular expression '" + regEx + "'");
50         }
51     }
52 }