Bug 2362: Added pattern validation for string types.
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / CompiledPatternContext.java
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/CompiledPatternContext.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/CompiledPatternContext.java
new file mode 100644 (file)
index 0000000..6e90122
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.codec;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import java.util.regex.Pattern;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+
+class CompiledPatternContext {
+
+    private final Pattern pattern;
+    private final String errorMessage;
+
+    CompiledPatternContext(final PatternConstraint yangConstraint) {
+        pattern = Pattern.compile("^" + yangConstraint.getRegularExpression() + "$");
+        final String yangMessage = yangConstraint.getErrorMessage();
+        if (Strings.isNullOrEmpty(yangMessage)) {
+            errorMessage = "Value %s does not match regular expression <" + pattern.pattern() + ">";
+        } else {
+            errorMessage = yangMessage;
+        }
+    }
+
+    public void validate(final String s) {
+        Preconditions.checkArgument(pattern.matcher(s).matches(), errorMessage, s);
+    }
+
+}
\ No newline at end of file